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