5fcb485eea2e0ce00b06bd3dae63a59d6fd7f180
[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         ast->tech_pvt = NULL;
1474
1475         ast_verb(3, "Hanging up on '%s'\n", ast->name);
1476
1477         return 0;
1478 }
1479
1480 int analog_answer(struct analog_pvt *p, struct ast_channel *ast)
1481 {
1482         int res = 0;
1483         int idx;
1484         int oldstate = ast->_state;
1485
1486         ast_debug(1, "%s %d\n", __FUNCTION__, p->channel);
1487         ast_setstate(ast, AST_STATE_UP);
1488         idx = analog_get_index(ast, p, 1);
1489         if (idx < 0) {
1490                 idx = ANALOG_SUB_REAL;
1491         }
1492         switch (p->sig) {
1493         case ANALOG_SIG_FXSLS:
1494         case ANALOG_SIG_FXSGS:
1495         case ANALOG_SIG_FXSKS:
1496                 analog_set_ringtimeout(p, 0);
1497                 /* Fall through */
1498         case ANALOG_SIG_EM:
1499         case ANALOG_SIG_EM_E1:
1500         case ANALOG_SIG_EMWINK:
1501         case ANALOG_SIG_FEATD:
1502         case ANALOG_SIG_FEATDMF:
1503         case ANALOG_SIG_FEATDMF_TA:
1504         case ANALOG_SIG_E911:
1505         case ANALOG_SIG_FGC_CAMA:
1506         case ANALOG_SIG_FGC_CAMAMF:
1507         case ANALOG_SIG_FEATB:
1508         case ANALOG_SIG_SF:
1509         case ANALOG_SIG_SFWINK:
1510         case ANALOG_SIG_SF_FEATD:
1511         case ANALOG_SIG_SF_FEATDMF:
1512         case ANALOG_SIG_SF_FEATB:
1513         case ANALOG_SIG_FXOLS:
1514         case ANALOG_SIG_FXOGS:
1515         case ANALOG_SIG_FXOKS:
1516                 /* Pick up the line */
1517                 ast_debug(1, "Took %s off hook\n", ast->name);
1518                 if (p->hanguponpolarityswitch) {
1519                         gettimeofday(&p->polaritydelaytv, NULL);
1520                 }
1521                 res = analog_off_hook(p);
1522                 analog_play_tone(p, idx, -1);
1523                 analog_set_dialing(p, 0);
1524                 if ((idx == ANALOG_SUB_REAL) && p->subs[ANALOG_SUB_THREEWAY].inthreeway) {
1525                         if (oldstate == AST_STATE_RINGING) {
1526                                 ast_debug(1, "Finally swapping real and threeway\n");
1527                                 analog_play_tone(p, ANALOG_SUB_THREEWAY, -1);
1528                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
1529                                 analog_set_new_owner(p, p->subs[ANALOG_SUB_REAL].owner);
1530                         }
1531                 }
1532
1533                 switch (p->sig) {
1534                 case ANALOG_SIG_FXSLS:
1535                 case ANALOG_SIG_FXSKS:
1536                 case ANALOG_SIG_FXSGS:
1537                         analog_set_echocanceller(p, 1);
1538                         analog_train_echocanceller(p);
1539                         break;
1540                 case ANALOG_SIG_FXOLS:
1541                 case ANALOG_SIG_FXOKS:
1542                 case ANALOG_SIG_FXOGS:
1543                         analog_answer_polarityswitch(p);
1544                         break;
1545                 default:
1546                         break;
1547                 }
1548                 break;
1549         default:
1550                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
1551                 res = -1;
1552                 break;
1553         }
1554         ast_setstate(ast, AST_STATE_UP);
1555         return res;
1556 }
1557
1558 static int analog_handles_digit(struct ast_frame *f)
1559 {
1560         char subclass = toupper(f->subclass.integer);
1561
1562         switch (subclass) {
1563         case '1':
1564         case '2':
1565         case '3':
1566         case '4':
1567         case '5':
1568         case '6':
1569         case '7':
1570         case '9':
1571         case 'A':
1572         case 'B':
1573         case 'C':
1574         case 'D':
1575         case 'E':
1576         case 'F':
1577                 return 1;
1578         default:
1579                 return 0;
1580         }
1581 }
1582
1583 void analog_handle_dtmf(struct analog_pvt *p, struct ast_channel *ast, enum analog_sub idx, struct ast_frame **dest)
1584 {
1585         struct ast_frame *f = *dest;
1586
1587         ast_debug(1, "%s DTMF digit: 0x%02X '%c' on %s\n",
1588                 f->frametype == AST_FRAME_DTMF_BEGIN ? "Begin" : "End",
1589                 f->subclass.integer, f->subclass.integer, ast->name);
1590
1591         if (analog_check_confirmanswer(p)) {
1592                 if (f->frametype == AST_FRAME_DTMF_END) {
1593                         ast_debug(1, "Confirm answer on %s!\n", ast->name);
1594                         /* Upon receiving a DTMF digit, consider this an answer confirmation instead
1595                         of a DTMF digit */
1596                         p->subs[idx].f.frametype = AST_FRAME_CONTROL;
1597                         p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
1598                         /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
1599                         analog_set_confirmanswer(p, 0);
1600                 } else {
1601                         p->subs[idx].f.frametype = AST_FRAME_NULL;
1602                         p->subs[idx].f.subclass.integer = 0;
1603                 }
1604                 *dest = &p->subs[idx].f;
1605         } else if (p->callwaitcas) {
1606                 if (f->frametype == AST_FRAME_DTMF_END) {
1607                         if ((f->subclass.integer == 'A') || (f->subclass.integer == 'D')) {
1608                                 ast_debug(1, "Got some DTMF, but it's for the CAS\n");
1609                                 p->caller.id.name.str = p->callwait_name;
1610                                 p->caller.id.number.str = p->callwait_num;
1611                                 analog_send_callerid(p, 1, &p->caller);
1612                         }
1613                         if (analog_handles_digit(f)) {
1614                                 p->callwaitcas = 0;
1615                         }
1616                 }
1617                 p->subs[idx].f.frametype = AST_FRAME_NULL;
1618                 p->subs[idx].f.subclass.integer = 0;
1619                 *dest = &p->subs[idx].f;
1620         } else {
1621                 analog_cb_handle_dtmf(p, ast, idx, dest);
1622         }
1623 }
1624
1625 static int analog_my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
1626 {
1627         char c;
1628
1629         *str = 0; /* start with empty output buffer */
1630         for (;;) {
1631                 /* Wait for the first digit (up to specified ms). */
1632                 c = ast_waitfordigit(chan, ms);
1633                 /* if timeout, hangup or error, return as such */
1634                 if (c < 1) {
1635                         return c;
1636                 }
1637                 *str++ = c;
1638                 *str = 0;
1639                 if (strchr(term, c)) {
1640                         return 1;
1641                 }
1642         }
1643 }
1644
1645 static int analog_handle_notify_message(struct ast_channel *chan, struct analog_pvt *p, int cid_flags, int neon_mwievent)
1646 {
1647         if (p->calls->handle_notify_message) {
1648                 p->calls->handle_notify_message(chan, p->chan_pvt, cid_flags, neon_mwievent);
1649                 return 0;
1650         }
1651         return -1;
1652 }
1653
1654 static int analog_increase_ss_count(struct analog_pvt *p)
1655 {
1656         if (p->calls->increase_ss_count) {
1657                 p->calls->increase_ss_count();
1658                 return 0;
1659         }
1660         return -1;
1661 }
1662
1663 static int analog_decrease_ss_count(struct analog_pvt *p)
1664 {
1665         if (p->calls->decrease_ss_count) {
1666                 p->calls->decrease_ss_count();
1667                 return 0;
1668         }
1669         return -1;
1670 }
1671
1672 static int analog_distinctive_ring(struct ast_channel *chan, struct analog_pvt *p, int idx, int *ringdata)
1673 {
1674         if (p->calls->distinctive_ring) {
1675                 return p->calls->distinctive_ring(chan, p->chan_pvt, idx, ringdata);
1676         }
1677         return -1;
1678
1679 }
1680
1681 static void analog_get_and_handle_alarms(struct analog_pvt *p)
1682 {
1683         if (p->calls->get_and_handle_alarms) {
1684                 return p->calls->get_and_handle_alarms(p->chan_pvt);
1685         }
1686 }
1687
1688 static void *analog_get_bridged_channel(struct analog_pvt *p, struct ast_channel *chan)
1689 {
1690         if (p->calls->get_sigpvt_bridged_channel) {
1691                 return p->calls->get_sigpvt_bridged_channel;
1692         }
1693         return NULL;
1694 }
1695
1696 static int analog_get_sub_fd(struct analog_pvt *p, enum analog_sub sub)
1697 {
1698         if (p->calls->get_sub_fd) {
1699                 return p->calls->get_sub_fd(p->chan_pvt, sub);
1700         }
1701         return -1;
1702 }
1703
1704 #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))
1705
1706 static void *__analog_ss_thread(void *data)
1707 {
1708         struct analog_pvt *p = data;
1709         struct ast_channel *chan = p->ss_astchan;
1710         char exten[AST_MAX_EXTENSION] = "";
1711         char exten2[AST_MAX_EXTENSION] = "";
1712         char dtmfcid[300];
1713         char dtmfbuf[300];
1714         char namebuf[ANALOG_MAX_CID];
1715         char numbuf[ANALOG_MAX_CID];
1716         struct callerid_state *cs = NULL;
1717         char *name = NULL, *number = NULL;
1718         int flags = 0;
1719         struct ast_smdi_md_message *smdi_msg = NULL;
1720         int timeout;
1721         int getforward = 0;
1722         char *s1, *s2;
1723         int len = 0;
1724         int res;
1725         int idx;
1726
1727         analog_increase_ss_count(p);
1728
1729         ast_debug(1, "%s %d\n", __FUNCTION__, p->channel);
1730
1731         if (!chan) {
1732                 /* What happened to the channel? */
1733                 goto quit;
1734         }
1735         /* in the bizarre case where the channel has become a zombie before we
1736            even get started here, abort safely
1737         */
1738         if (!chan->tech_pvt) {
1739                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1740                 ast_hangup(chan);
1741                 goto quit;
1742         }
1743
1744         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1745         idx = analog_get_index(chan, p, 0);
1746         if (idx < 0) {
1747                 ast_hangup(chan);
1748                 goto quit;
1749         }
1750         analog_dsp_reset_and_flush_digits(p);
1751         switch (p->sig) {
1752         case ANALOG_SIG_FEATD:
1753         case ANALOG_SIG_FEATDMF:
1754         case ANALOG_SIG_FEATDMF_TA:
1755         case ANALOG_SIG_E911:
1756         case ANALOG_SIG_FGC_CAMAMF:
1757         case ANALOG_SIG_FEATB:
1758         case ANALOG_SIG_EMWINK:
1759         case ANALOG_SIG_SF_FEATD:
1760         case ANALOG_SIG_SF_FEATDMF:
1761         case ANALOG_SIG_SF_FEATB:
1762         case ANALOG_SIG_SFWINK:
1763                 if (analog_wink(p, idx))
1764                         goto quit;
1765                 /* Fall through */
1766         case ANALOG_SIG_EM:
1767         case ANALOG_SIG_EM_E1:
1768         case ANALOG_SIG_SF:
1769         case ANALOG_SIG_FGC_CAMA:
1770                 res = analog_play_tone(p, idx, -1);
1771
1772                 analog_dsp_reset_and_flush_digits(p);
1773
1774                 /* set digit mode appropriately */
1775                 if (ANALOG_NEED_MFDETECT(p)) {
1776                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_MF);
1777                 } else {
1778                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1779                 }
1780
1781                 memset(dtmfbuf, 0, sizeof(dtmfbuf));
1782                 /* Wait for the first digit only if immediate=no */
1783                 if (!p->immediate) {
1784                         /* Wait for the first digit (up to 5 seconds). */
1785                         res = ast_waitfordigit(chan, 5000);
1786                 } else {
1787                         res = 0;
1788                 }
1789                 if (res > 0) {
1790                         /* save first char */
1791                         dtmfbuf[0] = res;
1792                         switch (p->sig) {
1793                         case ANALOG_SIG_FEATD:
1794                         case ANALOG_SIG_SF_FEATD:
1795                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
1796                                 if (res > 0) {
1797                                         res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
1798                                 }
1799                                 if (res < 1) {
1800                                         analog_dsp_reset_and_flush_digits(p);
1801                                 }
1802                                 break;
1803                         case ANALOG_SIG_FEATDMF_TA:
1804                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1805                                 if (res < 1) {
1806                                         analog_dsp_reset_and_flush_digits(p);
1807                                 }
1808                                 if (analog_wink(p, idx)) {
1809                                         goto quit;
1810                                 }
1811                                 dtmfbuf[0] = 0;
1812                                 /* Wait for the first digit (up to 5 seconds). */
1813                                 res = ast_waitfordigit(chan, 5000);
1814                                 if (res <= 0) {
1815                                         break;
1816                                 }
1817                                 dtmfbuf[0] = res;
1818                                 /* fall through intentionally */
1819                         case ANALOG_SIG_FEATDMF:
1820                         case ANALOG_SIG_E911:
1821                         case ANALOG_SIG_FGC_CAMAMF:
1822                         case ANALOG_SIG_SF_FEATDMF:
1823                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1824                                 /* if international caca, do it again to get real ANO */
1825                                 if ((p->sig == ANALOG_SIG_FEATDMF) && (dtmfbuf[1] != '0') 
1826                                         && (strlen(dtmfbuf) != 14)) {
1827                                         if (analog_wink(p, idx)) {
1828                                                 goto quit;
1829                                         }
1830                                         dtmfbuf[0] = 0;
1831                                         /* Wait for the first digit (up to 5 seconds). */
1832                                         res = ast_waitfordigit(chan, 5000);
1833                                         if (res <= 0) {
1834                                                 break;
1835                                         }
1836                                         dtmfbuf[0] = res;
1837                                         res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1838                                 }
1839                                 if (res > 0) {
1840                                         /* if E911, take off hook */
1841                                         if (p->sig == ANALOG_SIG_E911) {
1842                                                 analog_off_hook(p);
1843                                         }
1844                                         res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
1845                                 }
1846                                 if (res < 1) {
1847                                         analog_dsp_reset_and_flush_digits(p);
1848                                 }
1849                                 break;
1850                         case ANALOG_SIG_FEATB:
1851                         case ANALOG_SIG_SF_FEATB:
1852                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1853                                 if (res < 1) {
1854                                         analog_dsp_reset_and_flush_digits(p);
1855                                 }
1856                                 break;
1857                         case ANALOG_SIG_EMWINK:
1858                                 /* if we received a '*', we are actually receiving Feature Group D
1859                                    dial syntax, so use that mode; otherwise, fall through to normal
1860                                    mode
1861                                 */
1862                                 if (res == '*') {
1863                                         res = analog_my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
1864                                         if (res > 0) {
1865                                                 res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
1866                                         }
1867                                         if (res < 1) {
1868                                                 analog_dsp_reset_and_flush_digits(p);
1869                                         }
1870                                         break;
1871                                 }
1872                         default:
1873                                 /* If we got the first digit, get the rest */
1874                                 len = 1;
1875                                 dtmfbuf[len] = '\0';
1876                                 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
1877                                         if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
1878                                                 timeout = analog_matchdigittimeout;
1879                                         } else {
1880                                                 timeout = analog_gendigittimeout;
1881                                         }
1882                                         res = ast_waitfordigit(chan, timeout);
1883                                         if (res < 0) {
1884                                                 ast_debug(1, "waitfordigit returned < 0...\n");
1885                                                 ast_hangup(chan);
1886                                                 goto quit;
1887                                         } else if (res) {
1888                                                 dtmfbuf[len++] = res;
1889                                                 dtmfbuf[len] = '\0';
1890                                         } else {
1891                                                 break;
1892                                         }
1893                                 }
1894                                 break;
1895                         }
1896                 }
1897                 if (res == -1) {
1898                         ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
1899                         ast_hangup(chan);
1900                         goto quit;
1901                 } else if (res < 0) {
1902                         ast_debug(1, "Got hung up before digits finished\n");
1903                         ast_hangup(chan);
1904                         goto quit;
1905                 }
1906
1907                 if (p->sig == ANALOG_SIG_FGC_CAMA) {
1908                         char anibuf[100];
1909
1910                         if (ast_safe_sleep(chan,1000) == -1) {
1911                                 ast_hangup(chan);
1912                                 goto quit;
1913                         }
1914                         analog_off_hook(p);
1915                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_MF);
1916                         res = analog_my_getsigstr(chan, anibuf, "#", 10000);
1917                         if ((res > 0) && (strlen(anibuf) > 2)) {
1918                                 if (anibuf[strlen(anibuf) - 1] == '#') {
1919                                         anibuf[strlen(anibuf) - 1] = 0;
1920                                 }
1921                                 ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
1922                         }
1923                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1924                 }
1925
1926                 ast_copy_string(exten, dtmfbuf, sizeof(exten));
1927                 if (ast_strlen_zero(exten)) {
1928                         ast_copy_string(exten, "s", sizeof(exten));
1929                 }
1930                 if (p->sig == ANALOG_SIG_FEATD || p->sig == ANALOG_SIG_EMWINK) {
1931                         /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
1932                         if (exten[0] == '*') {
1933                                 char *stringp=NULL;
1934                                 ast_copy_string(exten2, exten, sizeof(exten2));
1935                                 /* Parse out extension and callerid */
1936                                 stringp=exten2 +1;
1937                                 s1 = strsep(&stringp, "*");
1938                                 s2 = strsep(&stringp, "*");
1939                                 if (s2) {
1940                                         if (!ast_strlen_zero(p->cid_num)) {
1941                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
1942                                         } else {
1943                                                 ast_set_callerid(chan, s1, NULL, s1);
1944                                         }
1945                                         ast_copy_string(exten, s2, sizeof(exten));
1946                                 } else {
1947                                         ast_copy_string(exten, s1, sizeof(exten));
1948                                 }
1949                         } else if (p->sig == ANALOG_SIG_FEATD) {
1950                                 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1951                         }
1952                 }
1953                 if ((p->sig == ANALOG_SIG_FEATDMF) || (p->sig == ANALOG_SIG_FEATDMF_TA)) {
1954                         if (exten[0] == '*') {
1955                                 char *stringp=NULL;
1956                                 ast_copy_string(exten2, exten, sizeof(exten2));
1957                                 /* Parse out extension and callerid */
1958                                 stringp=exten2 +1;
1959                                 s1 = strsep(&stringp, "#");
1960                                 s2 = strsep(&stringp, "#");
1961                                 if (s2) {
1962                                         if (!ast_strlen_zero(p->cid_num)) {
1963                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
1964                                         } else {
1965                                                 if (*(s1 + 2)) {
1966                                                         ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
1967                                                 }
1968                                         }
1969                                         ast_copy_string(exten, s2 + 1, sizeof(exten));
1970                                 } else {
1971                                         ast_copy_string(exten, s1 + 2, sizeof(exten));
1972                                 }
1973                         } else {
1974                                 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1975                         }
1976                 }
1977                 if ((p->sig == ANALOG_SIG_E911) || (p->sig == ANALOG_SIG_FGC_CAMAMF)) {
1978                         if (exten[0] == '*') {
1979                                 char *stringp=NULL;
1980                                 ast_copy_string(exten2, exten, sizeof(exten2));
1981                                 /* Parse out extension and callerid */
1982                                 stringp=exten2 +1;
1983                                 s1 = strsep(&stringp, "#");
1984                                 s2 = strsep(&stringp, "#");
1985                                 if (s2 && (*(s2 + 1) == '0')) {
1986                                         if (*(s2 + 2)) {
1987                                                 ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
1988                                         }
1989                                 }
1990                                 if (s1) {
1991                                         ast_copy_string(exten, s1, sizeof(exten));
1992                                 } else {
1993                                         ast_copy_string(exten, "911", sizeof(exten));
1994                                 }
1995                         } else {
1996                                 ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1997                         }
1998                 }
1999                 if (p->sig == ANALOG_SIG_FEATB) {
2000                         if (exten[0] == '*') {
2001                                 char *stringp=NULL;
2002                                 ast_copy_string(exten2, exten, sizeof(exten2));
2003                                 /* Parse out extension and callerid */
2004                                 stringp=exten2 +1;
2005                                 s1 = strsep(&stringp, "#");
2006                                 ast_copy_string(exten, exten2 + 1, sizeof(exten));
2007                         } else {
2008                                 ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
2009                         }
2010                 }
2011                 if ((p->sig == ANALOG_SIG_FEATDMF) || (p->sig == ANALOG_SIG_FEATDMF_TA)) {
2012                         analog_wink(p, idx);
2013                         /*
2014                          * Some switches require a minimum guard time between the last
2015                          * FGD wink and something that answers immediately.  This
2016                          * ensures it.
2017                          */
2018                         if (ast_safe_sleep(chan, 100)) {
2019                                 ast_hangup(chan);
2020                                 goto quit;
2021                         }
2022                 }
2023                 analog_set_echocanceller(p, 1);
2024
2025                 analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
2026
2027                 if (ast_exists_extension(chan, chan->context, exten, 1,
2028                         chan->caller.id.number.valid ? chan->caller.id.number.str : NULL)) {
2029                         ast_copy_string(chan->exten, exten, sizeof(chan->exten));
2030                         analog_dsp_reset_and_flush_digits(p);
2031                         res = ast_pbx_run(chan);
2032                         if (res) {
2033                                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2034                                 res = analog_play_tone(p, idx, ANALOG_TONE_CONGESTION);
2035                         }
2036                         goto quit;
2037                 } else {
2038                         ast_verb(3, "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
2039                         sleep(2);
2040                         res = analog_play_tone(p, idx, ANALOG_TONE_INFO);
2041                         if (res < 0) {
2042                                 ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
2043                         } else {
2044                                 sleep(1);
2045                         }
2046                         res = ast_streamfile(chan, "ss-noservice", chan->language);
2047                         if (res >= 0) {
2048                                 ast_waitstream(chan, "");
2049                         }
2050                         res = analog_play_tone(p, idx, ANALOG_TONE_CONGESTION);
2051                         ast_hangup(chan);
2052                         goto quit;
2053                 }
2054                 break;
2055         case ANALOG_SIG_FXOLS:
2056         case ANALOG_SIG_FXOGS:
2057         case ANALOG_SIG_FXOKS:
2058                 /* Read the first digit */
2059                 timeout = analog_firstdigittimeout;
2060                 /* If starting a threeway call, never timeout on the first digit so someone
2061                    can use flash-hook as a "hold" feature */
2062                 if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2063                         timeout = 999999;
2064                 }
2065                 while (len < AST_MAX_EXTENSION-1) {
2066                         /* Read digit unless it's supposed to be immediate, in which case the
2067                            only answer is 's' */
2068                         if (p->immediate) {
2069                                 res = 's';
2070                         } else {
2071                                 res = ast_waitfordigit(chan, timeout);
2072                         }
2073                         timeout = 0;
2074                         if (res < 0) {
2075                                 ast_debug(1, "waitfordigit returned < 0...\n");
2076                                 res = analog_play_tone(p, idx, -1);
2077                                 ast_hangup(chan);
2078                                 goto quit;
2079                         } else if (res) {
2080                                 ast_debug(1,"waitfordigit returned '%c' (%d), timeout = %d\n", res, res, timeout);
2081                                 exten[len++]=res;
2082                                 exten[len] = '\0';
2083                         }
2084                         if (!ast_ignore_pattern(chan->context, exten)) {
2085                                 analog_play_tone(p, idx, -1);
2086                         } else {
2087                                 analog_play_tone(p, idx, ANALOG_TONE_DIALTONE);
2088                         }
2089                         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && !ast_parking_ext_valid(exten, chan, chan->context)) {
2090                                 if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
2091                                         if (getforward) {
2092                                                 /* Record this as the forwarding extension */
2093                                                 ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
2094                                                 ast_verb(3, "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
2095                                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2096                                                 if (res) {
2097                                                         break;
2098                                                 }
2099                                                 usleep(500000);
2100                                                 res = analog_play_tone(p, idx, -1);
2101                                                 sleep(1);
2102                                                 memset(exten, 0, sizeof(exten));
2103                                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALTONE);
2104                                                 len = 0;
2105                                                 getforward = 0;
2106                                         } else {
2107                                                 res = analog_play_tone(p, idx, -1);
2108                                                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
2109                                                 if (!ast_strlen_zero(p->cid_num)) {
2110                                                         if (!p->hidecallerid) {
2111                                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
2112                                                         } else {
2113                                                                 ast_set_callerid(chan, NULL, NULL, p->cid_num);
2114                                                         }
2115                                                 }
2116                                                 if (!ast_strlen_zero(p->cid_name)) {
2117                                                         if (!p->hidecallerid) {
2118                                                                 ast_set_callerid(chan, NULL, p->cid_name, NULL);
2119                                                         }
2120                                                 }
2121                                                 ast_setstate(chan, AST_STATE_RING);
2122                                                 analog_set_echocanceller(p, 1);
2123                                                 res = ast_pbx_run(chan);
2124                                                 if (res) {
2125                                                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
2126                                                         res = analog_play_tone(p, idx, ANALOG_TONE_CONGESTION);
2127                                                 }
2128                                                 goto quit;
2129                                         }
2130                                 } else {
2131                                         /* It's a match, but they just typed a digit, and there is an ambiguous match,
2132                                            so just set the timeout to analog_matchdigittimeout and wait some more */
2133                                         timeout = analog_matchdigittimeout;
2134                                 }
2135                         } else if (res == 0) {
2136                                 ast_debug(1, "not enough digits (and no ambiguous match)...\n");
2137                                 res = analog_play_tone(p, idx, ANALOG_TONE_CONGESTION);
2138                                 analog_wait_event(p);
2139                                 ast_hangup(chan);
2140                                 goto quit;
2141                         } else if (p->callwaiting && !strcmp(exten, "*70")) {
2142                                 ast_verb(3, "Disabling call waiting on %s\n", chan->name);
2143                                 /* Disable call waiting if enabled */
2144                                 analog_set_callwaiting(p, 0);
2145                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2146                                 if (res) {
2147                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
2148                                                 chan->name, strerror(errno));
2149                                 }
2150                                 len = 0;
2151                                 memset(exten, 0, sizeof(exten));
2152                                 timeout = analog_firstdigittimeout;
2153
2154                         } else if (!strcmp(exten,ast_pickup_ext())) {
2155                                 /* Scan all channels and see if there are any
2156                                  * ringing channels that have call groups
2157                                  * that equal this channels pickup group
2158                                  */
2159                                 if (idx == ANALOG_SUB_REAL) {
2160                                         /* Switch us from Third call to Call Wait */
2161                                         if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2162                                                 /* If you make a threeway call and the *8# a call, it should actually
2163                                                    look like a callwait */
2164                                                 analog_alloc_sub(p, ANALOG_SUB_CALLWAIT);
2165                                                 analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_THREEWAY);
2166                                                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
2167                                         }
2168                                         analog_set_echocanceller(p, 1);
2169                                         if (ast_pickup_call(chan)) {
2170                                                 ast_debug(1, "No call pickup possible...\n");
2171                                                 res = analog_play_tone(p, idx, ANALOG_TONE_CONGESTION);
2172                                                 analog_wait_event(p);
2173                                         }
2174                                         ast_hangup(chan);
2175                                         goto quit;
2176                                 } else {
2177                                         ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
2178                                         ast_hangup(chan);
2179                                         goto quit;
2180                                 }
2181
2182                         } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
2183                                 ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
2184                                 /* Disable Caller*ID if enabled */
2185                                 p->hidecallerid = 1;
2186                                 ast_party_number_free(&chan->caller.id.number);
2187                                 ast_party_number_init(&chan->caller.id.number);
2188                                 ast_party_name_free(&chan->caller.id.name);
2189                                 ast_party_name_init(&chan->caller.id.name);
2190                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2191                                 if (res) {
2192                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
2193                                                 chan->name, strerror(errno));
2194                                 }
2195                                 len = 0;
2196                                 memset(exten, 0, sizeof(exten));
2197                                 timeout = analog_firstdigittimeout;
2198                         } else if (p->callreturn && !strcmp(exten, "*69")) {
2199                                 res = 0;
2200                                 if (!ast_strlen_zero(p->lastcid_num)) {
2201                                         res = ast_say_digit_str(chan, p->lastcid_num, "", chan->language);
2202                                 }
2203                                 if (!res) {
2204                                         res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2205                                 }
2206                                 break;
2207                         } else if (!strcmp(exten, "*78")) {
2208                                 /* Do not disturb enabled */
2209                                 analog_dnd(p, 1);
2210                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2211                                 getforward = 0;
2212                                 memset(exten, 0, sizeof(exten));
2213                                 len = 0;
2214                         } else if (!strcmp(exten, "*79")) {
2215                                 /* Do not disturb disabled */
2216                                 analog_dnd(p, 0);
2217                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2218                                 getforward = 0;
2219                                 memset(exten, 0, sizeof(exten));
2220                                 len = 0;
2221                         } else if (p->cancallforward && !strcmp(exten, "*72")) {
2222                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2223                                 getforward = 1;
2224                                 memset(exten, 0, sizeof(exten));
2225                                 len = 0;
2226                         } else if (p->cancallforward && !strcmp(exten, "*73")) {
2227                                 ast_verb(3, "Cancelling call forwarding on channel %d\n", p->channel);
2228                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2229                                 memset(p->call_forward, 0, sizeof(p->call_forward));
2230                                 getforward = 0;
2231                                 memset(exten, 0, sizeof(exten));
2232                                 len = 0;
2233                         } else if ((p->transfer || p->canpark) && ast_parking_ext_valid(exten, chan, chan->context) &&
2234                                                 p->subs[ANALOG_SUB_THREEWAY].owner &&
2235                                                 ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)) {
2236                                 /* This is a three way call, the main call being a real channel,
2237                                         and we're parking the first call. */
2238                                 ast_masq_park_call(ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner), chan, 0, NULL);
2239                                 ast_verb(3, "Parking call to '%s'\n", chan->name);
2240                                 break;
2241                         } else if (!ast_strlen_zero(p->lastcid_num) && !strcmp(exten, "*60")) {
2242                                 ast_verb(3, "Blacklisting number %s\n", p->lastcid_num);
2243                                 res = ast_db_put("blacklist", p->lastcid_num, "1");
2244                                 if (!res) {
2245                                         res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2246                                         memset(exten, 0, sizeof(exten));
2247                                         len = 0;
2248                                 }
2249                         } else if (p->hidecallerid && !strcmp(exten, "*82")) {
2250                                 ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
2251                                 /* Enable Caller*ID if enabled */
2252                                 p->hidecallerid = 0;
2253                                 ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
2254                                 res = analog_play_tone(p, idx, ANALOG_TONE_DIALRECALL);
2255                                 if (res) {
2256                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
2257                                                 chan->name, strerror(errno));
2258                                 }
2259                                 len = 0;
2260                                 memset(exten, 0, sizeof(exten));
2261                                 timeout = analog_firstdigittimeout;
2262                         } else if (!strcmp(exten, "*0")) {
2263                                 struct ast_channel *nbridge = p->subs[ANALOG_SUB_THREEWAY].owner;
2264                                 struct analog_pvt *pbridge = NULL;
2265                                 /* set up the private struct of the bridged one, if any */
2266                                 if (nbridge && ast_bridged_channel(nbridge)) {
2267                                         pbridge = analog_get_bridged_channel(p, nbridge);
2268                                 }
2269                                 if (nbridge && pbridge &&
2270                                     (nbridge->tech == p->chan_tech) &&
2271                                     (ast_bridged_channel(nbridge)->tech == p->chan_tech) &&
2272                                     ISTRUNK(pbridge)) {
2273                                         /* Clear out the dial buffer */
2274                                         p->dop.dialstr[0] = '\0';
2275                                         /* flash hookswitch */
2276                                         if ((analog_flash(p) == -1) && (errno != EINPROGRESS)) {
2277                                                 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
2278                                                         nbridge->name, strerror(errno));
2279                                         }
2280                                         analog_swap_subs(p, ANALOG_SUB_REAL, ANALOG_SUB_THREEWAY);
2281                                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
2282                                         analog_set_new_owner(p, p->subs[ANALOG_SUB_REAL].owner);
2283                                         if (ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner)) {
2284                                                 ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_UNHOLD);
2285                                         }
2286                                         ast_hangup(chan);
2287                                         goto quit;
2288                                 } else {
2289                                         analog_play_tone(p, idx, ANALOG_TONE_CONGESTION);
2290                                         analog_wait_event(p);
2291                                         analog_play_tone(p, idx, -1);
2292                                         analog_swap_subs(p, ANALOG_SUB_REAL, ANALOG_SUB_THREEWAY);
2293                                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
2294                                         analog_set_new_owner(p, p->subs[ANALOG_SUB_REAL].owner);
2295                                         ast_hangup(chan);
2296                                         goto quit;
2297                                 }
2298                         } else if (!ast_canmatch_extension(chan, chan->context, exten, 1,
2299                                 chan->caller.id.number.valid ? chan->caller.id.number.str : NULL)
2300                                 && ((exten[0] != '*') || (strlen(exten) > 2))) {
2301                                 ast_debug(1, "Can't match %s from '%s' in context %s\n", exten,
2302                                         chan->caller.id.number.valid && chan->caller.id.number.str
2303                                                 ? chan->caller.id.number.str : "<Unknown Caller>",
2304                                         chan->context);
2305                                 break;
2306                         }
2307                         if (!timeout) {
2308                                 timeout = analog_gendigittimeout;
2309                         }
2310                         if (len && !ast_ignore_pattern(chan->context, exten)) {
2311                                 analog_play_tone(p, idx, -1);
2312                         }
2313                 }
2314                 break;
2315         case ANALOG_SIG_FXSLS:
2316         case ANALOG_SIG_FXSGS:
2317         case ANALOG_SIG_FXSKS:
2318                 /* check for SMDI messages */
2319                 if (p->use_smdi && p->smdi_iface) {
2320                         smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, ANALOG_SMDI_MD_WAIT_TIMEOUT);
2321                         if (smdi_msg != NULL) {
2322                                 ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
2323
2324                                 if (smdi_msg->type == 'B')
2325                                         pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
2326                                 else if (smdi_msg->type == 'N')
2327                                         pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
2328
2329                                 ast_debug(1, "Received SMDI message on %s\n", chan->name);
2330                         } else {
2331                                 ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
2332                         }
2333                 }
2334
2335                 if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
2336                         number = smdi_msg->calling_st;
2337
2338                 /* If we want caller id, we're in a prering state due to a polarity reversal
2339                  * and we're set to use a polarity reversal to trigger the start of caller id,
2340                  * grab the caller id and wait for ringing to start... */
2341                 } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING
2342                         && (p->cid_start == ANALOG_CID_START_POLARITY
2343                                 || p->cid_start == ANALOG_CID_START_POLARITY_IN
2344                                 || p->cid_start == ANALOG_CID_START_DTMF_NOALERT))) {
2345                         /* If set to use DTMF CID signalling, listen for DTMF */
2346                         if (p->cid_signalling == CID_SIG_DTMF) {
2347                                 int k = 0;
2348                                 int oldlinearity; 
2349                                 cs = NULL;
2350                                 ast_debug(1, "Receiving DTMF cid on channel %s\n", chan->name);
2351
2352                                 oldlinearity = analog_set_linear_mode(p, idx, 0);
2353
2354                                 /*
2355                                  * We are the only party interested in the Rx stream since
2356                                  * we have not answered yet.  We don't need or even want DTMF
2357                                  * emulation.  The DTMF digits can come so fast that emulation
2358                                  * can drop some of them.
2359                                  */
2360                                 ast_set_flag(chan, AST_FLAG_END_DTMF_ONLY);
2361                                 res = 4000;/* This is a typical OFF time between rings. */
2362                                 for (;;) {
2363                                         struct ast_frame *f;
2364                                         res = ast_waitfor(chan, res);
2365                                         if (res <= 0) {
2366                                                 /*
2367                                                  * We do not need to restore the analog_set_linear_mode()
2368                                                  * or AST_FLAG_END_DTMF_ONLY flag settings since we
2369                                                  * are hanging up the channel.
2370                                                  */
2371                                                 ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
2372                                                         "Exiting simple switch\n");
2373                                                 ast_hangup(chan);
2374                                                 goto quit;
2375                                         }
2376                                         f = ast_read(chan);
2377                                         if (!f) {
2378                                                 break;
2379                                         }
2380                                         if (f->frametype == AST_FRAME_DTMF) {
2381                                                 if (k < ARRAY_LEN(dtmfbuf) - 1) {
2382                                                         dtmfbuf[k++] = f->subclass.integer;
2383                                                 }
2384                                                 ast_debug(1, "CID got digit '%c'\n", f->subclass.integer);
2385                                                 res = 4000;/* This is a typical OFF time between rings. */
2386                                         }
2387                                         ast_frfree(f);
2388                                         if (chan->_state == AST_STATE_RING ||
2389                                                 chan->_state == AST_STATE_RINGING) {
2390                                                 break; /* Got ring */
2391                                         }
2392                                 }
2393                                 ast_clear_flag(chan, AST_FLAG_END_DTMF_ONLY);
2394                                 dtmfbuf[k] = '\0';
2395
2396                                 analog_set_linear_mode(p, idx, oldlinearity);
2397
2398                                 /* Got cid and ring. */
2399                                 ast_debug(1, "CID got string '%s'\n", dtmfbuf);
2400                                 callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
2401                                 ast_debug(1, "CID is '%s', flags %d\n", dtmfcid, flags);
2402                                 /* If first byte is NULL, we have no cid */
2403                                 if (!ast_strlen_zero(dtmfcid)) {
2404                                         number = dtmfcid;
2405                                 } else {
2406                                         number = NULL;
2407                                 }
2408
2409                         /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
2410                         } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
2411                                 int timeout = 10000;  /* Ten seconds */
2412                                 struct timeval start = ast_tvnow();
2413                                 enum analog_event ev;
2414
2415                                 namebuf[0] = 0;
2416                                 numbuf[0] = 0;
2417
2418                                 if (!analog_start_cid_detect(p, p->cid_signalling)) {
2419                                         while (1) {
2420                                                 res = analog_get_callerid(p, namebuf, numbuf, &ev, timeout - ast_tvdiff_ms(ast_tvnow(), start));
2421
2422                                                 if (res == 0) {
2423                                                         break;
2424                                                 }
2425
2426                                                 if (res == 1) {
2427                                                         if (ev == ANALOG_EVENT_NOALARM) {
2428                                                                 analog_set_alarm(p, 0);
2429                                                         }
2430                                                         if (p->cid_signalling == CID_SIG_V23_JP) {
2431                                                                 if (ev == ANALOG_EVENT_RINGBEGIN) {
2432                                                                         analog_off_hook(p);
2433                                                                         usleep(1);
2434                                                                 }
2435                                                         } else {
2436                                                                 ev = ANALOG_EVENT_NONE;
2437                                                                 break;
2438                                                         }
2439                                                 }
2440
2441                                                 if (ast_tvdiff_ms(ast_tvnow(), start) > timeout)
2442                                                         break;
2443
2444                                         }
2445                                         name = namebuf;
2446                                         number = numbuf;
2447
2448                                         analog_stop_cid_detect(p);
2449
2450                                         if (p->cid_signalling == CID_SIG_V23_JP) {
2451                                                 res = analog_on_hook(p);
2452                                                 usleep(1);
2453                                         }
2454
2455                                         /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
2456                                         res = 4000;/* This is a typical OFF time between rings. */
2457                                         for (;;) {
2458                                                 struct ast_frame *f;
2459                                                 res = ast_waitfor(chan, res);
2460                                                 if (res <= 0) {
2461                                                         ast_log(LOG_WARNING, "CID timed out waiting for ring. "
2462                                                                 "Exiting simple switch\n");
2463                                                         ast_hangup(chan);
2464                                                         goto quit;
2465                                                 }
2466                                                 if (!(f = ast_read(chan))) {
2467                                                         ast_log(LOG_WARNING, "Hangup received waiting for ring. Exiting simple switch\n");
2468                                                         ast_hangup(chan);
2469                                                         goto quit;
2470                                                 }
2471                                                 ast_frfree(f);
2472                                                 if (chan->_state == AST_STATE_RING ||
2473                                                         chan->_state == AST_STATE_RINGING)
2474                                                         break; /* Got ring */
2475                                         }
2476
2477                                         if (analog_distinctive_ring(chan, p, idx, NULL)) {
2478                                                 goto quit;
2479                                         }
2480
2481                                         if (res < 0) {
2482                                                 ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
2483                                         }
2484                                 } else {
2485                                         ast_log(LOG_WARNING, "Unable to get caller ID space\n");
2486                                 }
2487                         } else {
2488                                 ast_log(LOG_WARNING, "Channel %s in prering "
2489                                         "state, but I have nothing to do. "
2490                                         "Terminating simple switch, should be "
2491                                         "restarted by the actual ring.\n",
2492                                         chan->name);
2493                                 ast_hangup(chan);
2494                                 goto quit;
2495                         }
2496                 } else if (p->use_callerid && p->cid_start == ANALOG_CID_START_RING) {
2497                         int timeout = 10000;  /* Ten seconds */
2498                         struct timeval start = ast_tvnow();
2499                         enum analog_event ev;
2500                         int curRingData[RING_PATTERNS] = { 0 };
2501                         int receivedRingT = 0;
2502
2503                         namebuf[0] = 0;
2504                         numbuf[0] = 0;
2505
2506                         if (!analog_start_cid_detect(p, p->cid_signalling)) {
2507                                 while (1) {
2508                                         res = analog_get_callerid(p, namebuf, numbuf, &ev, timeout - ast_tvdiff_ms(ast_tvnow(), start));
2509
2510                                         if (res == 0) {
2511                                                 break;
2512                                         }
2513
2514                                         if (res == 1 || res == 2) {
2515                                                 if (ev == ANALOG_EVENT_NOALARM) {
2516                                                         analog_set_alarm(p, 0);
2517                                                 } else if (ev == ANALOG_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
2518                                                         ast_debug(1, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
2519                                                         p->polarity = POLARITY_IDLE;
2520                                                         ast_hangup(chan);
2521                                                         goto quit;
2522                                                 } else if (ev != ANALOG_EVENT_NONE && ev != ANALOG_EVENT_RINGBEGIN && ev != ANALOG_EVENT_RINGOFFHOOK) {
2523                                                         break;
2524                                                 }
2525                                                 if (res != 2) {
2526                                                         /* Let us detect callerid when the telco uses distinctive ring */
2527                                                         curRingData[receivedRingT] = p->ringt;
2528
2529                                                         if (p->ringt < p->ringt_base/2) {
2530                                                                 break;
2531                                                         }
2532                                                         /* Increment the ringT counter so we can match it against
2533                                                            values in chan_dahdi.conf for distinctive ring */
2534                                                         if (++receivedRingT == RING_PATTERNS) {
2535                                                                 break;
2536                                                         }
2537                                                 }
2538                                         }
2539
2540                                         if (ast_tvdiff_ms(ast_tvnow(), start) > timeout) {
2541                                                 break;
2542                                         }
2543
2544                                 }
2545                                 name = namebuf;
2546                                 number = numbuf;
2547
2548                                 analog_stop_cid_detect(p);
2549
2550                                 if (analog_distinctive_ring(chan, p, idx, curRingData)) {
2551                                         goto quit;
2552                                 }
2553
2554                                 if (res < 0) {
2555                                         ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
2556                                 }
2557                         } else {
2558                                 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
2559                         }
2560                 } else {
2561                         cs = NULL;
2562                 }
2563
2564                 if (number) {
2565                         ast_shrink_phone_number(number);
2566                 }
2567                 ast_set_callerid(chan, number, name, number);
2568
2569                 if (cs) {
2570                         callerid_free(cs);
2571                 }
2572
2573                 analog_handle_notify_message(chan, p, flags, -1);
2574
2575                 ast_setstate(chan, AST_STATE_RING);
2576                 chan->rings = 1;
2577                 analog_set_ringtimeout(p, p->ringt_base);
2578                 res = ast_pbx_run(chan);
2579                 if (res) {
2580                         ast_hangup(chan);
2581                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
2582                 }
2583                 goto quit;
2584         default:
2585                 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);
2586                 break;
2587         }
2588         res = analog_play_tone(p, idx, ANALOG_TONE_CONGESTION);
2589         if (res < 0) {
2590                 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
2591         }
2592         ast_hangup(chan);
2593 quit:
2594         if (smdi_msg) {
2595                 ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
2596         }
2597         analog_decrease_ss_count(p);
2598         return NULL;
2599 }
2600
2601 int analog_ss_thread_start(struct analog_pvt *p, struct ast_channel *chan)
2602 {
2603         pthread_t threadid;
2604
2605         return ast_pthread_create_detached(&threadid, NULL, __analog_ss_thread, p);
2606 }
2607
2608 static struct ast_frame *__analog_handle_event(struct analog_pvt *p, struct ast_channel *ast)
2609 {
2610         int res, x;
2611         int mysig;
2612         enum analog_sub idx;
2613         char *c;
2614         pthread_t threadid;
2615         struct ast_channel *chan;
2616         struct ast_frame *f;
2617
2618         ast_debug(1, "%s %d\n", __FUNCTION__, p->channel);
2619
2620         idx = analog_get_index(ast, p, 0);
2621         if (idx < 0) {
2622                 return &ast_null_frame;
2623         }
2624         if (idx != ANALOG_SUB_REAL) {
2625                 ast_log(LOG_ERROR, "We got an event on a non real sub.  Fix it!\n");
2626         }
2627
2628         mysig = p->sig;
2629         if (p->outsigmod > -1) {
2630                 mysig = p->outsigmod;
2631         }
2632
2633         p->subs[idx].f.frametype = AST_FRAME_NULL;
2634         p->subs[idx].f.subclass.integer = 0;
2635         p->subs[idx].f.datalen = 0;
2636         p->subs[idx].f.samples = 0;
2637         p->subs[idx].f.mallocd = 0;
2638         p->subs[idx].f.offset = 0;
2639         p->subs[idx].f.src = "dahdi_handle_event";
2640         p->subs[idx].f.data.ptr = NULL;
2641         f = &p->subs[idx].f;
2642
2643         res = analog_get_event(p);
2644
2645         ast_debug(1, "Got event %s(%d) on channel %d (index %d)\n", analog_event2str(res), res, p->channel, idx);
2646
2647         if (res & (ANALOG_EVENT_PULSEDIGIT | ANALOG_EVENT_DTMFUP)) {
2648                 analog_set_pulsedial(p, (res & ANALOG_EVENT_PULSEDIGIT) ? 1 : 0);
2649                 ast_debug(1, "Detected %sdigit '%c'\n", (res & ANALOG_EVENT_PULSEDIGIT) ? "pulse ": "", res & 0xff);
2650                 analog_confmute(p, 0);
2651                 p->subs[idx].f.frametype = AST_FRAME_DTMF_END;
2652                 p->subs[idx].f.subclass.integer = res & 0xff;
2653                 analog_handle_dtmf(p, ast, idx, &f);
2654                 return f;
2655         }
2656
2657         if (res & ANALOG_EVENT_DTMFDOWN) {
2658                 ast_debug(1, "DTMF Down '%c'\n", res & 0xff);
2659                 /* Mute conference */
2660                 analog_confmute(p, 1);
2661                 p->subs[idx].f.frametype = AST_FRAME_DTMF_BEGIN;
2662                 p->subs[idx].f.subclass.integer = res & 0xff;
2663                 analog_handle_dtmf(p, ast, idx, &f);
2664                 return f;
2665         }
2666
2667         switch (res) {
2668         case ANALOG_EVENT_EC_DISABLED:
2669                 ast_verb(3, "Channel %d echo canceler disabled due to CED detection\n", p->channel);
2670                 analog_set_echocanceller(p, 0);
2671                 break;
2672 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
2673         case ANALOG_EVENT_TX_CED_DETECTED:
2674                 ast_verb(3, "Channel %d detected a CED tone towards the network.\n", p->channel);
2675                 break;
2676         case ANALOG_EVENT_RX_CED_DETECTED:
2677                 ast_verb(3, "Channel %d detected a CED tone from the network.\n", p->channel);
2678                 break;
2679         case ANALOG_EVENT_EC_NLP_DISABLED:
2680                 ast_verb(3, "Channel %d echo canceler disabled its NLP.\n", p->channel);
2681                 break;
2682         case ANALOG_EVENT_EC_NLP_ENABLED:
2683                 ast_verb(3, "Channel %d echo canceler enabled its NLP.\n", p->channel);
2684                 break;
2685 #endif
2686         case ANALOG_EVENT_PULSE_START:
2687                 /* Stop tone if there's a pulse start and the PBX isn't started */
2688                 if (!ast->pbx)
2689                         analog_play_tone(p, ANALOG_SUB_REAL, -1);
2690                 break;
2691         case ANALOG_EVENT_DIALCOMPLETE:
2692                 if (p->inalarm) {
2693                         break;
2694                 }
2695                 x = analog_is_dialing(p, idx);
2696                 if (!x) { /* if not still dialing in driver */
2697                         analog_set_echocanceller(p, 1);
2698                         if (p->echobreak) {
2699                                 analog_train_echocanceller(p);
2700                                 ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
2701                                 p->dop.op = ANALOG_DIAL_OP_REPLACE;
2702                                 analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop);
2703                                 p->echobreak = 0;
2704                         } else {
2705                                 analog_set_dialing(p, 0);
2706                                 if ((mysig == ANALOG_SIG_E911) || (mysig == ANALOG_SIG_FGC_CAMA) || (mysig == ANALOG_SIG_FGC_CAMAMF)) {
2707                                         /* if thru with dialing after offhook */
2708                                         if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
2709                                                 ast_setstate(ast, AST_STATE_UP);
2710                                                 p->subs[idx].f.frametype = AST_FRAME_CONTROL;
2711                                                 p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
2712                                                 break;
2713                                         } else { /* if to state wait for offhook to dial rest */
2714                                                 /* we now wait for off hook */
2715                                                 ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
2716                                         }
2717                                 }
2718                                 if (ast->_state == AST_STATE_DIALING) {
2719                                         if (analog_check_confirmanswer(p) || (!p->dialednone
2720                                                 && ((mysig == ANALOG_SIG_EM) || (mysig == ANALOG_SIG_EM_E1)
2721                                                         || (mysig == ANALOG_SIG_EMWINK) || (mysig == ANALOG_SIG_FEATD)
2722                                                         || (mysig == ANALOG_SIG_FEATDMF_TA) || (mysig == ANALOG_SIG_FEATDMF)
2723                                                         || (mysig == ANALOG_SIG_E911) || (mysig == ANALOG_SIG_FGC_CAMA)
2724                                                         || (mysig == ANALOG_SIG_FGC_CAMAMF) || (mysig == ANALOG_SIG_FEATB)
2725                                                         || (mysig == ANALOG_SIG_SF) || (mysig == ANALOG_SIG_SFWINK)
2726                                                         || (mysig == ANALOG_SIG_SF_FEATD) || (mysig == ANALOG_SIG_SF_FEATDMF)
2727                                                         || (mysig == ANALOG_SIG_SF_FEATB)))) {
2728                                                 ast_setstate(ast, AST_STATE_RINGING);
2729                                         } else if (!p->answeronpolarityswitch) {
2730                                                 ast_setstate(ast, AST_STATE_UP);
2731                                                 p->subs[idx].f.frametype = AST_FRAME_CONTROL;
2732                                                 p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
2733                                                 /* If aops=0 and hops=1, this is necessary */
2734                                                 p->polarity = POLARITY_REV;
2735                                         } else {
2736                                                 /* Start clean, so we can catch the change to REV polarity when party answers */
2737                                                 p->polarity = POLARITY_IDLE;
2738                                         }
2739                                 }
2740                         }
2741                 }
2742                 break;
2743         case ANALOG_EVENT_ALARM:
2744                 analog_set_alarm(p, 1);
2745                 analog_get_and_handle_alarms(p);
2746         case ANALOG_EVENT_ONHOOK:
2747                 switch (p->sig) {
2748                 case ANALOG_SIG_FXOLS:
2749                 case ANALOG_SIG_FXOGS:
2750                 case ANALOG_SIG_FXOKS:
2751                         analog_start_polarityswitch(p);
2752                         p->fxsoffhookstate = 0;
2753                         p->onhooktime = time(NULL);
2754                         p->msgstate = -1;
2755                         /* Check for some special conditions regarding call waiting */
2756                         if (idx == ANALOG_SUB_REAL) {
2757                                 /* The normal line was hung up */
2758                                 if (p->subs[ANALOG_SUB_CALLWAIT].owner) {
2759                                         /* Need to hold the lock for real-call, private, and call-waiting call */
2760                                         analog_lock_sub_owner(p, ANALOG_SUB_CALLWAIT);
2761                                         if (!p->subs[ANALOG_SUB_CALLWAIT].owner) {
2762                                                 /*
2763                                                  * The call waiting call dissappeared.
2764                                                  * This is now a normal hangup.
2765                                                  */
2766                                                 analog_set_echocanceller(p, 0);
2767                                                 return NULL;
2768                                         }
2769
2770                                         /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
2771                                         analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_REAL);
2772                                         ast_verb(3, "Channel %d still has (callwait) call, ringing phone\n", p->channel);
2773                                         analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
2774                                         analog_stop_callwait(p);
2775                                         analog_set_new_owner(p, NULL);
2776                                         /* Don't start streaming audio yet if the incoming call isn't up yet */
2777                                         if (p->subs[ANALOG_SUB_REAL].owner->_state != AST_STATE_UP) {
2778                                                 analog_set_dialing(p, 1);
2779                                         }
2780                                         /* Unlock the call-waiting call that we swapped to real-call. */
2781                                         ast_channel_unlock(p->subs[ANALOG_SUB_REAL].owner);
2782                                         analog_ring(p);
2783                                 } else if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2784                                         unsigned int mssinceflash;
2785
2786                                         /* Need to hold the lock for real-call, private, and 3-way call */
2787                                         analog_lock_sub_owner(p, ANALOG_SUB_THREEWAY);
2788                                         if (!p->subs[ANALOG_SUB_THREEWAY].owner) {
2789                                                 ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
2790                                                 /* Just hangup */
2791                                                 return NULL;
2792                                         }
2793                                         if (p->owner != ast) {
2794                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2795                                                 ast_log(LOG_WARNING, "This isn't good...\n");
2796                                                 /* Just hangup */
2797                                                 return NULL;
2798                                         }
2799
2800                                         mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
2801                                         ast_debug(1, "Last flash was %d ms ago\n", mssinceflash);
2802                                         if (mssinceflash < MIN_MS_SINCE_FLASH) {
2803                                                 /* It hasn't been long enough since the last flashook.  This is probably a bounce on
2804                                                    hanging up.  Hangup both channels now */
2805                                                 ast_debug(1, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
2806                                                 ast_queue_hangup_with_cause(p->subs[ANALOG_SUB_THREEWAY].owner, AST_CAUSE_NO_ANSWER);
2807                                                 ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2808                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2809                                         } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
2810                                                 if (p->transfer) {
2811                                                         int inthreeway;
2812
2813                                                         inthreeway = p->subs[ANALOG_SUB_THREEWAY].inthreeway;
2814
2815                                                         /* In any case this isn't a threeway call anymore */
2816                                                         analog_set_inthreeway(p, ANALOG_SUB_REAL, 0);
2817                                                         analog_set_inthreeway(p, ANALOG_SUB_THREEWAY, 0);
2818
2819                                                         /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
2820                                                         if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
2821                                                                 /* Swap subs and dis-own channel */
2822                                                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2823                                                                 /* Unlock the 3-way call that we swapped to real-call. */
2824                                                                 ast_channel_unlock(p->subs[ANALOG_SUB_REAL].owner);
2825                                                                 analog_set_new_owner(p, NULL);
2826                                                                 /* Ring the phone */
2827                                                                 analog_ring(p);
2828                                                         } else {
2829                                                                 res = analog_attempt_transfer(p, inthreeway);
2830                                                                 if (res < 0) {
2831                                                                         /* Transfer attempt failed. */
2832                                                                         ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2833                                                                         ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2834                                                                 } else if (res) {
2835                                                                         /* Don't actually hang up at this point */
2836                                                                         break;
2837                                                                 }
2838                                                         }
2839                                                 } else {
2840                                                         ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2841                                                         ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2842                                                 }
2843                                         } else {
2844                                                 /* Swap subs and dis-own channel */
2845                                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2846                                                 /* Unlock the 3-way call that we swapped to real-call. */
2847                                                 ast_channel_unlock(p->subs[ANALOG_SUB_REAL].owner);
2848                                                 analog_set_new_owner(p, NULL);
2849                                                 /* Ring the phone */
2850                                                 analog_ring(p);
2851                                         }
2852                                 }
2853                         } else {
2854                                 ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", idx);
2855                         }
2856                         /* Fall through */
2857                 default:
2858                         analog_set_echocanceller(p, 0);
2859                         return NULL;
2860                 }
2861                 break;
2862         case ANALOG_EVENT_RINGOFFHOOK:
2863                 if (p->inalarm) {
2864                         break;
2865                 }
2866                 /* for E911, its supposed to wait for offhook then dial
2867                    the second half of the dial string */
2868                 if (((mysig == ANALOG_SIG_E911) || (mysig == ANALOG_SIG_FGC_CAMA) || (mysig == ANALOG_SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
2869                         c = strchr(p->dialdest, '/');
2870                         if (c) {
2871                                 c++;
2872                         } else {
2873                                 c = p->dialdest;
2874                         }
2875                         if (*c) {
2876                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
2877                         } else {
2878                                 ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
2879                         }
2880                         if (strlen(p->dop.dialstr) > 4) {
2881                                 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2882                                 strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2883                                 p->echorest[sizeof(p->echorest) - 1] = '\0';
2884                                 p->echobreak = 1;
2885                                 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2886                         } else {
2887                                 p->echobreak = 0;
2888                         }
2889                         if (analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop)) {
2890                                 int saveerr = errno;
2891                                 analog_on_hook(p);
2892                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
2893                                 return NULL;
2894                         }
2895                         analog_set_dialing(p, 1);
2896                         return &p->subs[idx].f;
2897                 }
2898                 switch (p->sig) {
2899                 case ANALOG_SIG_FXOLS:
2900                 case ANALOG_SIG_FXOGS:
2901                 case ANALOG_SIG_FXOKS:
2902                         p->fxsoffhookstate = 1;
2903                         switch (ast->_state) {
2904                         case AST_STATE_RINGING:
2905                                 analog_set_echocanceller(p, 1);
2906                                 analog_train_echocanceller(p);
2907                                 p->subs[idx].f.frametype = AST_FRAME_CONTROL;
2908                                 p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
2909                                 /* Make sure it stops ringing */
2910                                 analog_set_needringing(p, 0);
2911                                 analog_off_hook(p);
2912                                 ast_debug(1, "channel %d answered\n", p->channel);
2913
2914                                 /* Cancel any running CallerID spill */
2915                                 analog_cancel_cidspill(p);
2916
2917                                 analog_set_dialing(p, 0);
2918                                 p->callwaitcas = 0;
2919                                 if (analog_check_confirmanswer(p)) {
2920                                         /* Ignore answer if "confirm answer" is enabled */
2921                                         p->subs[idx].f.frametype = AST_FRAME_NULL;
2922                                         p->subs[idx].f.subclass.integer = 0;
2923                                 } else if (!ast_strlen_zero(p->dop.dialstr)) {
2924                                         /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
2925                                         res = analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop);
2926                                         if (res < 0) {
2927                                                 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
2928                                                 p->dop.dialstr[0] = '\0';
2929                                                 return NULL;
2930                                         } else {
2931                                                 ast_debug(1, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
2932                                                 p->subs[idx].f.frametype = AST_FRAME_NULL;
2933                                                 p->subs[idx].f.subclass.integer = 0;
2934                                                 analog_set_dialing(p, 1);
2935                                         }
2936                                         p->dop.dialstr[0] = '\0';
2937                                         ast_setstate(ast, AST_STATE_DIALING);
2938                                 } else {
2939                                         ast_setstate(ast, AST_STATE_UP);
2940                                         analog_answer_polarityswitch(p);
2941                                 }
2942                                 return &p->subs[idx].f;
2943                         case AST_STATE_DOWN:
2944                                 ast_setstate(ast, AST_STATE_RING);
2945                                 ast->rings = 1;
2946                                 p->subs[idx].f.frametype = AST_FRAME_CONTROL;
2947                                 p->subs[idx].f.subclass.integer = AST_CONTROL_OFFHOOK;
2948                                 ast_debug(1, "channel %d picked up\n", p->channel);
2949                                 return &p->subs[idx].f;
2950                         case AST_STATE_UP:
2951                                 /* Make sure it stops ringing */
2952                                 analog_off_hook(p);
2953                                 /* Okay -- probably call waiting*/
2954                                 if (ast_bridged_channel(p->owner)) {
2955                                         ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
2956                                 }
2957                                 break;
2958                         case AST_STATE_RESERVED:
2959                                 /* Start up dialtone */
2960                                 if (analog_has_voicemail(p)) {
2961                                         res = analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_STUTTER);
2962                                 } else {
2963                                         res = analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_DIALTONE);
2964                                 }
2965                                 break;
2966                         default:
2967                                 ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
2968                         }
2969                         break;
2970                 case ANALOG_SIG_FXSLS:
2971                 case ANALOG_SIG_FXSGS:
2972                 case ANALOG_SIG_FXSKS:
2973                         if (ast->_state == AST_STATE_RING) {
2974                                 analog_set_ringtimeout(p, p->ringt_base);
2975                         }
2976
2977                         /* Fall through */
2978                 case ANALOG_SIG_EM:
2979                 case ANALOG_SIG_EM_E1:
2980                 case ANALOG_SIG_EMWINK:
2981                 case ANALOG_SIG_FEATD:
2982                 case ANALOG_SIG_FEATDMF:
2983                 case ANALOG_SIG_FEATDMF_TA:
2984                 case ANALOG_SIG_E911:
2985                 case ANALOG_SIG_FGC_CAMA:
2986                 case ANALOG_SIG_FGC_CAMAMF:
2987                 case ANALOG_SIG_FEATB:
2988                 case ANALOG_SIG_SF:
2989                 case ANALOG_SIG_SFWINK:
2990                 case ANALOG_SIG_SF_FEATD:
2991                 case ANALOG_SIG_SF_FEATDMF:
2992                 case ANALOG_SIG_SF_FEATB:
2993                         switch (ast->_state) {
2994                         case AST_STATE_PRERING:
2995                                 ast_setstate(ast, AST_STATE_RING);
2996                                 /* Fall through */
2997                         case AST_STATE_DOWN:
2998                         case AST_STATE_RING:
2999                                 ast_debug(1, "Ring detected\n");
3000                                 p->subs[idx].f.frametype = AST_FRAME_CONTROL;
3001                                 p->subs[idx].f.subclass.integer = AST_CONTROL_RING;
3002                                 break;
3003                         case AST_STATE_RINGING:
3004                         case AST_STATE_DIALING:
3005                                 if (p->outgoing) {
3006                                         ast_debug(1, "Line answered\n");
3007                                         if (analog_check_confirmanswer(p)) {
3008                                                 p->subs[idx].f.frametype = AST_FRAME_NULL;
3009                                                 p->subs[idx].f.subclass.integer = 0;
3010                                         } else {
3011                                                 p->subs[idx].f.frametype = AST_FRAME_CONTROL;
3012                                                 p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
3013                                                 ast_setstate(ast, AST_STATE_UP);
3014                                         }
3015                                         break;
3016                                 }
3017                                 /* Fall through */
3018                         default:
3019                                 ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
3020                                 break;
3021                         }
3022                         break;
3023                 default:
3024                         ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
3025                         break;
3026                 }
3027                 break;
3028         case ANALOG_EVENT_RINGBEGIN:
3029                 switch (p->sig) {
3030                 case ANALOG_SIG_FXSLS:
3031                 case ANALOG_SIG_FXSGS:
3032                 case ANALOG_SIG_FXSKS:
3033                         if (ast->_state == AST_STATE_RING) {
3034                                 analog_set_ringtimeout(p, p->ringt_base);
3035                         }
3036                         break;
3037                 default:
3038                         break;
3039                 }
3040                 break;
3041         case ANALOG_EVENT_RINGEROFF:
3042                 if (p->inalarm) break;
3043                 ast->rings++;
3044                 if (ast->rings == p->cidrings) {
3045                         analog_send_callerid(p, 0, &p->caller);
3046                 }
3047
3048                 if (ast->rings > p->cidrings) {
3049                         analog_cancel_cidspill(p);
3050                         p->callwaitcas = 0;
3051                 }
3052                 p->subs[idx].f.frametype = AST_FRAME_CONTROL;
3053                 p->subs[idx].f.subclass.integer = AST_CONTROL_RINGING;
3054                 break;
3055         case ANALOG_EVENT_RINGERON:
3056                 break;
3057         case ANALOG_EVENT_NOALARM:
3058                 analog_set_alarm(p, 0);
3059                 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
3060                 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
3061                         "Channel: %d\r\n", p->channel);
3062                 break;
3063         case ANALOG_EVENT_WINKFLASH:
3064                 if (p->inalarm) {
3065                         break;
3066                 }
3067                 /* Remember last time we got a flash-hook */
3068                 gettimeofday(&p->flashtime, NULL);
3069                 switch (mysig) {
3070                 case ANALOG_SIG_FXOLS:
3071                 case ANALOG_SIG_FXOGS:
3072                 case ANALOG_SIG_FXOKS:
3073                         ast_debug(1, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
3074                                 idx, analog_get_sub_fd(p, ANALOG_SUB_REAL), analog_get_sub_fd(p, ANALOG_SUB_CALLWAIT), analog_get_sub_fd(p, ANALOG_SUB_THREEWAY));
3075
3076                         /* Cancel any running CallerID spill */
3077                         analog_cancel_cidspill(p);
3078                         p->callwaitcas = 0;
3079
3080                         if (idx != ANALOG_SUB_REAL) {
3081                                 ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", idx, p->channel);
3082                                 goto winkflashdone;
3083                         }