New signaling module to handle PRI/BRI operations in chan_dahdi
[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)
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);
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)
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);
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         case ANALOG_SIG_EMWINK:
792         case ANALOG_SIG_EM:
793         case ANALOG_SIG_EM_E1:
794         case ANALOG_SIG_FEATD:
795         case ANALOG_SIG_FEATDMF:
796         case ANALOG_SIG_E911:
797         case ANALOG_SIG_FGC_CAMA:
798         case ANALOG_SIG_FGC_CAMAMF:
799         case ANALOG_SIG_FEATB:
800         case ANALOG_SIG_SFWINK:
801         case ANALOG_SIG_SF:
802         case ANALOG_SIG_SF_FEATD:
803         case ANALOG_SIG_SF_FEATDMF:
804         case ANALOG_SIG_FEATDMF_TA:
805         case ANALOG_SIG_SF_FEATB:
806                 c = strchr(dest, '/');
807                 if (c)
808                         c++;
809                 else
810                         c = "";
811                 if (strlen(c) < p->stripmsd) {
812                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
813                         return -1;
814                 }
815                 res = analog_start(p);
816                 if (res < 0) {
817                         if (errno != EINPROGRESS) {
818                                 return -1;
819                         }
820                 }
821                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
822                 p->dop.op = ANALOG_DIAL_OP_REPLACE;
823
824                 c += p->stripmsd;
825
826                 switch (mysig) {
827                 case ANALOG_SIG_FEATD:
828                         l = ast->connected.id.number;
829                         if (l) 
830                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
831                         else
832                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
833                         break;
834                 case ANALOG_SIG_FEATDMF:
835                         l = ast->connected.id.number;
836                         if (l) 
837                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
838                         else
839                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
840                         break;
841                 case ANALOG_SIG_FEATDMF_TA:
842                 {
843                         const char *cic = "", *ozz = "";
844
845                         /* If you have to go through a Tandem Access point you need to use this */
846 #ifndef STANDALONE
847                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
848                         if (!ozz)
849                                 ozz = analog_defaultozz;
850                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
851                         if (!cic)
852                                 cic = analog_defaultcic;
853 #endif
854                         if (!ozz || !cic) {
855                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
856                                 return -1;
857                         }
858                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
859                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
860                         p->whichwink = 0;
861                 }
862                         break;
863                 case ANALOG_SIG_E911:
864                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
865                         break;
866                 case ANALOG_SIG_FGC_CAMA:
867                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
868                         break;
869                 case ANALOG_SIG_FGC_CAMAMF:
870                 case ANALOG_SIG_FEATB:
871                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
872                         break;
873                 default:
874                         if (p->pulse)
875                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
876                         else
877                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
878                         break;
879                 }
880
881                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
882                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
883                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
884                         p->echorest[sizeof(p->echorest) - 1] = '\0';
885                         p->echobreak = 1;
886                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
887                 } else
888                         p->echobreak = 0;
889                 if (!res) {
890                         if (analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop)) {
891                                 int saveerr = errno;
892
893                                 analog_on_hook(p);
894                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
895                                 return -1;
896                         }
897                 } else
898                         ast_debug(1, "Deferring dialing...\n");
899                 p->dialing = 1;
900                 if (ast_strlen_zero(c))
901                         p->dialednone = 1;
902                 ast_setstate(ast, AST_STATE_DIALING);
903                 break;
904         default:
905                 ast_debug(1, "not yet implemented\n");
906                 return -1;
907         }
908         return 0;
909 }
910
911 int analog_hangup(struct analog_pvt *p, struct ast_channel *ast)
912 {
913         int res;
914         int index, x;
915
916         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
917         if (!ast->tech_pvt) {
918                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
919                 return 0;
920         }
921
922         index = analog_get_index(ast, p, 1);
923
924         x = 0;
925         if (p->origcid_num) {
926                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
927                 free(p->origcid_num);
928                 p->origcid_num = NULL;
929         }
930         if (p->origcid_name) {
931                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
932                 free(p->origcid_name);
933                 p->origcid_name = NULL;
934         }
935
936         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
937
938         ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
939                 p->channel, index, p->subs[ANALOG_SUB_REAL].allocd, p->subs[ANALOG_SUB_CALLWAIT].allocd, p->subs[ANALOG_SUB_THREEWAY].allocd);
940         if (index > -1) {
941                 /* Real channel, do some fixup */
942                 p->subs[index].owner = NULL;
943                 p->subs[index].needcallerid = 0;
944                 p->polarity = POLARITY_IDLE;
945                 if (index == ANALOG_SUB_REAL) {
946                         if (p->subs[ANALOG_SUB_CALLWAIT].allocd && p->subs[ANALOG_SUB_THREEWAY].allocd) {
947                                 ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
948                                 if (p->subs[ANALOG_SUB_CALLWAIT].inthreeway) {
949                                         /* We had flipped over to answer a callwait and now it's gone */
950                                         ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
951                                         /* Move to the call-wait, but un-own us until they flip back. */
952                                         analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_REAL);
953                                         analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
954                                         p->owner = NULL;
955                                 } else {
956                                         /* The three way hung up, but we still have a call wait */
957                                         ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
958                                         analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
959                                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
960                                         if (p->subs[ANALOG_SUB_REAL].inthreeway) {
961                                                 /* This was part of a three way call.  Immediately make way for
962                                                    another call */
963                                                 ast_debug(1, "Call was complete, setting owner to former third call\n");
964                                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
965                                         } else {
966                                                 /* This call hasn't been completed yet...  Set owner to NULL */
967                                                 ast_debug(1, "Call was incomplete, setting owner to NULL\n");
968                                                 p->owner = NULL;
969                                         }
970                                         p->subs[ANALOG_SUB_REAL].inthreeway = 0;
971                                 }
972                         } else if (p->subs[ANALOG_SUB_CALLWAIT].allocd) {
973                                 /* Move to the call-wait and switch back to them. */
974                                 analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_REAL);
975                                 analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
976                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
977                                 if (p->owner->_state != AST_STATE_UP)
978                                         ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_ANSWER);
979                                 if (ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner))
980                                         ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_UNHOLD);
981                         } else if (p->subs[ANALOG_SUB_THREEWAY].allocd) {
982                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
983                                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
984                                 if (p->subs[ANALOG_SUB_REAL].inthreeway) {
985                                         /* This was part of a three way call.  Immediately make way for
986                                            another call */
987                                         ast_debug(1, "Call was complete, setting owner to former third call\n");
988                                         p->owner = p->subs[ANALOG_SUB_REAL].owner;
989                                 } else {
990                                         /* This call hasn't been completed yet...  Set owner to NULL */
991                                         ast_debug(1, "Call was incomplete, setting owner to NULL\n");
992                                         p->owner = NULL;
993                                 }
994                                 p->subs[ANALOG_SUB_REAL].inthreeway = 0;
995                         }
996                 } else if (index == ANALOG_SUB_CALLWAIT) {
997                         /* Ditch the holding callwait call, and immediately make it availabe */
998                         if (p->subs[ANALOG_SUB_CALLWAIT].inthreeway) {
999                                 /* This is actually part of a three way, placed on hold.  Place the third part
1000                                    on music on hold now */
1001                                 if (p->subs[ANALOG_SUB_THREEWAY].owner && ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)) {
1002                                         ast_queue_control_data(p->subs[ANALOG_SUB_THREEWAY].owner, AST_CONTROL_HOLD, 
1003                                                 S_OR(p->mohsuggest, NULL),
1004                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
1005                                 }
1006                                 p->subs[ANALOG_SUB_THREEWAY].inthreeway = 0;
1007                                 /* Make it the call wait now */
1008                                 analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_THREEWAY);
1009                                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1010                         } else
1011                                 analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
1012                 } else if (index == ANALOG_SUB_THREEWAY) {
1013                         if (p->subs[ANALOG_SUB_CALLWAIT].inthreeway) {
1014                                 /* The other party of the three way call is currently in a call-wait state.
1015                                    Start music on hold for them, and take the main guy out of the third call */
1016                                 if (p->subs[ANALOG_SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[ANALOG_SUB_CALLWAIT].owner)) {
1017                                         ast_queue_control_data(p->subs[ANALOG_SUB_CALLWAIT].owner, AST_CONTROL_HOLD, 
1018                                                 S_OR(p->mohsuggest, NULL),
1019                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
1020                                 }
1021                                 p->subs[ANALOG_SUB_CALLWAIT].inthreeway = 0;
1022                         }
1023                         p->subs[ANALOG_SUB_REAL].inthreeway = 0;
1024                         /* If this was part of a three way call index, let us make
1025                            another three way call */
1026                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1027                 } else {
1028                         /* This wasn't any sort of call, but how are we an index? */
1029                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
1030                 }
1031         }
1032
1033         if (!p->subs[ANALOG_SUB_REAL].owner && !p->subs[ANALOG_SUB_CALLWAIT].owner && !p->subs[ANALOG_SUB_THREEWAY].owner) {
1034                 p->owner = NULL;
1035 #if 0
1036                 p->ringt = 0;
1037 #endif
1038 #if 0 /* Since we set it in _call */
1039                 p->cidrings = 1;
1040 #endif
1041                 p->outgoing = 0;
1042
1043                 /* Perform low level hangup if no owner left */
1044                 res = analog_on_hook(p);
1045                 if (res < 0) {
1046                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
1047                 }
1048                 switch (p->sig) {
1049                 case ANALOG_SIG_FXOGS:
1050                 case ANALOG_SIG_FXOLS:
1051                 case ANALOG_SIG_FXOKS:
1052                         /* If they're off hook, try playing congestion */
1053                         if (analog_is_off_hook(p))
1054                                 analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_CONGESTION);
1055                         else
1056                                 analog_play_tone(p, ANALOG_SUB_REAL, -1);
1057                         break;
1058                 case ANALOG_SIG_FXSGS:
1059                 case ANALOG_SIG_FXSLS:
1060                 case ANALOG_SIG_FXSKS:
1061                         /* Make sure we're not made available for at least two seconds assuming
1062                            we were actually used for an inbound or outbound call. */
1063                         if (ast->_state != AST_STATE_RESERVED) {
1064                                 time(&p->guardtime);
1065                                 p->guardtime += 2;
1066                         }
1067                         break;
1068                 default:
1069                         analog_play_tone(p, ANALOG_SUB_REAL, -1);
1070                 }
1071
1072
1073                 analog_set_echocanceller(p, 0);
1074
1075                 x = 0;
1076                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
1077                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
1078                 p->callwaitcas = 0;
1079                 p->callwaiting = p->permcallwaiting;
1080                 p->hidecallerid = p->permhidecallerid;
1081                 p->dialing = 0;
1082                 analog_update_conf(p);
1083                 analog_all_subchannels_hungup(p);
1084         }
1085
1086         analog_stop_callwait(p);
1087         ast->tech_pvt = NULL;
1088
1089         ast_verb(3, "Hanging up on '%s'\n", ast->name);
1090
1091         return 0;
1092 }
1093
1094 int analog_answer(struct analog_pvt *p, struct ast_channel *ast)
1095 {
1096         int res = 0;
1097         int index;
1098         int oldstate = ast->_state;
1099         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
1100         ast_setstate(ast, AST_STATE_UP);
1101         index = analog_get_index(ast, p, 1);
1102         if (index < 0)
1103                 index = ANALOG_SUB_REAL;
1104         switch (p->sig) {
1105         case ANALOG_SIG_FXSLS:
1106         case ANALOG_SIG_FXSGS:
1107         case ANALOG_SIG_FXSKS:
1108 #if 0
1109                 p->ringt = 0;
1110 #endif
1111                 /* Fall through */
1112         case ANALOG_SIG_EM:
1113         case ANALOG_SIG_EM_E1:
1114         case ANALOG_SIG_EMWINK:
1115         case ANALOG_SIG_FEATD:
1116         case ANALOG_SIG_FEATDMF:
1117         case ANALOG_SIG_FEATDMF_TA:
1118         case ANALOG_SIG_E911:
1119         case ANALOG_SIG_FGC_CAMA:
1120         case ANALOG_SIG_FGC_CAMAMF:
1121         case ANALOG_SIG_FEATB:
1122         case ANALOG_SIG_SF:
1123         case ANALOG_SIG_SFWINK:
1124         case ANALOG_SIG_SF_FEATD:
1125         case ANALOG_SIG_SF_FEATDMF:
1126         case ANALOG_SIG_SF_FEATB:
1127         case ANALOG_SIG_FXOLS:
1128         case ANALOG_SIG_FXOGS:
1129         case ANALOG_SIG_FXOKS:
1130                 /* Pick up the line */
1131                 ast_debug(1, "Took %s off hook\n", ast->name);
1132                 if (p->hanguponpolarityswitch) {
1133                         gettimeofday(&p->polaritydelaytv, NULL);
1134                 }
1135                 res = analog_off_hook(p);
1136                 analog_play_tone(p, index, -1);
1137                 p->dialing = 0;
1138                 if ((index == ANALOG_SUB_REAL) && p->subs[ANALOG_SUB_THREEWAY].inthreeway) {
1139                         if (oldstate == AST_STATE_RINGING) {
1140                                 ast_debug(1, "Finally swapping real and threeway\n");
1141                                 analog_play_tone(p, ANALOG_SUB_THREEWAY, -1);
1142                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
1143                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
1144                         }
1145                 }
1146                 if ((p->sig == ANALOG_SIG_FXSLS) || (p->sig == ANALOG_SIG_FXSKS) || (p->sig == ANALOG_SIG_FXSGS)) {
1147                         analog_set_echocanceller(p, 1);
1148                         analog_train_echocanceller(p);
1149                 }
1150                 break;
1151         default:
1152                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
1153                 res = -1;
1154         }
1155         ast_setstate(ast, AST_STATE_UP);
1156         return res;
1157 }
1158
1159 static int analog_handles_digit(struct ast_frame *f)
1160 {
1161         char subclass = toupper(f->subclass);
1162
1163         switch (subclass) {
1164         case '1':
1165         case '2':
1166         case '3':
1167         case '4':
1168         case '5':
1169         case '6':
1170         case '7':
1171         case '9':
1172         case 'A':
1173         case 'B':
1174         case 'C':
1175         case 'D':
1176         case 'E':
1177         case 'F':
1178                 return 1;
1179         default:
1180                 return 0;
1181         }
1182 }
1183
1184 void analog_handle_dtmfup(struct analog_pvt *p, struct ast_channel *ast, enum analog_sub index, struct ast_frame **dest)
1185 {
1186         struct ast_frame *f = *dest;
1187
1188         if (p->callwaitcas) {
1189                 if ((f->subclass == 'A') || (f->subclass == 'D')) {
1190                         ast_log(LOG_ERROR, "Got some DTMF, but it's for the CAS\n");
1191                         p->cid.cid_name = p->callwait_name;
1192                         p->cid.cid_num = p->callwait_num;
1193                         analog_send_callerid(p, 1, &p->cid);
1194                 }
1195                 if (analog_handles_digit(f))
1196                         p->callwaitcas = 0;
1197                 p->subs[index].f.frametype = AST_FRAME_NULL;
1198                 p->subs[index].f.subclass = 0;
1199                 *dest = &p->subs[index].f;
1200         } else {
1201                 analog_cb_handle_dtmfup(p, ast, index, dest);
1202         }
1203 }
1204
1205 static int analog_my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
1206 {
1207         char c;
1208
1209         *str = 0; /* start with empty output buffer */
1210         for (;;)
1211         {
1212                 /* Wait for the first digit (up to specified ms). */
1213                 c = ast_waitfordigit(chan, ms);
1214                 /* if timeout, hangup or error, return as such */
1215                 if (c < 1)
1216                         return c;
1217                 *str++ = c;
1218                 *str = 0;
1219                 if (strchr(term, c))
1220                         return 1;
1221         }
1222 }
1223
1224 static int analog_handle_notify_message(struct ast_channel *chan, struct analog_pvt *p, int cid_flags, int neon_mwievent)
1225 {
1226         if (p->calls->handle_notify_message) {
1227                 p->calls->handle_notify_message(chan, p->chan_pvt, cid_flags, neon_mwievent);
1228                 return 0;
1229         }
1230         else
1231                 return -1;
1232 }
1233
1234 static int analog_increase_ss_count(struct analog_pvt *p)
1235 {
1236         if (p->calls->increase_ss_count) {
1237                 p->calls->increase_ss_count();
1238                 return 0;
1239         } else
1240                 return -1;
1241 }
1242
1243 static int analog_decrease_ss_count(struct analog_pvt *p)
1244 {
1245         if (p->calls->decrease_ss_count) {
1246                 p->calls->decrease_ss_count();
1247                 return 0;
1248         } else
1249                 return -1;
1250 }
1251
1252 #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))
1253
1254 /* Note by jpeeler: This function has a rather large section of code ifdefed
1255  * away. I'd like to leave the code there until more testing is done and I
1256  * know for sure that nothing got left out. The plan is at the latest for this
1257  * comment and code below to be removed shortly after the merging of sig_pri.
1258  */
1259 static void *__analog_ss_thread(void *data)
1260 {
1261         struct analog_pvt *p = data;
1262         struct ast_channel *chan = p->ss_astchan;
1263         char exten[AST_MAX_EXTENSION] = "";
1264         char exten2[AST_MAX_EXTENSION] = "";
1265         char dtmfcid[300];
1266         char dtmfbuf[300];
1267         char namebuf[ANALOG_MAX_CID];
1268         char numbuf[ANALOG_MAX_CID];
1269         struct callerid_state *cs = NULL;
1270         char *name = NULL, *number = NULL;
1271         int flags;
1272 #if 0
1273         unsigned char buf[256];
1274         int distMatches;
1275         int curRingData[3];
1276         int receivedRingT;
1277         int samples = 0;
1278         int counter1;
1279         int counter;
1280         int i;
1281 #endif
1282         int timeout;
1283         int getforward = 0;
1284         char *s1, *s2;
1285         int len = 0;
1286         int res;
1287         int index;
1288
1289         analog_increase_ss_count(p);
1290
1291         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
1292
1293         /* in the bizarre case where the channel has become a zombie before we
1294            even get started here, abort safely
1295         */
1296         if (!p) {
1297                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1298                 ast_hangup(chan);
1299                 goto quit;
1300         }
1301
1302         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1303         index = analog_get_index(chan, p, 1);
1304         if (index < 0) {
1305                 ast_log(LOG_WARNING, "Huh?\n");
1306                 ast_hangup(chan);
1307                 goto quit;
1308         }
1309         analog_dsp_reset_and_flush_digits(p);
1310         switch (p->sig) {
1311         case ANALOG_SIG_FEATD:
1312         case ANALOG_SIG_FEATDMF:
1313         case ANALOG_SIG_FEATDMF_TA:
1314         case ANALOG_SIG_E911:
1315         case ANALOG_SIG_FGC_CAMAMF:
1316         case ANALOG_SIG_FEATB:
1317         case ANALOG_SIG_EMWINK:
1318         case ANALOG_SIG_SF_FEATD:
1319         case ANALOG_SIG_SF_FEATDMF:
1320         case ANALOG_SIG_SF_FEATB:
1321         case ANALOG_SIG_SFWINK:
1322                 if (analog_wink(p, index))
1323                         goto quit;
1324                 /* Fall through */
1325         case ANALOG_SIG_EM:
1326         case ANALOG_SIG_EM_E1:
1327         case ANALOG_SIG_SF:
1328         case ANALOG_SIG_FGC_CAMA:
1329                 res = analog_play_tone(p, index, -1);
1330
1331                 analog_dsp_reset_and_flush_digits(p);
1332
1333                 if (ANALOG_NEED_MFDETECT(p)) {
1334                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_MF);
1335                 } else
1336                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1337
1338                 memset(dtmfbuf, 0, sizeof(dtmfbuf));
1339                 /* Wait for the first digit only if immediate=no */
1340                 if (!p->immediate)
1341                         /* Wait for the first digit (up to 5 seconds). */
1342                         res = ast_waitfordigit(chan, 5000);
1343                 else
1344                         res = 0;
1345                 if (res > 0) {
1346                         /* save first char */
1347                         dtmfbuf[0] = res;
1348                         switch (p->sig) {
1349                         case ANALOG_SIG_FEATD:
1350                         case ANALOG_SIG_SF_FEATD:
1351                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
1352                                 if (res > 0)
1353                                         res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
1354                                 if (res < 1)
1355                                         analog_dsp_reset_and_flush_digits(p);
1356                                 break;
1357                         case ANALOG_SIG_FEATDMF_TA:
1358                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1359                                 if (res < 1)
1360                                         analog_dsp_reset_and_flush_digits(p);
1361                                 if (analog_wink(p, index)) goto quit;
1362                                 dtmfbuf[0] = 0;
1363                                 /* Wait for the first digit (up to 5 seconds). */
1364                                 res = ast_waitfordigit(chan, 5000);
1365                                 if (res <= 0) break;
1366                                 dtmfbuf[0] = res;
1367                                 /* fall through intentionally */
1368                         case ANALOG_SIG_FEATDMF:
1369                         case ANALOG_SIG_E911:
1370                         case ANALOG_SIG_FGC_CAMAMF:
1371                         case ANALOG_SIG_SF_FEATDMF:
1372                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1373                                 /* if international caca, do it again to get real ANO */
1374                                 if ((p->sig == ANALOG_SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
1375                                 {
1376                                         if (analog_wink(p, index)) goto quit;
1377                                         dtmfbuf[0] = 0;
1378                                         /* Wait for the first digit (up to 5 seconds). */
1379                                         res = ast_waitfordigit(chan, 5000);
1380                                         if (res <= 0) break;
1381                                         dtmfbuf[0] = res;
1382                                         res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1383                                 }
1384                                 if (res > 0) {
1385                                         /* if E911, take off hook */
1386                                         if (p->sig == ANALOG_SIG_E911)
1387                                                 analog_off_hook(p);
1388                                         res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
1389                                 }
1390                                 if (res < 1)
1391                                         analog_dsp_reset_and_flush_digits(p);
1392                                 break;
1393                         case ANALOG_SIG_FEATB:
1394                         case ANALOG_SIG_SF_FEATB:
1395                                 res = analog_my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
1396                                 if (res < 1)
1397                                         analog_dsp_reset_and_flush_digits(p);
1398                                 break;
1399                         case ANALOG_SIG_EMWINK:
1400                                 /* if we received a '*', we are actually receiving Feature Group D
1401                                    dial syntax, so use that mode; otherwise, fall through to normal
1402                                    mode
1403                                 */
1404                                 if (res == '*') {
1405                                         res = analog_my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
1406                                         if (res > 0)
1407                                                 res = analog_my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
1408                                         if (res < 1)
1409                                                 analog_dsp_reset_and_flush_digits(p);
1410                                         break;
1411                                 }
1412                         default:
1413                                 /* If we got the first digit, get the rest */
1414                                 len = 1;
1415                                 dtmfbuf[len] = '\0';
1416                                 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
1417                                         if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
1418                                                 timeout = analog_matchdigittimeout;
1419                                         } else {
1420                                                 timeout = analog_gendigittimeout;
1421                                         }
1422                                         res = ast_waitfordigit(chan, timeout);
1423                                         if (res < 0) {
1424                                                 ast_debug(1, "waitfordigit returned < 0...\n");
1425                                                 ast_hangup(chan);
1426                                                 goto quit;
1427                                         } else if (res) {
1428                                                 dtmfbuf[len++] = res;
1429                                                 dtmfbuf[len] = '\0';
1430                                         } else {
1431                                                 break;
1432                                         }
1433                                 }
1434                                 break;
1435                         }
1436                 }
1437                 if (res == -1) {
1438                         ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
1439                         ast_hangup(chan);
1440                         goto quit;
1441                 } else if (res < 0) {
1442                         ast_debug(1, "Got hung up before digits finished\n");
1443                         ast_hangup(chan);
1444                         goto quit;
1445                 }
1446
1447                 if (p->sig == ANALOG_SIG_FGC_CAMA) {
1448                         char anibuf[100];
1449
1450                         if (ast_safe_sleep(chan,1000) == -1) {
1451                                 ast_hangup(chan);
1452                                 goto quit;
1453                         }
1454                         analog_off_hook(p);
1455                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_MF);
1456                         res = analog_my_getsigstr(chan, anibuf, "#", 10000);
1457                         if ((res > 0) && (strlen(anibuf) > 2)) {
1458                                 if (anibuf[strlen(anibuf) - 1] == '#')
1459                                         anibuf[strlen(anibuf) - 1] = 0;
1460                                 ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
1461                         }
1462                         analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1463                 }
1464
1465                 ast_copy_string(exten, dtmfbuf, sizeof(exten));
1466                 if (ast_strlen_zero(exten))
1467                         ast_copy_string(exten, "s", sizeof(exten));
1468                 if (p->sig == ANALOG_SIG_FEATD || p->sig == ANALOG_SIG_EMWINK) {
1469                         /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
1470                         if (exten[0] == '*') {
1471                                 char *stringp=NULL;
1472                                 ast_copy_string(exten2, exten, sizeof(exten2));
1473                                 /* Parse out extension and callerid */
1474                                 stringp=exten2 +1;
1475                                 s1 = strsep(&stringp, "*");
1476                                 s2 = strsep(&stringp, "*");
1477                                 if (s2) {
1478                                         if (!ast_strlen_zero(p->cid_num))
1479                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
1480                                         else
1481                                                 ast_set_callerid(chan, s1, NULL, s1);
1482                                         ast_copy_string(exten, s2, sizeof(exten));
1483                                 } else
1484                                         ast_copy_string(exten, s1, sizeof(exten));
1485                         } else if (p->sig == ANALOG_SIG_FEATD)
1486                                 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1487                 }
1488                 if ((p->sig == ANALOG_SIG_FEATDMF) || (p->sig == ANALOG_SIG_FEATDMF_TA)) {
1489                         if (exten[0] == '*') {
1490                                 char *stringp=NULL;
1491                                 ast_copy_string(exten2, exten, sizeof(exten2));
1492                                 /* Parse out extension and callerid */
1493                                 stringp=exten2 +1;
1494                                 s1 = strsep(&stringp, "#");
1495                                 s2 = strsep(&stringp, "#");
1496                                 if (s2) {
1497                                         if (!ast_strlen_zero(p->cid_num))
1498                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
1499                                         else
1500                                                 if (*(s1 + 2))
1501                                                         ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
1502                                         ast_copy_string(exten, s2 + 1, sizeof(exten));
1503                                 } else
1504                                         ast_copy_string(exten, s1 + 2, sizeof(exten));
1505                         } else
1506                                 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1507                 }
1508                 if ((p->sig == ANALOG_SIG_E911) || (p->sig == ANALOG_SIG_FGC_CAMAMF)) {
1509                         if (exten[0] == '*') {
1510                                 char *stringp=NULL;
1511                                 ast_copy_string(exten2, exten, sizeof(exten2));
1512                                 /* Parse out extension and callerid */
1513                                 stringp=exten2 +1;
1514                                 s1 = strsep(&stringp, "#");
1515                                 s2 = strsep(&stringp, "#");
1516                                 if (s2 && (*(s2 + 1) == '0')) {
1517                                         if (*(s2 + 2))
1518                                                 ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
1519                                 }
1520                                 if (s1) ast_copy_string(exten, s1, sizeof(exten));
1521                                 else ast_copy_string(exten, "911", sizeof(exten));
1522                         } else
1523                                 ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1524                 }
1525                 if (p->sig == ANALOG_SIG_FEATB) {
1526                         if (exten[0] == '*') {
1527                                 char *stringp=NULL;
1528                                 ast_copy_string(exten2, exten, sizeof(exten2));
1529                                 /* Parse out extension and callerid */
1530                                 stringp=exten2 +1;
1531                                 s1 = strsep(&stringp, "#");
1532                                 ast_copy_string(exten, exten2 + 1, sizeof(exten));
1533                         } else
1534                                 ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
1535                 }
1536                 if ((p->sig == ANALOG_SIG_FEATDMF) || (p->sig == ANALOG_SIG_FEATDMF_TA)) {
1537                         analog_wink(p, index);
1538                         /* some switches require a minimum guard time between
1539                         the last FGD wink and something that answers
1540                         immediately. This ensures it */
1541                         if (ast_safe_sleep(chan,100)) goto quit;
1542                 }
1543                 analog_set_echocanceller(p, 1);
1544
1545                 analog_dsp_set_digitmode(p, ANALOG_DIGITMODE_DTMF);
1546
1547                 if (ast_exists_extension(chan, chan->context, exten, 1, chan->cid.cid_num)) {
1548                         ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1549                         analog_dsp_reset_and_flush_digits(p);
1550                         res = ast_pbx_run(chan);
1551                         if (res) {
1552                                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
1553                                 res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1554                         }
1555                         goto quit;
1556                 } else {
1557                         ast_verb(3, "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
1558                         sleep(2);
1559                         res = analog_play_tone(p, index, ANALOG_TONE_INFO);
1560                         if (res < 0)
1561                                 ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
1562                         else
1563                                 sleep(1);
1564                         res = ast_streamfile(chan, "ss-noservice", chan->language);
1565                         if (res >= 0)
1566                                 ast_waitstream(chan, "");
1567                         res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1568                         ast_hangup(chan);
1569                         goto quit;
1570                 }
1571                 break;
1572         case ANALOG_SIG_FXOLS:
1573         case ANALOG_SIG_FXOGS:
1574         case ANALOG_SIG_FXOKS:
1575                 /* Read the first digit */
1576                 timeout = analog_firstdigittimeout;
1577                 /* If starting a threeway call, never timeout on the first digit so someone
1578                    can use flash-hook as a "hold" feature */
1579                 if (p->subs[ANALOG_SUB_THREEWAY].owner) 
1580                         timeout = 999999;
1581                 while (len < AST_MAX_EXTENSION-1) {
1582                         /* Read digit unless it's supposed to be immediate, in which case the
1583                            only answer is 's' */
1584                         if (p->immediate) 
1585                                 res = 's';
1586                         else
1587                                 res = ast_waitfordigit(chan, timeout);
1588                         timeout = 0;
1589                         if (res < 0) {
1590                                 ast_debug(1, "waitfordigit returned < 0...\n");
1591                                 res = analog_play_tone(p, index, -1);
1592                                 ast_hangup(chan);
1593                                 goto quit;
1594                         } else if (res)  {
1595                                 exten[len++]=res;
1596                                 exten[len] = '\0';
1597                         }
1598                         if (!ast_ignore_pattern(chan->context, exten))
1599                                 analog_play_tone(p, index, -1);
1600                         else
1601                                 analog_play_tone(p, index, ANALOG_TONE_DIALTONE);
1602                         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && strcmp(exten, ast_parking_ext())) {
1603                                 if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1604                                         if (getforward) {
1605                                                 /* Record this as the forwarding extension */
1606                                                 ast_copy_string(p->call_forward, exten, sizeof(p->call_forward)); 
1607                                                 ast_verb(3, "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
1608                                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1609                                                 if (res)
1610                                                         break;
1611                                                 usleep(500000);
1612                                                 res = analog_play_tone(p, index, -1);
1613                                                 sleep(1);
1614                                                 memset(exten, 0, sizeof(exten));
1615                                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALTONE);
1616                                                 len = 0;
1617                                                 getforward = 0;
1618                                         } else  {
1619                                                 res = analog_play_tone(p, index, -1);
1620                                                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1621                                                 if (!ast_strlen_zero(p->cid_num)) {
1622                                                         if (!p->hidecallerid)
1623                                                                 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num); 
1624                                                         else
1625                                                                 ast_set_callerid(chan, NULL, NULL, p->cid_num); 
1626                                                 }
1627                                                 if (!ast_strlen_zero(p->cid_name)) {
1628                                                         if (!p->hidecallerid)
1629                                                                 ast_set_callerid(chan, NULL, p->cid_name, NULL);
1630                                                 }
1631                                                 ast_setstate(chan, AST_STATE_RING);
1632                                                 analog_set_echocanceller(p, 1);
1633                                                 res = ast_pbx_run(chan);
1634                                                 if (res) {
1635                                                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
1636                                                         res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1637                                                 }
1638                                                 goto quit;
1639                                         }
1640                                 } else {
1641                                         /* It's a match, but they just typed a digit, and there is an ambiguous match,
1642                                            so just set the timeout to analog_matchdigittimeout and wait some more */
1643                                         timeout = analog_matchdigittimeout;
1644                                 }
1645                         } else if (res == 0) {
1646                                 ast_debug(1, "not enough digits (and no ambiguous match)...\n");
1647                                 res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1648                                 analog_wait_event(p);
1649                                 ast_hangup(chan);
1650                                 goto quit;
1651                         } else if (p->callwaiting && !strcmp(exten, "*70")) {
1652                                 ast_verb(3, "Disabling call waiting on %s\n", chan->name);
1653                                 /* Disable call waiting if enabled */
1654                                 p->callwaiting = 0;
1655                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1656                                 if (res) {
1657                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n", 
1658                                                 chan->name, strerror(errno));
1659                                 }
1660                                 len = 0;
1661                                 memset(exten, 0, sizeof(exten));
1662                                 timeout = analog_firstdigittimeout;
1663
1664                         } else if (!strcmp(exten,ast_pickup_ext())) {
1665                                 /* Scan all channels and see if there are any
1666                                  * ringing channels that have call groups
1667                                  * that equal this channels pickup group
1668                                  */
1669                                 if (index == ANALOG_SUB_REAL) {
1670                                         /* Switch us from Third call to Call Wait */
1671                                         if (p->subs[ANALOG_SUB_THREEWAY].owner) {
1672                                                 /* If you make a threeway call and the *8# a call, it should actually
1673                                                    look like a callwait */
1674                                                 analog_alloc_sub(p, ANALOG_SUB_CALLWAIT);
1675                                                 analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_THREEWAY);
1676                                                 analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1677                                         }
1678                                         analog_set_echocanceller(p, 1);
1679                                         if (ast_pickup_call(chan)) {
1680                                                 ast_debug(1, "No call pickup possible...\n");
1681                                                 res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1682                                                 analog_wait_event(p);
1683                                         }
1684                                         ast_hangup(chan);
1685                                         goto quit;
1686                                 } else {
1687                                         ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
1688                                         ast_hangup(chan);
1689                                         goto quit;
1690                                 }
1691                         } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
1692                                 ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
1693                                 /* Disable Caller*ID if enabled */
1694                                 p->hidecallerid = 1;
1695                                 if (chan->cid.cid_num)
1696                                         free(chan->cid.cid_num);
1697                                 chan->cid.cid_num = NULL;
1698                                 if (chan->cid.cid_name)
1699                                         free(chan->cid.cid_name);
1700                                 chan->cid.cid_name = NULL;
1701                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1702                                 if (res) {
1703                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
1704                                                 chan->name, strerror(errno));
1705                                 }
1706                                 len = 0;
1707                                 memset(exten, 0, sizeof(exten));
1708                                 timeout = analog_firstdigittimeout;
1709                         } else if (p->callreturn && !strcmp(exten, "*69")) {
1710                                 res = 0;
1711                                 if (!ast_strlen_zero(p->lastcid_num)) {
1712                                         res = ast_say_digit_str(chan, p->lastcid_num, "", chan->language);
1713                                 }
1714                                 if (!res)
1715                                         res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1716                                 break;
1717                         } else if (!strcmp(exten, "*78")) {
1718                                 /* Do not disturb */
1719                                 ast_verb(3, "Enabled DND on channel %d\n", p->channel);
1720                                 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
1721                                               "Channel: DAHDI/%d\r\n"
1722                                               "Status: enabled\r\n", p->channel);
1723                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1724                                 p->dnd = 1;
1725                                 getforward = 0;
1726                                 memset(exten, 0, sizeof(exten));
1727                                 len = 0;
1728                         } else if (!strcmp(exten, "*79")) {
1729                                 /* Do not disturb */
1730                                 ast_verb(3, "Disabled DND on channel %d\n", p->channel);
1731                                 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
1732                                               "Channel: DAHDI/%d\r\n"
1733                                               "Status: disabled\r\n", p->channel);
1734                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1735                                 p->dnd = 0;
1736                                 getforward = 0;
1737                                 memset(exten, 0, sizeof(exten));
1738                                 len = 0;
1739                         } else if (p->cancallforward && !strcmp(exten, "*72")) {
1740                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1741                                 getforward = 1;
1742                                 memset(exten, 0, sizeof(exten));
1743                                 len = 0;
1744                         } else if (p->cancallforward && !strcmp(exten, "*73")) {
1745                                 ast_verb(3, "Cancelling call forwarding on channel %d\n", p->channel);
1746                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1747                                 memset(p->call_forward, 0, sizeof(p->call_forward));
1748                                 getforward = 0;
1749                                 memset(exten, 0, sizeof(exten));
1750                                 len = 0;
1751                         } else if ((p->transfer || p->canpark) && !strcmp(exten, ast_parking_ext()) &&
1752                                                 p->subs[ANALOG_SUB_THREEWAY].owner &&
1753                                                 ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)) {
1754                                 /* This is a three way call, the main call being a real channel,
1755                                         and we're parking the first call. */
1756                                 ast_masq_park_call(ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner), chan, 0, NULL);
1757                                 ast_verb(3, "Parking call to '%s'\n", chan->name);
1758                                 break;
1759                         } else if (!ast_strlen_zero(p->lastcid_num) && !strcmp(exten, "*60")) {
1760                                 ast_verb(3, "Blacklisting number %s\n", p->lastcid_num);
1761                                 res = ast_db_put("blacklist", p->lastcid_num, "1");
1762                                 if (!res) {
1763                                         res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1764                                         memset(exten, 0, sizeof(exten));
1765                                         len = 0;
1766                                 }
1767                         } else if (p->hidecallerid && !strcmp(exten, "*82")) {
1768                                 ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
1769                                 /* Enable Caller*ID if enabled */
1770                                 p->hidecallerid = 0;
1771                                 if (chan->cid.cid_num)
1772                                         free(chan->cid.cid_num);
1773                                 chan->cid.cid_num = NULL;
1774                                 if (chan->cid.cid_name)
1775                                         free(chan->cid.cid_name);
1776                                 chan->cid.cid_name = NULL;
1777                                 ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
1778                                 res = analog_play_tone(p, index, ANALOG_TONE_DIALRECALL);
1779                                 if (res) {
1780                                         ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
1781                                                 chan->name, strerror(errno));
1782                                 }
1783                                 len = 0;
1784                                 memset(exten, 0, sizeof(exten));
1785                                 timeout = analog_firstdigittimeout;
1786                         } else if (!strcmp(exten, "*0")) {
1787 #ifdef XXX
1788                                 struct ast_channel *nbridge = p->subs[ANALOG_SUB_THREEWAY].owner;
1789                                 struct dahdi_pvt *pbridge = NULL;
1790                                   /* set up the private struct of the bridged one, if any */
1791                                 if (nbridge && ast_bridged_channel(nbridge))
1792                                         pbridge = ast_bridged_channel(nbridge)->tech_pvt;
1793                                 if (nbridge && pbridge &&
1794                                     (nbridge->tech == chan_tech) &&
1795                                     (ast_bridged_channel(nbridge)->tech == chan_tech) &&
1796                                     ISTRUNK(pbridge)) {
1797                                         int func = DAHDI_FLASH;
1798                                         /* Clear out the dial buffer */
1799                                         p->dop.dialstr[0] = '\0';
1800                                         /* flash hookswitch */
1801                                         if ((ioctl(pbridge->subs[ANALOG_SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
1802                                                 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
1803                                                         nbridge->name, strerror(errno));
1804                                         }
1805                                         analog_swap_subs(p, ANALOG_SUB_REAL, ANALOG_SUB_THREEWAY);
1806                                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1807                                         p->owner = p->subs[ANALOG_SUB_REAL].owner;
1808                                         if (ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner))
1809                                                 ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_UNHOLD);
1810                                         ast_hangup(chan);
1811                                         goto quit;
1812                                 } else {
1813                                         analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
1814                                         analog_wait_event(p);
1815                                         analog_play_tone(p, index, -1);
1816                                         analog_swap_subs(p, ANALOG_SUB_REAL, ANALOG_SUB_THREEWAY);
1817                                         analog_unalloc_sub(p, ANALOG_SUB_THREEWAY);
1818                                         p->owner = p->subs[ANALOG_SUB_REAL].owner;
1819                                         ast_hangup(chan);
1820                                         goto quit;
1821                                 }
1822 #endif
1823                         } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
1824                                                         ((exten[0] != '*') || (strlen(exten) > 2))) {
1825                                 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);
1826                                 break;
1827                         }
1828                         if (!timeout)
1829                                 timeout = analog_gendigittimeout;
1830                         if (len && !ast_ignore_pattern(chan->context, exten))
1831                                 analog_play_tone(p, index, -1);
1832                 }
1833                 break;
1834         case ANALOG_SIG_FXSLS:
1835         case ANALOG_SIG_FXSGS:
1836         case ANALOG_SIG_FXSKS:
1837
1838                 /* If we want caller id, we're in a prering state due to a polarity reversal
1839                  * and we're set to use a polarity reversal to trigger the start of caller id,
1840                  * grab the caller id and wait for ringing to start... */
1841                 if (p->use_callerid && (chan->_state == AST_STATE_PRERING && (p->cid_start == ANALOG_CID_START_POLARITY || p->cid_start == ANALOG_CID_START_POLARITY_IN))) {
1842                         /* If set to use DTMF CID signalling, listen for DTMF */
1843                         if (p->cid_signalling == CID_SIG_DTMF) {
1844                                 int i = 0;
1845                                 cs = NULL;
1846                                 ast_debug(1, "Receiving DTMF cid on "
1847                                         "channel %s\n", chan->name);
1848 #if 0
1849                                 dahdi_setlinear(p->subs[index].dfd, 0);
1850 #endif
1851                                 res = 2000;
1852                                 for (;;) {
1853                                         struct ast_frame *f;
1854                                         res = ast_waitfor(chan, res);
1855                                         if (res <= 0) {
1856                                                 ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
1857                                                         "Exiting simple switch\n");
1858                                                 ast_hangup(chan);
1859                                                 goto quit;
1860                                         }
1861                                         f = ast_read(chan);
1862                                         if (!f)
1863                                                 break;
1864                                         if (f->frametype == AST_FRAME_DTMF) {
1865                                                 dtmfbuf[i++] = f->subclass;
1866                                                 ast_debug(1, "CID got digit '%c'\n", f->subclass);
1867                                                 res = 2000;
1868                                         }
1869                                         ast_frfree(f);
1870                                         if (chan->_state == AST_STATE_RING ||
1871                                             chan->_state == AST_STATE_RINGING)
1872                                                 break; /* Got ring */
1873                                 }
1874                                 dtmfbuf[i] = '\0';
1875 #if 0
1876                                 dahdi_setlinear(p->subs[index].dfd, p->subs[index].linear);
1877 #endif
1878                                 /* Got cid and ring. */
1879                                 ast_debug(1, "CID got string '%s'\n", dtmfbuf);
1880                                 callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
1881                                 ast_debug(1, "CID is '%s', flags %d\n",
1882                                         dtmfcid, flags);
1883                                 /* If first byte is NULL, we have no cid */
1884                                 if (!ast_strlen_zero(dtmfcid))
1885                                         number = dtmfcid;
1886                                 else
1887                                         number = NULL;
1888 #if 0
1889                         /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
1890                         } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
1891                                 cs = callerid_new(p->cid_signalling);
1892                                 if (cs) {
1893                                         samples = 0;
1894 #if 1
1895                                         bump_gains(p);
1896 #endif                          
1897                                         /* Take out of linear mode for Caller*ID processing */
1898                                         dahdi_setlinear(p->subs[index].dfd, 0);
1899                                         
1900                                         /* First we wait and listen for the Caller*ID */
1901                                         for (;;) {      
1902                                                 i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
1903                                                 if ((res = ioctl(p->subs[index].dfd, DAHDI_IOMUX, &i))) {
1904                                                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
1905                                                         callerid_free(cs);
1906                                                         ast_hangup(chan);
1907                                                         goto quit;
1908                                                 }
1909                                                 if (i & DAHDI_IOMUX_SIGEVENT) {
1910                                                         res = dahdi_get_event(p->subs[index].dfd);
1911                                                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
1912
1913                                                         if (p->cid_signalling == CID_SIG_V23_JP) {
1914 #ifdef DAHDI_EVENT_RINGBEGIN
1915                                                                 if (res == ANALOG_EVENT_RINGBEGIN) {
1916                                                                         res = analog_off_hook(p);
1917                                                                         usleep(1);
1918                                                                 }
1919 #endif
1920                                                         } else {
1921                                                                 res = 0;
1922                                                                 break;
1923                                                         }
1924                                                 } else if (i & DAHDI_IOMUX_READ) {
1925                                                         res = read(p->subs[index].dfd, buf, sizeof(buf));
1926                                                         if (res < 0) {
1927                                                                 if (errno != ELAST) {
1928                                                                         ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
1929                                                                         callerid_free(cs);
1930                                                                         ast_hangup(chan);
1931                                                                         goto quit;
1932                                                                 }
1933                                                                 break;
1934                                                         }
1935                                                         samples += res;
1936
1937                                                         if  (p->cid_signalling == CID_SIG_V23_JP) {
1938                                                                 res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
1939                                                         } else {
1940                                                                 res = callerid_feed(cs, buf, res, AST_LAW(p));
1941                                                         }
1942
1943                                                         if (res < 0) {
1944                                                                 ast_log(LOG_WARNING, "CallerID feed failed on channel '%s'\n", chan->name);
1945                                                                 break;
1946                                                         } else if (res)
1947                                                                 break;
1948                                                         else if (samples > (8000 * 10))
1949                                                                 break;
1950                                                 }
1951                                         }
1952                                         if (res == 1) {
1953                                                 callerid_get(cs, &name, &number, &flags);
1954                                                 ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
1955                                         }
1956
1957                                         if (p->cid_signalling == CID_SIG_V23_JP) {
1958                                                 res = analog_on_hook(p);
1959                                                 usleep(1);
1960                                                 res = 4000;
1961                                         } else {
1962
1963                                                 /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */ 
1964                                                 res = 2000;
1965                                         }
1966
1967                                         for (;;) {
1968                                                 struct ast_frame *f;
1969                                                 res = ast_waitfor(chan, res);
1970                                                 if (res <= 0) {
1971                                                         ast_log(LOG_WARNING, "CID timed out waiting for ring. "
1972                                                                 "Exiting simple switch\n");
1973                                                         ast_hangup(chan);
1974                                                         goto quit;
1975                                                 } 
1976                                                 if (!(f = ast_read(chan))) {
1977                                                         ast_log(LOG_WARNING, "Hangup received waiting for ring. Exiting simple switch\n");
1978                                                         ast_hangup(chan);
1979                                                         goto quit;
1980                                                 }
1981                                                 ast_frfree(f);
1982                                                 if (chan->_state == AST_STATE_RING ||
1983                                                     chan->_state == AST_STATE_RINGING) 
1984                                                         break; /* Got ring */
1985                                         }
1986         
1987                                         /* Restore linear mode (if appropriate) for Caller*ID processing */
1988                                         dahdi_setlinear(p->subs[index].dfd, p->subs[index].linear);
1989 #if 1
1990                                         restore_gains(p);
1991 #endif                          
1992                                 } else
1993                                         ast_log(LOG_WARNING, "Unable to get caller ID space\n");                        
1994 #endif
1995                         } else {
1996                                 ast_log(LOG_WARNING, "Channel %s in prering "
1997                                         "state, but I have nothing to do. "
1998                                         "Terminating simple switch, should be "
1999                                         "restarted by the actual ring.\n", 
2000                                         chan->name);
2001                                 ast_hangup(chan);
2002                                 goto quit;
2003                         }
2004                 } else if (p->use_callerid && p->cid_start == ANALOG_CID_START_RING) {
2005                         int timeout = 10000;  /* Ten seconds */
2006                         struct timeval start = ast_tvnow();
2007                         enum analog_event ev;
2008
2009                         namebuf[0] = 0;
2010                         numbuf[0] = 0;
2011
2012                         if (!analog_start_cid_detect(p, p->cid_signalling)) {
2013                                 while (1) {
2014                                         res = analog_get_callerid(p, namebuf, numbuf, &ev, timeout - ast_tvdiff_ms(ast_tvnow(), start));
2015
2016                                         if (res == 0) {
2017                                                 break;
2018                                         }
2019
2020                                         if (res == 1) {
2021                                                 if (ev == ANALOG_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
2022                                                         ast_debug(1, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
2023                                                         p->polarity = POLARITY_IDLE;
2024                                                         ast_hangup(chan);
2025                                                         goto quit;
2026                                                 } else if (ev != ANALOG_EVENT_NONE) {
2027                                                         break;
2028                                                 }
2029                                         }
2030
2031                                         if (ast_tvdiff_ms(ast_tvnow(), start) > timeout)
2032                                                 break;
2033
2034                                 }
2035                                 name = namebuf;
2036                                 number = numbuf;
2037
2038                                 analog_stop_cid_detect(p);
2039
2040 #if 0
2041                         /* XXX */
2042                         if (strcmp(p->context,p->defcontext) != 0) {
2043                                 ast_copy_string(p->context, p->defcontext, sizeof(p->context));
2044                                 ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
2045                         }
2046
2047                         analog_get_callerid(p, name, number);
2048                         /* FSK Bell202 callerID */
2049                         cs = callerid_new(p->cid_signalling);
2050                         if (cs) {
2051 #if 1
2052                                 bump_gains(p);
2053 #endif                          
2054                                 samples = 0;
2055                                 len = 0;
2056                                 distMatches = 0;
2057                                 /* Clear the current ring data array so we dont have old data in it. */
2058                                 for (receivedRingT = 0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
2059                                         curRingData[receivedRingT] = 0;
2060                                 receivedRingT = 0;
2061                                 counter = 0;
2062                                 counter1 = 0;
2063                                 /* Check to see if context is what it should be, if not set to be. */
2064
2065                                 /* Take out of linear mode for Caller*ID processing */
2066                                 dahdi_setlinear(p->subs[index].dfd, 0);
2067                                 for (;;) {      
2068                                         i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
2069                                         if ((res = ioctl(p->subs[index].dfd, DAHDI_IOMUX, &i))) {
2070                                                 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
2071                                                 callerid_free(cs);
2072                                                 ast_hangup(chan);
2073                                                 goto quit;
2074                                         }
2075                                         if (i & DAHDI_IOMUX_SIGEVENT) {
2076                                                 res = dahdi_get_event(p->subs[index].dfd);
2077                                                 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
2078                                                 /* If we get a PR event, they hung up while processing calerid */
2079                                                 if ( res == ANALOG_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
2080                                                         ast_debug(1, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
2081                                                         p->polarity = POLARITY_IDLE;
2082                                                         callerid_free(cs);
2083                                                         ast_hangup(chan);
2084                                                         goto quit;
2085                                                 }
2086                                                 res = 0;
2087                                                 /* Let us detect callerid when the telco uses distinctive ring */
2088
2089                                                 curRingData[receivedRingT] = p->ringt;
2090
2091                                                 if (p->ringt < p->ringt_base/2)
2092                                                         break;
2093                                                 /* Increment the ringT counter so we can match it against
2094                                                    values in chan_dahdi.conf for distinctive ring */
2095                                                 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
2096                                                         break;
2097                                         } else if (i & DAHDI_IOMUX_READ) {
2098                                                 res = read(p->subs[index].dfd, buf, sizeof(buf));
2099                                                 if (res < 0) {
2100                                                         if (errno != ELAST) {
2101                                                                 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
2102                                                                 callerid_free(cs);
2103                                                                 ast_hangup(chan);
2104                                                                 goto quit;
2105                                                         }
2106                                                         break;
2107                                                 }
2108                                                 if (p->ringt) 
2109                                                         p->ringt--;
2110                                                 if (p->ringt == 1) {
2111                                                         res = -1;
2112                                                         break;
2113                                                 }
2114                                                 samples += res;
2115                                                 res = callerid_feed(cs, buf, res, AST_LAW(p));
2116                                                 if (res < 0) {
2117                                                         ast_log(LOG_WARNING, "CallerID feed failed: %s\n", strerror(errno));
2118                                                         break;
2119                                                 } else if (res)
2120                                                         break;
2121                                                 else if (samples > (8000 * 10))
2122                                                         break;
2123                                         }
2124                                 }
2125                                 if (res == 1) {
2126                                         callerid_get(cs, &name, &number, &flags);
2127                                         ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
2128                                 }
2129                                 /* Restore linear mode (if appropriate) for Caller*ID processing */
2130                                 dahdi_setlinear(p->subs[index].dfd, p->subs[index].linear);
2131 #if 1
2132                                 restore_gains(p);
2133 #endif                          
2134                                 if (res < 0) {
2135                                         ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
2136                                 }
2137                         } else
2138                                 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
2139 #endif
2140                         } else
2141                                 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
2142                 }
2143                 else
2144                         cs = NULL;
2145
2146                 if (number)
2147                         ast_shrink_phone_number(number);
2148                 ast_set_callerid(chan, number, name, number);
2149
2150                 if (cs)
2151                         callerid_free(cs);
2152
2153                 analog_handle_notify_message(chan, p, flags, -1);
2154
2155                 ast_setstate(chan, AST_STATE_RING);
2156                 chan->rings = 1;
2157 #if 0
2158                 p->ringt = p->ringt_base;
2159 #endif
2160                 res = ast_pbx_run(chan);
2161                 if (res) {
2162                         ast_hangup(chan);
2163                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
2164                 }
2165                 goto quit;
2166         default:
2167                 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);
2168                 res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
2169                 if (res < 0)
2170                                 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
2171         }
2172         res = analog_play_tone(p, index, ANALOG_TONE_CONGESTION);
2173         if (res < 0)
2174                         ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
2175         ast_hangup(chan);
2176 quit:
2177         analog_decrease_ss_count(p);
2178         return NULL;
2179 }
2180
2181 int analog_ss_thread_start(struct analog_pvt *p, struct ast_channel *chan)
2182 {
2183         pthread_t threadid;
2184         return ast_pthread_create_detached(&threadid, NULL, __analog_ss_thread, chan);
2185 }
2186
2187 static struct ast_frame *__analog_handle_event(struct analog_pvt *p, struct ast_channel *ast)
2188 {
2189         int res, x;
2190         int mysig;
2191         enum analog_sub index;
2192         char *c;
2193         pthread_t threadid;
2194         pthread_attr_t attr;
2195         struct ast_channel *chan;
2196         struct ast_frame *f;
2197         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
2198
2199         index = analog_get_index(ast, p, 0);
2200         mysig = p->sig;
2201         if (p->outsigmod > -1)
2202                 mysig = p->outsigmod;
2203         p->subs[index].f.frametype = AST_FRAME_NULL;
2204         p->subs[index].f.subclass = 0;
2205         p->subs[index].f.datalen = 0;
2206         p->subs[index].f.samples = 0;
2207         p->subs[index].f.mallocd = 0;
2208         p->subs[index].f.offset = 0;
2209         p->subs[index].f.src = "dahdi_handle_event";
2210         p->subs[index].f.data.ptr = NULL;
2211         f = &p->subs[index].f;
2212
2213         if (index < 0)
2214                 return &p->subs[index].f;
2215
2216         if (index != ANALOG_SUB_REAL) {
2217                 ast_log(LOG_ERROR, "We got an event on a non real sub.  Fix it!\n");
2218         }
2219
2220         res = analog_get_event(p);
2221
2222         ast_debug(1, "Got event %s(%d) on channel %d (index %d)\n", analog_event2str(res), res, p->channel, index);
2223
2224         switch (res) {
2225 #ifdef ANALOG_EVENT_EC_DISABLED
2226         case ANALOG_EVENT_EC_DISABLED:
2227                 ast_verb(3, "Channel %d echo canceler disabled due to CED detection\n", p->channel);
2228                 p->echocanon = 0;
2229                 break;
2230 #endif
2231         case ANALOG_EVENT_PULSE_START:
2232                 /* Stop tone if there's a pulse start and the PBX isn't started */
2233                 if (!ast->pbx)
2234                         analog_play_tone(p, ANALOG_SUB_REAL, -1);
2235                 break;
2236         case ANALOG_EVENT_DIALCOMPLETE:
2237                 if (p->inalarm) break;
2238                 x = analog_is_dialing(p, index);
2239                 if (!x) { /* if not still dialing in driver */
2240                         analog_set_echocanceller(p, 1);
2241                         if (p->echobreak) {
2242                                 analog_train_echocanceller(p);
2243                                 ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
2244                                 p->dop.op = ANALOG_DIAL_OP_REPLACE;
2245                                 analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop);
2246                                 p->echobreak = 0;
2247                         } else {
2248                                 p->dialing = 0;
2249                                 if ((mysig == ANALOG_SIG_E911) || (mysig == ANALOG_SIG_FGC_CAMA) || (mysig == ANALOG_SIG_FGC_CAMAMF)) {
2250                                         /* if thru with dialing after offhook */
2251                                         if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
2252                                                 ast_setstate(ast, AST_STATE_UP);
2253                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2254                                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2255                                                 break;
2256                                         } else { /* if to state wait for offhook to dial rest */
2257                                                 /* we now wait for off hook */
2258                                                 ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
2259                                         }
2260                                 }
2261                                 if (ast->_state == AST_STATE_DIALING) {
2262                                         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)))) {
2263                                                 ast_setstate(ast, AST_STATE_RINGING);
2264                                         } else if (!p->answeronpolarityswitch) {
2265                                                 ast_setstate(ast, AST_STATE_UP);
2266                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2267                                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2268                                                 /* If aops=0 and hops=1, this is necessary */
2269                                                 p->polarity = POLARITY_REV;
2270                                         } else {
2271                                                 /* Start clean, so we can catch the change to REV polarity when party answers */
2272                                                 p->polarity = POLARITY_IDLE;
2273                                         }
2274                                 }
2275                         }
2276                 }
2277                 break;
2278         case ANALOG_EVENT_ALARM:
2279                 p->inalarm = 1;
2280 #if 0
2281                 res = get_alarms(p);
2282                 handle_alarms(p, res);  
2283 #endif
2284         case ANALOG_EVENT_ONHOOK:
2285                 switch (p->sig) {
2286                 case ANALOG_SIG_FXOLS:
2287                 case ANALOG_SIG_FXOGS:
2288                 case ANALOG_SIG_FXOKS:
2289                         /* Check for some special conditions regarding call waiting */
2290                         if (index == ANALOG_SUB_REAL) {
2291                                 /* The normal line was hung up */
2292                                 if (p->subs[ANALOG_SUB_CALLWAIT].owner) {
2293                                         /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
2294                                         analog_swap_subs(p, ANALOG_SUB_CALLWAIT, ANALOG_SUB_REAL);
2295                                         ast_verb(3, "Channel %d still has (callwait) call, ringing phone\n", p->channel);
2296                                         analog_unalloc_sub(p, ANALOG_SUB_CALLWAIT);
2297                                         analog_stop_callwait(p);
2298                                         p->owner = NULL;
2299                                         /* Don't start streaming audio yet if the incoming call isn't up yet */
2300                                         if (p->subs[ANALOG_SUB_REAL].owner->_state != AST_STATE_UP)
2301                                                 p->dialing = 1;
2302                                         analog_ring(p);
2303                                 } else if (p->subs[ANALOG_SUB_THREEWAY].owner) {
2304                                         unsigned int mssinceflash;
2305                                         /* Here we have to retain the lock on both the main channel, the 3-way channel, and
2306                                            the private structure -- not especially easy or clean */
2307                                         while (p->subs[ANALOG_SUB_THREEWAY].owner && ast_channel_trylock(p->subs[ANALOG_SUB_THREEWAY].owner)) {
2308                                                 /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
2309                                                 analog_unlock_private(p);
2310                                                 CHANNEL_DEADLOCK_AVOIDANCE(ast);
2311                                                 /* We can grab ast and p in that order, without worry.  We should make sure
2312                                                    nothing seriously bad has happened though like some sort of bizarre double
2313                                                    masquerade! */
2314                                                 analog_lock_private(p);
2315                                                 if (p->owner != ast) {
2316                                                         ast_log(LOG_WARNING, "This isn't good...\n");
2317                                                         return NULL;
2318                                                 }
2319                                         }
2320                                         if (!p->subs[ANALOG_SUB_THREEWAY].owner) {
2321                                                 ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
2322                                                 return NULL;
2323                                         }
2324                                         mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
2325                                         ast_debug(1, "Last flash was %d ms ago\n", mssinceflash);
2326                                         if (mssinceflash < MIN_MS_SINCE_FLASH) {
2327                                                 /* It hasn't been long enough since the last flashook.  This is probably a bounce on
2328                                                    hanging up.  Hangup both channels now */
2329                                                 if (p->subs[ANALOG_SUB_THREEWAY].owner)
2330                                                         ast_queue_hangup(p->subs[ANALOG_SUB_THREEWAY].owner);
2331                                                 ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2332                                                 ast_debug(1, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
2333                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2334                                         } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
2335                                                 if (p->transfer) {
2336                                                         /* In any case this isn't a threeway call anymore */
2337                                                         p->subs[ANALOG_SUB_REAL].inthreeway = 0;
2338                                                         p->subs[ANALOG_SUB_THREEWAY].inthreeway = 0;
2339                                                         /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
2340                                                         if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
2341                                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2342                                                                 /* Swap subs and dis-own channel */
2343                                                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2344                                                                 p->owner = NULL;
2345                                                                 /* Ring the phone */
2346                                                                 analog_ring(p);
2347                                                         } else {
2348                                                                 if ((res = analog_attempt_transfer(p)) < 0) {
2349                                                                         ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2350                                                                         if (p->subs[ANALOG_SUB_THREEWAY].owner)
2351                                                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2352                                                                 } else if (res) {
2353                                                                         /* Don't actually hang up at this point */
2354                                                                         if (p->subs[ANALOG_SUB_THREEWAY].owner)
2355                                                                                 ast_channel_unlock(&p->subs[ANALOG_SUB_THREEWAY].owner);
2356                                                                         break;
2357                                                                 }
2358                                                         }
2359                                                 } else {
2360                                                         ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2361                                                         if (p->subs[ANALOG_SUB_THREEWAY].owner)
2362                                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2363                                                 }
2364                                         } else {
2365                                                 ast_channel_unlock(p->subs[ANALOG_SUB_THREEWAY].owner);
2366                                                 /* Swap subs and dis-own channel */
2367                                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2368                                                 p->owner = NULL;
2369                                                 /* Ring the phone */
2370                                                 analog_ring(p);
2371                                         }
2372                                 }
2373                         } else {
2374                                 ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
2375                         }
2376                         /* Fall through */
2377                 default:
2378                         analog_set_echocanceller(p, 0);
2379                         return NULL;
2380                 }
2381                 break;
2382         case ANALOG_EVENT_RINGOFFHOOK:
2383                 if (p->inalarm) break;
2384                 /* for E911, its supposed to wait for offhook then dial
2385                    the second half of the dial string */
2386                 if (((mysig == ANALOG_SIG_E911) || (mysig == ANALOG_SIG_FGC_CAMA) || (mysig == ANALOG_SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
2387                         c = strchr(p->dialdest, '/');
2388                         if (c)
2389                                 c++;
2390                         else
2391                                 c = p->dialdest;
2392                         if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
2393                         else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
2394                         if (strlen(p->dop.dialstr) > 4) {
2395                                 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2396                                 strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2397                                 p->echorest[sizeof(p->echorest) - 1] = '\0';
2398                                 p->echobreak = 1;
2399                                 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2400                         } else
2401                                 p->echobreak = 0;
2402                         if (analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop)) {
2403                                 int saveerr = errno;
2404                                 analog_on_hook(p);
2405                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
2406                                 return NULL;
2407                         }
2408                         p->dialing = 1;
2409                         return &p->subs[index].f;
2410                 }
2411                 switch (p->sig) {
2412                 case ANALOG_SIG_FXOLS:
2413                 case ANALOG_SIG_FXOGS:
2414                 case ANALOG_SIG_FXOKS:
2415                         switch (ast->_state) {
2416                         case AST_STATE_RINGING:
2417                                 analog_set_echocanceller(p, 1);
2418                                 analog_train_echocanceller(p);
2419                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2420                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2421                                 /* Make sure it stops ringing */
2422                                 analog_off_hook(p);
2423                                 ast_debug(1, "channel %d answered\n", p->channel);
2424                                 p->dialing = 0;
2425                                 p->callwaitcas = 0;
2426                                 if (!ast_strlen_zero(p->dop.dialstr)) {
2427                                         /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
2428                                         res = analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop);
2429                                         if (res < 0) {
2430                                                 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
2431                                                 p->dop.dialstr[0] = '\0';
2432                                                 return NULL;
2433                                         } else {
2434                                                 ast_debug(1, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
2435                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
2436                                                 p->subs[index].f.subclass = 0;
2437                                                 p->dialing = 1;
2438                                         }
2439                                         p->dop.dialstr[0] = '\0';
2440                                         ast_setstate(ast, AST_STATE_DIALING);
2441                                 } else
2442                                         ast_setstate(ast, AST_STATE_UP);
2443                                 return &p->subs[index].f;
2444                         case AST_STATE_DOWN:
2445                                 ast_setstate(ast, AST_STATE_RING);
2446                                 ast->rings = 1;
2447                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2448                                 p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
2449                                 ast_debug(1, "channel %d picked up\n", p->channel);
2450                                 return &p->subs[index].f;
2451                         case AST_STATE_UP:
2452                                 /* Make sure it stops ringing */
2453                                 analog_off_hook(p);
2454                                 /* Okay -- probably call waiting*/
2455                                 if (ast_bridged_channel(p->owner))
2456                                         ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
2457                                 break;
2458                         case AST_STATE_RESERVED:
2459                                 /* Start up dialtone */
2460                                 if (analog_has_voicemail(p))
2461                                         res = analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_STUTTER);
2462                                 else
2463                                         res = analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_DIALTONE);
2464                                 break;
2465                         default:
2466                                 ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
2467                         }
2468                         break;
2469                 case ANALOG_SIG_FXSLS:
2470                 case ANALOG_SIG_FXSGS:
2471                 case ANALOG_SIG_FXSKS:
2472 #if 0
2473                         if (ast->_state == AST_STATE_RING) {
2474                                 p->ringt = p->ringt_base;
2475                         }
2476 #endif
2477
2478                         /* Fall through */
2479                 case ANALOG_SIG_EM:
2480                 case ANALOG_SIG_EM_E1:
2481                 case ANALOG_SIG_EMWINK:
2482                 case ANALOG_SIG_FEATD:
2483                 case ANALOG_SIG_FEATDMF:
2484                 case ANALOG_SIG_FEATDMF_TA:
2485                 case ANALOG_SIG_E911:
2486                 case ANALOG_SIG_FGC_CAMA:
2487                 case ANALOG_SIG_FGC_CAMAMF:
2488                 case ANALOG_SIG_FEATB:
2489                 case ANALOG_SIG_SF:
2490                 case ANALOG_SIG_SFWINK:
2491                 case ANALOG_SIG_SF_FEATD:
2492                 case ANALOG_SIG_SF_FEATDMF:
2493                 case ANALOG_SIG_SF_FEATB:
2494                         if (ast->_state == AST_STATE_PRERING)
2495                                 ast_setstate(ast, AST_STATE_RING);
2496                         if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
2497                                 ast_debug(1, "Ring detected\n");
2498                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2499                                 p->subs[index].f.subclass = AST_CONTROL_RING;
2500                         } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
2501                                 ast_debug(1, "Line answered\n");
2502                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2503                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2504                                 ast_setstate(ast, AST_STATE_UP);
2505                         } else if (ast->_state != AST_STATE_RING)
2506                                 ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
2507                         break;
2508                 default:
2509                         ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
2510                 }
2511                 break;
2512 #ifdef ANALOG_EVENT_RINGBEGIN
2513         case ANALOG_EVENT_RINGBEGIN:
2514                 switch (p->sig) {
2515                 case ANALOG_SIG_FXSLS:
2516                 case ANALOG_SIG_FXSGS:
2517                 case ANALOG_SIG_FXSKS:
2518 #if 0
2519                         if (ast->_state == AST_STATE_RING) {
2520                                 p->ringt = p->ringt_base;
2521                         }
2522 #endif
2523                         break;
2524                 }
2525                 break;
2526 #endif
2527         case ANALOG_EVENT_RINGEROFF:
2528                 if (p->inalarm) break;
2529                 ast->rings++;
2530                 if (ast->rings == p->cidrings) {
2531                         analog_send_callerid(p, 0, &p->cid);
2532                 }
2533
2534                 if (ast->rings > p->cidrings) {
2535                         p->callwaitcas = 0;
2536                 }
2537                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2538                 p->subs[index].f.subclass = AST_CONTROL_RINGING;
2539                 break;
2540         case ANALOG_EVENT_RINGERON:
2541                 break;
2542         case ANALOG_EVENT_NOALARM:
2543                 p->inalarm = 0;
2544                 if (!p->unknown_alarm) {
2545                         ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
2546                         manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
2547                                 "Channel: %d\r\n", p->channel);
2548                 } else {
2549                         p->unknown_alarm = 0;
2550                 }
2551                 break;
2552         case ANALOG_EVENT_WINKFLASH:
2553                 if (p->inalarm) break;
2554                 /* Remember last time we got a flash-hook */
2555                 gettimeofday(&p->flashtime, NULL);
2556                 switch (mysig) {
2557                 case ANALOG_SIG_FXOLS:
2558                 case ANALOG_SIG_FXOGS:
2559                 case ANALOG_SIG_FXOKS:
2560 #if 0
2561                         ast_debug(1, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
2562                                 index, p->subs[ANALOG_SUB_REAL].dfd, p->subs[ANALOG_SUB_CALLWAIT].dfd, p->subs[ANALOG_SUB_THREEWAY].dfd);
2563 #endif
2564                         p->callwaitcas = 0;
2565
2566                         if (index != ANALOG_SUB_REAL) {
2567                                 ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", index, p->channel);
2568                                 goto winkflashdone;
2569                         }
2570
2571                         if (p->subs[ANALOG_SUB_CALLWAIT].owner) {
2572                                 /* Swap to call-wait */
2573                                 int previous_state = p->subs[ANALOG_SUB_CALLWAIT].owner->_state;
2574                                 if (p->subs[ANALOG_SUB_CALLWAIT].owner->_state == AST_STATE_RINGING) {
2575                                         ast_setstate(p->subs[ANALOG_SUB_CALLWAIT].owner, AST_STATE_UP);
2576                                 }
2577                                 analog_swap_subs(p, ANALOG_SUB_REAL, ANALOG_SUB_CALLWAIT);
2578                                 analog_play_tone(p, ANALOG_SUB_REAL, -1);
2579                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
2580                                 ast_debug(1, "Making %s the new owner\n", p->owner->name);
2581                                 if (previous_state == AST_STATE_RINGING) {
2582                                         ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_ANSWER);
2583                                 }
2584                                 analog_stop_callwait(p);
2585                                 /* Start music on hold if appropriate */
2586                                 if (!p->subs[ANALOG_SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[ANALOG_SUB_CALLWAIT].owner)) {
2587                                         ast_queue_control_data(p->subs[ANALOG_SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
2588                                                 S_OR(p->mohsuggest, NULL),
2589                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2590                                 }
2591                                 ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_ANSWER);
2592                                 if (ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner)) {
2593                                         ast_queue_control_data(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_HOLD,
2594                                                 S_OR(p->mohsuggest, NULL),
2595                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2596                                 }
2597                                 ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_UNHOLD);
2598                         } else if (!p->subs[ANALOG_SUB_THREEWAY].owner) {
2599                                 char cid_num[256];
2600                                 char cid_name[256];
2601
2602                                 if (!p->threewaycalling) {
2603                                         /* Just send a flash if no 3-way calling */
2604                                         ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_FLASH);
2605                                         goto winkflashdone;
2606                                 } else if (!analog_check_for_conference(p)) {
2607                                         if (p->dahditrcallerid && p->owner) {
2608                                                 if (p->owner->cid.cid_num)
2609                                                         ast_copy_string(cid_num, p->owner->cid.cid_num, sizeof(cid_num));
2610                                                 if (p->owner->cid.cid_name)
2611                                                         ast_copy_string(cid_name, p->owner->cid.cid_name, sizeof(cid_name));
2612                                         }
2613                                         /* XXX This section needs much more error checking!!! XXX */
2614                                         /* Start a 3-way call if feasible */
2615                                         if (!((ast->pbx) ||
2616                                               (ast->_state == AST_STATE_UP) ||
2617                                               (ast->_state == AST_STATE_RING))) {
2618                                                 ast_debug(1, "Flash when call not up or ringing\n");
2619                                                         goto winkflashdone;
2620                                         }
2621                                         if (analog_alloc_sub(p, ANALOG_SUB_THREEWAY)) {
2622                                                 ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
2623                                                 goto winkflashdone;
2624                                         }
2625                                         /* Make new channel */
2626                                         chan = analog_new_ast_channel(p, AST_STATE_RESERVED, 0, ANALOG_SUB_THREEWAY);
2627                                         if (p->dahditrcallerid) {
2628                                                 if (!p->origcid_num)
2629                                                         p->origcid_num = ast_strdup(p->cid_num);
2630                                                 if (!p->origcid_name)
2631                                                         p->origcid_name = ast_strdup(p->cid_name);
2632                                                 ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
2633                                                 ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
2634                                         }
2635                                         /* Swap things around between the three-way and real call */
2636                                         analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2637                                         /* Disable echo canceller for better dialing */
2638                                         analog_set_echocanceller(p, 0);
2639                                         res = analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_DIALRECALL);
2640                                         if (res)
2641                                                 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
2642                                         p->ss_astchan = p->owner = chan;
2643                                         pthread_attr_init(&attr);
2644                                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2645                                         if (!chan) {
2646                                                 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
2647                                         } else if (ast_pthread_create(&threadid, &attr, __analog_ss_thread, p)) {
2648                                                 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
2649                                                 res = analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_CONGESTION);
2650                                                 analog_set_echocanceller(p, 1);
2651                                                 ast_hangup(chan);
2652                                         } else {
2653                                                 struct ast_channel *other = ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner);
2654                                                 int way3bridge = 0, cdr3way = 0;
2655
2656                                                 if (!other) {
2657                                                         other = ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner);
2658                                                 } else
2659                                                         way3bridge = 1;
2660
2661                                                 if (p->subs[ANALOG_SUB_THREEWAY].owner->cdr)
2662                                                         cdr3way = 1;
2663                                                 
2664                                                 ast_verb(3, "Started three way call on channel %d\n", p->channel);
2665                                                 /* Start music on hold if appropriate */
2666                                                 if (ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner)) {
2667                                                         ast_queue_control_data(p->subs[ANALOG_SUB_THREEWAY].owner, AST_CONTROL_HOLD,
2668                                                                 S_OR(p->mohsuggest, NULL),
2669                                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2670                                                 }
2671                                         }
2672                                         pthread_attr_destroy(&attr);
2673                                 }
2674                         } else {
2675                                 /* Already have a 3 way call */
2676                                 if (p->subs[ANALOG_SUB_THREEWAY].inthreeway) {
2677                                         /* Call is already up, drop the last person */
2678                                         ast_debug(1, "Got flash with three way call up, dropping last call on %d\n", p->channel);
2679                                         /* If the primary call isn't answered yet, use it */
2680                                         if ((p->subs[ANALOG_SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[ANALOG_SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
2681                                                 /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
2682                                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2683                                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
2684                                         }
2685                                         /* Drop the last call and stop the conference */
2686                                         ast_verb(3, "Dropping three-way call on %s\n", p->subs[ANALOG_SUB_THREEWAY].owner->name);
2687                                         ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2688                                         p->subs[ANALOG_SUB_REAL].inthreeway = 0;
2689                                         p->subs[ANALOG_SUB_THREEWAY].inthreeway = 0;
2690                                 } else {
2691                                         /* Lets see what we're up to */
2692                                         if (((ast->pbx) || (ast->_state == AST_STATE_UP)) && 
2693                                             (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
2694                                                 int otherindex = ANALOG_SUB_THREEWAY;
2695                                                 struct ast_channel *other = ast_bridged_channel(p->subs[ANALOG_SUB_THREEWAY].owner);
2696                                                 int way3bridge = 0, cdr3way = 0;
2697
2698                                                 if (!other) {
2699                                                         other = ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner);
2700                                                 } else
2701                                                         way3bridge = 1;
2702
2703                                                 if (p->subs[ANALOG_SUB_THREEWAY].owner->cdr)
2704                                                         cdr3way = 1;
2705
2706                                                 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);
2707                                                 /* Put them in the threeway, and flip */
2708                                                 p->subs[ANALOG_SUB_THREEWAY].inthreeway = 1;
2709                                                 p->subs[ANALOG_SUB_REAL].inthreeway = 1;
2710                                                 if (ast->_state == AST_STATE_UP) {
2711                                                         analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2712                                                         otherindex = ANALOG_SUB_REAL;
2713                                                 }
2714                                                 if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
2715                                                         ast_queue_control(p->subs[otherindex].owner, AST_CONTROL_UNHOLD);
2716                                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
2717                                                 if (ast->_state == AST_STATE_RINGING) {
2718                                                         ast_debug(1, "Enabling ringtone on real and threeway\n");
2719                                                         analog_play_tone(p, ANALOG_SUB_REAL, ANALOG_TONE_RINGTONE);
2720                                                         analog_play_tone(p, ANALOG_SUB_THREEWAY, ANALOG_TONE_RINGTONE);
2721                                                 }
2722                                         } else {
2723                                                 ast_verb(3, "Dumping incomplete call on on %s\n", p->subs[ANALOG_SUB_THREEWAY].owner->name);
2724                                                 analog_swap_subs(p, ANALOG_SUB_THREEWAY, ANALOG_SUB_REAL);
2725                                                 ast_softhangup_nolock(p->subs[ANALOG_SUB_THREEWAY].owner, AST_SOFTHANGUP_DEV);
2726                                                 p->owner = p->subs[ANALOG_SUB_REAL].owner;
2727                                                 if (p->subs[ANALOG_SUB_REAL].owner && ast_bridged_channel(p->subs[ANALOG_SUB_REAL].owner))
2728                                                         ast_queue_control(p->subs[ANALOG_SUB_REAL].owner, AST_CONTROL_UNHOLD);
2729                                                 analog_set_echocanceller(p, 1);
2730                                         }
2731                                 }
2732                         }
2733                 winkflashdone:
2734                         analog_update_conf(p);
2735                         break;
2736                 case ANALOG_SIG_EM:
2737                 case ANALOG_SIG_EM_E1:
2738                 case ANALOG_SIG_EMWINK:
2739                 case ANALOG_SIG_FEATD:
2740                 case ANALOG_SIG_SF:
2741                 case ANALOG_SIG_SFWINK:
2742                 case ANALOG_SIG_SF_FEATD:
2743                 case ANALOG_SIG_FXSLS:
2744                 case ANALOG_SIG_FXSGS:
2745                         if (p->dialing)
2746                                 ast_debug(1, "Ignoring wink on channel %d\n", p->channel);
2747                         else
2748                                 ast_debug(1, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
2749                         break;
2750                 case ANALOG_SIG_FEATDMF_TA:
2751                         switch (p->whichwink) {
2752                         case 0:
2753                                 ast_debug(1, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
2754                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
2755                                 break;
2756                         case 1:
2757                                 ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
2758                                 break;
2759                         case 2:
2760                                 ast_log(LOG_WARNING, "Received unexpected wink on channel of type ANALOG_SIG_FEATDMF_TA\n");
2761                                 return NULL;
2762                         }
2763                         p->whichwink++;
2764                         /* Fall through */
2765                 case ANALOG_SIG_FEATDMF:
2766                 case ANALOG_SIG_E911:
2767                 case ANALOG_SIG_FGC_CAMAMF:
2768                 case ANALOG_SIG_FGC_CAMA:
2769                 case ANALOG_SIG_FEATB:
2770                 case ANALOG_SIG_SF_FEATDMF:
2771                 case ANALOG_SIG_SF_FEATB:
2772                         /* FGD MF *Must* wait for wink */
2773                         if (!ast_strlen_zero(p->dop.dialstr)) {
2774                                 res = analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop);
2775                                 if (res < 0) {
2776                                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
2777                                         p->dop.dialstr[0] = '\0';
2778                                         return NULL;
2779                                 } else
2780                                         ast_debug(1, "Sent deferred digit string on channel %d: %s\n", p->channel, p->dop.dialstr);
2781                         }
2782                         p->dop.dialstr[0] = '\0';
2783                         break;
2784                 default:
2785                         ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
2786                 }
2787                 break;
2788         case ANALOG_EVENT_HOOKCOMPLETE:
2789                 if (p->inalarm) break;
2790                 switch (mysig) {
2791                 case ANALOG_SIG_FXSLS:  /* only interesting for FXS */
2792                 case ANALOG_SIG_FXSGS:
2793                 case ANALOG_SIG_FXSKS:
2794                 case ANALOG_SIG_EM:
2795                 case ANALOG_SIG_EM_E1:
2796                 case ANALOG_SIG_EMWINK:
2797                 case ANALOG_SIG_FEATD:
2798                 case ANALOG_SIG_SF:
2799                 case ANALOG_SIG_SFWINK:
2800                 case ANALOG_SIG_SF_FEATD:
2801                         if (!ast_strlen_zero(p->dop.dialstr)) {
2802                                 res = analog_dial_digits(p, ANALOG_SUB_REAL, &p->dop);
2803                                 if (res < 0) {
2804                                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
2805                                         p->dop.dialstr[0] = '\0';
2806                                         return NULL;
2807                                 } else 
2808                                         ast_debug(1, "Sent deferred digit string on channel %d: %s\n", p->channel, p->dop.dialstr);
2809                         }
2810                         p->dop.dialstr[0] = '\0';
2811                         p->dop.op = ANALOG_DIAL_OP_REPLACE;
2812                         break;
2813                 case ANALOG_SIG_FEATDMF:
2814                 case ANALOG_SIG_FEATDMF_TA:
2815                 case ANALOG_SIG_E911:
2816                 case ANALOG_SIG_FGC_CAMA:
2817                 case ANALOG_SIG_FGC_CAMAMF:
2818                 case ANALOG_SIG_FEATB:
2819                 case ANALOG_SIG_SF_FEATDMF:
2820                 case ANALOG_SIG_SF_FEATB:
2821                         ast_debug(1, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
2822                         break;
2823                 default:
2824                         break;
2825                 }
2826                 break;
2827         case ANALOG_EVENT_POLARITY:
2828                 /*
2829                  * If we get a Polarity Switch event, check to see
2830                  * if we should change the polarity state and
2831                  * mark the channel as UP or if this is an indication
2832                  * of remote end disconnect.
2833                  */
2834                 if (p->polarity == POLARITY_IDLE) {
2835                         p->polarity = POLARITY_REV;
2836                         if (p->answeronpolarityswitch &&
2837                             ((ast->_state == AST_STATE_DIALING) ||
2838                                  (ast->_state == AST_STATE_RINGING))) {
2839                                 ast_debug(1, "Answering on polarity switch!\n");
2840                                 ast_setstate(p->owner, AST_STATE_UP);
2841                                 if (p->hanguponpolarityswitch) {
2842                                         gettimeofday(&p->polaritydelaytv, NULL);
2843                                 }
2844                         } else
2845                                 ast_debug(1, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
2846                 }
2847                 /* Removed else statement from here as it was preventing hangups from ever happening*/
2848                 /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
2849                 if (p->hanguponpolarityswitch &&
2850                         (p->polarityonanswerdelay > 0) &&
2851                        (p->polarity == POLARITY_REV) &&
2852                         ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
2853                                /* Added log_debug information below to provide a better indication of what is going on */
2854                         ast_debug(1, "Polarity Reversal event occured - DEBUG 1: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %d\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
2855
2856                         if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
2857                                 ast_debug(1, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
2858                                 ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
2859                                 p->polarity = POLARITY_IDLE;
2860                         } else {
2861                                 ast_debug(1, "Polarity Reversal detected but NOT hanging up (too close to answer event) on channel %d, state %d\n", p->channel, ast->_state);
2862                         }
2863                 } else {
2864                         p->polarity = POLARITY_IDLE;
2865                         ast_debug(1, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
2866                 }
2867                 /* Added more log_debug information below to provide a better indication of what is going on */
2868                 ast_debug(1, "Polarity Reversal event occured - DEBUG 2: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %d\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
2869                 break;
2870         default:
2871                 ast_debug(1, "Dunno what to do with event %d on channel %d\n", res, p->channel);
2872         }
2873         return &p->subs[index].f;
2874 }
2875
2876 struct ast_frame *analog_exception(struct analog_pvt *p, struct ast_channel *ast)
2877 {
2878         int&n