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