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