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