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