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