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