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