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