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