Fix regression with distinctive ring detection.
[asterisk/asterisk.git] / channels / sig_analog.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2009, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Analog signaling module
22  *
23  * \author Matthew Fredrickson <creslin@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 #include <errno.h>
29 #include <ctype.h>
30
31 #include "asterisk/utils.h"
32 #include "asterisk/options.h"
33 #include "asterisk/pbx.h"
34 #include "asterisk/file.h"
35 #include "asterisk/callerid.h"
36 #include "asterisk/say.h"
37 #include "asterisk/manager.h"
38 #include "asterisk/astdb.h"
39 #include "asterisk/features.h"
40 #include "asterisk/cel.h"
41 #include "asterisk/causes.h"
42
43 #include "sig_analog.h"
44
45 #define POLARITY_IDLE 0
46 #define POLARITY_REV    1
47 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /*!< 2000 ms */
48 static int analog_matchdigittimeout = 3000;
49 static int analog_gendigittimeout = 8000;
50 static int analog_firstdigittimeout = 16000;
51 static char analog_defaultcic[64] = "";
52 static char analog_defaultozz[64] = "";
53
54 static const struct {
55         enum analog_sigtype sigtype;
56         const char const *name;
57 } sigtypes[] = {
58         { ANALOG_SIG_FXOLS, "fxo_ls" },
59         { ANALOG_SIG_FXOKS, "fxo_ks" },
60         { ANALOG_SIG_FXOGS, "fxo_gs" },
61         { ANALOG_SIG_FXSLS, "fxs_ls" },
62         { ANALOG_SIG_FXSKS, "fxs_ks" },
63         { ANALOG_SIG_FXSGS, "fxs_gs" },
64         { ANALOG_SIG_EMWINK, "em_w" },
65         { ANALOG_SIG_EM, "em" },
66         { ANALOG_SIG_EM_E1, "em_e1" },
67         { ANALOG_SIG_FEATD, "featd" },
68         { ANALOG_SIG_FEATDMF, "featdmf" },
69         { ANALOG_SIG_FEATDMF_TA, "featdmf_ta" },
70         { ANALOG_SIG_FEATB, "featb" },
71         { ANALOG_SIG_FGC_CAMA, "fgccama" },
72         { ANALOG_SIG_FGC_CAMAMF, "fgccamamf" },
73         { ANALOG_SIG_SF, "sf" },
74         { ANALOG_SIG_SFWINK, "sf_w" },
75         { ANALOG_SIG_SF_FEATD, "sf_featd" },
76         { ANALOG_SIG_SF_FEATDMF, "sf_featdmf" },
77         { ANALOG_SIG_SF_FEATB, "sf_featb" },
78         { ANALOG_SIG_E911, "e911" },
79 };
80
81 static const struct {
82         unsigned int cid_type;
83         const char const *name;
84 } cidtypes[] = {
85         { CID_SIG_BELL,   "bell" },
86         { CID_SIG_V23,    "v23" },
87         { CID_SIG_V23_JP, "v23_jp" },
88         { CID_SIG_DTMF,   "dtmf" },
89         /* "smdi" is intentionally not supported here, as there is a much better
90          * way to do this in the dialplan now. */
91 };
92
93 #define ISTRUNK(p) ((p->sig == ANALOG_SIG_FXSLS) || (p->sig == ANALOG_SIG_FXSKS) || \
94                                         (p->sig == ANALOG_SIG_FXSGS))
95
96 enum analog_sigtype analog_str_to_sigtype(const char *name)
97 {
98         int i;
99
100         for (i = 0; i < ARRAY_LEN(sigtypes); i++) {
101                 if (!strcasecmp(sigtypes[i].name, name)) {
102                         return sigtypes[i].sigtype;
103                 }
104         }
105
106         return 0;
107 }
108
109 const char *analog_sigtype_to_str(enum analog_sigtype sigtype)
110 {
111         int i;
112
113         for (i = 0; i < ARRAY_LEN(sigtypes); i++) {
114                 if (sigtype == sigtypes[i].sigtype) {
115                         return sigtypes[i].name;
116                 }
117         }
118
119         return "Unknown";
120 }
121
122 unsigned int analog_str_to_cidtype(const char *name)
123 {
124         int i;
125
126         for (i = 0; i < ARRAY_LEN(cidtypes); i++) {
127                 if (!strcasecmp(cidtypes[i].name, name)) {
128                         return cidtypes[i].cid_type;
129                 }
130         }
131
132         return 0;
133 }
134
135 const char *analog_cidtype_to_str(unsigned int cid_type)
136 {
137         int i;
138
139         for (i = 0; i < ARRAY_LEN(cidtypes); i++) {
140                 if (cid_type == cidtypes[i].cid_type) {
141                         return cidtypes[i].name;
142                 }
143         }
144
145         return "Unknown";
146 }
147
148 static int analog_start_cid_detect(struct analog_pvt *p, int cid_signalling)
149 {
150         if (p->calls->start_cid_detect) {
151                 return p->calls->start_cid_detect(p->chan_pvt, cid_signalling);
152         }
153         return -1;
154 }
155
156 static int analog_stop_cid_detect(struct analog_pvt *p)
157 {
158         if (p->calls->stop_cid_detect) {
159                 return p->calls->stop_cid_detect(p->chan_pvt);
160         }
161         return -1;
162 }
163
164 static int analog_get_callerid(struct analog_pvt *p, char *name, char *number, enum analog_event *ev, size_t timeout)
165 {
166         if (p->calls->get_callerid) {
167                 return p->calls->get_callerid(p->chan_pvt, name, number, ev, timeout);
168         }
169         return -1;
170 }
171
172 static const char *analog_get_orig_dialstring(struct analog_pvt *p)
173 {
174         if (p->calls->get_orig_dialstring) {
175                 return p->calls->get_orig_dialstring(p->chan_pvt);
176         }
177         return "";
178 }
179
180 static int analog_get_event(struct analog_pvt *p)
181 {
182         if (p->calls->get_event) {
183                 return p->calls->get_event(p->chan_pvt);
184         }
185         return -1;
186 }
187
188 static int analog_wait_event(struct analog_pvt *p)
189 {
190         if (p->calls->wait_event) {
191                 return p->calls->wait_event(p->chan_pvt);
192         }
193         return -1;
194 }
195
196 enum analog_cid_start analog_str_to_cidstart(const char *value)
197 {
198         if (!strcasecmp(value, "ring")) {
199                 return ANALOG_CID_START_RING;
200         } else if (!strcasecmp(value, "polarity")) {
201                 return ANALOG_CID_START_POLARITY;
202         } else if (!strcasecmp(value, "polarity_in")) {
203                 return ANALOG_CID_START_POLARITY_IN;
204         } else if (!strcasecmp(value, "dtmf")) {
205                 return ANALOG_CID_START_DTMF_NOALERT;
206         }
207
208         return 0;
209 }
210
211 const char *analog_cidstart_to_str(enum analog_cid_start cid_start)
212 {
213         switch (cid_start) {
214         case ANALOG_CID_START_RING:
215                 return "Ring";
216         case ANALOG_CID_START_POLARITY:
217                 return "Polarity";
218         case ANALOG_CID_START_POLARITY_IN:
219                 return "Polarity_In";
220         case ANALOG_CID_START_DTMF_NOALERT:
221                 return "DTMF";
222         }
223
224         return "Unknown";
225 }
226
227 static char *analog_event2str(enum analog_event event)
228 {
229         char *res;
230         switch (event) {
231         case ANALOG_EVENT_ONHOOK:
232                 res = "ANALOG_EVENT_ONHOOK";
233                 break;
234         case ANALOG_EVENT_RINGOFFHOOK:
235                 res = "ANALOG_EVENT_RINGOFFHOOK";
236                 break;
237         case ANALOG_EVENT_WINKFLASH:
238                 res = "ANALOG_EVENT_WINKFLASH";
239                 break;
240         case ANALOG_EVENT_ALARM:
241                 res = "ANALOG_EVENT_ALARM";
242                 break;
243         case ANALOG_EVENT_NOALARM:
244                 res = "ANALOG_EVENT_NOALARM";
245                 break;
246         case ANALOG_EVENT_DIALCOMPLETE:
247                 res = "ANALOG_EVENT_DIALCOMPLETE";
248                 break;
249         case ANALOG_EVENT_HOOKCOMPLETE:
250                 res = "ANALOG_EVENT_HOOKCOMPLETE";
251                 break;
252         case ANALOG_EVENT_PULSE_START:
253                 res = "ANALOG_EVENT_PULSE_START";
254                 break;
255         case ANALOG_EVENT_POLARITY:
256                 res = "ANALOG_EVENT_POLARITY";
257                 break;
258         case ANALOG_EVENT_RINGBEGIN:
259                 res = "ANALOG_EVENT_RINGBEGIN";
260                 break;
261         case ANALOG_EVENT_EC_DISABLED:
262                 res = "ANALOG_EVENT_EC_DISABLED";
263                 break;
264         case ANALOG_EVENT_RINGERON:
265                 res = "ANALOG_EVENT_RINGERON";
266                 break;
267         case ANALOG_EVENT_RINGEROFF:
268                 res = "ANALOG_EVENT_RINGEROFF";
269                 break;
270         case ANALOG_EVENT_REMOVED:
271                 res = "ANALOG_EVENT_REMOVED";
272                 break;
273         case ANALOG_EVENT_NEONMWI_ACTIVE:
274                 res = "ANALOG_EVENT_NEONMWI_ACTIVE";
275                 break;
276         case ANALOG_EVENT_NEONMWI_INACTIVE:
277                 res = "ANALOG_EVENT_NEONMWI_INACTIVE";
278                 break;
279 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
280         case ANALOG_EVENT_TX_CED_DETECTED:
281                 res = "ANALOG_EVENT_TX_CED_DETECTED";
282                 break;
283         case ANALOG_EVENT_RX_CED_DETECTED:
284                 res = "ANALOG_EVENT_RX_CED_DETECTED";
285                 break;
286         case ANALOG_EVENT_EC_NLP_DISABLED:
287                 res = "ANALOG_EVENT_EC_NLP_DISABLED";
288                 break;
289         case ANALOG_EVENT_EC_NLP_ENABLED:
290                 res = "ANALOG_EVENT_EC_NLP_ENABLED";
291                 break;
292 #endif
293         case ANALOG_EVENT_PULSEDIGIT:
294                 res = "ANALOG_EVENT_PULSEDIGIT";
295                 break;
296         case ANALOG_EVENT_DTMFDOWN:
297                 res = "ANALOG_EVENT_DTMFDOWN";
298                 break;
299         case ANALOG_EVENT_DTMFUP:
300                 res = "ANALOG_EVENT_DTMFUP";
301                 break;
302         default:
303                 res = "UNKNOWN/OTHER";
304                 break;
305         }
306
307         return res;
308 }
309
310 static void analog_swap_subs(struct analog_pvt *p, enum analog_sub a, enum analog_sub b)
311 {
312         int tinthreeway;
313         struct ast_channel *towner;
314
315         ast_debug(1, "Swapping %d and %d\n", a, b);
316
317         towner = p->subs[a].owner;
318         tinthreeway = p->subs[a].inthreeway;
319
320         p->subs[a].owner = p->subs[b].owner;
321         p->subs[a].inthreeway = p->subs[b].inthreeway;
322
323         p->subs[b].owner = towner;
324         p->subs[b].inthreeway = tinthreeway;
325
326         if (p->calls->swap_subs) {
327                 p->calls->swap_subs(p->chan_pvt, a, p->subs[a].owner, b, p->subs[b].owner);
328         }
329 }
330
331 static int analog_alloc_sub(struct analog_pvt *p, enum analog_sub x)
332 {
333         if (p->calls->allocate_sub) {
334                 int res;
335                 res = p->calls->allocate_sub(p->chan_pvt, x);
336                 if (!res) {
337                         p->subs[x].allocd = 1;
338                 }
339                 return res;
340         }
341         return 0;
342 }
343
344 static int analog_unalloc_sub(struct analog_pvt *p, enum analog_sub x)
345 {
346         p->subs[x].allocd = 0;
347         p->subs[x].owner = NULL;
348         if (p->calls->unallocate_sub) {
349                 return p->calls->unallocate_sub(p->chan_pvt, x);
350         }
351         return 0;
352 }
353
354 static int analog_send_callerid(struct analog_pvt *p, int cwcid, struct ast_party_caller *caller)
355 {
356         ast_debug(1, "Sending callerid.  CID_NAME: '%s' CID_NUM: '%s'\n",
357                 caller->id.name.str,
358                 caller->id.number.str);
359
360         if (cwcid) {
361                 p->callwaitcas = 0;
362         }
363
364         if (p->calls->send_callerid) {
365                 return p->calls->send_callerid(p->chan_pvt, cwcid, caller);
366         }
367         return 0;
368 }
369
370 static int analog_get_index(struct ast_channel *ast, struct analog_pvt *p, int nullok)
371 {
372         int res;
373         if (p->subs[ANALOG_SUB_REAL].owner == ast) {
374                 res = ANALOG_SUB_REAL;
375         } else if (p->subs[ANALOG_SUB_CALLWAIT].owner == ast) {
376                 res = ANALOG_SUB_CALLWAIT;
377         } else if (p->subs[ANALOG_SUB_THREEWAY].owner == ast) {
378                 res = ANALOG_SUB_THREEWAY;
379         } else {
380                 res = -1;
381                 if (!nullok) {
382                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
383                 }
384         }
385         return res;
386 }
387
388 static int analog_dsp_reset_and_flush_digits(struct analog_pvt *p)
389 {
390         if (p->calls->dsp_reset_and_flush_digits) {
391                 return p->calls->dsp_reset_and_flush_digits(p->chan_pvt);
392         }
393
394         /* Return 0 since I think this is unnecessary to do in most cases it is used.  Mostly only for ast_dsp */
395         return 0;
396 }
397
398 static int analog_play_tone(struct analog_pvt *p, enum analog_sub sub, enum analog_tone tone)
399 {
400         if (p->calls->play_tone) {
401                 return p->calls->play_tone(p->chan_pvt, sub, tone);
402         }
403         return -1;
404 }
405
406 static struct ast_channel * analog_new_ast_channel(struct analog_pvt *p, int state, int startpbx, enum analog_sub sub, const struct ast_channel *requestor)
407 {
408         struct ast_channel *c;
409
410         if (!p->calls->new_ast_channel) {
411                 return NULL;
412         }
413
414         c = p->calls->new_ast_channel(p->chan_pvt, state, startpbx, sub, requestor);
415         if (c) {
416                 ast_string_field_set(c, call_forward, p->call_forward);
417         }
418         p->subs[sub].owner = c;
419         if (!p->owner) {
420                 p->owner = c;
421         }
422         return c;
423 }
424
425 static int analog_set_echocanceller(struct analog_pvt *p, int enable)
426 {
427         if (p->calls->set_echocanceller) {
428                 return p->calls->set_echocanceller(p->chan_pvt, enable);
429         }
430         return -1;
431 }
432
433 static int analog_train_echocanceller(struct analog_pvt *p)
434 {
435         if (p->calls->train_echocanceller) {
436                 return p->calls->train_echocanceller(p->chan_pvt);
437         }
438         return -1;
439 }
440
441 static int analog_is_off_hook(struct analog_pvt *p)
442 {
443         if (p->calls->is_off_hook) {
444                 return p->calls->is_off_hook(p->chan_pvt);
445         }
446         return -1;
447 }
448
449 static int analog_ring(struct analog_pvt *p)
450 {
451         if (p->calls->ring) {
452                 return p->calls->ring(p->chan_pvt);
453         }
454         return -1;
455 }
456
457 static int analog_flash(struct analog_pvt *p)
458 {
459         if (p->calls->flash) {
460                 return p->calls->flash(p->chan_pvt);
461         }
462         return -1;
463 }
464
465 static int analog_start(struct analog_pvt *p)
466 {
467         if (p->calls->start) {
468                 return p->calls->start(p->chan_pvt);
469         }
470         return -1;
471 }
472
473 static int analog_dial_digits(struct analog_pvt *p, enum analog_sub sub, struct analog_dialoperation *dop)
474 {
475         if (p->calls->dial_digits) {
476                 return p->calls->dial_digits(p->chan_pvt, sub, dop);
477         }
478         return -1;
479 }
480
481 static int analog_on_hook(struct analog_pvt *p)
482 {
483         if (p->calls->on_hook) {
484                 return p->calls->on_hook(p->chan_pvt);
485         }
486         return -1;
487 }
488
489 static int analog_check_for_conference(struct analog_pvt *p)
490 {
491         if (p->calls->check_for_conference) {
492                 return p->calls->check_for_conference(p->chan_pvt);
493         }
494         return -1;
495 }
496
497 static void analog_all_subchannels_hungup(struct analog_pvt *p)
498 {
499         if (p->calls->all_subchannels_hungup) {
500                 p->calls->all_subchannels_hungup(p->chan_pvt);
501         }
502 }
503
504 static void analog_unlock_private(struct analog_pvt *p)
505 {
506         if (p->calls->unlock_private) {
507                 p->calls->unlock_private(p->chan_pvt);
508         }
509 }
510
511 static void analog_lock_private(struct analog_pvt *p)
512 {
513         if (p->calls->lock_private) {
514                 p->calls->lock_private(p->chan_pvt);
515         }
516 }
517
518 static int analog_off_hook(struct analog_pvt *p)
519 {
520         if (p->calls->off_hook) {
521                 return p->calls->off_hook(p->chan_pvt);
522         }
523         return -1;
524 }
525
526 static void analog_set_needringing(struct analog_pvt *p, int value)
527 {
528         if (p->calls->set_needringing) {
529                 return p->calls->set_needringing(p->chan_pvt, value);
530         }
531 }
532
533 static int analog_dsp_set_digitmode(struct analog_pvt *p, enum analog_dsp_digitmode mode)
534 {
535         if (p->calls->dsp_set_digitmode) {
536                 return p->calls->dsp_set_digitmode(p->chan_pvt, mode);
537         }
538         return -1;
539 }
540
541 static void analog_cb_handle_dtmfup(struct analog_pvt *p, struct ast_channel *ast, enum analog_sub analog_index, struct ast_frame **dest)
542 {
543         if (p->calls->handle_dtmfup) {
544                 p->calls->handle_dtmfup(p->chan_pvt, ast, analog_index, dest);
545         }
546 }
547
548 static int analog_wink(struct analog_pvt *p, enum analog_sub index)
549 {
550         if (p->calls->wink) {
551                 return p->calls->wink(p->chan_pvt, index);
552         }
553         return -1;
554 }
555
556 static int analog_has_voicemail(struct analog_pvt *p)
557 {
558         if (p->calls->has_voicemail) {
559                 return p->calls->has_voicemail(p->chan_pvt);
560         }
561         return -1;
562 }
563
564 static int analog_is_dialing(struct analog_pvt *p, enum analog_sub index)
565 {
566         if (p->calls->is_dialing) {
567                 return p->calls->is_dialing(p->chan_pvt, index);
568         }
569         return -1;
570 }
571
572 static int analog_attempt_transfer(struct analog_pvt *p)
573 {
574         /* In order to transfer, we need at least one of the channels to
575            actually be in a call bridge.  We can't conference two applications
576            together (but then, why would we want to?) */
577         if (ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner)) {
578                 /* The three-way person we're about to transfer to could still be in MOH, so
579                    stop if now if appropriate */
580                 if (ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)) {
581                         ast_queue_control(p->subs[ANALOG_SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
582                 }
583                 if (p->subs[ANALOG_SUB_REAL].owner->_state == AST_STATE_RINGING) {
584                         ast_indicate(ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner), AST_CONTROL_RINGING);
585                 }
586                 if (p->subs[ANALOG_SUB_THREEWAY].owner->_state == AST_STATE_RING) {
587                         analog_play_tone(p, ANALOG_SUB_THREEWAY, ANALOG_TONE_RINGTONE);
588                 }
589                 if (!p->subs[ANALOG_SUB_THREEWAY].inthreeway) {
590                         ast_cel_report_event(p->subs[ANALOG_SUB_THREEWAY].owner, AST_CEL_ATTENDEDTRANSFER, NULL, p->subs[ANALOG_SUB_THREEWAY].owner->linkedid, NULL);
591                 }
592                 if (ast_channel_masquerade(p->subs[ANALOG_SUB_THREEWAY].owner, ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner))) {
593                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
594                                         ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner)->name, p->subs[ANALOG_SUB_THREEWAY].owner->name);
595                         return -1;
596                 }
597                 /* Orphan the channel after releasing the lock */
598                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
599                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
600         } else if (ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)) {
601                 ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_UNHOLD);
602                 if (p->subs[ANALOG_SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
603                         ast_indicate(ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner), AST_CONTROL_RINGING);
604                 }
605                 if (p->subs[ANALOG_SUB_REAL].owner->_state == AST_STATE_RING) {
606                         analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_RINGTONE);
607                 }
608                 ast_cel_report_event(p->subs[ANALOG_SUB_THREEWAY].owner, AST_CEL_BLINDTRANSFER, NULL, p->subs[ANALOG_SUB_THREEWAY].owner->linkedid, NULL);
609                 if (ast_channel_masquerade(p->subs[ANALOG_SUB_REAL].owner, ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner))) {
610                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
611                                         ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)->name, p->subs[ANALOG_SUB_REAL].owner->name);
612                         return -1;
613                 }
614                 /* Three-way is now the REAL */
615                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
616                 ast_channel_unlock(p->subs[ANALOG_SUB_REAL].owner); /* unlock REAL because THREEWAY has become REAL */
617                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
618                 /* Tell the caller not to hangup */
619                 return 1;
620         } else {
621                 ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
622                                         p->subs[ANALOG_SUB_REAL].owner->name, p->subs[ANALOG_SUB_THREEWAY].owner->name);
623                 ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
624                 return -1;
625         }
626         return 0;
627 }
628
629 static int analog_update_conf(struct analog_pvt *p)
630 {
631         int x;
632         int needconf = 0;
633
634         /* Start with the obvious, general stuff */
635         for (x = 0; x < 3; x++) {
636                 /* Look for three way calls */
637                 if ((p->subs[x].allocd) && p->subs[x].inthreeway) {
638                         if (p->calls->conf_add) {
639                                 p->calls->conf_add(p->chan_pvt, x);
640                         }
641                         needconf++;
642                 } else {
643                         if (p->calls->conf_del) {
644                                 p->calls->conf_del(p->chan_pvt, x);
645                         }
646                 }
647         }
648         ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
649
650         if (p->calls->complete_conference_update) {
651                 p->calls->complete_conference_update(p->chan_pvt, needconf);
652         }
653         return 0;
654 }
655
656 struct ast_channel * analog_request(struct analog_pvt *p, int *callwait, const struct ast_channel *requestor)
657 {
658         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
659         *callwait = (p->owner != NULL);
660
661         if (p->owner) {
662                 if (analog_alloc_sub(p, ANALOG_SUB_CALLWAIT)) {
663                         ast_log(LOG_ERROR, "Unable to alloc subchannel\n");
664                         return NULL;
665                 }
666         }
667
668         return analog_new_ast_channel(p, AST_STATE_RESERVED, 0, p->owner ? ANALOG_SUB_CALLWAIT : ANALOG_SUB_REAL, requestor);
669 }
670
671 int analog_available(struct analog_pvt *p)
672 {
673         int offhook;
674
675         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
676         /* If do not disturb, definitely not */
677         if (p->dnd) {
678                 return 0;
679         }
680         /* If guard time, definitely not */
681         if (p->guardtime && (time(NULL) < p->guardtime)) {
682                 return 0;
683         }
684
685         /* If no owner definitely available */
686         if (!p->owner) {
687                 if (p->sig == ANALOG_SIG_FXSLS) {
688                         return 1;
689                 }
690
691                 offhook = analog_is_off_hook(p);
692
693                 if ((p->sig == ANALOG_SIG_FXSKS) || (p->sig == ANALOG_SIG_FXSGS)) {
694                         /* When "onhook" that means no battery on the line, and thus
695                           it is out of service..., if it's on a TDM card... If it's a channel
696                           bank, there is no telling... */
697                         if (offhook) {
698                                 return 1;
699                         }
700                         return 0;
701                 } else if (offhook) {
702                         ast_debug(1, "Channel %d off hook, can't use\n", p->channel);
703                         /* Not available when the other end is off hook */
704                         return 0;
705                 }
706                 return 1;
707         }
708
709         /* If it's not an FXO, forget about call wait */
710         if ((p->sig != ANALOG_SIG_FXOKS) && (p->sig != ANALOG_SIG_FXOLS) && (p->sig != ANALOG_SIG_FXOGS)) {
711                 return 0;
712         }
713
714         if (!p->callwaiting) {
715                 /* If they don't have call waiting enabled, then for sure they're unavailable at this point */
716                 return 0;
717         }
718
719         if (p->subs[ANALOG_SUB_CALLWAIT].allocd) {
720                 /* If there is already a call waiting call, then we can't take a second one */
721                 return 0;
722         }
723
724         if ((p->owner->_state != AST_STATE_UP) &&
725             ((p->owner->_state != AST_STATE_RINGING) || p->outgoing)) {
726                 /* If the current call is not up, then don't allow the call */
727                 return 0;
728         }
729         if ((p->subs[ANALOG_SUB_THREEWAY].owner) && (!p->subs[ANALOG_SUB_THREEWAY].inthreeway)) {
730                 /* Can't take a call wait when the three way calling hasn't been merged yet. */
731                 return 0;
732         }
733         /* We're cool */
734         return 1;
735 }
736
737 static int analog_stop_callwait(struct analog_pvt *p)
738 {
739         if (p->callwaitingcallerid) {
740                 p->callwaitcas = 0;
741         }
742
743         if (p->calls->stop_callwait) {
744                 return p->calls->stop_callwait(p->chan_pvt);
745         }
746         return 0;
747 }
748
749 static int analog_callwait(struct analog_pvt *p)
750 {
751         if (p->callwaitingcallerid) {
752                 p->callwaitcas = 1;
753         }
754         if (p->calls->callwait) {
755                 return p->calls->callwait(p->chan_pvt);
756         }
757         return 0;
758 }
759
760 static void analog_set_cadence(struct analog_pvt *p, struct ast_channel *chan)
761 {
762         if (p->calls->set_cadence) {
763                 return p->calls->set_cadence(p->chan_pvt, &p->cidrings, chan);
764         }
765 }
766
767 static void analog_set_dialing(struct analog_pvt *p, int is_dialing)
768 {
769         p->dialing = is_dialing;
770         if (p->calls->set_dialing) {
771                 return p->calls->set_dialing(p->chan_pvt, is_dialing);
772         }
773 }
774
775 static void analog_set_alarm(struct analog_pvt *p, int in_alarm)
776 {
777         p->inalarm = in_alarm;
778         if (p->calls->set_alarm) {
779                 return p->calls->set_alarm(p->chan_pvt, in_alarm);
780         }
781 }
782
783 static void analog_set_ringtimeout(struct analog_pvt *p, int ringt)
784 {
785         p->ringt = ringt;
786         if (!p->calls->set_ringtimeout) {
787                 return;
788         }
789         p->calls->set_ringtimeout(p->chan_pvt, ringt);
790 }
791
792 static void analog_set_waitingfordt(struct analog_pvt *p, struct ast_channel *ast)
793 {
794         if (p->calls->set_waitingfordt) {
795                 return p->calls->set_waitingfordt(p->chan_pvt, ast);
796         }
797 }
798
799 static int analog_check_waitingfordt(struct analog_pvt *p)
800 {
801         if (p->calls->check_waitingfordt) {
802                 return p->calls->check_waitingfordt(p->chan_pvt);
803         }
804
805         return 0;
806 }
807
808 static void analog_set_confirmanswer(struct analog_pvt *p, int flag)
809 {
810         if (!p->calls->set_confirmanswer) {
811                 return;
812         }
813         p->calls->set_confirmanswer(p->chan_pvt, flag);
814 }
815
816 static int analog_check_confirmanswer(struct analog_pvt *p)
817 {
818         if (p->calls->check_confirmanswer) {
819                 return p->calls->check_confirmanswer(p->chan_pvt);
820         }
821
822         return 0;
823 }
824
825 static void analog_cancel_cidspill(struct analog_pvt *p)
826 {
827         if (!p->calls->cancel_cidspill) {
828                 return;
829         }
830
831         p->calls->cancel_cidspill(p->chan_pvt);
832 }
833
834 static int analog_confmute(struct analog_pvt *p, int mute)
835 {
836         if (p->calls->confmute) {
837                 return p->calls->confmute(p->chan_pvt, mute);
838         }
839         return 0;
840 }
841
842 static void analog_set_pulsedial(struct analog_pvt *p, int flag)
843 {
844         if (!p->calls->set_pulsedial) {
845                 return;
846         }
847         p->calls->set_pulsedial(p->chan_pvt, flag);
848 }
849
850 static int analog_set_linear_mode(struct analog_pvt *p, int index, int linear_mode)
851 {
852         if (p->calls->set_linear_mode) {
853                 /* Return provides old linear_mode setting or error indication */
854                 return p->calls->set_linear_mode(p->chan_pvt, index, linear_mode);
855         }
856         return -1;
857 }
858
859 int analog_call(struct analog_pvt *p, struct ast_channel *ast, char *rdest, int timeout)
860 {
861         int res, index,mysig;
862         char *c, *n, *l;
863         char dest[256]; /* must be same length as p->dialdest */
864
865         ast_log(LOG_DEBUG, "CALLING CID_NAME: %s CID_NUM:: %s\n",
866                 S_COR(ast->connected.id.name.valid, ast->connected.id.name.str, ""),
867                 S_COR(ast->connected.id.number.valid, ast->connected.id.number.str, ""));
868
869         ast_copy_string(dest, rdest, sizeof(dest));
870         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
871
872         if ((ast->_state == AST_STATE_BUSY)) {
873                 ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_BUSY);
874                 return 0;
875         }
876
877         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
878                 ast_log(LOG_WARNING, "analog_call called on %s, neither down nor reserved\n", ast->name);
879                 return -1;
880         }
881
882         p->dialednone = 0;
883
884         mysig = p->sig;
885         if (p->outsigmod > -1) {
886                 mysig = p->outsigmod;
887         }
888
889         switch (mysig) {
890         case ANALOG_SIG_FXOLS:
891         case ANALOG_SIG_FXOGS:
892         case ANALOG_SIG_FXOKS:
893                 if (p->owner == ast) {
894                         /* Normal ring, on hook */
895
896                         /* Don't send audio while on hook, until the call is answered */
897                         analog_set_dialing(p, 1);
898                         analog_set_cadence(p, ast); /* and set p->cidrings */
899
900                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
901                         c = strchr(dest, '/');
902                         if (c) {
903                                 c++;
904                         }
905                         if (c && (strlen(c) < p->stripmsd)) {
906                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
907                                 c = NULL;
908                         }
909                         if (c) {
910                                 p->dop.op = ANALOG_DIAL_OP_REPLACE;
911                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
912                                 ast_debug(1, "FXO: setup deferred dialstring: %s\n", c);
913                         } else {
914                                 p->dop.dialstr[0] = '\0';
915                         }
916
917                         if (analog_ring(p)) {
918                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
919                                 return -1;
920                         }
921                         analog_set_dialing(p, 1);
922                 } else {
923                         if (ast->connected.id.number.valid && ast->connected.id.number.str) {
924                                 ast_copy_string(p->callwait_num, ast->connected.id.number.str, sizeof(p->callwait_num));
925                         } else {
926                                 p->callwait_num[0] = '\0';
927                         }
928                         if (ast->connected.id.name.valid && ast->connected.id.name.str) {
929                                 ast_copy_string(p->callwait_name, ast->connected.id.name.str, sizeof(p->callwait_name));
930                         } else {
931                                 p->callwait_name[0] = '\0';
932                         }
933
934                         /* Call waiting tone instead */
935                         if (analog_callwait(p)) {
936                                 return -1;
937                         }
938                         /* Make ring-back */
939                         if (analog_play_tone(p, ANALOG_SUB_CALLWAIT, ANALOG_TONE_RINGTONE)) {
940                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
941                         }
942
943                 }
944                 n = ast->connected.id.name.valid ? ast->connected.id.name.str : NULL;
945                 l = ast->connected.id.number.valid ? ast->connected.id.number.str : NULL;
946                 if (l) {
947                         ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
948                 } else {
949                         p->lastcid_num[0] = '\0';
950                 }
951                 if (n) {
952                         ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
953                 } else {
954                         p->lastcid_name[0] = '\0';
955                 }
956
957                 if (p->use_callerid) {
958                         p->caller.id.name.str = p->lastcid_name;
959                         p->caller.id.number.str = p->lastcid_num;
960                 }
961
962                 ast_setstate(ast, AST_STATE_RINGING);
963                 index = analog_get_index(ast, p, 0);
964                 if (index > -1) {
965                         struct ast_cc_config_params *cc_params;
966
967                         /* This is where the initial ringing frame is queued for an analog call.
968                          * As such, this is a great time to offer CCNR to the caller if it's available.
969                          */
970                         cc_params = ast_channel_get_cc_config_params(p->subs[index].owner);
971                         if (cc_params) {
972                                 switch (ast_get_cc_monitor_policy(cc_params)) {
973                                 case AST_CC_MONITOR_NEVER:
974                                         break;
975                                 case AST_CC_MONITOR_NATIVE:
976                                 case AST_CC_MONITOR_ALWAYS:
977                                 case AST_CC_MONITOR_GENERIC:
978                                         ast_queue_cc_frame(p->subs[index].owner, AST_CC_GENERIC_MONITOR_TYPE,
979                                                 analog_get_orig_dialstring(p), AST_CC_CCNR, NULL);
980                                         break;
981                                 }
982                         }
983                         ast_queue_control(p->subs[index].owner, AST_CONTROL_RINGING);
984                 }
985                 break;
986         case ANALOG_SIG_FXSLS:
987         case ANALOG_SIG_FXSGS:
988         case ANALOG_SIG_FXSKS:
989                 if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
990                         ast_debug(1, "Ignore possible polarity reversal on line seizure\n");
991                         p->polaritydelaytv = ast_tvnow();
992                 }
993                 /* fall through */
994         case ANALOG_SIG_EMWINK:
995         case ANALOG_SIG_EM:
996         case ANALOG_SIG_EM_E1:
997         case ANALOG_SIG_FEATD:
998         case ANALOG_SIG_FEATDMF:
999         case ANALOG_SIG_E911:
1000         case ANALOG_SIG_FGC_CAMA:
1001         case ANALOG_SIG_FGC_CAMAMF:
1002         case ANALOG_SIG_FEATB:
1003         case ANALOG_SIG_SFWINK:
1004         case ANALOG_SIG_SF:
1005         case ANALOG_SIG_SF_FEATD:
1006         case ANALOG_SIG_SF_FEATDMF:
1007         case ANALOG_SIG_FEATDMF_TA:
1008         case ANALOG_SIG_SF_FEATB:
1009                 c = strchr(dest, '/');
1010                 if (c) {
1011                         c++;
1012                 } else {
1013                         c = "";
1014                 }
1015                 if (strlen(c) < p->stripmsd) {
1016                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1017                         return -1;
1018                 }
1019                 res = analog_start(p);
1020                 if (res < 0) {
1021                         if (errno != EINPROGRESS) {
1022                                 return -1;
1023                         }
1024                 }
1025                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1026                 p->dop.op = ANALOG_DIAL_OP_REPLACE;
1027
1028                 c += p->stripmsd;
1029
1030                 switch (mysig) {
1031                 case ANALOG_SIG_FEATD:
1032                         l = ast->connected.id.number.valid ? ast->connected.id.number.str : NULL;
1033                         if (l) {
1034                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
1035                         } else {
1036                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
1037                         }
1038                         break;
1039                 case ANALOG_SIG_FEATDMF:
1040                         l = ast->connected.id.number.valid ? ast->connected.id.number.str : NULL;
1041                         if (l) {
1042                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
1043                         } else {
1044                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
1045                         }
1046                         break;
1047                 case ANALOG_SIG_FEATDMF_TA:
1048                 {
1049                         const char *cic = "", *ozz = "";
1050
1051                         /* If you have to go through a Tandem Access point you need to use this */
1052 #ifndef STANDALONE
1053                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
1054                         if (!ozz) {
1055                                 ozz = analog_defaultozz;
1056                         }
1057                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
1058                         if (!cic) {
1059                                 cic = analog_defaultcic;
1060                         }
1061 #endif
1062                         if (!ozz || !cic) {
1063                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
1064                                 return -1;
1065                         }
1066                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
1067                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
1068                         p->whichwink = 0;
1069                 }
1070                         break;
1071                 case ANALOG_SIG_E911:
1072                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
1073                         break;
1074                 case ANALOG_SIG_FGC_CAMA:
1075                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
1076                         break;
1077                 case ANALOG_SIG_FGC_CAMAMF:
1078                 case ANALOG_SIG_FEATB:
1079                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
1080                         break;
1081                 default:
1082                         if (p->pulse) {
1083                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
1084                         } else {
1085                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
1086                         }
1087                         break;
1088                 }
1089
1090                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
1091                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1092                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1093                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1094                         p->echobreak = 1;
1095                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1096                 } else {
1097                         p->echobreak = 0;
1098                 }
1099                 analog_set_waitingfordt(p, ast);
1100                 if (!res) {
1101                         if (analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop)) {
1102                                 int saveerr = errno;
1103
1104                                 analog_on_hook(p);
1105                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
1106                                 return -1;
1107                         }
1108                 } else {
1109                         ast_debug(1, "Deferring dialing...\n");
1110                 }
1111                 analog_set_dialing(p, 1);
1112                 if (ast_strlen_zero(c)) {
1113                         p->dialednone = 1;
1114                 }
1115                 ast_setstate(ast, AST_STATE_DIALING);
1116                 break;
1117         default:
1118                 ast_debug(1, "not yet implemented\n");
1119                 return -1;
1120         }
1121         return 0;
1122 }
1123
1124 int analog_hangup(struct analog_pvt *p, struct ast_channel *ast)
1125 {
1126         int res;
1127         int index, x;
1128
1129         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
1130         if (!ast->tech_pvt) {
1131                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1132                 return 0;
1133         }
1134
1135         index = analog_get_index(ast, p, 1);
1136
1137         x = 0;
1138         if (p->origcid_num) {
1139                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
1140                 free(p->origcid_num);
1141                 p->origcid_num = NULL;
1142         }
1143         if (p->origcid_name) {
1144                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
1145                 free(p->origcid_name);
1146                 p->origcid_name = NULL;
1147         }
1148
1149         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1150
1151         ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
1152                 p->channel, index, p->subs[ANALOG_SUB_REAL].allocd, p->subs[ANALOG_SUB_CALLWAIT].allocd, p->subs[ANALOG_SUB_THREEWAY].allocd);
1153         if (index > -1) {
1154                 /* Real channel, do some fixup */
1155                 p->subs[index].owner = NULL;
1156                 p->polarity = POLARITY_IDLE;
1157                 analog_set_linear_mode(p, index, 0);
1158                 if (index == ANALOG_SUB_REAL) {
1159                         if (p->subs[ANALOG_SUB_CALLWAIT].allocd && p->subs[ANALOG_SUB_THREEWAY].allocd) {
1160                                 ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
1161                                 if (p->subs[ANALOG_SUB_CALLWAIT].inthreeway) {
1162                                         /* We had flipped over to answer a callwait and now it's gone */
1163                                         ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
1164                                         /* Move to the call-wait, but un-own us until they flip back. */
1165                                         analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_REAL);
1166                                         analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
1167                                         p->owner = NULL;
1168                                 } else {
1169                                         /* The three way hung up, but we still have a call wait */
1170                                         ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
1171                                         analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
1172                                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1173                                         if (p->subs[ANALOG_SUB_REAL].inthreeway) {
1174                                                 /* This was part of a three way call.  Immediately make way for
1175                                                    another call */
1176                                                 ast_debug(1, "Call was complete, setting owner to former third call\n");
1177                                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
1178                                         } else {
1179                                                 /* This call hasn't been completed yet...  Set owner to NULL */
1180                                                 ast_debug(1, "Call was incomplete, setting owner to NULL\n");
1181                                                 p->owner = NULL;
1182                                         }
1183                                         p->subs[ANALOG_SUB_REAL].inthreeway = 0;
1184                                 }
1185                         } else if (p->subs[ANALOG_SUB_CALLWAIT].allocd) {
1186                                 /* Move to the call-wait and switch back to them. */
1187                                 analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_REAL);
1188                                 analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
1189                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
1190                                 if (p->owner->_state != AST_STATE_UP) {
1191                                         ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_ANSWER);
1192                                 }
1193                                 if (ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner)) {
1194                                         ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_UNHOLD);
1195                                 }
1196                         } else if (p->subs[ANALOG_SUB_THREEWAY].allocd) {
1197                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
1198                                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1199                                 if (p->subs[ANALOG_SUB_REAL].inthreeway) {
1200                                         /* This was part of a three way call.  Immediately make way for
1201                                            another call */
1202                                         ast_debug(1, "Call was complete, setting owner to former third call\n");
1203                                         p->owner = p->subs[ANALOG_SUB_REAL].owner;
1204                                 } else {
1205                                         /* This call hasn't been completed yet...  Set owner to NULL */
1206                                         ast_debug(1, "Call was incomplete, setting owner to NULL\n");
1207                                         p->owner = NULL;
1208                                 }
1209                                 p->subs[ANALOG_SUB_REAL].inthreeway = 0;
1210                         }
1211                 } else if (index == ANALOG_SUB_CALLWAIT) {
1212                         /* Ditch the holding callwait call, and immediately make it availabe */
1213                         if (p->subs[ANALOG_SUB_CALLWAIT].inthreeway) {
1214                                 /* This is actually part of a three way, placed on hold.  Place the third part
1215                                    on music on hold now */
1216                                 if (p->subs[ANALOG_SUB_THREEWAY].owner && ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)) {
1217                                         ast_queue_control_data(p->subs[ANALOG_SUB_THREEWAY].owner, AST_CONTROL_HOLD,
1218                                                 S_OR(p->mohsuggest, NULL),
1219                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
1220                                 }
1221                                 p->subs[ANALOG_SUB_THREEWAY].inthreeway = 0;
1222                                 /* Make it the call wait now */
1223                                 analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_THREEWAY);
1224                                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1225                         } else {
1226                                 analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
1227                         }
1228                 } else if (index == ANALOG_SUB_THREEWAY) {
1229                         if (p->subs[ANALOG_SUB_CALLWAIT].inthreeway) {
1230                                 /* The other party of the three way call is currently in a call-wait state.
1231                                    Start music on hold for them, and take the main guy out of the third call */
1232                                 if (p->subs[ANALOG_SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[ANALOG_SUB_CALLWAIT].owner)) {
1233                                         ast_queue_control_data(p->subs[ANALOG_SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
1234                                                 S_OR(p->mohsuggest, NULL),
1235                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
1236                                 }
1237                                 p->subs[ANALOG_SUB_CALLWAIT].inthreeway = 0;
1238                         }
1239                         p->subs[ANALOG_SUB_REAL].inthreeway = 0;
1240                         /* If this was part of a three way call index, let us make
1241                            another three way call */
1242                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1243                 } else {
1244                         /* This wasn't any sort of call, but how are we an index? */
1245                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
1246                 }
1247         }
1248
1249         if (!p->subs[ANALOG_SUB_REAL].owner && !p->subs[ANALOG_SUB_CALLWAIT].owner && !p->subs[ANALOG_SUB_THREEWAY].owner) {
1250                 p->owner = NULL;
1251                 analog_set_ringtimeout(p, 0);
1252                 analog_set_confirmanswer(p, 0);
1253                 analog_set_pulsedial(p, 0);
1254                 p->outgoing = 0;
1255                 p->onhooktime = time(NULL);
1256                 p->cidrings = 1;
1257
1258                 /* Perform low level hangup if no owner left */
1259                 res = analog_on_hook(p);
1260                 if (res < 0) {
1261                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
1262                 }
1263                 switch (p->sig) {
1264                 case ANALOG_SIG_FXOGS:
1265                 case ANALOG_SIG_FXOLS:
1266                 case ANALOG_SIG_FXOKS:
1267                         /* If they're off hook, try playing congestion */
1268                         if (analog_is_off_hook(p)) {
1269                                 analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_CONGESTION);
1270                         } else {
1271                                 analog_play_tone(p, ANALOG_SUB_REAL, -1);
1272                         }
1273                         break;
1274                 case ANALOG_SIG_FXSGS:
1275                 case ANALOG_SIG_FXSLS:
1276                 case ANALOG_SIG_FXSKS:
1277                         /* Make sure we're not made available for at least two seconds assuming
1278                            we were actually used for an inbound or outbound call. */
1279                         if (ast->_state != AST_STATE_RESERVED) {
1280                                 time(&p->guardtime);
1281                                 p->guardtime += 2;
1282                         }
1283                         break;
1284                 default:
1285                         analog_play_tone(p, ANALOG_SUB_REAL, -1);
1286                 }
1287
1288                 analog_set_echocanceller(p, 0);
1289
1290                 x = 0;
1291                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
1292                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
1293                 p->callwaitcas = 0;
1294                 p->callwaiting = p->permcallwaiting;
1295                 p->hidecallerid = p->permhidecallerid;
1296                 analog_set_dialing(p, 0);
1297                 analog_update_conf(p);
1298                 analog_all_subchannels_hungup(p);
1299         }
1300
1301         analog_stop_callwait(p);
1302         ast->tech_pvt = NULL;
1303
1304         ast_verb(3, "Hanging up on '%s'\n", ast->name);
1305
1306         return 0;
1307 }
1308
1309 int analog_answer(struct analog_pvt *p, struct ast_channel *ast)
1310 {
1311         int res = 0;
1312         int index;
1313         int oldstate = ast->_state;
1314         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
1315         ast_setstate(ast, AST_STATE_UP);
1316         index = analog_get_index(ast, p, 1);
1317         if (index < 0) {
1318                 index = ANALOG_SUB_REAL;
1319         }
1320         switch (p->sig) {
1321         case ANALOG_SIG_FXSLS:
1322         case ANALOG_SIG_FXSGS:
1323         case ANALOG_SIG_FXSKS:
1324                 analog_set_ringtimeout(p, 0);
1325                 /* Fall through */
1326         case ANALOG_SIG_EM:
1327         case ANALOG_SIG_EM_E1:
1328         case ANALOG_SIG_EMWINK:
1329         case ANALOG_SIG_FEATD:
1330         case ANALOG_SIG_FEATDMF:
1331         case ANALOG_SIG_FEATDMF_TA:
1332         case ANALOG_SIG_E911:
1333         case ANALOG_SIG_FGC_CAMA:
1334         case ANALOG_SIG_FGC_CAMAMF:
1335         case ANALOG_SIG_FEATB:
1336         case ANALOG_SIG_SF:
1337         case ANALOG_SIG_SFWINK:
1338         case ANALOG_SIG_SF_FEATD:
1339         case ANALOG_SIG_SF_FEATDMF:
1340         case ANALOG_SIG_SF_FEATB:
1341         case ANALOG_SIG_FXOLS:
1342         case ANALOG_SIG_FXOGS:
1343         case ANALOG_SIG_FXOKS:
1344                 /* Pick up the line */
1345                 ast_debug(1, "Took %s off hook\n", ast->name);
1346                 if (p->hanguponpolarityswitch) {
1347                         gettimeofday(&p->polaritydelaytv, NULL);
1348                 }
1349                 res = analog_off_hook(p);
1350                 analog_play_tone(p, index, -1);
1351                 analog_set_dialing(p, 0);
1352                 if ((index == ANALOG_SUB_REAL) && p->subs[ANALOG_SUB_THREEWAY].inthreeway) {
1353                         if (oldstate == AST_STATE_RINGING) {
1354                                 ast_debug(1, "Finally swapping real and threeway\n");
1355                                 analog_play_tone(p, ANALOG_SUB_THREEWAY, -1);
1356                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
1357                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
1358                         }
1359                 }
1360                 if ((p->sig == ANALOG_SIG_FXSLS) || (p->sig == ANALOG_SIG_FXSKS) || (p->sig == ANALOG_SIG_FXSGS)) {
1361                         analog_set_echocanceller(p, 1);
1362                         analog_train_echocanceller(p);
1363                 }
1364                 break;
1365         default:
1366                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
1367                 res = -1;
1368         }
1369         ast_setstate(ast, AST_STATE_UP);
1370         return res;
1371 }
1372
1373 static int analog_handles_digit(struct ast_frame *f)
1374 {
1375         char subclass = toupper(f->subclass.integer);
1376
1377         switch (subclass) {
1378         case '1':
1379         case '2':
1380         case '3':
1381         case '4':
1382         case '5':
1383         case '6':
1384         case '7':
1385         case '9':
1386         case 'A':
1387         case 'B':
1388         case 'C':
1389         case 'D':
1390         case 'E':
1391         case 'F':
1392                 return 1;
1393         default:
1394                 return 0;
1395         }
1396 }
1397
1398 void analog_handle_dtmfup(struct analog_pvt *p, struct ast_channel *ast, enum analog_sub index, struct ast_frame **dest)
1399 {
1400         struct ast_frame *f = *dest;
1401
1402         if (analog_check_confirmanswer(p)) {
1403                 ast_debug(1, "Confirm answer on %s!\n", ast->name);
1404                 /* Upon receiving a DTMF digit, consider this an answer confirmation instead
1405                 of a DTMF digit */
1406                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
1407                 p->subs[index].f.subclass.integer = AST_CONTROL_ANSWER;
1408                 *dest = &p->subs[index].f;
1409                 /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
1410                 analog_set_confirmanswer(p, 0);
1411         }
1412         if (p->callwaitcas) {
1413                 if ((f->subclass.integer == 'A') || (f->subclass.integer == 'D')) {
1414                         ast_debug(1, "Got some DTMF, but it's for the CAS\n");
1415                         p->caller.id.name.str = p->callwait_name;
1416                         p->caller.id.number.str = p->callwait_num;
1417                         analog_send_callerid(p, 1, &p->caller);
1418                 }
1419                 if (analog_handles_digit(f))
1420                         p->callwaitcas = 0;
1421                 p->subs[index].f.frametype = AST_FRAME_NULL;
1422                 p->subs[index].f.subclass.integer = 0;
1423                 *dest = &p->subs[index].f;
1424         } else {
1425                 analog_cb_handle_dtmfup(p, ast, index, dest);
1426         }
1427 }
1428
1429 static int analog_my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
1430 {
1431         char c;
1432
1433         *str = 0; /* start with empty output buffer */
1434         for (;;) {
1435                 /* Wait for the first digit (up to specified ms). */
1436                 c = ast_waitfordigit(chan, ms);
1437                 /* if timeout, hangup or error, return as such */
1438                 if (c < 1) {
1439                         return c;
1440                 }
1441                 *str++ = c;
1442                 *str = 0;
1443                 if (strchr(term, c)) {
1444                         return 1;
1445                 }
1446         }
1447 }
1448
1449 static int analog_handle_notify_message(struct ast_channel *chan, struct analog_pvt *p, int cid_flags, int neon_mwievent)
1450 {
1451         if (p->calls->handle_notify_message) {
1452                 p->calls->handle_notify_message(chan, p->chan_pvt, cid_flags, neon_mwievent);
1453                 return 0;
1454         }
1455         return -1;
1456 }
1457
1458 static int analog_increase_ss_count(struct analog_pvt *p)
1459 {
1460         if (p->calls->increase_ss_count) {
1461                 p->calls->increase_ss_count();
1462                 return 0;
1463         }
1464         return -1;
1465 }
1466
1467 static int analog_decrease_ss_count(struct analog_pvt *p)
1468 {
1469         if (p->calls->decrease_ss_count) {
1470                 p->calls->decrease_ss_count();
1471                 return 0;
1472         }
1473         return -1;
1474 }
1475
1476 static int analog_distinctive_ring(struct ast_channel *chan, struct analog_pvt *p, int idx, int *ringdata)
1477 {
1478         if (p->calls->distinctive_ring) {
1479                 return p->calls->distinctive_ring(chan, p->chan_pvt, idx, ringdata);
1480         }
1481         return -1;
1482
1483 }
1484
1485 static void analog_get_and_handle_alarms(struct analog_pvt *p)
1486 {
1487         if (p->calls->get_and_handle_alarms) {
1488                 return p->calls->get_and_handle_alarms(p->chan_pvt);
1489         }
1490 }
1491
1492 static void *analog_get_bridged_channel(struct analog_pvt *p, struct ast_channel *chan)
1493 {
1494         if (p->calls->get_sigpvt_bridged_channel) {
1495                 return p->calls->get_sigpvt_bridged_channel;
1496         }
1497         return NULL;
1498 }
1499
1500 static int analog_get_sub_fd(struct analog_pvt *p, enum analog_sub sub)
1501 {
1502         if (p->calls->get_sub_fd) {
1503                 return p->calls->get_sub_fd(p->chan_pvt, sub);
1504         }
1505         return -1;
1506 }
1507
1508 #define ANALOG_NEED_MFDETECT(p) (((p)->sig == ANALOG_SIG_FEATDMF) || ((p)->sig == ANALOG_SIG_FEATDMF_TA) || ((p)->sig == ANALOG_SIG_E911) || ((p)->sig == ANALOG_SIG_FGC_CAMA) || ((p)->sig == ANALOG_SIG_FGC_CAMAMF) || ((p)->sig == ANALOG_SIG_FEATB))
1509
1510 static void *__analog_ss_thread(void *data)
1511 {
1512         struct analog_pvt *p = data;
1513         struct ast_channel *chan = p->ss_astchan;
1514         char exten[AST_MAX_EXTENSION] = "";
1515         char exten2[AST_MAX_EXTENSION] = "";
1516         char dtmfcid[300];
1517         char dtmfbuf[300];
1518         char namebuf[ANALOG_MAX_CID];
1519         char numbuf[ANALOG_MAX_CID];
1520         struct callerid_state *cs = NULL;
1521         char *name = NULL, *number = NULL;
1522         int flags = 0;
1523         int timeout;
1524         int getforward = 0;
1525         char *s1, *s2;
1526         int len = 0;
1527         int res;
1528         int index;
1529
1530         analog_increase_ss_count(p);
1531
1532         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
1533
1534         if (!chan) {
1535                 /* What happened to the channel? */
1536                 goto quit;
1537         }
1538         /* in the bizarre case where the channel has become a zombie before we
1539            even get started here, abort safely
1540         */
1541         if (!chan->tech_pvt) {
1542                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1543                 ast_hangup(chan);
1544                 goto quit;
1545         }
1546
1547         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1548         index = analog_get_index(chan, p, 1);
1549         if (index < 0) {
1550                 ast_log(LOG_WARNING, "Huh?\n");
1551                 ast_hangup(chan);
1552                 goto quit;
1553         }
1554         analog_dsp_reset_and_flush_digits(p);
1555         switch (p->sig) {
1556         case ANALOG_SIG_FEATD:
1557         case ANALOG_SIG_FEATDMF:
1558         case ANALOG_SIG_FEATDMF_TA:
1559         case ANALOG_SIG_E911:
1560         case ANALOG_SIG_FGC_CAMAMF:
1561         case ANALOG_SIG_FEATB:
1562         case ANALOG_SIG_EMWINK:
1563         case ANALOG_SIG_SF_FEATD:
1564         case ANALOG_SIG_SF_FEATDMF:
1565         case ANALOG_SIG_SF_FEATB:
1566         case ANALOG_SIG_SFWINK:
1567                 if (analog_wink(p, index))
1568                         goto quit;
1569                 /* Fall through */
1570         case ANALOG_SIG_EM:
1571         case ANALOG_SIG_EM_E1:
1572         case ANALOG_SIG_SF:
1573         case ANALOG_SIG_FGC_CAMA:
1574                 res = analog_play_tone(p, index, -1);
1575
1576                 analog_dsp_reset_and_flush_digits(p);
1577
1578                 if (ANALOG_NEED_MFDETECT(p)) {
1579                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_MF);
1580                 } else {
1581                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1582                 }
1583
1584                 memset(dtmfbuf, 0, sizeof(dtmfbuf));
1585                 /* Wait for the first digit only if immediate=no */
1586                 if (!p->immediate) {
1587                         /* Wait for the first digit (up to 5 seconds). */
1588                         res = ast_waitfordigit(chan, 5000);
1589                 } else {
1590                         res = 0;
1591                 }
1592                 if (res > 0) {
1593                         /* save first char */
1594                         dtmfbuf[0] = res;
1595                         switch (p->sig) {
1596                         case ANALOG_SIG_FEATD:
1597                         case ANALOG_SIG_SF_FEATD:
1598                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
1599                                 if (res > 0) {
1600                                         res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
1601                                 }
1602                                 if (res < 1) {
1603                                         analog_dsp_reset_and_flush_digits(p);
1604                                 }
1605                                 break;
1606                         case ANALOG_SIG_FEATDMF_TA:
1607                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1608                                 if (res < 1) {
1609                                         analog_dsp_reset_and_flush_digits(p);
1610                                 }
1611                                 if (analog_wink(p, index)) {
1612                                         goto quit;
1613                                 }
1614                                 dtmfbuf[0] = 0;
1615                                 /* Wait for the first digit (up to 5 seconds). */
1616                                 res = ast_waitfordigit(chan, 5000);
1617                                 if (res <= 0) {
1618                                         break;
1619                                 }
1620                                 dtmfbuf[0] = res;
1621                                 /* fall through intentionally */
1622                         case ANALOG_SIG_FEATDMF:
1623                         case ANALOG_SIG_E911:
1624                         case ANALOG_SIG_FGC_CAMAMF:
1625                         case ANALOG_SIG_SF_FEATDMF:
1626                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1627                                 /* if international caca, do it again to get real ANO */
1628                                 if ((p->sig == ANALOG_SIG_FEATDMF) && (dtmfbuf[1] != '0') 
1629                                         && (strlen(dtmfbuf) != 14)) {
1630                                         if (analog_wink(p, index)) {
1631                                                 goto quit;
1632                                         }
1633                                         dtmfbuf[0] = 0;
1634                                         /* Wait for the first digit (up to 5 seconds). */
1635                                         res = ast_waitfordigit(chan, 5000);
1636                                         if (res <= 0) {
1637                                                 break;
1638                                         }
1639                                         dtmfbuf[0] = res;
1640                                         res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1641                                 }
1642                                 if (res > 0) {
1643                                         /* if E911, take off hook */
1644                                         if (p->sig == ANALOG_SIG_E911) {
1645                                                 analog_off_hook(p);
1646                                         }
1647                                         res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
1648                                 }
1649                                 if (res < 1) {
1650                                         analog_dsp_reset_and_flush_digits(p);
1651                                 }
1652                                 break;
1653                         case ANALOG_SIG_FEATB:
1654                         case ANALOG_SIG_SF_FEATB:
1655                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1656                                 if (res < 1) {
1657                                         analog_dsp_reset_and_flush_digits(p);
1658                                 }
1659                                 break;
1660                         case ANALOG_SIG_EMWINK:
1661                                 /* if we received a '*', we are actually receiving Feature Group D
1662                                    dial syntax, so use that mode; otherwise, fall through to normal
1663                                    mode
1664                                 */
1665                                 if (res == '*') {
1666                                         res = analog_my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
1667                                         if (res > 0) {
1668                                                 res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
1669                                         }
1670                                         if (res < 1) {
1671                                                 analog_dsp_reset_and_flush_digits(p);
1672                                         }
1673                                         break;
1674                                 }
1675                         default:
1676                                 /* If we got the first digit, get the rest */
1677                                 len = 1;
1678                                 dtmfbuf[len] = '\0';
1679                                 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
1680                                         if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
1681                                                 timeout = analog_matchdigittimeout;
1682                                         } else {
1683                                                 timeout = analog_gendigittimeout;
1684                                         }
1685                                         res = ast_waitfordigit(chan, timeout);
1686                                         if (res < 0) {
1687                                                 ast_debug(1, "waitfordigit returned < 0...\n");
1688                                                 ast_hangup(chan);
1689                                                 goto quit;
1690                                         } else if (res) {
1691                                                 dtmfbuf[len++] = res;
1692                                                 dtmfbuf[len] = '\0';
1693                                         } else {
1694                                                 break;
1695                                         }
1696                                 }
1697                                 break;
1698                         }
1699                 }
1700                 if (res == -1) {
1701                         ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
1702                         ast_hangup(chan);
1703                         goto quit;
1704                 } else if (res < 0) {
1705                         ast_debug(1, "Got hung up before digits finished\n");
1706                         ast_hangup(chan);
1707                         goto quit;
1708                 }
1709
1710                 if (p->sig == ANALOG_SIG_FGC_CAMA) {
1711                         char anibuf[100];
1712
1713                         if (ast_safe_sleep(chan,1000) == -1) {
1714                                 ast_hangup(chan);
1715                                 goto quit;
1716                         }
1717                         analog_off_hook(p);
1718                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_MF);
1719                         res = analog_my_getsigstr(chan, anibuf, "#", 10000);
1720                         if ((res > 0) && (strlen(anibuf) > 2)) {
1721                                 if (anibuf[strlen(anibuf) - 1] == '#') {
1722                                         anibuf[strlen(anibuf) - 1] = 0;
1723                                 }
1724                                 ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
1725                         }
1726                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1727                 }
1728
1729                 ast_copy_string(exten, dtmfbuf, sizeof(exten));
1730                 if (ast_strlen_zero(exten)) {
1731                         ast_copy_string(exten, "s", sizeof(exten));
1732                 }
1733                 if (p->sig == ANALOG_SIG_FEATD || p->sig == ANALOG_SIG_EMWINK) {
1734                         /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
1735                         if (exten[0] == '*') {
1736                                 char *stringp=NULL;
1737                                 ast_copy_string(exten2, exten, sizeof(exten2));
1738                                 /* Parse out extension and callerid */
1739                                 stringp=exten2 +1;
1740                                 s1 = strsep(&stringp, "*");
1741                                 s2 = strsep(&stringp, "*");
1742                                 if (s2) {
1743                                         if (!ast_strlen_zero(p->cid_num)) {
1744                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
1745                                         } else {
1746                                                 ast_set_callerid(chan, s1, NULL, s1);
1747                                         }
1748                                         ast_copy_string(exten, s2, sizeof(exten));
1749                                 } else {
1750                                         ast_copy_string(exten, s1, sizeof(exten));
1751                                 }
1752                         } else if (p->sig == ANALOG_SIG_FEATD) {
1753                                 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1754                         }
1755                 }
1756                 if ((p->sig == ANALOG_SIG_FEATDMF) || (p->sig == ANALOG_SIG_FEATDMF_TA)) {
1757                         if (exten[0] == '*') {
1758                                 char *stringp=NULL;
1759                                 ast_copy_string(exten2, exten, sizeof(exten2));
1760                                 /* Parse out extension and callerid */
1761                                 stringp=exten2 +1;
1762                                 s1 = strsep(&stringp, "#");
1763                                 s2 = strsep(&stringp, "#");
1764                                 if (s2) {
1765                                         if (!ast_strlen_zero(p->cid_num)) {
1766                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
1767                                         } else {
1768                                                 if (*(s1 + 2)) {
1769                                                         ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
1770                                                 }
1771                                         }
1772                                         ast_copy_string(exten, s2 + 1, sizeof(exten));
1773                                 } else {
1774                                         ast_copy_string(exten, s1 + 2, sizeof(exten));
1775                                 }
1776                         } else {
1777                                 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1778                         }
1779                 }
1780                 if ((p->sig == ANALOG_SIG_E911) || (p->sig == ANALOG_SIG_FGC_CAMAMF)) {
1781                         if (exten[0] == '*') {
1782                                 char *stringp=NULL;
1783                                 ast_copy_string(exten2, exten, sizeof(exten2));
1784                                 /* Parse out extension and callerid */
1785                                 stringp=exten2 +1;
1786                                 s1 = strsep(&stringp, "#");
1787                                 s2 = strsep(&stringp, "#");
1788                                 if (s2 && (*(s2 + 1) == '0')) {
1789                                         if (*(s2 + 2)) {
1790                                                 ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
1791                                         }
1792                                 }
1793                                 if (s1) {
1794                                         ast_copy_string(exten, s1, sizeof(exten));
1795                                 } else {
1796                                         ast_copy_string(exten, "911", sizeof(exten));
1797                                 }
1798                         } else {
1799                                 ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1800                         }
1801                 }
1802                 if (p->sig == ANALOG_SIG_FEATB) {
1803                         if (exten[0] == '*') {
1804                                 char *stringp=NULL;
1805                                 ast_copy_string(exten2, exten, sizeof(exten2));
1806                                 /* Parse out extension and callerid */
1807                                 stringp=exten2 +1;
1808                                 s1 = strsep(&stringp, "#");
1809                                 ast_copy_string(exten, exten2 + 1, sizeof(exten));
1810                         } else {
1811                                 ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1812                         }
1813                 }
1814                 if ((p->sig == ANALOG_SIG_FEATDMF) || (p->sig == ANALOG_SIG_FEATDMF_TA)) {
1815                         analog_wink(p, index);
1816                         /* some switches require a minimum guard time between
1817                         the last FGD wink and something that answers
1818                         immediately. This ensures it */
1819                         if (ast_safe_sleep(chan,100)) {
1820                                 goto quit;
1821                         }
1822                 }
1823                 analog_set_echocanceller(p, 1);
1824
1825                 analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1826
1827                 if (ast_exists_extension(chan, chan->context, exten, 1,
1828                         chan->caller.id.number.valid ? chan->caller.id.number.str : NULL)) {
1829                         ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1830                         analog_dsp_reset_and_flush_digits(p);
1831                         res = ast_pbx_run(chan);
1832                         if (res) {
1833                                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
1834                                 res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1835                         }
1836                         goto quit;
1837                 } else {
1838                         ast_verb(3, "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
1839                         sleep(2);
1840                         res = analog_play_tone(p, index, ANALOG_TONE_INFO);
1841                         if (res < 0) {
1842                                 ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
1843                         } else {
1844                                 sleep(1);
1845                         }
1846                         res = ast_streamfile(chan, "ss-noservice", chan->language);
1847                         if (res >= 0) {
1848                                 ast_waitstream(chan, "");
1849                         }
1850                         res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1851                         ast_hangup(chan);
1852                         goto quit;
1853                 }
1854                 break;
1855         case ANALOG_SIG_FXOLS:
1856         case ANALOG_SIG_FXOGS:
1857         case ANALOG_SIG_FXOKS:
1858                 /* Read the first digit */
1859                 timeout = analog_firstdigittimeout;
1860                 /* If starting a threeway call, never timeout on the first digit so someone
1861                    can use flash-hook as a "hold" feature */
1862                 if (p->subs[ANALOG_SUB_THREEWAY].owner) {
1863                         timeout = 999999;
1864                 }
1865                 while (len < AST_MAX_EXTENSION-1) {
1866                         /* Read digit unless it's supposed to be immediate, in which case the
1867                            only answer is 's' */
1868                         if (p->immediate) {
1869                                 res = 's';
1870                         } else {
1871                                 res = ast_waitfordigit(chan, timeout);
1872                         }
1873                         timeout = 0;
1874                         if (res < 0) {
1875                                 ast_debug(1, "waitfordigit returned < 0...\n");
1876                                 res = analog_play_tone(p, index, -1);
1877                                 ast_hangup(chan);
1878                                 goto quit;
1879                         } else if (res) {
1880                                 exten[len++]=res;
1881                                 exten[len] = '\0';
1882                         }
1883                         if (!ast_ignore_pattern(chan->context, exten)) {
1884                                 analog_play_tone(p, index, -1);
1885                         } else {
1886                                 analog_play_tone(p, index, ANALOG_TONE_DIALTONE);
1887                         }
1888                         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && strcmp(exten, ast_parking_ext())) {
1889                                 if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1890                                         if (getforward) {
1891                                                 /* Record this as the forwarding extension */
1892                                                 ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
1893                                                 ast_verb(3, "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
1894                                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1895                                                 if (res) {
1896                                                         break;
1897                                                 }
1898                                                 usleep(500000);
1899                                                 res = analog_play_tone(p, index, -1);
1900                                                 sleep(1);
1901                                                 memset(exten, 0, sizeof(exten));
1902                                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALTONE);
1903                                                 len = 0;
1904                                                 getforward = 0;
1905                                         } else {
1906                                                 res = analog_play_tone(p, index, -1);
1907                                                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1908                                                 if (!ast_strlen_zero(p->cid_num)) {
1909                                                         if (!p->hidecallerid) {
1910                                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
1911                                                         } else {
1912                                                                 ast_set_callerid(chan, NULL, NULL, p->cid_num);
1913                                                         }
1914                                                 }
1915                                                 if (!ast_strlen_zero(p->cid_name)) {
1916                                                         if (!p->hidecallerid) {
1917                                                                 ast_set_callerid(chan, NULL, p->cid_name, NULL);
1918                                                         }
1919                                                 }
1920                                                 ast_setstate(chan, AST_STATE_RING);
1921                                                 analog_set_echocanceller(p, 1);
1922                                                 res = ast_pbx_run(chan);
1923                                                 if (res) {
1924                                                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
1925                                                         res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1926                                                 }
1927                                                 goto quit;
1928                                         }
1929                                 } else {
1930                                         /* It's a match, but they just typed a digit, and there is an ambiguous match,
1931                                            so just set the timeout to analog_matchdigittimeout and wait some more */
1932                                         timeout = analog_matchdigittimeout;
1933                                 }
1934                         } else if (res == 0) {
1935                                 ast_debug(1, "not enough digits (and no ambiguous match)...\n");
1936                                 res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1937                                 analog_wait_event(p);
1938                                 ast_hangup(chan);
1939                                 goto quit;
1940                         } else if (p->callwaiting && !strcmp(exten, "*70")) {
1941                                 ast_verb(3, "Disabling call waiting on %s\n", chan->name);
1942                                 /* Disable call waiting if enabled */
1943                                 p->callwaiting = 0;
1944                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1945                                 if (res) {
1946                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
1947                                                 chan->name, strerror(errno));
1948                                 }
1949                                 len = 0;
1950                                 memset(exten, 0, sizeof(exten));
1951                                 timeout = analog_firstdigittimeout;
1952
1953                         } else if (!strcmp(exten,ast_pickup_ext())) {
1954                                 /* Scan all channels and see if there are any
1955                                  * ringing channels that have call groups
1956                                  * that equal this channels pickup group
1957                                  */
1958                                 if (index == ANALOG_SUB_REAL) {
1959                                         /* Switch us from Third call to Call Wait */
1960                                         if (p->subs[ANALOG_SUB_THREEWAY].owner) {
1961                                                 /* If you make a threeway call and the *8# a call, it should actually
1962                                                    look like a callwait */
1963                                                 analog_alloc_sub(p, ANALOG_SUB_CALLWAIT);
1964                                                 analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_THREEWAY);
1965                                                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1966                                         }
1967                                         analog_set_echocanceller(p, 1);
1968                                         if (ast_pickup_call(chan)) {
1969                                                 ast_debug(1, "No call pickup possible...\n");
1970                                                 res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1971                                                 analog_wait_event(p);
1972                                         }
1973                                         ast_hangup(chan);
1974                                         goto quit;
1975                                 } else {
1976                                         ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
1977                                         ast_hangup(chan);
1978                                         goto quit;
1979                                 }
1980                         } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
1981                                 ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
1982                                 /* Disable Caller*ID if enabled */
1983                                 p->hidecallerid = 1;
1984                                 ast_party_number_free(&chan->caller.id.number);
1985                                 ast_party_number_init(&chan->caller.id.number);
1986                                 ast_party_name_free(&chan->caller.id.name);
1987                                 ast_party_name_init(&chan->caller.id.name);
1988                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1989                                 if (res) {
1990                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
1991                                                 chan->name, strerror(errno));
1992                                 }
1993                                 len = 0;
1994                                 memset(exten, 0, sizeof(exten));
1995                                 timeout = analog_firstdigittimeout;
1996                         } else if (p->callreturn && !strcmp(exten, "*69")) {
1997                                 res = 0;
1998                                 if (!ast_strlen_zero(p->lastcid_num)) {
1999                                         res = ast_say_digit_str(chan, p->lastcid_num, "", chan->language);
2000                                 }
2001                                 if (!res) {
2002                                         res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
2003                                 }
2004                                 break;
2005                         } else if (!strcmp(exten, "*78")) {
2006                                 /* Do not disturb */
2007                                 ast_verb(3, "Enabled DND on channel %d\n", p->channel);
2008                                 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
2009                                               "Channel: DAHDI/%d\r\n"
2010                                               "Status: enabled\r\n", p->channel);
2011                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
2012                                 p->dnd = 1;
2013                                 getforward = 0;
2014                                 memset(exten, 0, sizeof(exten));
2015                                 len = 0;
2016                         } else if (!strcmp(exten, "*79")) {
2017                                 /* Do not disturb */
2018                                 ast_verb(3, "Disabled DND on channel %d\n", p->channel);
2019                                 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
2020                                               "Channel: DAHDI/%d\r\n"
2021                                               "Status: disabled\r\n", p->channel);
2022                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
2023                                 p->dnd = 0;
2024                                 getforward = 0;
2025                                 memset(exten, 0, sizeof(exten));
2026                                 len = 0;
2027                         } else if (p->cancallforward && !strcmp(exten, "*72")) {
2028                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
2029                                 getforward = 1;
2030                                 memset(exten, 0, sizeof(exten));
2031                                 len = 0;
2032                         } else if (p->cancallforward && !strcmp(exten, "*73")) {
2033                                 ast_verb(3, "Cancelling call forwarding on channel %d\n", p->channel);
2034                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
2035                                 memset(p->call_forward, 0, sizeof(p->call_forward));
2036                                 getforward = 0;
2037                                 memset(exten, 0, sizeof(exten));
2038                                 len = 0;
2039                         } else if ((p->transfer || p->canpark) && !strcmp(exten, ast_parking_ext()) &&
2040                                                 p->subs[ANALOG_SUB_THREEWAY].owner &&
2041                                                 ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)) {
2042                                 /* This is a three way call, the main call being a real channel,
2043                                         and we're parking the first call. */
2044                                 ast_masq_park_call(ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner), chan, 0, NULL);
2045                                 ast_verb(3, "Parking call to '%s'\n", chan->name);
2046                                 break;
2047                         } else if (!ast_strlen_zero(p->lastcid_num) && !strcmp(exten, "*60")) {
2048                                 ast_verb(3, "Blacklisting number %s\n", p->lastcid_num);
2049                                 res = ast_db_put("blacklist", p->lastcid_num, "1");
2050                                 if (!res) {
2051                                         res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
2052                                         memset(exten, 0, sizeof(exten));
2053                                         len = 0;
2054                                 }
2055                         } else if (p->hidecallerid && !strcmp(exten, "*82")) {
2056                                 ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
2057                                 /* Enable Caller*ID if enabled */
2058                                 p->hidecallerid = 0;
2059                                 ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
2060                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
2061                                 if (res) {
2062                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
2063                                                 chan->name, strerror(errno));
2064                                 }
2065                                 len = 0;
2066                                 memset(exten, 0, sizeof(exten));
2067                                 timeout = analog_firstdigittimeout;
2068                         } else if (!strcmp(exten, "*0")) {
2069                                 struct ast_channel *nbridge = p->subs[ANALOG_SUB_THREEWAY].owner;
2070                                 struct analog_pvt *pbridge = NULL;
2071                                   /* set up the private struct of the bridged one, if any */
2072                                 if (nbridge && ast_bridged_channel(nbridge)) {
2073                                         pbridge = analog_get_bridged_channel(p, nbridge);
2074                                 }
2075                                 if (nbridge && pbridge &&
2076                                     (nbridge->tech == p->chan_tech) &&
2077                                     (ast_bridged_channel(nbridge)->tech == p->chan_tech) &&
2078                                     ISTRUNK(pbridge)) {
2079                                         /* Clear out the dial buffer */
2080                                         p->dop.dialstr[0] = '\0';
2081                                         /* flash hookswitch */
2082                                         if ((analog_flash(p) == -1) && (errno != EINPROGRESS)) {
2083                                                 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
2084                                                         nbridge->name, strerror(errno));
2085                                         }
2086                                         analog_swap_subs(p, ANALOG_SUB_REAL, ANALOG_SUB_THREEWAY);
2087                                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
2088                                         p->owner = p->subs[ANALOG_SUB_REAL].owner;
2089                                         if (ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner)) {
2090                                                 ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_UNHOLD);
2091                                         }
2092                                         ast_hangup(chan);
2093                                         goto quit;
2094                                 } else {
2095                                         analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
2096                                         analog_wait_event(p);
2097                                         analog_play_tone(p, index, -1);
2098                                         analog_swap_subs(p, ANALOG_SUB_REAL, ANALOG_SUB_THREEWAY);
2099                                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
2100                                         p->owner = p->subs[ANALOG_SUB_REAL].owner;
2101                                         ast_hangup(chan);
2102                                         goto quit;
2103                                 }
2104                         } else if (!ast_canmatch_extension(chan, chan->context, exten, 1,
2105                                 chan->caller.id.number.valid ? chan->caller.id.number.str : NULL)
2106                                 && ((exten[0] != '*') || (strlen(exten) > 2))) {
2107                                 ast_debug(1, "Can't match %s from '%s' in context %s\n", exten,
2108                                         chan->caller.id.number.valid && chan->caller.id.number.str
2109                                                 ? chan->caller.id.number.str : "<Unknown Caller>",
2110                                         chan->context);
2111                                 break;
2112                         }
2113                         if (!timeout) {
2114                                 timeout = analog_gendigittimeout;
2115                         }
2116                         if (len && !ast_ignore_pattern(chan->context, exten)) {
2117                                 analog_play_tone(p, index, -1);
2118                         }
2119                 }
2120                 break;
2121         case ANALOG_SIG_FXSLS:
2122         case ANALOG_SIG_FXSGS:
2123         case ANALOG_SIG_FXSKS:
2124
2125                 /* If we want caller id, we're in a prering state due to a polarity reversal
2126                  * and we're set to use a polarity reversal to trigger the start of caller id,
2127                  * grab the caller id and wait for ringing to start... */
2128                 if (p->use_callerid && (chan->_state == AST_STATE_PRERING &&
2129                                   (p->cid_start == ANALOG_CID_START_POLARITY || p->cid_start == ANALOG_CID_START_POLARITY_IN || p->cid_start == ANALOG_CID_START_DTMF_NOALERT))) {
2130                         /* If set to use DTMF CID signalling, listen for DTMF */
2131                         if (p->cid_signalling == CID_SIG_DTMF) {
2132                                 int i = 0;
2133                                 int oldlinearity; 
2134                                 cs = NULL;
2135                                 ast_debug(1, "Receiving DTMF cid on channel %s\n", chan->name);
2136
2137                                 oldlinearity = analog_set_linear_mode(p, index, 0);
2138
2139                                 /*
2140                                  * We are the only party interested in the Rx stream since
2141                                  * we have not answered yet.  We don't need or even want DTMF
2142                                  * emulation.  The DTMF digits can come so fast that emulation
2143                                  * can drop some of them.
2144                                  */
2145                                 ast_set_flag(chan, AST_FLAG_END_DTMF_ONLY);
2146                                 res = 4000;/* This is a typical OFF time between rings. */
2147                                 for (;;) {
2148                                         struct ast_frame *f;
2149                                         res = ast_waitfor(chan, res);
2150                                         if (res <= 0) {
2151                                                 /*
2152                                                  * We do not need to restore the analog_set_linear_mode()
2153                                                  * or AST_FLAG_END_DTMF_ONLY flag settings since we
2154                                                  * are hanging up the channel.
2155                                                  */
2156                                                 ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
2157                                                         "Exiting simple switch\n");
2158                                                 ast_hangup(chan);
2159                                                 goto quit;
2160                                         }
2161                                         if (!(f = ast_read(chan))) {
2162                                                 break;
2163                                         }
2164                                         if (f->frametype == AST_FRAME_DTMF) {
2165                                                 if (i < ARRAY_LEN(dtmfbuf) - 1) {
2166                                                         dtmfbuf[i++] = f->subclass.integer;
2167                                                 }
2168                                                 ast_debug(1, "CID got digit '%c'\n", f->subclass.integer);
2169                                                 res = 4000;/* This is a typical OFF time between rings. */
2170                                         }
2171                                         ast_frfree(f);
2172                                         if (chan->_state == AST_STATE_RING || chan->_state == AST_STATE_RINGING) {
2173                                                 break; /* Got ring */
2174                                         }
2175                                 }
2176                                 ast_clear_flag(chan, AST_FLAG_END_DTMF_ONLY);
2177                                 dtmfbuf[i] = '\0';
2178
2179                                 analog_set_linear_mode(p, index, oldlinearity);
2180
2181                                 /* Got cid and ring. */
2182                                 ast_debug(1, "CID got string '%s'\n", dtmfbuf);
2183                                 callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
2184                                 ast_debug(1, "CID is '%s', flags %d\n", dtmfcid, flags);
2185                                 /* If first byte is NULL, we have no cid */
2186                                 if (!ast_strlen_zero(dtmfcid)) {
2187                                         number = dtmfcid;
2188                                 } else {
2189                                         number = NULL;
2190                                 }
2191
2192                         /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
2193                         } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
2194                                 int timeout = 10000;  /* Ten seconds */
2195                                 struct timeval start = ast_tvnow();
2196                                 enum analog_event ev;
2197
2198                                 namebuf[0] = 0;
2199                                 numbuf[0] = 0;
2200
2201                                 if (!analog_start_cid_detect(p, p->cid_signalling)) {
2202                                         while (1) {
2203                                                 res = analog_get_callerid(p, namebuf, numbuf, &ev, timeout - ast_tvdiff_ms(ast_tvnow(), start));
2204
2205                                                 if (res == 0) {
2206                                                         break;
2207                                                 }
2208
2209                                                 if (res == 1) {
2210                                                         if (ev == ANALOG_EVENT_NOALARM) {
2211                                                                 analog_set_alarm(p, 0);
2212                                                         }
2213                                                         if (p->cid_signalling == CID_SIG_V23_JP) {
2214                                                                 if (ev == ANALOG_EVENT_RINGBEGIN) {
2215                                                                         analog_off_hook(p);
2216                                                                         usleep(1);
2217                                                                 }
2218                                                         } else {
2219                                                                 ev = ANALOG_EVENT_NONE;
2220                                                                 break;
2221                                                         }
2222                                                 }
2223
2224                                                 if (ast_tvdiff_ms(ast_tvnow(), start) > timeout)
2225                                                         break;
2226
2227                                         }
2228                                         name = namebuf;
2229                                         number = numbuf;
2230
2231                                         analog_stop_cid_detect(p);
2232
2233                                         if (p->cid_signalling == CID_SIG_V23_JP) {
2234                                                 res = analog_on_hook(p);
2235                                                 usleep(1);
2236                                         }
2237
2238                                         /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
2239                                         res = 4000;/* This is a typical OFF time between rings. */
2240                                         for (;;) {
2241                                                 struct ast_frame *f;
2242                                                 res = ast_waitfor(chan, res);
2243                                                 if (res <= 0) {
2244                                                         ast_log(LOG_WARNING, "CID timed out waiting for ring. "
2245                                                                 "Exiting simple switch\n");
2246                                                         ast_hangup(chan);
2247                                                         goto quit;
2248                                                 }
2249                                                 if (!(f = ast_read(chan))) {
2250                                                         ast_log(LOG_WARNING, "Hangup received waiting for ring. Exiting simple switch\n");
2251                                                         ast_hangup(chan);
2252                                                         goto quit;
2253                                                 }
2254                                                 ast_frfree(f);
2255                                                 if (chan->_state == AST_STATE_RING ||
2256                                                         chan->_state == AST_STATE_RINGING)
2257                                                         break; /* Got ring */
2258                                         }
2259
2260                                         if (analog_distinctive_ring(chan, p, index, NULL)) {
2261                                                 goto quit;
2262                                         }
2263
2264                                         if (res < 0) {
2265                                                 ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
2266                                         }
2267                                 } else {
2268                                         ast_log(LOG_WARNING, "Unable to get caller ID space\n");
2269                                 }
2270
2271                         } else {
2272                                 ast_log(LOG_WARNING, "Channel %s in prering "
2273                                         "state, but I have nothing to do. "
2274                                         "Terminating simple switch, should be "
2275                                         "restarted by the actual ring.\n",
2276                                         chan->name);
2277                                 ast_hangup(chan);
2278                                 goto quit;
2279                         }
2280                 } else if (p->use_callerid && p->cid_start == ANALOG_CID_START_RING) {
2281                         int timeout = 10000;  /* Ten seconds */
2282                         struct timeval start = ast_tvnow();
2283                         enum analog_event ev;
2284                         int curRingData[RING_PATTERNS] = { 0 };
2285                         int receivedRingT = 0;
2286
2287                         namebuf[0] = 0;
2288                         numbuf[0] = 0;
2289
2290                         if (!analog_start_cid_detect(p, p->cid_signalling)) {
2291                                 while (1) {
2292                                         res = analog_get_callerid(p, namebuf, numbuf, &ev, timeout - ast_tvdiff_ms(ast_tvnow(), start));
2293
2294                                         if (res == 0) {
2295                                                 break;
2296                                         }
2297
2298                                         if (res == 1 || res == 2) {
2299                                                 if (ev == ANALOG_EVENT_NOALARM) {
2300                                                         analog_set_alarm(p, 0);
2301                                                 } else if (ev == ANALOG_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
2302                                                         ast_debug(1, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
2303                                                         p->polarity = POLARITY_IDLE;
2304                                                         ast_hangup(chan);
2305                                                         goto quit;
2306                                                 } else if (ev != ANALOG_EVENT_NONE && ev != ANALOG_EVENT_RINGBEGIN && ev != ANALOG_EVENT_RINGOFFHOOK) {
2307                                                         break;
2308                                                 }
2309                                                 if (res != 2) {
2310                                                         /* Let us detect callerid when the telco uses distinctive ring */
2311                                                         curRingData[receivedRingT] = p->ringt;
2312
2313                                                         if (p->ringt < p->ringt_base/2) {
2314                                                                 break;
2315                                                         }
2316                                                         /* Increment the ringT counter so we can match it against
2317                                                            values in chan_dahdi.conf for distinctive ring */
2318                                                         if (++receivedRingT == RING_PATTERNS) {
2319                                                                 break;
2320                                                         }
2321                                                 }
2322                                         }
2323
2324                                         if (ast_tvdiff_ms(ast_tvnow(), start) > timeout) {
2325                                                 break;
2326                                         }
2327
2328                                 }
2329                                 name = namebuf;
2330                                 number = numbuf;
2331
2332                                 analog_stop_cid_detect(p);
2333
2334                                 if (analog_distinctive_ring(chan, p, index, curRingData)) {
2335                                         goto quit;
2336                                 }
2337
2338                                 if (res < 0) {
2339                                         ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
2340                                 }
2341                         } else {
2342                                 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
2343                         }
2344                 } else {
2345                         cs = NULL;
2346                 }
2347
2348                 if (number) {
2349                         ast_shrink_phone_number(number);
2350                 }
2351                 ast_set_callerid(chan, number, name, number);
2352
2353                 if (cs) {
2354                         callerid_free(cs);
2355                 }
2356
2357                 analog_handle_notify_message(chan, p, flags, -1);
2358
2359                 ast_setstate(chan, AST_STATE_RING);
2360                 chan->rings = 1;
2361                 analog_set_ringtimeout(p, p->ringt_base);
2362                 res = ast_pbx_run(chan);
2363                 if (res) {
2364                         ast_hangup(chan);
2365                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
2366                 }
2367                 goto quit;
2368         default:
2369                 ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", analog_sigtype_to_str(p->sig), p->channel);
2370                 break;
2371         }
2372         res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
2373         if (res < 0) {
2374                 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
2375         }
2376         ast_hangup(chan);
2377 quit:
2378         analog_decrease_ss_count(p);
2379         return NULL;
2380 }
2381
2382 int analog_ss_thread_start(struct analog_pvt *p, struct ast_channel *chan)
2383 {
2384         pthread_t threadid;
2385
2386         return ast_pthread_create_detached(&threadid, NULL, __analog_ss_thread, p);
2387 }
2388
2389 static struct ast_frame *__analog_handle_event(struct analog_pvt *p, struct ast_channel *ast)
2390 {
2391         int res, x;
2392         int mysig;
2393         enum analog_sub index;
2394         char *c;
2395         pthread_t threadid;
2396         pthread_attr_t attr;
2397         struct ast_channel *chan;
2398         struct ast_frame *f;
2399         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
2400
2401         index = analog_get_index(ast, p, 0);
2402         mysig = p->sig;
2403         if (p->outsigmod > -1) {
2404                 mysig = p->outsigmod;
2405         }
2406         p->subs[index].f.frametype = AST_FRAME_NULL;
2407         p->subs[index].f.subclass.integer = 0;
2408         p->subs[index].f.datalen = 0;
2409         p->subs[index].f.samples = 0;
2410         p->subs[index].f.mallocd = 0;
2411         p->subs[index].f.offset = 0;
2412         p->subs[index].f.src = "dahdi_handle_event";
2413         p->subs[index].f.data.ptr = NULL;
2414         f = &p->subs[index].f;
2415
2416         if (index < 0) {
2417                 return &p->subs[index].f;
2418         }
2419
2420         if (index != ANALOG_SUB_REAL) {
2421                 ast_log(LOG_ERROR, "We got an event on a non real sub.  Fix it!\n");
2422         }
2423
2424         res = analog_get_event(p);
2425
2426         ast_debug(1, "Got event %s(%d) on channel %d (index %d)\n", analog_event2str(res), res, p->channel, index);
2427
2428         if (res & (ANALOG_EVENT_PULSEDIGIT | ANALOG_EVENT_DTMFUP)) {
2429                 analog_set_pulsedial(p, (res & ANALOG_EVENT_PULSEDIGIT));
2430                 ast_debug(1, "Detected %sdigit '%c'\n", (res & ANALOG_EVENT_PULSEDIGIT) ? "pulse ": "", res & 0xff);
2431                 analog_confmute(p, 0);
2432                 p->subs[index].f.frametype = AST_FRAME_DTMF_END;
2433                 p->subs[index].f.subclass.integer = res & 0xff;
2434                 analog_handle_dtmfup(p, ast, index, &f);
2435                 return f;
2436         }
2437
2438         if (res & ANALOG_EVENT_DTMFDOWN) {
2439                 ast_debug(1, "DTMF Down '%c'\n", res & 0xff);
2440                 /* Mute conference */
2441                 analog_confmute(p, 1);
2442                 p->subs[index].f.frametype = AST_FRAME_DTMF_BEGIN;
2443                 p->subs[index].f.subclass.integer = res & 0xff;
2444                 return f;
2445         }
2446
2447         switch (res) {
2448         case ANALOG_EVENT_EC_DISABLED:
2449                 ast_verb(3, "Channel %d echo canceler disabled due to CED detection\n", p->channel);
2450                 analog_set_echocanceller(p, 0);
2451                 break;
2452 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
2453         case ANALOG_EVENT_TX_CED_DETECTED:
2454                 ast_verb(3, "Channel %d detected a CED tone towards the network.\n", p->channel);
2455                 break;
2456         case ANALOG_EVENT_RX_CED_DETECTED:
2457                 ast_verb(3, "Channel %d detected a CED tone from the network.\n", p->channel);
2458                 break;
2459         case ANALOG_EVENT_EC_NLP_DISABLED:
2460                 ast_verb(3, "Channel %d echo canceler disabled its NLP.\n", p->channel);
2461                 break;
2462         case ANALOG_EVENT_EC_NLP_ENABLED:
2463                 ast_verb(3, "Channel %d echo canceler enabled its NLP.\n", p->channel);
2464                 break;
2465 #endif
2466         case ANALOG_EVENT_PULSE_START:
2467                 /* Stop tone if there's a pulse start and the PBX isn't started */
2468                 if (!ast->pbx)
2469                         analog_play_tone(p, ANALOG_SUB_REAL, -1);
2470                 break;
2471         case ANALOG_EVENT_DIALCOMPLETE:
2472                 if (p->inalarm) {
2473                         break;
2474                 }
2475                 x = analog_is_dialing(p, index);
2476                 if (!x) { /* if not still dialing in driver */
2477                         analog_set_echocanceller(p, 1);
2478                         if (p->echobreak) {
2479                                 analog_train_echocanceller(p);
2480                                 ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
2481                                 p->dop.op = ANALOG_DIAL_OP_REPLACE;
2482                                 analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop);
2483                                 p->echobreak = 0;
2484                         } else {
2485                                 analog_set_dialing(p, 0);
2486                                 if ((mysig == ANALOG_SIG_E911) || (mysig == ANALOG_SIG_FGC_CAMA) || (mysig == ANALOG_SIG_FGC_CAMAMF)) {
2487                                         /* if thru with dialing after offhook */
2488                                         if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
2489                                                 ast_setstate(ast, AST_STATE_UP);
2490                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2491                                                 p->subs[index].f.subclass.integer = AST_CONTROL_ANSWER;
2492                                                 break;
2493                                         } else { /* if to state wait for offhook to dial rest */
2494                                                 /* we now wait for off hook */
2495                                                 ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
2496                                         }
2497                                 }
2498                                 if (ast->_state == AST_STATE_DIALING) {
2499                                         if (analog_check_confirmanswer(p) || (!p->dialednone && ((mysig == ANALOG_SIG_EM) || (mysig == ANALOG_SIG_EM_E1) ||  (mysig == ANALOG_SIG_EMWINK) || (mysig == ANALOG_SIG_FEATD) || (mysig == ANALOG_SIG_FEATDMF_TA) || (mysig == ANALOG_SIG_FEATDMF) || (mysig == ANALOG_SIG_E911) || (mysig == ANALOG_SIG_FGC_CAMA) || (mysig == ANALOG_SIG_FGC_CAMAMF) || (mysig == ANALOG_SIG_FEATB) || (mysig == ANALOG_SIG_SF) || (mysig == ANALOG_SIG_SFWINK) || (mysig == ANALOG_SIG_SF_FEATD) || (mysig == ANALOG_SIG_SF_FEATDMF) || (mysig == ANALOG_SIG_SF_FEATB)))) {
2500                                                 ast_setstate(ast, AST_STATE_RINGING);
2501                                         } else if (!p->answeronpolarityswitch) {
2502                                                 ast_setstate(ast, AST_STATE_UP);
2503                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2504                                                 p->subs[index].f.subclass.integer = AST_CONTROL_ANSWER;
2505                                                 /* If aops=0 and hops=1, this is necessary */
2506                                                 p->polarity = POLARITY_REV;
2507                                         } else {
2508                                                 /* Start clean, so we can catch the change to REV polarity when party answers */
2509                                                 p->polarity = POLARITY_IDLE;
2510                                         }
2511                                 }
2512                         }
2513                 }
2514                 break;
2515         case ANALOG_EVENT_ALARM:
2516                 analog_set_alarm(p, 1);
2517                 analog_get_and_handle_alarms(p);
2518
2519         case ANALOG_EVENT_ONHOOK:
2520                 switch (p->sig) {
2521                 case ANALOG_SIG_FXOLS:
2522                 case ANALOG_SIG_FXOGS:
2523                 case ANALOG_SIG_FXOKS:
2524                         p->fxsoffhookstate = 0;
2525                         p->onhooktime = time(NULL);
2526                         p->msgstate = -1;
2527                         /* Check for some special conditions regarding call waiting */
2528                         if (index == ANALOG_SUB_REAL) {
2529                                 /* The normal line was hung up */
2530                                 if (p->subs[ANALOG_SUB_CALLWAIT].owner) {
2531                                         /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
2532                                         analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_REAL);
2533                                         ast_verb(3, "Channel %d still has (callwait) call, ringing phone\n", p->channel);
2534                                         analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
2535                                         analog_stop_callwait(p);
2536                                         p->owner = NULL;
2537                                         /* Don't start streaming audio yet if the incoming call isn't up yet */
2538                                         if (p->subs[ANALOG_SUB_REAL].owner->_state != AST_STATE_UP) {
2539                                                 analog_set_dialing(p, 1);
2540                                         }
2541                                         analog_ring(p);
2542                                 } else if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2543                                         unsigned int mssinceflash;
2544                                         /* Here we have to retain the lock on both the main channel, the 3-way channel, and
2545                                            the private structure -- not especially easy or clean */
2546                                         while (p->subs[ANALOG_SUB_THREEWAY].owner && ast_channel_trylock(p->subs[ANALOG_SUB_THREEWAY].owner)) {
2547                                                 /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
2548                                                 analog_unlock_private(p);
2549                                                 CHANNEL_DEADLOCK_AVOIDANCE(ast);
2550                                                 /* We can grab ast and p in that order, without worry.  We should make sure
2551                                                    nothing seriously bad has happened though like some sort of bizarre double
2552                                                    masquerade! */
2553                                                 analog_lock_private(p);
2554                                                 if (p->owner != ast) {
2555                                                         ast_log(LOG_WARNING, "This isn't good...\n");
2556                                                         return NULL;
2557                                                 }
2558                                         }
2559                                         if (!p->subs[ANALOG_SUB_THREEWAY].owner) {
2560                                                 ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
2561                                                 return NULL;
2562                                         }
2563                                         mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
2564                                         ast_debug(1, "Last flash was %d ms ago\n", mssinceflash);
2565                                         if (mssinceflash < MIN_MS_SINCE_FLASH) {
2566                                                 /* It hasn't been long enough since the last flashook.  This is probably a bounce on
2567                                                    hanging up.  Hangup both channels now */
2568                                                 if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2569                                                         ast_queue_hangup_with_cause(p->subs[ANALOG_SUB_THREEWAY].owner, AST_CAUSE_NO_ANSWER);
2570                                                 }
2571                                                 ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2572                                                 ast_debug(1, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
2573                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2574                                         } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
2575                                                 if (p->transfer) {
2576                                                         /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
2577                                                         if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
2578                                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2579                                                                 /* Swap subs and dis-own channel */
2580                                                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2581                                                                 p->owner = NULL;
2582                                                                 /* Ring the phone */
2583                                                                 analog_ring(p);
2584                                                         } else {
2585                                                                 if ((res = analog_attempt_transfer(p)) < 0) {
2586                                                                         ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2587                                                                         if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2588                                                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2589                                                                         }
2590                                                                 } else if (res) {
2591                                                                         /* this isn't a threeway call anymore */
2592                                                                         p->subs[ANALOG_SUB_REAL].inthreeway = 0;
2593                                                                         p->subs[ANALOG_SUB_THREEWAY].inthreeway = 0;
2594
2595                                                                         /* Don't actually hang up at this point */
2596                                                                         if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2597                                                                                 ast_channel_unlock(&p->subs[ANALOG_SUB_THREEWAY].owner);
2598                                                                         }
2599                                                                         break;
2600                                                                 }
2601                                                         }
2602                                                         /* this isn't a threeway call anymore */
2603                                                         p->subs[ANALOG_SUB_REAL].inthreeway = 0;
2604                                                         p->subs[ANALOG_SUB_THREEWAY].inthreeway = 0;
2605                                                 } else {
2606                                                         ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2607                                                         if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2608                                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2609                                                         }
2610                                                 }
2611                                         } else {
2612                                                 ast_cel_report_event(ast, AST_CEL_BLINDTRANSFER, NULL, ast->linkedid, NULL);
2613                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2614                                                 /* Swap subs and dis-own channel */
2615                                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2616                                                 p->owner = NULL;
2617                                                 /* Ring the phone */
2618                                                 analog_ring(p);
2619                                         }
2620                                 }
2621                         } else {
2622                                 ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
2623                         }
2624                         /* Fall through */
2625                 default:
2626                         analog_set_echocanceller(p, 0);
2627                         return NULL;
2628                 }
2629                 break;
2630         case ANALOG_EVENT_RINGOFFHOOK:
2631                 if (p->inalarm) {
2632                         break;
2633                 }
2634                 /* for E911, its supposed to wait for offhook then dial
2635                    the second half of the dial string */
2636                 if (((mysig == ANALOG_SIG_E911) || (mysig == ANALOG_SIG_FGC_CAMA) || (mysig == ANALOG_SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
2637                         c = strchr(p->dialdest, '/');
2638                         if (c) {
2639                                 c++;
2640                         } else {
2641                                 c = p->dialdest;
2642                         }
2643                         if (*c) {
2644                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
2645                         } else {
2646                                 ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
2647                         }
2648                         if (strlen(p->dop.dialstr) > 4) {
2649                                 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2650                                 strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2651                                 p->echorest[sizeof(p->echorest) - 1] = '\0';
2652                                 p->echobreak = 1;
2653                                 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2654                         } else {
2655                                 p->echobreak = 0;
2656                         }
2657                         if (analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop)) {
2658                                 int saveerr = errno;
2659                                 analog_on_hook(p);
2660                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
2661                                 return NULL;
2662                         }
2663                         analog_set_dialing(p, 1);
2664                         return &p->subs[index].f;
2665                 }
2666                 switch (p->sig) {
2667                 case ANALOG_SIG_FXOLS:
2668                 case ANALOG_SIG_FXOGS:
2669                 case ANALOG_SIG_FXOKS:
2670                         p->fxsoffhookstate = 1;
2671                         switch (ast->_state) {
2672                         case AST_STATE_RINGING:
2673                                 analog_set_echocanceller(p, 1);
2674                                 analog_train_echocanceller(p);
2675                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2676                                 p->subs[index].f.subclass.integer = AST_CONTROL_ANSWER;
2677                                 /* Make sure it stops ringing */
2678                                 analog_set_needringing(p, 0);
2679                                 analog_off_hook(p);
2680                                 ast_debug(1, "channel %d answered\n", p->channel);
2681                                 analog_cancel_cidspill(p);
2682                                 analog_set_dialing(p, 0);
2683                                 p->callwaitcas = 0;
2684                                 if (analog_check_confirmanswer(p)) {
2685                                         /* Ignore answer if "confirm answer" is enabled */
2686                                         p->subs[index].f.frametype = AST_FRAME_NULL;
2687                                         p->subs[index].f.subclass.integer = 0;
2688                                 } else if (!ast_strlen_zero(p->dop.dialstr)) {
2689                                         /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
2690                                         res = analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop);
2691                                         if (res < 0) {
2692                                                 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
2693                                                 p->dop.dialstr[0] = '\0';
2694                                                 return NULL;
2695                                         } else {
2696                                                 ast_debug(1, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
2697                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
2698                                                 p->subs[index].f.subclass.integer = 0;
2699                                                 analog_set_dialing(p, 1);
2700                                         }
2701                                         p->dop.dialstr[0] =