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