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