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