update thread creation code a bit
[asterisk-bristuff.git] / channels / chan_zap.c
blob869a33313accd52b160eb8177d4cd44f40072c39
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Zaptel Pseudo TDM interface
23 * \author Mark Spencer <markster@digium.com>
25 * Connects to the zaptel telephony library as well as
26 * libpri. Libpri is optional and needed only if you are
27 * going to use ISDN connections.
29 * You need to install libraries before you attempt to compile
30 * and install the zaptel channel.
32 * \par See also
33 * \arg \ref Config_zap
35 * \ingroup channel_drivers
37 * \todo Deprecate the "musiconhold" configuration option post 1.4
40 /*** MODULEINFO
41 <depend>zaptel</depend>
42 <depend>tonezone</depend>
43 <use>pri</use>
44 ***/
46 #include "asterisk.h"
48 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50 #include <stdio.h>
51 #include <string.h>
52 #ifdef __NetBSD__
53 #include <pthread.h>
54 #include <signal.h>
55 #else
56 #include <sys/signal.h>
57 #endif
58 #include <errno.h>
59 #include <stdlib.h>
60 #if !defined(SOLARIS) && !defined(__FreeBSD__)
61 #include <stdint.h>
62 #endif
63 #include <unistd.h>
64 #include <sys/ioctl.h>
65 #include <math.h>
66 #include <ctype.h>
67 #include <zaptel/zaptel.h>
68 #include <zaptel/tonezone.h>
70 #ifdef HAVE_PRI
71 #include <libpri.h>
72 #endif
74 #include "asterisk/lock.h"
75 #include "asterisk/channel.h"
76 #include "asterisk/config.h"
77 #include "asterisk/logger.h"
78 #include "asterisk/module.h"
79 #include "asterisk/pbx.h"
80 #include "asterisk/options.h"
81 #include "asterisk/file.h"
82 #include "asterisk/ulaw.h"
83 #include "asterisk/alaw.h"
84 #include "asterisk/callerid.h"
85 #include "asterisk/adsi.h"
86 #include "asterisk/cli.h"
87 #include "asterisk/cdr.h"
88 #include "asterisk/features.h"
89 #include "asterisk/musiconhold.h"
90 #include "asterisk/say.h"
91 #include "asterisk/tdd.h"
92 #include "asterisk/app.h"
93 #include "asterisk/dsp.h"
94 #include "asterisk/astdb.h"
95 #include "asterisk/manager.h"
96 #include "asterisk/causes.h"
97 #include "asterisk/term.h"
98 #include "asterisk/utils.h"
99 #include "asterisk/transcap.h"
100 #include "asterisk/stringfields.h"
101 #include "asterisk/abstract_jb.h"
102 #include "asterisk/smdi.h"
103 #include "asterisk/astobj.h"
104 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
106 /*! Global jitterbuffer configuration - by default, jb is disabled */
107 static struct ast_jb_conf default_jbconf =
109 .flags = 0,
110 .max_size = -1,
111 .resync_threshold = -1,
112 .impl = ""
114 static struct ast_jb_conf global_jbconf;
116 #if !defined(ZT_SIG_EM_E1) || (defined(HAVE_PRI) && !defined(ZT_SIG_HARDHDLC))
117 #error "Your zaptel is too old. Please update"
118 #endif
120 #ifndef ZT_TONEDETECT
121 /* Work around older code with no tone detect */
122 #define ZT_EVENT_DTMFDOWN 0
123 #define ZT_EVENT_DTMFUP 0
124 #endif
126 /* define this to send PRI user-user information elements */
127 #undef SUPPORT_USERUSER
129 /*!
130 * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
131 * the user hangs up to reset the state machine so ring works properly.
132 * This is used to be able to support kewlstart by putting the zhone in
133 * groundstart mode since their forward disconnect supervision is entirely
134 * broken even though their documentation says it isn't and their support
135 * is entirely unwilling to provide any assistance with their channel banks
136 * even though their web site says they support their products for life.
138 /* #define ZHONE_HACK */
140 /*! \note
141 * Define if you want to check the hook state for an FXO (FXS signalled) interface
142 * before dialing on it. Certain FXO interfaces always think they're out of
143 * service with this method however.
145 /* #define ZAP_CHECK_HOOKSTATE */
147 /*! \brief Typically, how many rings before we should send Caller*ID */
148 #define DEFAULT_CIDRINGS 1
150 #define CHANNEL_PSEUDO -12
152 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
154 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
155 #define NEED_MFDETECT(p) (((p)->sig == SIG_FEATDMF) || ((p)->sig == SIG_FEATDMF_TA) || ((p)->sig == SIG_E911) || ((p)->sig == SIG_FGC_CAMA) || ((p)->sig == SIG_FGC_CAMAMF) || ((p)->sig == SIG_FEATB))
157 static const char tdesc[] = "Zapata Telephony Driver"
158 #ifdef HAVE_PRI
159 " w/PRI"
160 #endif
163 static const char config[] = "zapata.conf";
165 #define SIG_EM ZT_SIG_EM
166 #define SIG_EMWINK (0x0100000 | ZT_SIG_EM)
167 #define SIG_FEATD (0x0200000 | ZT_SIG_EM)
168 #define SIG_FEATDMF (0x0400000 | ZT_SIG_EM)
169 #define SIG_FEATB (0x0800000 | ZT_SIG_EM)
170 #define SIG_E911 (0x1000000 | ZT_SIG_EM)
171 #define SIG_FEATDMF_TA (0x2000000 | ZT_SIG_EM)
172 #define SIG_FGC_CAMA (0x4000000 | ZT_SIG_EM)
173 #define SIG_FGC_CAMAMF (0x8000000 | ZT_SIG_EM)
174 #define SIG_FXSLS ZT_SIG_FXSLS
175 #define SIG_FXSGS ZT_SIG_FXSGS
176 #define SIG_FXSKS ZT_SIG_FXSKS
177 #define SIG_FXOLS ZT_SIG_FXOLS
178 #define SIG_FXOGS ZT_SIG_FXOGS
179 #define SIG_FXOKS ZT_SIG_FXOKS
180 #define SIG_PRI ZT_SIG_CLEAR
181 #define SIG_SF ZT_SIG_SF
182 #define SIG_SFWINK (0x0100000 | ZT_SIG_SF)
183 #define SIG_SF_FEATD (0x0200000 | ZT_SIG_SF)
184 #define SIG_SF_FEATDMF (0x0400000 | ZT_SIG_SF)
185 #define SIG_SF_FEATB (0x0800000 | ZT_SIG_SF)
186 #define SIG_EM_E1 ZT_SIG_EM_E1
187 #define SIG_GR303FXOKS (0x0100000 | ZT_SIG_FXOKS)
188 #define SIG_GR303FXSKS (0x0100000 | ZT_SIG_FXSKS)
190 #define NUM_SPANS 32
191 #define NUM_DCHANS 4 /*!< No more than 4 d-channels */
192 #define MAX_CHANNELS 672 /*!< No more than a DS3 per trunk group */
194 #define CHAN_PSEUDO -2
196 #define DCHAN_PROVISIONED (1 << 0)
197 #define DCHAN_NOTINALARM (1 << 1)
198 #define DCHAN_UP (1 << 2)
200 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
202 static char context[AST_MAX_CONTEXT] = "default";
203 static char cid_num[256] = "";
204 static char cid_name[256] = "";
205 static char defaultcic[64] = "";
206 static char defaultozz[64] = "";
208 static char language[MAX_LANGUAGE] = "";
209 static char mohinterpret[MAX_MUSICCLASS] = "default";
210 static char mohsuggest[MAX_MUSICCLASS] = "";
211 static char progzone[10] = "";
213 static int usedistinctiveringdetection = 0;
214 static int distinctiveringaftercid = 0;
216 static int transfertobusy = 1;
218 static int use_callerid = 1;
219 static int cid_signalling = CID_SIG_BELL;
220 static int cid_start = CID_START_RING;
221 static int zaptrcallerid = 0;
222 static int cur_radio = 0;
223 static int cur_signalling = -1;
224 static int cur_outsignalling = -1;
226 static ast_group_t cur_group = 0;
227 static ast_group_t cur_callergroup = 0;
228 static ast_group_t cur_pickupgroup = 0;
229 static int relaxdtmf = 0;
231 static int immediate = 0;
233 static int stripmsd = 0;
235 static int callwaiting = 0;
237 static int callwaitingcallerid = 0;
239 static int hidecallerid = 0;
241 static int restrictcid = 0;
243 static int use_callingpres = 0;
245 static int callreturn = 0;
247 static int threewaycalling = 0;
249 static int transfer = 0;
251 static int canpark = 0;
253 static int cancallforward = 0;
255 static float rxgain = 0.0;
257 static float txgain = 0.0;
259 static int tonezone = -1;
261 static int echocancel;
263 static int echotraining;
265 static int pulse;
267 static int echocanbridged = 0;
269 static int busydetect = 0;
271 static int busycount = 3;
272 static int busy_tonelength = 0;
273 static int busy_quietlength = 0;
275 static int callprogress = 0;
277 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
279 static char mailbox[AST_MAX_EXTENSION];
281 static int amaflags = 0;
283 static int adsi = 0;
284 static int use_smdi = 0;
285 static char smdi_port[SMDI_MAX_FILENAME_LEN] = "/dev/ttyS0";
286 static int numbufs = 4;
288 static int cur_prewink = -1;
289 static int cur_preflash = -1;
290 static int cur_wink = -1;
291 static int cur_flash = -1;
292 static int cur_start = -1;
293 static int cur_rxwink = -1;
294 static int cur_rxflash = -1;
295 static int cur_debounce = -1;
296 static int cur_priexclusive = 0;
298 static int priindication_oob = 0;
300 #ifdef HAVE_PRI
301 static int minunused = 2;
302 static int minidle = 0;
303 static char idleext[AST_MAX_EXTENSION];
304 static char idledial[AST_MAX_EXTENSION];
305 static int overlapdial = 0;
306 static int facilityenable = 0;
307 static char internationalprefix[10] = "";
308 static char nationalprefix[10] = "";
309 static char localprefix[20] = "";
310 static char privateprefix[20] = "";
311 static char unknownprefix[20] = "";
312 static long resetinterval = 3600; /*!< How often (in seconds) to reset unused channels. Default 1 hour. */
313 static struct ast_channel inuse;
314 #ifdef PRI_GETSET_TIMERS
315 static int pritimers[PRI_MAX_TIMERS];
316 #endif
317 static int pridebugfd = -1;
318 static char pridebugfilename[1024] = "";
319 #endif
321 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
322 static int firstdigittimeout = 16000;
324 /*! \brief How long to wait for following digits (FXO logic) */
325 static int gendigittimeout = 8000;
327 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
328 static int matchdigittimeout = 3000;
330 static int usecnt = 0;
332 /*! \brief Protect the interface list (of zt_pvt's) */
333 AST_MUTEX_DEFINE_STATIC(iflock);
336 static int ifcount = 0;
338 #ifdef HAVE_PRI
339 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
340 #endif
342 /*! \brief Whether we answer on a Polarity Switch event */
343 static int answeronpolarityswitch = 0;
345 /*! \brief Whether we hang up on a Polarity Switch event */
346 static int hanguponpolarityswitch = 0;
348 /*! \brief How long (ms) to ignore Polarity Switch events after we answer a call */
349 static int polarityonanswerdelay = 600;
351 /*! \brief When to send the CallerID signals (rings) */
352 static int sendcalleridafter = DEFAULT_CIDRINGS;
354 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
355 when it's doing something critical. */
356 AST_MUTEX_DEFINE_STATIC(monlock);
358 /*! \brief This is the thread for the monitor which checks for input on the channels
359 which are not currently in use. */
360 static pthread_t monitor_thread = AST_PTHREADT_NULL;
362 static int restart_monitor(void);
364 static enum ast_bridge_result zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
366 static int zt_sendtext(struct ast_channel *c, const char *text);
368 /*! \brief Avoid the silly zt_getevent which ignores a bunch of events */
369 static inline int zt_get_event(int fd)
371 int j;
372 if (ioctl(fd, ZT_GETEVENT, &j) == -1)
373 return -1;
374 return j;
377 /*! \brief Avoid the silly zt_waitevent which ignores a bunch of events */
378 static inline int zt_wait_event(int fd)
380 int i, j = 0;
381 i = ZT_IOMUX_SIGEVENT;
382 if (ioctl(fd, ZT_IOMUX, &i) == -1)
383 return -1;
384 if (ioctl(fd, ZT_GETEVENT, &j) == -1)
385 return -1;
386 return j;
389 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
390 #define READ_SIZE 160
392 #define MASK_AVAIL (1 << 0) /*!< Channel available for PRI use */
393 #define MASK_INUSE (1 << 1) /*!< Channel currently in use */
395 #define CALLWAITING_SILENT_SAMPLES ( (300 * 8) / READ_SIZE) /*!< 300 ms */
396 #define CALLWAITING_REPEAT_SAMPLES ( (10000 * 8) / READ_SIZE) /*!< 300 ms */
397 #define CIDCW_EXPIRE_SAMPLES ( (500 * 8) / READ_SIZE) /*!< 500 ms */
398 #define MIN_MS_SINCE_FLASH ( (2000) ) /*!< 2000 ms */
399 #define DEFAULT_RINGT ( (8000 * 8) / READ_SIZE)
401 struct zt_pvt;
403 static int ringt_base = DEFAULT_RINGT;
405 #ifdef HAVE_PRI
407 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
408 #define PRI_CHANNEL(p) ((p) & 0xff)
409 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
410 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
412 struct zt_pri {
413 pthread_t master; /*!< Thread of master */
414 ast_mutex_t lock; /*!< Mutex */
415 char idleext[AST_MAX_EXTENSION]; /*!< Where to idle extra calls */
416 char idlecontext[AST_MAX_CONTEXT]; /*!< What context to use for idle */
417 char idledial[AST_MAX_EXTENSION]; /*!< What to dial before dumping */
418 int minunused; /*!< Min # of channels to keep empty */
419 int minidle; /*!< Min # of "idling" calls to keep active */
420 int nodetype; /*!< Node type */
421 int switchtype; /*!< Type of switch to emulate */
422 int nsf; /*!< Network-Specific Facilities */
423 int dialplan; /*!< Dialing plan */
424 int localdialplan; /*!< Local dialing plan */
425 char internationalprefix[10]; /*!< country access code ('00' for european dialplans) */
426 char nationalprefix[10]; /*!< area access code ('0' for european dialplans) */
427 char localprefix[20]; /*!< area access code + area code ('0'+area code for european dialplans) */
428 char privateprefix[20]; /*!< for private dialplans */
429 char unknownprefix[20]; /*!< for unknown dialplans */
430 int dchannels[NUM_DCHANS]; /*!< What channel are the dchannels on */
431 int trunkgroup; /*!< What our trunkgroup is */
432 int mastertrunkgroup; /*!< What trunk group is our master */
433 int prilogicalspan; /*!< Logical span number within trunk group */
434 int numchans; /*!< Num of channels we represent */
435 int overlapdial; /*!< In overlap dialing mode */
436 int facilityenable; /*!< Enable facility IEs */
437 struct pri *dchans[NUM_DCHANS]; /*!< Actual d-channels */
438 int dchanavail[NUM_DCHANS]; /*!< Whether each channel is available */
439 struct pri *pri; /*!< Currently active D-channel */
440 int debug;
441 int fds[NUM_DCHANS]; /*!< FD's for d-channels */
442 int offset;
443 int span;
444 int resetting;
445 int resetpos;
446 time_t lastreset; /*!< time when unused channels were last reset */
447 long resetinterval; /*!< Interval (in seconds) for resetting unused channels */
448 struct zt_pvt *pvts[MAX_CHANNELS]; /*!< Member channel pvt structs */
449 struct zt_pvt *crvs; /*!< Member CRV structs */
450 struct zt_pvt *crvend; /*!< Pointer to end of CRV structs */
454 static struct zt_pri pris[NUM_SPANS];
456 static int pritype = PRI_CPE;
458 #if 0
459 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
460 #else
461 #define DEFAULT_PRI_DEBUG 0
462 #endif
464 static inline void pri_rel(struct zt_pri *pri)
466 ast_mutex_unlock(&pri->lock);
469 static int switchtype = PRI_SWITCH_NI2;
470 static int nsf = PRI_NSF_NONE;
471 static int dialplan = PRI_NATIONAL_ISDN + 1;
472 static int localdialplan = PRI_NATIONAL_ISDN + 1;
474 #else
475 /*! Shut up the compiler */
476 struct zt_pri;
477 #endif
479 #define SUB_REAL 0 /*!< Active call */
480 #define SUB_CALLWAIT 1 /*!< Call-Waiting call on hold */
481 #define SUB_THREEWAY 2 /*!< Three-way call */
483 /* Polarity states */
484 #define POLARITY_IDLE 0
485 #define POLARITY_REV 1
488 static struct zt_distRings drings;
490 struct distRingData {
491 int ring[3];
493 struct ringContextData {
494 char contextData[AST_MAX_CONTEXT];
496 struct zt_distRings {
497 struct distRingData ringnum[3];
498 struct ringContextData ringContext[3];
501 static char *subnames[] = {
502 "Real",
503 "Callwait",
504 "Threeway"
507 struct zt_subchannel {
508 int zfd;
509 struct ast_channel *owner;
510 int chan;
511 short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
512 struct ast_frame f; /*!< One frame for each channel. How did this ever work before? */
513 unsigned int needringing:1;
514 unsigned int needbusy:1;
515 unsigned int needcongestion:1;
516 unsigned int needcallerid:1;
517 unsigned int needanswer:1;
518 unsigned int needflash:1;
519 unsigned int needhold:1;
520 unsigned int needunhold:1;
521 unsigned int linear:1;
522 unsigned int inthreeway:1;
523 ZT_CONFINFO curconf;
526 #define CONF_USER_REAL (1 << 0)
527 #define CONF_USER_THIRDCALL (1 << 1)
529 #define MAX_SLAVES 4
531 static struct zt_pvt {
532 ast_mutex_t lock;
533 struct ast_channel *owner; /*!< Our current active owner (if applicable) */
534 /*!< Up to three channels can be associated with this call */
536 struct zt_subchannel sub_unused; /*!< Just a safety precaution */
537 struct zt_subchannel subs[3]; /*!< Sub-channels */
538 struct zt_confinfo saveconf; /*!< Saved conference info */
540 struct zt_pvt *slaves[MAX_SLAVES]; /*!< Slave to us (follows our conferencing) */
541 struct zt_pvt *master; /*!< Master to us (we follow their conferencing) */
542 int inconference; /*!< If our real should be in the conference */
544 int sig; /*!< Signalling style */
545 int radio; /*!< radio type */
546 int outsigmod; /*!< Outbound Signalling style (modifier) */
547 int oprmode; /*!< "Operator Services" mode */
548 struct zt_pvt *oprpeer; /*!< "Operator Services" peer tech_pvt ptr */
549 float rxgain;
550 float txgain;
551 int tonezone; /*!< tone zone for this chan, or -1 for default */
552 struct zt_pvt *next; /*!< Next channel in list */
553 struct zt_pvt *prev; /*!< Prev channel in list */
555 /* flags */
556 unsigned int adsi:1;
557 unsigned int answeronpolarityswitch:1;
558 unsigned int busydetect:1;
559 unsigned int callreturn:1;
560 unsigned int callwaiting:1;
561 unsigned int callwaitingcallerid:1;
562 unsigned int cancallforward:1;
563 unsigned int canpark:1;
564 unsigned int confirmanswer:1; /*!< Wait for '#' to confirm answer */
565 unsigned int destroy:1;
566 unsigned int didtdd:1; /*!< flag to say its done it once */
567 unsigned int dialednone:1;
568 unsigned int dialing:1;
569 unsigned int digital:1;
570 unsigned int dnd:1;
571 unsigned int echobreak:1;
572 unsigned int echocanbridged:1;
573 unsigned int echocanon:1;
574 unsigned int faxhandled:1; /*!< Has a fax tone already been handled? */
575 unsigned int firstradio:1;
576 unsigned int hanguponpolarityswitch:1;
577 unsigned int hardwaredtmf:1;
578 unsigned int hidecallerid;
579 unsigned int ignoredtmf:1;
580 unsigned int immediate:1; /*!< Answer before getting digits? */
581 unsigned int inalarm:1;
582 unsigned int mate:1; /*!< flag to say its in MATE mode */
583 unsigned int outgoing:1;
584 unsigned int overlapdial:1;
585 unsigned int permcallwaiting:1;
586 unsigned int permhidecallerid:1; /*!< Whether to hide our outgoing caller ID or not */
587 unsigned int priindication_oob:1;
588 unsigned int priexclusive:1;
589 unsigned int pulse:1;
590 unsigned int pulsedial:1; /*!< whether a pulse dial phone is detected */
591 unsigned int restrictcid:1; /*!< Whether restrict the callerid -> only send ANI */
592 unsigned int threewaycalling:1;
593 unsigned int transfer:1;
594 unsigned int use_callerid:1; /*!< Whether or not to use caller id on this channel */
595 unsigned int use_callingpres:1; /*!< Whether to use the callingpres the calling switch sends */
596 unsigned int usedistinctiveringdetection:1;
597 unsigned int zaptrcallerid:1; /*!< should we use the callerid from incoming call on zap transfer or not */
598 unsigned int transfertobusy:1; /*!< allow flash-transfers to busy channels */
599 #if defined(HAVE_PRI)
600 unsigned int alerting:1;
601 unsigned int alreadyhungup:1;
602 unsigned int isidlecall:1;
603 unsigned int proceeding:1;
604 unsigned int progress:1;
605 unsigned int resetting:1;
606 unsigned int setup_ack:1;
607 #endif
608 unsigned int use_smdi:1; /* Whether to use SMDI on this channel */
609 struct ast_smdi_interface *smdi_iface; /* The serial port to listen for SMDI data on */
611 struct zt_distRings drings;
613 char context[AST_MAX_CONTEXT];
614 char defcontext[AST_MAX_CONTEXT];
615 char exten[AST_MAX_EXTENSION];
616 char language[MAX_LANGUAGE];
617 char mohinterpret[MAX_MUSICCLASS];
618 char mohsuggest[MAX_MUSICCLASS];
619 #ifdef PRI_ANI
620 char cid_ani[AST_MAX_EXTENSION];
621 #endif
622 char cid_num[AST_MAX_EXTENSION];
623 int cid_ton; /*!< Type Of Number (TON) */
624 char cid_name[AST_MAX_EXTENSION];
625 char lastcid_num[AST_MAX_EXTENSION];
626 char lastcid_name[AST_MAX_EXTENSION];
627 char *origcid_num; /*!< malloced original callerid */
628 char *origcid_name; /*!< malloced original callerid */
629 char callwait_num[AST_MAX_EXTENSION];
630 char callwait_name[AST_MAX_EXTENSION];
631 char rdnis[AST_MAX_EXTENSION];
632 char dnid[AST_MAX_EXTENSION];
633 unsigned int group;
634 int law;
635 int confno; /*!< Our conference */
636 int confusers; /*!< Who is using our conference */
637 int propconfno; /*!< Propagated conference number */
638 ast_group_t callgroup;
639 ast_group_t pickupgroup;
640 int channel; /*!< Channel Number or CRV */
641 int span; /*!< Span number */
642 time_t guardtime; /*!< Must wait this much time before using for new call */
643 int cid_signalling; /*!< CID signalling type bell202 or v23 */
644 int cid_start; /*!< CID start indicator, polarity or ring */
645 int callingpres; /*!< The value of callling presentation that we're going to use when placing a PRI call */
646 int callwaitingrepeat; /*!< How many samples to wait before repeating call waiting */
647 int cidcwexpire; /*!< When to expire our muting for CID/CW */
648 unsigned char *cidspill;
649 int cidpos;
650 int cidlen;
651 int ringt;
652 int ringt_base;
653 int stripmsd;
654 int callwaitcas;
655 int callwaitrings;
656 int echocancel;
657 int echotraining;
658 char echorest[20];
659 int busycount;
660 int busy_tonelength;
661 int busy_quietlength;
662 int callprogress;
663 struct timeval flashtime; /*!< Last flash-hook time */
664 struct ast_dsp *dsp;
665 int cref; /*!< Call reference number */
666 ZT_DIAL_OPERATION dop;
667 int whichwink; /*!< SIG_FEATDMF_TA Which wink are we on? */
668 char finaldial[64];
669 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
670 int amaflags; /*!< AMA Flags */
671 struct tdd_state *tdd; /*!< TDD flag */
672 char call_forward[AST_MAX_EXTENSION];
673 char mailbox[AST_MAX_EXTENSION];
674 char dialdest[256];
675 int onhooktime;
676 int msgstate;
677 int distinctivering; /*!< Which distinctivering to use */
678 int cidrings; /*!< Which ring to deliver CID on */
679 int dtmfrelax; /*!< whether to run in relaxed DTMF mode */
680 int fake_event;
681 int polarityonanswerdelay;
682 struct timeval polaritydelaytv;
683 int sendcalleridafter;
684 #ifdef HAVE_PRI
685 struct zt_pri *pri;
686 struct zt_pvt *bearer;
687 struct zt_pvt *realcall;
688 q931_call *call;
689 int prioffset;
690 int logicalspan;
691 #endif
692 int polarity;
693 int dsp_features;
694 char begindigit;
695 } *iflist = NULL, *ifend = NULL;
697 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
698 static int zt_digit_begin(struct ast_channel *ast, char digit);
699 static int zt_digit_end(struct ast_channel *ast, char digit);
700 static int zt_sendtext(struct ast_channel *c, const char *text);
701 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
702 static int zt_hangup(struct ast_channel *ast);
703 static int zt_answer(struct ast_channel *ast);
704 static struct ast_frame *zt_read(struct ast_channel *ast);
705 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
706 static struct ast_frame *zt_exception(struct ast_channel *ast);
707 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
708 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
709 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
710 static int zt_func_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
712 static const struct ast_channel_tech zap_tech = {
713 .type = "Zap",
714 .description = tdesc,
715 .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
716 .requester = zt_request,
717 .send_digit_begin = zt_digit_begin,
718 .send_digit_end = zt_digit_end,
719 .send_text = zt_sendtext,
720 .call = zt_call,
721 .hangup = zt_hangup,
722 .answer = zt_answer,
723 .read = zt_read,
724 .write = zt_write,
725 .bridge = zt_bridge,
726 .exception = zt_exception,
727 .indicate = zt_indicate,
728 .fixup = zt_fixup,
729 .setoption = zt_setoption,
730 .func_channel_read = zt_func_read,
733 #ifdef HAVE_PRI
734 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
735 #else
736 #define GET_CHANNEL(p) ((p)->channel)
737 #endif
739 struct zt_pvt *round_robin[32];
741 #ifdef HAVE_PRI
742 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
744 int res;
745 /* Grab the lock first */
746 do {
747 res = ast_mutex_trylock(&pri->lock);
748 if (res) {
749 ast_mutex_unlock(&pvt->lock);
750 /* Release the lock and try again */
751 usleep(1);
752 ast_mutex_lock(&pvt->lock);
754 } while (res);
755 /* Then break the poll */
756 pthread_kill(pri->master, SIGURG);
757 return 0;
759 #endif
761 #define NUM_CADENCE_MAX 25
762 static int num_cadence = 4;
763 static int user_has_defined_cadences = 0;
765 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
766 { { 125, 125, 2000, 4000 } }, /*!< Quick chirp followed by normal ring */
767 { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
768 { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
769 { { 1000, 500, 2500, 5000 } }, /*!< Long ring */
772 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
773 * is 1, the second pause is 2 and so on.
776 static int cidrings[NUM_CADENCE_MAX] = {
777 2, /*!< Right after first long ring */
778 4, /*!< Right after long part */
779 3, /*!< After third chirp */
780 2, /*!< Second spell */
783 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
784 (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
786 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
787 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
789 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
791 int res;
792 if (p->subs[0].owner == ast)
793 res = 0;
794 else if (p->subs[1].owner == ast)
795 res = 1;
796 else if (p->subs[2].owner == ast)
797 res = 2;
798 else {
799 res = -1;
800 if (!nullok)
801 ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
803 return res;
806 #ifdef HAVE_PRI
807 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
808 #else
809 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
810 #endif
812 #ifdef HAVE_PRI
813 if (pri)
814 ast_mutex_unlock(&pri->lock);
815 #endif
816 for (;;) {
817 if (p->subs[a].owner) {
818 if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
819 ast_mutex_unlock(&p->lock);
820 usleep(1);
821 ast_mutex_lock(&p->lock);
822 } else {
823 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
824 ast_mutex_unlock(&p->subs[a].owner->lock);
825 break;
827 } else
828 break;
830 #ifdef HAVE_PRI
831 if (pri)
832 ast_mutex_lock(&pri->lock);
833 #endif
836 #ifdef HAVE_PRI
837 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, struct zt_pri *pri)
838 #else
839 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *pri)
840 #endif
842 /* We must unlock the PRI to avoid the possibility of a deadlock */
843 #ifdef HAVE_PRI
844 if (pri)
845 ast_mutex_unlock(&pri->lock);
846 #endif
847 for (;;) {
848 if (p->owner) {
849 if (ast_mutex_trylock(&p->owner->lock)) {
850 ast_mutex_unlock(&p->lock);
851 usleep(1);
852 ast_mutex_lock(&p->lock);
853 } else {
854 ast_queue_frame(p->owner, f);
855 ast_mutex_unlock(&p->owner->lock);
856 break;
858 } else
859 break;
861 #ifdef HAVE_PRI
862 if (pri)
863 ast_mutex_lock(&pri->lock);
864 #endif
867 static int restore_gains(struct zt_pvt *p);
869 static void swap_subs(struct zt_pvt *p, int a, int b)
871 int tchan;
872 int tinthreeway;
873 struct ast_channel *towner;
875 ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
877 tchan = p->subs[a].chan;
878 towner = p->subs[a].owner;
879 tinthreeway = p->subs[a].inthreeway;
881 p->subs[a].chan = p->subs[b].chan;
882 p->subs[a].owner = p->subs[b].owner;
883 p->subs[a].inthreeway = p->subs[b].inthreeway;
885 p->subs[b].chan = tchan;
886 p->subs[b].owner = towner;
887 p->subs[b].inthreeway = tinthreeway;
889 if (p->subs[a].owner)
890 p->subs[a].owner->fds[0] = p->subs[a].zfd;
891 if (p->subs[b].owner)
892 p->subs[b].owner->fds[0] = p->subs[b].zfd;
893 wakeup_sub(p, a, NULL);
894 wakeup_sub(p, b, NULL);
897 static int zt_open(char *fn)
899 int fd;
900 int isnum;
901 int chan = 0;
902 int bs;
903 int x;
904 isnum = 1;
905 for (x = 0; x < strlen(fn); x++) {
906 if (!isdigit(fn[x])) {
907 isnum = 0;
908 break;
911 if (isnum) {
912 chan = atoi(fn);
913 if (chan < 1) {
914 ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
915 return -1;
917 fn = "/dev/zap/channel";
919 fd = open(fn, O_RDWR | O_NONBLOCK);
920 if (fd < 0) {
921 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
922 return -1;
924 if (chan) {
925 if (ioctl(fd, ZT_SPECIFY, &chan)) {
926 x = errno;
927 close(fd);
928 errno = x;
929 ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
930 return -1;
933 bs = READ_SIZE;
934 if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) return -1;
935 return fd;
938 static void zt_close(int fd)
940 if (fd > 0)
941 close(fd);
944 static int zt_setlinear(int zfd, int linear)
946 int res;
947 res = ioctl(zfd, ZT_SETLINEAR, &linear);
948 if (res)
949 return res;
950 return 0;
954 static int alloc_sub(struct zt_pvt *p, int x)
956 ZT_BUFFERINFO bi;
957 int res;
958 if (p->subs[x].zfd < 0) {
959 p->subs[x].zfd = zt_open("/dev/zap/pseudo");
960 if (p->subs[x].zfd > -1) {
961 res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
962 if (!res) {
963 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
964 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
965 bi.numbufs = numbufs;
966 res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
967 if (res < 0) {
968 ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
970 } else
971 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
972 if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
973 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d\n", p->subs[x].zfd);
974 zt_close(p->subs[x].zfd);
975 p->subs[x].zfd = -1;
976 return -1;
978 if (option_debug)
979 ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
980 return 0;
981 } else
982 ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
983 return -1;
985 ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
986 return -1;
989 static int unalloc_sub(struct zt_pvt *p, int x)
991 if (!x) {
992 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
993 return -1;
995 ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
996 if (p->subs[x].zfd > -1) {
997 zt_close(p->subs[x].zfd);
999 p->subs[x].zfd = -1;
1000 p->subs[x].linear = 0;
1001 p->subs[x].chan = 0;
1002 p->subs[x].owner = NULL;
1003 p->subs[x].inthreeway = 0;
1004 p->polarity = POLARITY_IDLE;
1005 memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
1006 return 0;
1009 static int digit_to_dtmfindex(char digit)
1011 if (isdigit(digit))
1012 return ZT_TONE_DTMF_BASE + (digit - '0');
1013 else if (digit >= 'A' && digit <= 'D')
1014 return ZT_TONE_DTMF_A + (digit - 'A');
1015 else if (digit >= 'a' && digit <= 'd')
1016 return ZT_TONE_DTMF_A + (digit - 'a');
1017 else if (digit == '*')
1018 return ZT_TONE_DTMF_s;
1019 else if (digit == '#')
1020 return ZT_TONE_DTMF_p;
1021 else
1022 return -1;
1025 static int zt_digit_begin(struct ast_channel *chan, char digit)
1027 struct zt_pvt *pvt;
1028 int index;
1029 int dtmf = -1;
1031 pvt = chan->tech_pvt;
1033 ast_mutex_lock(&pvt->lock);
1035 index = zt_get_index(chan, pvt, 0);
1037 if ((index != SUB_REAL) || !pvt->owner)
1038 goto out;
1040 #ifdef HAVE_PRI
1041 if ((pvt->sig == SIG_PRI) && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
1042 if (pvt->setup_ack) {
1043 if (!pri_grab(pvt, pvt->pri)) {
1044 pri_information(pvt->pri->pri, pvt->call, digit);
1045 pri_rel(pvt->pri);
1046 } else
1047 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
1048 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
1049 int res;
1050 ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
1051 res = strlen(pvt->dialdest);
1052 pvt->dialdest[res++] = digit;
1053 pvt->dialdest[res] = '\0';
1055 goto out;
1057 #endif
1058 if ((dtmf = digit_to_dtmfindex(digit)) == -1)
1059 goto out;
1061 if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &dtmf)) {
1062 int res;
1063 ZT_DIAL_OPERATION zo = {
1064 .op = ZT_DIAL_OP_APPEND,
1065 .dialstr[0] = 'T',
1066 .dialstr[1] = digit,
1067 .dialstr[2] = 0,
1069 if ((res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
1070 ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
1071 else
1072 pvt->dialing = 1;
1073 } else {
1074 ast_log(LOG_DEBUG, "Started VLDTMF digit '%c'\n", digit);
1075 pvt->dialing = 1;
1076 pvt->begindigit = digit;
1079 out:
1080 ast_mutex_unlock(&pvt->lock);
1082 return 0; /* Tell Asterisk not to generate inband indications */
1085 static int zt_digit_end(struct ast_channel *chan, char digit)
1087 struct zt_pvt *pvt;
1088 int res = 0;
1089 int index;
1090 int x;
1092 pvt = chan->tech_pvt;
1094 ast_mutex_lock(&pvt->lock);
1096 index = zt_get_index(chan, pvt, 0);
1098 if ((index != SUB_REAL) || !pvt->owner || pvt->pulse)
1099 goto out;
1101 #ifdef HAVE_PRI
1102 /* This means that the digit was already sent via PRI signalling */
1103 if (pvt->sig == SIG_PRI && !pvt->begindigit)
1104 goto out;
1105 #endif
1107 if (pvt->begindigit) {
1108 x = -1;
1109 ast_log(LOG_DEBUG, "Ending VLDTMF digit '%c'\n", digit);
1110 res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &x);
1111 pvt->dialing = 0;
1112 pvt->begindigit = 0;
1115 out:
1116 ast_mutex_unlock(&pvt->lock);
1118 return res;
1121 static char *events[] = {
1122 "No event",
1123 "On hook",
1124 "Ring/Answered",
1125 "Wink/Flash",
1126 "Alarm",
1127 "No more alarm",
1128 "HDLC Abort",
1129 "HDLC Overrun",
1130 "HDLC Bad FCS",
1131 "Dial Complete",
1132 "Ringer On",
1133 "Ringer Off",
1134 "Hook Transition Complete",
1135 "Bits Changed",
1136 "Pulse Start",
1137 "Timer Expired",
1138 "Timer Ping",
1139 "Polarity Reversal",
1140 "Ring Begin",
1143 static struct {
1144 int alarm;
1145 char *name;
1146 } alarms[] = {
1147 { ZT_ALARM_RED, "Red Alarm" },
1148 { ZT_ALARM_YELLOW, "Yellow Alarm" },
1149 { ZT_ALARM_BLUE, "Blue Alarm" },
1150 { ZT_ALARM_RECOVER, "Recovering" },
1151 { ZT_ALARM_LOOPBACK, "Loopback" },
1152 { ZT_ALARM_NOTOPEN, "Not Open" },
1153 { ZT_ALARM_NONE, "None" },
1156 static char *alarm2str(int alarm)
1158 int x;
1159 for (x = 0; x < sizeof(alarms) / sizeof(alarms[0]); x++) {
1160 if (alarms[x].alarm & alarm)
1161 return alarms[x].name;
1163 return alarm ? "Unknown Alarm" : "No Alarm";
1166 static char *event2str(int event)
1168 static char buf[256];
1169 if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
1170 return events[event];
1171 sprintf(buf, "Event %d", event); /* safe */
1172 return buf;
1175 #ifdef HAVE_PRI
1176 static char *dialplan2str(int dialplan)
1178 if (dialplan == -1) {
1179 return("Dynamically set dialplan in ISDN");
1181 return (pri_plan2str(dialplan));
1183 #endif
1185 static char *zap_sig2str(int sig)
1187 static char buf[256];
1188 switch (sig) {
1189 case SIG_EM:
1190 return "E & M Immediate";
1191 case SIG_EMWINK:
1192 return "E & M Wink";
1193 case SIG_EM_E1:
1194 return "E & M E1";
1195 case SIG_FEATD:
1196 return "Feature Group D (DTMF)";
1197 case SIG_FEATDMF:
1198 return "Feature Group D (MF)";
1199 case SIG_FEATDMF_TA:
1200 return "Feature Groud D (MF) Tandem Access";
1201 case SIG_FEATB:
1202 return "Feature Group B (MF)";
1203 case SIG_E911:
1204 return "E911 (MF)";
1205 case SIG_FGC_CAMA:
1206 return "FGC/CAMA (Dialpulse)";
1207 case SIG_FGC_CAMAMF:
1208 return "FGC/CAMA (MF)";
1209 case SIG_FXSLS:
1210 return "FXS Loopstart";
1211 case SIG_FXSGS:
1212 return "FXS Groundstart";
1213 case SIG_FXSKS:
1214 return "FXS Kewlstart";
1215 case SIG_FXOLS:
1216 return "FXO Loopstart";
1217 case SIG_FXOGS:
1218 return "FXO Groundstart";
1219 case SIG_FXOKS:
1220 return "FXO Kewlstart";
1221 case SIG_PRI:
1222 return "PRI Signalling";
1223 case SIG_SF:
1224 return "SF (Tone) Signalling Immediate";
1225 case SIG_SFWINK:
1226 return "SF (Tone) Signalling Wink";
1227 case SIG_SF_FEATD:
1228 return "SF (Tone) Signalling with Feature Group D (DTMF)";
1229 case SIG_SF_FEATDMF:
1230 return "SF (Tone) Signalling with Feature Group D (MF)";
1231 case SIG_SF_FEATB:
1232 return "SF (Tone) Signalling with Feature Group B (MF)";
1233 case SIG_GR303FXOKS:
1234 return "GR-303 Signalling with FXOKS";
1235 case SIG_GR303FXSKS:
1236 return "GR-303 Signalling with FXSKS";
1237 case 0:
1238 return "Pseudo Signalling";
1239 default:
1240 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1241 return buf;
1245 #define sig2str zap_sig2str
1247 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1249 /* If the conference already exists, and we're already in it
1250 don't bother doing anything */
1251 ZT_CONFINFO zi;
1253 memset(&zi, 0, sizeof(zi));
1254 zi.chan = 0;
1256 if (slavechannel > 0) {
1257 /* If we have only one slave, do a digital mon */
1258 zi.confmode = ZT_CONF_DIGITALMON;
1259 zi.confno = slavechannel;
1260 } else {
1261 if (!index) {
1262 /* Real-side and pseudo-side both participate in conference */
1263 zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1264 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1265 } else
1266 zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1267 zi.confno = p->confno;
1269 if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1270 return 0;
1271 if (c->zfd < 0)
1272 return 0;
1273 if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1274 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1275 return -1;
1277 if (slavechannel < 1) {
1278 p->confno = zi.confno;
1280 memcpy(&c->curconf, &zi, sizeof(c->curconf));
1281 ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1282 return 0;
1285 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1287 /* If they're listening to our channel, they're ours */
1288 if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1289 return 1;
1290 /* If they're a talker on our (allocated) conference, they're ours */
1291 if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1292 return 1;
1293 return 0;
1296 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1298 ZT_CONFINFO zi;
1299 if (/* Can't delete if there's no zfd */
1300 (c->zfd < 0) ||
1301 /* Don't delete from the conference if it's not our conference */
1302 !isourconf(p, c)
1303 /* Don't delete if we don't think it's conferenced at all (implied) */
1304 ) return 0;
1305 memset(&zi, 0, sizeof(zi));
1306 zi.chan = 0;
1307 zi.confno = 0;
1308 zi.confmode = 0;
1309 if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1310 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1311 return -1;
1313 ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1314 memcpy(&c->curconf, &zi, sizeof(c->curconf));
1315 return 0;
1318 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1320 int x;
1321 int useslavenative;
1322 struct zt_pvt *slave = NULL;
1323 /* Start out optimistic */
1324 useslavenative = 1;
1325 /* Update conference state in a stateless fashion */
1326 for (x = 0; x < 3; x++) {
1327 /* Any three-way calling makes slave native mode *definitely* out
1328 of the question */
1329 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1330 useslavenative = 0;
1332 /* If we don't have any 3-way calls, check to see if we have
1333 precisely one slave */
1334 if (useslavenative) {
1335 for (x = 0; x < MAX_SLAVES; x++) {
1336 if (p->slaves[x]) {
1337 if (slave) {
1338 /* Whoops already have a slave! No
1339 slave native and stop right away */
1340 slave = NULL;
1341 useslavenative = 0;
1342 break;
1343 } else {
1344 /* We have one slave so far */
1345 slave = p->slaves[x];
1350 /* If no slave, slave native definitely out */
1351 if (!slave)
1352 useslavenative = 0;
1353 else if (slave->law != p->law) {
1354 useslavenative = 0;
1355 slave = NULL;
1357 if (out)
1358 *out = slave;
1359 return useslavenative;
1362 static int reset_conf(struct zt_pvt *p)
1364 ZT_CONFINFO zi;
1365 memset(&zi, 0, sizeof(zi));
1366 p->confno = -1;
1367 memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1368 if (p->subs[SUB_REAL].zfd > -1) {
1369 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1370 ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1372 return 0;
1375 static int update_conf(struct zt_pvt *p)
1377 int needconf = 0;
1378 int x;
1379 int useslavenative;
1380 struct zt_pvt *slave = NULL;
1382 useslavenative = isslavenative(p, &slave);
1383 /* Start with the obvious, general stuff */
1384 for (x = 0; x < 3; x++) {
1385 /* Look for three way calls */
1386 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1387 conf_add(p, &p->subs[x], x, 0);
1388 needconf++;
1389 } else {
1390 conf_del(p, &p->subs[x], x);
1393 /* If we have a slave, add him to our conference now. or DAX
1394 if this is slave native */
1395 for (x = 0; x < MAX_SLAVES; x++) {
1396 if (p->slaves[x]) {
1397 if (useslavenative)
1398 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1399 else {
1400 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1401 needconf++;
1405 /* If we're supposed to be in there, do so now */
1406 if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1407 if (useslavenative)
1408 conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1409 else {
1410 conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1411 needconf++;
1414 /* If we have a master, add ourselves to his conference */
1415 if (p->master) {
1416 if (isslavenative(p->master, NULL)) {
1417 conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1418 } else {
1419 conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1422 if (!needconf) {
1423 /* Nobody is left (or should be left) in our conference.
1424 Kill it. */
1425 p->confno = -1;
1427 ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1428 return 0;
1431 static void zt_enable_ec(struct zt_pvt *p)
1433 int x;
1434 int res;
1435 if (!p)
1436 return;
1437 if (p->echocanon) {
1438 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1439 return;
1441 if (p->digital) {
1442 ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
1443 return;
1445 if (p->echocancel) {
1446 if (p->sig == SIG_PRI) {
1447 x = 1;
1448 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1449 if (res)
1450 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1452 x = p->echocancel;
1453 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1454 if (res)
1455 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1456 else {
1457 p->echocanon = 1;
1458 ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1460 } else
1461 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1464 static void zt_train_ec(struct zt_pvt *p)
1466 int x;
1467 int res;
1468 if (p && p->echocancel && p->echotraining) {
1469 x = p->echotraining;
1470 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1471 if (res)
1472 ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1473 else {
1474 ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1476 } else
1477 ast_log(LOG_DEBUG, "No echo training requested\n");
1480 static void zt_disable_ec(struct zt_pvt *p)
1482 int x;
1483 int res;
1484 if (p->echocancel) {
1485 x = 0;
1486 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1487 if (res)
1488 ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1489 else
1490 ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1492 p->echocanon = 0;
1495 static void fill_txgain(struct zt_gains *g, float gain, int law)
1497 int j;
1498 int k;
1499 float linear_gain = pow(10.0, gain / 20.0);
1501 switch (law) {
1502 case ZT_LAW_ALAW:
1503 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1504 if (gain) {
1505 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1506 if (k > 32767) k = 32767;
1507 if (k < -32767) k = -32767;
1508 g->txgain[j] = AST_LIN2A(k);
1509 } else {
1510 g->txgain[j] = j;
1513 break;
1514 case ZT_LAW_MULAW:
1515 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1516 if (gain) {
1517 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1518 if (k > 32767) k = 32767;
1519 if (k < -32767) k = -32767;
1520 g->txgain[j] = AST_LIN2MU(k);
1521 } else {
1522 g->txgain[j] = j;
1525 break;
1529 static void fill_rxgain(struct zt_gains *g, float gain, int law)
1531 int j;
1532 int k;
1533 float linear_gain = pow(10.0, gain / 20.0);
1535 switch (law) {
1536 case ZT_LAW_ALAW:
1537 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1538 if (gain) {
1539 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1540 if (k > 32767) k = 32767;
1541 if (k < -32767) k = -32767;
1542 g->rxgain[j] = AST_LIN2A(k);
1543 } else {
1544 g->rxgain[j] = j;
1547 break;
1548 case ZT_LAW_MULAW:
1549 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1550 if (gain) {
1551 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1552 if (k > 32767) k = 32767;
1553 if (k < -32767) k = -32767;
1554 g->rxgain[j] = AST_LIN2MU(k);
1555 } else {
1556 g->rxgain[j] = j;
1559 break;
1563 static int set_actual_txgain(int fd, int chan, float gain, int law)
1565 struct zt_gains g;
1566 int res;
1568 memset(&g, 0, sizeof(g));
1569 g.chan = chan;
1570 res = ioctl(fd, ZT_GETGAINS, &g);
1571 if (res) {
1572 ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1573 return res;
1576 fill_txgain(&g, gain, law);
1578 return ioctl(fd, ZT_SETGAINS, &g);
1581 static int set_actual_rxgain(int fd, int chan, float gain, int law)
1583 struct zt_gains g;
1584 int res;
1586 memset(&g, 0, sizeof(g));
1587 g.chan = chan;
1588 res = ioctl(fd, ZT_GETGAINS, &g);
1589 if (res) {
1590 ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1591 return res;
1594 fill_rxgain(&g, gain, law);
1596 return ioctl(fd, ZT_SETGAINS, &g);
1599 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1601 return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
1604 static int bump_gains(struct zt_pvt *p)
1606 int res;
1608 /* Bump receive gain by 5.0db */
1609 res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + 5.0, p->txgain, p->law);
1610 if (res) {
1611 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
1612 return -1;
1615 return 0;
1618 static int restore_gains(struct zt_pvt *p)
1620 int res;
1622 res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1623 if (res) {
1624 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
1625 return -1;
1628 return 0;
1631 static inline int zt_set_hook(int fd, int hs)
1633 int x, res;
1634 x = hs;
1635 res = ioctl(fd, ZT_HOOK, &x);
1636 if (res < 0)
1638 if (errno == EINPROGRESS) return 0;
1639 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1641 return res;
1644 static inline int zt_confmute(struct zt_pvt *p, int muted)
1646 int x, y, res;
1647 x = muted;
1648 if (p->sig == SIG_PRI) {
1649 y = 1;
1650 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1651 if (res)
1652 ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1654 res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1655 if (res < 0)
1656 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1657 return res;
1660 static int save_conference(struct zt_pvt *p)
1662 struct zt_confinfo c;
1663 int res;
1664 if (p->saveconf.confmode) {
1665 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1666 return -1;
1668 p->saveconf.chan = 0;
1669 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1670 if (res) {
1671 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1672 p->saveconf.confmode = 0;
1673 return -1;
1675 c.chan = 0;
1676 c.confno = 0;
1677 c.confmode = ZT_CONF_NORMAL;
1678 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1679 if (res) {
1680 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1681 return -1;
1683 if (option_debug)
1684 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1685 return 0;
1688 static int restore_conference(struct zt_pvt *p)
1690 int res;
1691 if (p->saveconf.confmode) {
1692 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1693 p->saveconf.confmode = 0;
1694 if (res) {
1695 ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1696 return -1;
1699 if (option_debug)
1700 ast_log(LOG_DEBUG, "Restored conferencing\n");
1701 return 0;
1704 static int send_callerid(struct zt_pvt *p);
1706 static int send_cwcidspill(struct zt_pvt *p)
1708 p->callwaitcas = 0;
1709 p->cidcwexpire = 0;
1710 if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
1711 return -1;
1712 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1713 /* Make sure we account for the end */
1714 p->cidlen += READ_SIZE * 4;
1715 p->cidpos = 0;
1716 send_callerid(p);
1717 if (option_verbose > 2)
1718 ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID. Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1719 return 0;
1722 static int has_voicemail(struct zt_pvt *p)
1725 return ast_app_has_voicemail(p->mailbox, NULL);
1728 static int send_callerid(struct zt_pvt *p)
1730 /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1731 int res;
1732 /* Take out of linear mode if necessary */
1733 if (p->subs[SUB_REAL].linear) {
1734 p->subs[SUB_REAL].linear = 0;
1735 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1737 while (p->cidpos < p->cidlen) {
1738 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1739 if (res < 0) {
1740 if (errno == EAGAIN)
1741 return 0;
1742 else {
1743 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1744 return -1;
1747 if (!res)
1748 return 0;
1749 p->cidpos += res;
1751 free(p->cidspill);
1752 p->cidspill = NULL;
1753 if (p->callwaitcas) {
1754 /* Wait for CID/CW to expire */
1755 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1756 } else
1757 restore_conference(p);
1758 return 0;
1761 static int zt_callwait(struct ast_channel *ast)
1763 struct zt_pvt *p = ast->tech_pvt;
1764 p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1765 if (p->cidspill) {
1766 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1767 free(p->cidspill);
1769 if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
1770 return -1;
1771 save_conference(p);
1772 /* Silence */
1773 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1774 if (!p->callwaitrings && p->callwaitingcallerid) {
1775 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1776 p->callwaitcas = 1;
1777 p->cidlen = 2400 + 680 + READ_SIZE * 4;
1778 } else {
1779 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1780 p->callwaitcas = 0;
1781 p->cidlen = 2400 + READ_SIZE * 4;
1783 p->cidpos = 0;
1784 send_callerid(p);
1786 return 0;
1789 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1791 struct zt_pvt *p = ast->tech_pvt;
1792 int x, res, index,mysig;
1793 char *c, *n, *l;
1794 #ifdef HAVE_PRI
1795 char *s = NULL;
1796 #endif
1797 char dest[256]; /* must be same length as p->dialdest */
1798 ast_mutex_lock(&p->lock);
1799 ast_copy_string(dest, rdest, sizeof(dest));
1800 ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
1801 if ((ast->_state == AST_STATE_BUSY)) {
1802 p->subs[SUB_REAL].needbusy = 1;
1803 ast_mutex_unlock(&p->lock);
1804 return 0;
1806 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1807 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1808 ast_mutex_unlock(&p->lock);
1809 return -1;
1811 p->dialednone = 0;
1812 if ((p->radio || (p->oprmode < 0))) /* if a radio channel, up immediately */
1814 /* Special pseudo -- automatically up */
1815 ast_setstate(ast, AST_STATE_UP);
1816 ast_mutex_unlock(&p->lock);
1817 return 0;
1819 x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1820 res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1821 if (res)
1822 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1823 p->outgoing = 1;
1825 set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1827 mysig = p->sig;
1828 if (p->outsigmod > -1)
1829 mysig = p->outsigmod;
1831 switch (mysig) {
1832 case SIG_FXOLS:
1833 case SIG_FXOGS:
1834 case SIG_FXOKS:
1835 if (p->owner == ast) {
1836 /* Normal ring, on hook */
1838 /* Don't send audio while on hook, until the call is answered */
1839 p->dialing = 1;
1840 if (p->use_callerid) {
1841 /* Generate the Caller-ID spill if desired */
1842 if (p->cidspill) {
1843 ast_log(LOG_WARNING, "cidspill already exists??\n");
1844 free(p->cidspill);
1846 p->callwaitcas = 0;
1847 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
1848 p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1849 p->cidpos = 0;
1850 send_callerid(p);
1853 /* Choose proper cadence */
1854 if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1855 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering - 1]))
1856 ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1857 p->cidrings = cidrings[p->distinctivering - 1];
1858 } else {
1859 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1860 ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1861 p->cidrings = p->sendcalleridafter;
1864 /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1865 c = strchr(dest, '/');
1866 if (c)
1867 c++;
1868 if (c && (strlen(c) < p->stripmsd)) {
1869 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1870 c = NULL;
1872 if (c) {
1873 p->dop.op = ZT_DIAL_OP_REPLACE;
1874 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1875 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1876 } else {
1877 p->dop.dialstr[0] = '\0';
1879 x = ZT_RING;
1880 if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1881 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1882 ast_mutex_unlock(&p->lock);
1883 return -1;
1885 p->dialing = 1;
1886 } else {
1887 /* Call waiting call */
1888 p->callwaitrings = 0;
1889 if (ast->cid.cid_num)
1890 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
1891 else
1892 p->callwait_num[0] = '\0';
1893 if (ast->cid.cid_name)
1894 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
1895 else
1896 p->callwait_name[0] = '\0';
1897 /* Call waiting tone instead */
1898 if (zt_callwait(ast)) {
1899 ast_mutex_unlock(&p->lock);
1900 return -1;
1902 /* Make ring-back */
1903 if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1904 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1907 n = ast->cid.cid_name;
1908 l = ast->cid.cid_num;
1909 if (l)
1910 ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
1911 else
1912 p->lastcid_num[0] = '\0';
1913 if (n)
1914 ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
1915 else
1916 p->lastcid_name[0] = '\0';
1917 ast_setstate(ast, AST_STATE_RINGING);
1918 index = zt_get_index(ast, p, 0);
1919 if (index > -1) {
1920 p->subs[index].needringing = 1;
1922 break;
1923 case SIG_FXSLS:
1924 case SIG_FXSGS:
1925 case SIG_FXSKS:
1926 case SIG_EMWINK:
1927 case SIG_EM:
1928 case SIG_EM_E1:
1929 case SIG_FEATD:
1930 case SIG_FEATDMF:
1931 case SIG_E911:
1932 case SIG_FGC_CAMA:
1933 case SIG_FGC_CAMAMF:
1934 case SIG_FEATB:
1935 case SIG_SFWINK:
1936 case SIG_SF:
1937 case SIG_SF_FEATD:
1938 case SIG_SF_FEATDMF:
1939 case SIG_FEATDMF_TA:
1940 case SIG_SF_FEATB:
1941 c = strchr(dest, '/');
1942 if (c)
1943 c++;
1944 else
1945 c = "";
1946 if (strlen(c) < p->stripmsd) {
1947 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1948 ast_mutex_unlock(&p->lock);
1949 return -1;
1951 #ifdef HAVE_PRI
1952 /* Start the trunk, if not GR-303 */
1953 if (!p->pri) {
1954 #endif
1955 x = ZT_START;
1956 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1957 if (res < 0) {
1958 if (errno != EINPROGRESS) {
1959 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1960 ast_mutex_unlock(&p->lock);
1961 return -1;
1964 #ifdef HAVE_PRI
1966 #endif
1967 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1968 p->dop.op = ZT_DIAL_OP_REPLACE;
1970 c += p->stripmsd;
1972 switch (mysig) {
1973 case SIG_FEATD:
1974 l = ast->cid.cid_num;
1975 if (l)
1976 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
1977 else
1978 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
1979 break;
1980 case SIG_FEATDMF:
1981 l = ast->cid.cid_num;
1982 if (l)
1983 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
1984 else
1985 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
1986 break;
1987 case SIG_FEATDMF_TA:
1989 const char *cic, *ozz;
1991 /* If you have to go through a Tandem Access point you need to use this */
1992 ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
1993 if (!ozz)
1994 ozz = defaultozz;
1995 cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
1996 if (!cic)
1997 cic = defaultcic;
1998 if (!ozz || !cic) {
1999 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
2000 ast_mutex_unlock(&p->lock);
2001 return -1;
2003 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
2004 snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
2005 p->whichwink = 0;
2007 break;
2008 case SIG_E911:
2009 ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
2010 break;
2011 case SIG_FGC_CAMA:
2012 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
2013 break;
2014 case SIG_FGC_CAMAMF:
2015 case SIG_FEATB:
2016 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
2017 break;
2018 default:
2019 if (p->pulse)
2020 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
2021 else
2022 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
2023 break;
2026 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
2027 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2028 strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2029 p->echorest[sizeof(p->echorest) - 1] = '\0';
2030 p->echobreak = 1;
2031 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2032 } else
2033 p->echobreak = 0;
2034 if (!res) {
2035 if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
2036 x = ZT_ONHOOK;
2037 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2038 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
2039 ast_mutex_unlock(&p->lock);
2040 return -1;
2042 } else
2043 ast_log(LOG_DEBUG, "Deferring dialing...\n");
2044 p->dialing = 1;
2045 if (ast_strlen_zero(c))
2046 p->dialednone = 1;
2047 ast_setstate(ast, AST_STATE_DIALING);
2048 break;
2049 case 0:
2050 /* Special pseudo -- automatically up*/
2051 ast_setstate(ast, AST_STATE_UP);
2052 break;
2053 case SIG_PRI:
2054 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
2055 p->dialdest[0] = '\0';
2056 break;
2057 default:
2058 ast_log(LOG_DEBUG, "not yet implemented\n");
2059 ast_mutex_unlock(&p->lock);
2060 return -1;
2062 #ifdef HAVE_PRI
2063 if (p->pri) {
2064 struct pri_sr *sr;
2065 #ifdef SUPPORT_USERUSER
2066 const char *useruser;
2067 #endif
2068 int pridialplan;
2069 int dp_strip;
2070 int prilocaldialplan;
2071 int ldp_strip;
2072 int exclusive;
2073 const char *rr_str;
2074 int redirect_reason;
2076 c = strchr(dest, '/');
2077 if (c)
2078 c++;
2079 else
2080 c = dest;
2081 if (!p->hidecallerid) {
2082 l = ast->cid.cid_num;
2083 n = ast->cid.cid_name;
2084 } else {
2085 l = NULL;
2086 n = NULL;
2088 if (strlen(c) < p->stripmsd) {
2089 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2090 ast_mutex_unlock(&p->lock);
2091 return -1;
2093 if (mysig != SIG_FXSKS) {
2094 p->dop.op = ZT_DIAL_OP_REPLACE;
2095 s = strchr(c + p->stripmsd, 'w');
2096 if (s) {
2097 if (strlen(s) > 1)
2098 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2099 else
2100 p->dop.dialstr[0] = '\0';
2101 *s = '\0';
2102 } else {
2103 p->dop.dialstr[0] = '\0';
2106 if (pri_grab(p, p->pri)) {
2107 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2108 ast_mutex_unlock(&p->lock);
2109 return -1;
2111 if (!(p->call = pri_new_call(p->pri->pri))) {
2112 ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2113 pri_rel(p->pri);
2114 ast_mutex_unlock(&p->lock);
2115 return -1;
2117 if (!(sr = pri_sr_new())) {
2118 ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2119 pri_rel(p->pri);
2120 ast_mutex_unlock(&p->lock);
2122 if (p->bearer || (mysig == SIG_FXSKS)) {
2123 if (p->bearer) {
2124 ast_log(LOG_DEBUG, "Oooh, I have a bearer on %d (%d:%d)\n", PVT_TO_CHANNEL(p->bearer), p->bearer->logicalspan, p->bearer->channel);
2125 p->bearer->call = p->call;
2126 } else
2127 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
2128 pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2130 p->digital = IS_DIGITAL(ast->transfercapability);
2131 /* Add support for exclusive override */
2132 if (p->priexclusive)
2133 exclusive = 1;
2134 else {
2135 /* otherwise, traditional behavior */
2136 if (p->pri->nodetype == PRI_NETWORK)
2137 exclusive = 0;
2138 else
2139 exclusive = 1;
2142 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2143 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability,
2144 (p->digital ? -1 :
2145 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2146 if (p->pri->facilityenable)
2147 pri_facility_enable(p->pri->pri);
2149 if (option_verbose > 2)
2150 ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2151 dp_strip = 0;
2152 pridialplan = p->pri->dialplan - 1;
2153 if (pridialplan == -2) { /* compute dynamically */
2154 if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2155 dp_strip = strlen(p->pri->internationalprefix);
2156 pridialplan = PRI_INTERNATIONAL_ISDN;
2157 } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2158 dp_strip = strlen(p->pri->nationalprefix);
2159 pridialplan = PRI_NATIONAL_ISDN;
2160 } else {
2161 pridialplan = PRI_LOCAL_ISDN;
2164 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2166 ldp_strip = 0;
2167 prilocaldialplan = p->pri->localdialplan - 1;
2168 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
2169 if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2170 ldp_strip = strlen(p->pri->internationalprefix);
2171 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2172 } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2173 ldp_strip = strlen(p->pri->nationalprefix);
2174 prilocaldialplan = PRI_NATIONAL_ISDN;
2175 } else {
2176 prilocaldialplan = PRI_LOCAL_ISDN;
2179 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2180 p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2181 if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
2182 if (!strcasecmp(rr_str, "UNKNOWN"))
2183 redirect_reason = 0;
2184 else if (!strcasecmp(rr_str, "BUSY"))
2185 redirect_reason = 1;
2186 else if (!strcasecmp(rr_str, "NO_REPLY"))
2187 redirect_reason = 2;
2188 else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
2189 redirect_reason = 15;
2190 else
2191 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2192 } else
2193 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2194 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
2196 #ifdef SUPPORT_USERUSER
2197 /* User-user info */
2198 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2200 if (useruser)
2201 pri_sr_set_useruser(sr, useruser);
2202 #endif
2204 if (pri_setup(p->pri->pri, p->call, sr)) {
2205 ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n",
2206 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2207 pri_rel(p->pri);
2208 ast_mutex_unlock(&p->lock);
2209 pri_sr_free(sr);
2210 return -1;
2212 pri_sr_free(sr);
2213 ast_setstate(ast, AST_STATE_DIALING);
2214 pri_rel(p->pri);
2216 #endif
2217 ast_mutex_unlock(&p->lock);
2218 return 0;
2221 static void destroy_zt_pvt(struct zt_pvt **pvt)
2223 struct zt_pvt *p = *pvt;
2224 /* Remove channel from the list */
2225 if (p->prev)
2226 p->prev->next = p->next;
2227 if (p->next)
2228 p->next->prev = p->prev;
2229 if (p->use_smdi)
2230 ASTOBJ_UNREF(p->smdi_iface, ast_smdi_interface_destroy);
2231 ast_mutex_destroy(&p->lock);
2232 free(p);
2233 *pvt = NULL;
2236 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
2238 int owned = 0;
2239 int i = 0;
2241 if (!now) {
2242 if (cur->owner) {
2243 owned = 1;
2246 for (i = 0; i < 3; i++) {
2247 if (cur->subs[i].owner) {
2248 owned = 1;
2251 if (!owned) {
2252 if (prev) {
2253 prev->next = cur->next;
2254 if (prev->next)
2255 prev->next->prev = prev;
2256 else
2257 ifend = prev;
2258 } else {
2259 iflist = cur->next;
2260 if (iflist)
2261 iflist->prev = NULL;
2262 else
2263 ifend = NULL;
2265 if (cur->subs[SUB_REAL].zfd > -1) {
2266 zt_close(cur->subs[SUB_REAL].zfd);
2268 destroy_zt_pvt(&cur);
2270 } else {
2271 if (prev) {
2272 prev->next = cur->next;
2273 if (prev->next)
2274 prev->next->prev = prev;
2275 else
2276 ifend = prev;
2277 } else {
2278 iflist = cur->next;
2279 if (iflist)
2280 iflist->prev = NULL;
2281 else
2282 ifend = NULL;
2284 if (cur->subs[SUB_REAL].zfd > -1) {
2285 zt_close(cur->subs[SUB_REAL].zfd);
2287 destroy_zt_pvt(&cur);
2289 return 0;
2292 #ifdef HAVE_PRI
2293 static char *zap_send_keypad_facility_app = "ZapSendKeypadFacility";
2295 static char *zap_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
2297 static char *zap_send_keypad_facility_descrip =
2298 " ZapSendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
2299 " IE over the current channel.\n";
2301 static int zap_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2303 /* Data will be our digit string */
2304 struct zt_pvt *p;
2305 char *digits = (char *) data;
2307 if (ast_strlen_zero(digits)) {
2308 ast_log(LOG_DEBUG, "No digit string sent to application!\n");
2309 return -1;
2312 p = (struct zt_pvt *)chan->tech_pvt;
2314 if (!p) {
2315 ast_log(LOG_DEBUG, "Unable to find technology private\n");
2316 return -1;
2319 ast_mutex_lock(&p->lock);
2321 if (!p->pri || !p->call) {
2322 ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
2323 ast_mutex_unlock(&p->lock);
2324 return -1;
2327 if (!pri_grab(p, p->pri)) {
2328 pri_keypad_facility(p->pri->pri, p->call, digits);
2329 pri_rel(p->pri);
2330 } else {
2331 ast_log(LOG_DEBUG, "Unable to grab pri to send keypad facility!\n");
2332 ast_mutex_unlock(&p->lock);
2333 return -1;
2336 ast_mutex_unlock(&p->lock);
2338 return 0;
2341 static int pri_is_up(struct zt_pri *pri)
2343 int x;
2344 for (x = 0; x < NUM_DCHANS; x++) {
2345 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2346 return 1;
2348 return 0;
2351 static int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2353 bearer->owner = &inuse;
2354 bearer->realcall = crv;
2355 crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2356 if (crv->subs[SUB_REAL].owner)
2357 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2358 crv->bearer = bearer;
2359 crv->call = bearer->call;
2360 crv->pri = pri;
2361 return 0;
2364 static char *pri_order(int level)
2366 switch (level) {
2367 case 0:
2368 return "Primary";
2369 case 1:
2370 return "Secondary";
2371 case 2:
2372 return "Tertiary";
2373 case 3:
2374 return "Quaternary";
2375 default:
2376 return "<Unknown>";
2380 /* Returns fd of the active dchan */
2381 static int pri_active_dchan_fd(struct zt_pri *pri)
2383 int x = -1;
2385 for (x = 0; x < NUM_DCHANS; x++) {
2386 if ((pri->dchans[x] == pri->pri))
2387 break;
2390 return pri->fds[x];
2393 static int pri_find_dchan(struct zt_pri *pri)
2395 int oldslot = -1;
2396 struct pri *old;
2397 int newslot = -1;
2398 int x;
2399 old = pri->pri;
2400 for (x = 0; x < NUM_DCHANS; x++) {
2401 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2402 newslot = x;
2403 if (pri->dchans[x] == old) {
2404 oldslot = x;
2407 if (newslot < 0) {
2408 newslot = 0;
2409 ast_log(LOG_WARNING, "No D-channels available! Using Primary channel %d as D-channel anyway!\n",
2410 pri->dchannels[newslot]);
2412 if (old && (oldslot != newslot))
2413 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2414 pri->dchannels[oldslot], pri->dchannels[newslot]);
2415 pri->pri = pri->dchans[newslot];
2416 return 0;
2418 #endif
2420 static int zt_hangup(struct ast_channel *ast)
2422 int res;
2423 int index,x, law;
2424 /*static int restore_gains(struct zt_pvt *p);*/
2425 struct zt_pvt *p = ast->tech_pvt;
2426 struct zt_pvt *tmp = NULL;
2427 struct zt_pvt *prev = NULL;
2428 ZT_PARAMS par;
2430 if (option_debug)
2431 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2432 if (!ast->tech_pvt) {
2433 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2434 return 0;
2437 ast_mutex_lock(&p->lock);
2439 index = zt_get_index(ast, p, 1);
2441 if (p->sig == SIG_PRI) {
2442 x = 1;
2443 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2446 x = 0;
2447 zt_confmute(p, 0);
2448 restore_gains(p);
2449 if (p->origcid_num) {
2450 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2451 free(p->origcid_num);
2452 p->origcid_num = NULL;
2454 if (p->origcid_name) {
2455 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2456 free(p->origcid_name);
2457 p->origcid_name = NULL;
2459 if (p->dsp)
2460 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2461 if (p->exten)
2462 p->exten[0] = '\0';
2464 ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2465 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2466 p->ignoredtmf = 0;
2468 if (index > -1) {
2469 /* Real channel, do some fixup */
2470 p->subs[index].owner = NULL;
2471 p->subs[index].needanswer = 0;
2472 p->subs[index].needflash = 0;
2473 p->subs[index].needringing = 0;
2474 p->subs[index].needbusy = 0;
2475 p->subs[index].needcongestion = 0;
2476 p->subs[index].linear = 0;
2477 p->subs[index].needcallerid = 0;
2478 p->polarity = POLARITY_IDLE;
2479 zt_setlinear(p->subs[index].zfd, 0);
2480 if (index == SUB_REAL) {
2481 if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2482 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2483 if (p->subs[SUB_CALLWAIT].inthreeway) {
2484 /* We had flipped over to answer a callwait and now it's gone */
2485 ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2486 /* Move to the call-wait, but un-own us until they flip back. */
2487 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2488 unalloc_sub(p, SUB_CALLWAIT);
2489 p->owner = NULL;
2490 } else {
2491 /* The three way hung up, but we still have a call wait */
2492 ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still. Ditching the threeway.\n");
2493 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2494 unalloc_sub(p, SUB_THREEWAY);
2495 if (p->subs[SUB_REAL].inthreeway) {
2496 /* This was part of a three way call. Immediately make way for
2497 another call */
2498 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2499 p->owner = p->subs[SUB_REAL].owner;
2500 } else {
2501 /* This call hasn't been completed yet... Set owner to NULL */
2502 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2503 p->owner = NULL;
2505 p->subs[SUB_REAL].inthreeway = 0;
2507 } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2508 /* Move to the call-wait and switch back to them. */
2509 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2510 unalloc_sub(p, SUB_CALLWAIT);
2511 p->owner = p->subs[SUB_REAL].owner;
2512 if (p->owner->_state != AST_STATE_UP)
2513 p->subs[SUB_REAL].needanswer = 1;
2514 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2515 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
2516 } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2517 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2518 unalloc_sub(p, SUB_THREEWAY);
2519 if (p->subs[SUB_REAL].inthreeway) {
2520 /* This was part of a three way call. Immediately make way for
2521 another call */
2522 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2523 p->owner = p->subs[SUB_REAL].owner;
2524 } else {
2525 /* This call hasn't been completed yet... Set owner to NULL */
2526 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2527 p->owner = NULL;
2529 p->subs[SUB_REAL].inthreeway = 0;
2531 } else if (index == SUB_CALLWAIT) {
2532 /* Ditch the holding callwait call, and immediately make it availabe */
2533 if (p->subs[SUB_CALLWAIT].inthreeway) {
2534 /* This is actually part of a three way, placed on hold. Place the third part
2535 on music on hold now */
2536 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
2537 ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
2538 S_OR(p->mohsuggest, NULL),
2539 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2541 p->subs[SUB_THREEWAY].inthreeway = 0;
2542 /* Make it the call wait now */
2543 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2544 unalloc_sub(p, SUB_THREEWAY);
2545 } else
2546 unalloc_sub(p, SUB_CALLWAIT);
2547 } else if (index == SUB_THREEWAY) {
2548 if (p->subs[SUB_CALLWAIT].inthreeway) {
2549 /* The other party of the three way call is currently in a call-wait state.
2550 Start music on hold for them, and take the main guy out of the third call */
2551 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
2552 ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
2553 S_OR(p->mohsuggest, NULL),
2554 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2556 p->subs[SUB_CALLWAIT].inthreeway = 0;
2558 p->subs[SUB_REAL].inthreeway = 0;
2559 /* If this was part of a three way call index, let us make
2560 another three way call */
2561 unalloc_sub(p, SUB_THREEWAY);
2562 } else {
2563 /* This wasn't any sort of call, but how are we an index? */
2564 ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2568 if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2569 p->owner = NULL;
2570 p->ringt = 0;
2571 p->distinctivering = 0;
2572 p->confirmanswer = 0;
2573 p->cidrings = 1;
2574 p->outgoing = 0;
2575 p->digital = 0;
2576 p->faxhandled = 0;
2577 p->pulsedial = 0;
2578 p->onhooktime = time(NULL);
2579 #ifdef HAVE_PRI
2580 p->proceeding = 0;
2581 p->progress = 0;
2582 p->alerting = 0;
2583 p->setup_ack = 0;
2584 #endif
2585 if (p->dsp) {
2586 ast_dsp_free(p->dsp);
2587 p->dsp = NULL;
2590 law = ZT_LAW_DEFAULT;
2591 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2592 if (res < 0)
2593 ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2594 /* Perform low level hangup if no owner left */
2595 #ifdef HAVE_PRI
2596 if (p->pri) {
2597 #ifdef SUPPORT_USERUSER
2598 const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
2599 #endif
2601 /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2602 if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2603 if (!pri_grab(p, p->pri)) {
2604 if (p->alreadyhungup) {
2605 ast_log(LOG_DEBUG, "Already hungup... Calling hangup once, and clearing call\n");
2607 #ifdef SUPPORT_USERUSER
2608 pri_call_set_useruser(p->call, useruser);
2609 #endif
2611 pri_hangup(p->pri->pri, p->call, -1);
2612 p->call = NULL;
2613 if (p->bearer)
2614 p->bearer->call = NULL;
2615 } else {
2616 const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2617 int icause = ast->hangupcause ? ast->hangupcause : -1;
2618 ast_log(LOG_DEBUG, "Not yet hungup... Calling hangup once with icause, and clearing call\n");
2620 #ifdef SUPPORT_USERUSER
2621 pri_call_set_useruser(p->call, useruser);
2622 #endif
2624 p->alreadyhungup = 1;
2625 if (p->bearer)
2626 p->bearer->alreadyhungup = 1;
2627 if (cause) {
2628 if (atoi(cause))
2629 icause = atoi(cause);
2631 pri_hangup(p->pri->pri, p->call, icause);
2633 if (res < 0)
2634 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2635 pri_rel(p->pri);
2636 } else {
2637 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2638 res = -1;
2640 } else {
2641 if (p->bearer)
2642 ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2643 p->call = NULL;
2644 res = 0;
2647 #endif
2648 if (p->sig && (p->sig != SIG_PRI))
2649 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2650 if (res < 0) {
2651 ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2653 switch (p->sig) {
2654 case SIG_FXOGS:
2655 case SIG_FXOLS:
2656 case SIG_FXOKS:
2657 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2658 if (!res) {
2659 #if 0
2660 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2661 #endif
2662 /* If they're off hook, try playing congestion */
2663 if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
2664 tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2665 else
2666 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2668 break;
2669 case SIG_FXSGS:
2670 case SIG_FXSLS:
2671 case SIG_FXSKS:
2672 /* Make sure we're not made available for at least two seconds assuming
2673 we were actually used for an inbound or outbound call. */
2674 if (ast->_state != AST_STATE_RESERVED) {
2675 time(&p->guardtime);
2676 p->guardtime += 2;
2678 break;
2679 default:
2680 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2682 if (p->cidspill)
2683 free(p->cidspill);
2684 if (p->sig)
2685 zt_disable_ec(p);
2686 x = 0;
2687 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2688 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2689 p->didtdd = 0;
2690 p->cidspill = NULL;
2691 p->callwaitcas = 0;
2692 p->callwaiting = p->permcallwaiting;
2693 p->hidecallerid = p->permhidecallerid;
2694 p->dialing = 0;
2695 p->rdnis[0] = '\0';
2696 update_conf(p);
2697 reset_conf(p);
2698 /* Restore data mode */
2699 if (p->sig == SIG_PRI) {
2700 x = 0;
2701 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2703 #ifdef HAVE_PRI
2704 if (p->bearer) {
2705 ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2706 /* Free up the bearer channel as well, and
2707 don't use its file descriptor anymore */
2708 update_conf(p->bearer);
2709 reset_conf(p->bearer);
2710 p->bearer->owner = NULL;
2711 p->bearer->realcall = NULL;
2712 p->bearer = NULL;
2713 p->subs[SUB_REAL].zfd = -1;
2714 p->pri = NULL;
2716 #endif
2717 restart_monitor();
2720 p->callwaitingrepeat = 0;
2721 p->cidcwexpire = 0;
2722 p->oprmode = 0;
2723 ast->tech_pvt = NULL;
2724 ast_mutex_unlock(&p->lock);
2725 ast_atomic_fetchadd_int(&usecnt, -1);
2726 ast_update_use_count();
2727 if (option_verbose > 2)
2728 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2730 ast_mutex_lock(&iflock);
2731 tmp = iflist;
2732 prev = NULL;
2733 if (p->destroy) {
2734 while (tmp) {
2735 if (tmp == p) {
2736 destroy_channel(prev, tmp, 0);
2737 break;
2738 } else {
2739 prev = tmp;
2740 tmp = tmp->next;
2744 ast_mutex_unlock(&iflock);
2745 return 0;
2748 static int zt_answer(struct ast_channel *ast)
2750 struct zt_pvt *p = ast->tech_pvt;
2751 int res = 0;
2752 int index;
2753 int oldstate = ast->_state;
2754 ast_setstate(ast, AST_STATE_UP);
2755 ast_mutex_lock(&p->lock);
2756 index = zt_get_index(ast, p, 0);
2757 if (index < 0)
2758 index = SUB_REAL;
2759 /* nothing to do if a radio channel */
2760 if ((p->radio || (p->oprmode < 0))) {
2761 ast_mutex_unlock(&p->lock);
2762 return 0;
2764 switch (p->sig) {
2765 case SIG_FXSLS:
2766 case SIG_FXSGS:
2767 case SIG_FXSKS:
2768 p->ringt = 0;
2769 /* Fall through */
2770 case SIG_EM:
2771 case SIG_EM_E1:
2772 case SIG_EMWINK:
2773 case SIG_FEATD:
2774 case SIG_FEATDMF:
2775 case SIG_FEATDMF_TA:
2776 case SIG_E911:
2777 case SIG_FGC_CAMA:
2778 case SIG_FGC_CAMAMF:
2779 case SIG_FEATB:
2780 case SIG_SF:
2781 case SIG_SFWINK:
2782 case SIG_SF_FEATD:
2783 case SIG_SF_FEATDMF:
2784 case SIG_SF_FEATB:
2785 case SIG_FXOLS:
2786 case SIG_FXOGS:
2787 case SIG_FXOKS:
2788 /* Pick up the line */
2789 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2790 if (p->hanguponpolarityswitch) {
2791 gettimeofday(&p->polaritydelaytv, NULL);
2793 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2794 tone_zone_play_tone(p->subs[index].zfd, -1);
2795 p->dialing = 0;
2796 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2797 if (oldstate == AST_STATE_RINGING) {
2798 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2799 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2800 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2801 p->owner = p->subs[SUB_REAL].owner;
2804 if (p->sig & __ZT_SIG_FXS) {
2805 zt_enable_ec(p);
2806 zt_train_ec(p);
2808 break;
2809 #ifdef HAVE_PRI
2810 case SIG_PRI:
2811 /* Send a pri acknowledge */
2812 if (!pri_grab(p, p->pri)) {
2813 p->proceeding = 1;
2814 res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2815 pri_rel(p->pri);
2816 } else {
2817 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2818 res = -1;
2820 break;
2821 #endif
2822 case 0:
2823 ast_mutex_unlock(&p->lock);
2824 return 0;
2825 default:
2826 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2827 res = -1;
2829 ast_mutex_unlock(&p->lock);
2830 return res;
2833 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2835 char *cp;
2836 signed char *scp;
2837 int x;
2838 int index;
2839 struct zt_pvt *p = chan->tech_pvt, *pp;
2840 struct oprmode *oprmode;
2843 /* all supported options require data */
2844 if (!data || (datalen < 1)) {
2845 errno = EINVAL;
2846 return -1;
2849 switch (option) {
2850 case AST_OPTION_TXGAIN:
2851 scp = (signed char *) data;
2852 index = zt_get_index(chan, p, 0);
2853 if (index < 0) {
2854 ast_log(LOG_WARNING, "No index in TXGAIN?\n");
2855 return -1;
2857 ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
2858 return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
2859 case AST_OPTION_RXGAIN:
2860 scp = (signed char *) data;
2861 index = zt_get_index(chan, p, 0);
2862 if (index < 0) {
2863 ast_log(LOG_WARNING, "No index in RXGAIN?\n");
2864 return -1;
2866 ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
2867 return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
2868 case AST_OPTION_TONE_VERIFY:
2869 if (!p->dsp)
2870 break;
2871 cp = (char *) data;
2872 switch (*cp) {
2873 case 1:
2874 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2875 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax); /* set mute mode if desired */
2876 break;
2877 case 2:
2878 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2879 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax); /* set mute mode if desired */
2880 break;
2881 default:
2882 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2883 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax); /* set mute mode if desired */
2884 break;
2886 break;
2887 case AST_OPTION_TDD:
2888 /* turn on or off TDD */
2889 cp = (char *) data;
2890 p->mate = 0;
2891 if (!*cp) { /* turn it off */
2892 ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2893 if (p->tdd)
2894 tdd_free(p->tdd);
2895 p->tdd = 0;
2896 break;
2898 ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
2899 (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
2900 zt_disable_ec(p);
2901 /* otherwise, turn it on */
2902 if (!p->didtdd) { /* if havent done it yet */
2903 unsigned char mybuf[41000], *buf;
2904 int size, res, fd, len;
2905 struct pollfd fds[1];
2907 buf = mybuf;
2908 memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
2909 ast_tdd_gen_ecdisa(buf + 16000, 16000); /* put in tone */
2910 len = 40000;
2911 index = zt_get_index(chan, p, 0);
2912 if (index < 0) {
2913 ast_log(LOG_WARNING, "No index in TDD?\n");
2914 return -1;
2916 fd = p->subs[index].zfd;
2917 while (len) {
2918 if (ast_check_hangup(chan))
2919 return -1;
2920 size = len;
2921 if (size > READ_SIZE)
2922 size = READ_SIZE;
2923 fds[0].fd = fd;
2924 fds[0].events = POLLPRI | POLLOUT;
2925 fds[0].revents = 0;
2926 res = poll(fds, 1, -1);
2927 if (!res) {
2928 ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2929 continue;
2931 /* if got exception */
2932 if (fds[0].revents & POLLPRI)
2933 return -1;
2934 if (!(fds[0].revents & POLLOUT)) {
2935 ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2936 continue;
2938 res = write(fd, buf, size);
2939 if (res != size) {
2940 if (res == -1) return -1;
2941 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2942 break;
2944 len -= size;
2945 buf += size;
2947 p->didtdd = 1; /* set to have done it now */
2949 if (*cp == 2) { /* Mate mode */
2950 if (p->tdd)
2951 tdd_free(p->tdd);
2952 p->tdd = 0;
2953 p->mate = 1;
2954 break;
2956 if (!p->tdd) { /* if we dont have one yet */
2957 p->tdd = tdd_new(); /* allocate one */
2959 break;
2960 case AST_OPTION_RELAXDTMF: /* Relax DTMF decoding (or not) */
2961 if (!p->dsp)
2962 break;
2963 cp = (char *) data;
2964 ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
2965 *cp ? "ON" : "OFF", (int) *cp, chan->name);
2966 ast_dsp_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
2967 break;
2968 case AST_OPTION_AUDIO_MODE: /* Set AUDIO mode (or not) */
2969 cp = (char *) data;
2970 if (!*cp) {
2971 ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
2972 x = 0;
2973 zt_disable_ec(p);
2974 } else {
2975 ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
2976 x = 1;
2978 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2979 ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2980 break;
2981 case AST_OPTION_OPRMODE: /* Operator services mode */
2982 oprmode = (struct oprmode *) data;
2983 pp = oprmode->peer->tech_pvt;
2984 p->oprmode = pp->oprmode = 0;
2985 /* setup peers */
2986 p->oprpeer = pp;
2987 pp->oprpeer = p;
2988 /* setup modes, if any */
2989 if (oprmode->mode)
2991 pp->oprmode = oprmode->mode;
2992 p->oprmode = -oprmode->mode;
2994 ast_log(LOG_DEBUG, "Set Operator Services mode, value: %d on %s/%s\n",
2995 oprmode->mode, chan->name,oprmode->peer->name);;
2996 break;
2997 case AST_OPTION_ECHOCAN:
2998 cp = (char *) data;
2999 if (*cp) {
3000 ast_log(LOG_DEBUG, "Enabling echo cancelation on %s\n", chan->name);
3001 zt_enable_ec(p);
3002 } else {
3003 ast_log(LOG_DEBUG, "Disabling echo cancelation on %s\n", chan->name);
3004 zt_disable_ec(p);
3006 break;
3008 errno = 0;
3010 return 0;
3013 static int zt_func_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
3015 struct zt_pvt *p = chan->tech_pvt;
3017 if (!strcasecmp(data, "rxgain")) {
3018 ast_mutex_lock(&p->lock);
3019 snprintf(buf, len, "%f", p->rxgain);
3020 ast_mutex_unlock(&p->lock);
3021 } else if (!strcasecmp(data, "txgain")) {
3022 ast_mutex_lock(&p->lock);
3023 snprintf(buf, len, "%f", p->txgain);
3024 ast_mutex_unlock(&p->lock);
3025 } else {
3026 ast_copy_string(buf, "", len);
3028 return 0;
3032 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
3034 /* Unlink a specific slave or all slaves/masters from a given master */
3035 int x;
3036 int hasslaves;
3037 if (!master)
3038 return;
3039 if (needlock) {
3040 ast_mutex_lock(&master->lock);
3041 if (slave) {
3042 while (ast_mutex_trylock(&slave->lock)) {
3043 ast_mutex_unlock(&master->lock);
3044 usleep(1);
3045 ast_mutex_lock(&master->lock);
3049 hasslaves = 0;
3050 for (x = 0; x < MAX_SLAVES; x++) {
3051 if (master->slaves[x]) {
3052 if (!slave || (master->slaves[x] == slave)) {
3053 /* Take slave out of the conference */
3054 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
3055 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
3056 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
3057 master->slaves[x]->master = NULL;
3058 master->slaves[x] = NULL;
3059 } else
3060 hasslaves = 1;
3062 if (!hasslaves)
3063 master->inconference = 0;
3065 if (!slave) {
3066 if (master->master) {
3067 /* Take master out of the conference */
3068 conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
3069 conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
3070 hasslaves = 0;
3071 for (x = 0; x < MAX_SLAVES; x++) {
3072 if (master->master->slaves[x] == master)
3073 master->master->slaves[x] = NULL;
3074 else if (master->master->slaves[x])
3075 hasslaves = 1;
3077 if (!hasslaves)
3078 master->master->inconference = 0;
3080 master->master = NULL;
3082 update_conf(master);
3083 if (needlock) {
3084 if (slave)
3085 ast_mutex_unlock(&slave->lock);
3086 ast_mutex_unlock(&master->lock);
3090 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
3091 int x;
3092 if (!slave || !master) {
3093 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
3094 return;
3096 for (x = 0; x < MAX_SLAVES; x++) {
3097 if (!master->slaves[x]) {
3098 master->slaves[x] = slave;
3099 break;
3102 if (x >= MAX_SLAVES) {
3103 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
3104 master->slaves[MAX_SLAVES - 1] = slave;
3106 if (slave->master)
3107 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
3108 slave->master = master;
3110 ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
3113 static void disable_dtmf_detect(struct zt_pvt *p)
3115 #ifdef ZT_TONEDETECT
3116 int val;
3117 #endif
3119 p->ignoredtmf = 1;
3121 #ifdef ZT_TONEDETECT
3122 val = 0;
3123 ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3124 #endif
3125 if (!p->hardwaredtmf && p->dsp) {
3126 p->dsp_features &= ~DSP_FEATURE_DTMF_DETECT;
3127 ast_dsp_set_features(p->dsp, p->dsp_features);
3131 static void enable_dtmf_detect(struct zt_pvt *p)
3133 #ifdef ZT_TONEDETECT
3134 int val;
3135 #endif
3137 if (p->channel == CHAN_PSEUDO)
3138 return;
3140 p->ignoredtmf = 0;
3142 #ifdef ZT_TONEDETECT
3143 val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
3144 ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3145 #endif
3146 if (!p->hardwaredtmf && p->dsp) {
3147 p->dsp_features |= DSP_FEATURE_DTMF_DETECT;
3148 ast_dsp_set_features(p->dsp, p->dsp_features);
3152 static enum ast_bridge_result zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
3154 struct ast_channel *who;
3155 struct zt_pvt *p0, *p1, *op0, *op1;
3156 struct zt_pvt *master = NULL, *slave = NULL;
3157 struct ast_frame *f;
3158 int inconf = 0;
3159 int nothingok = 1;
3160 int ofd0, ofd1;
3161 int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
3162 int os0 = -1, os1 = -1;
3163 int priority = 0;
3164 struct ast_channel *oc0, *oc1;
3165 enum ast_bridge_result res;
3167 #ifdef PRI_2BCT
3168 int triedtopribridge = 0;
3169 q931_call *q931c0 = NULL, *q931c1 = NULL;
3170 #endif
3172 /* For now, don't attempt to native bridge if either channel needs DTMF detection.
3173 There is code below to handle it properly until DTMF is actually seen,
3174 but due to currently unresolved issues it's ignored...
3177 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
3178 return AST_BRIDGE_FAILED_NOWARN;
3180 ast_mutex_lock(&c0->lock);
3181 ast_mutex_lock(&c1->lock);
3183 p0 = c0->tech_pvt;
3184 p1 = c1->tech_pvt;
3185 /* cant do pseudo-channels here */
3186 if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
3187 ast_mutex_unlock(&c0->lock);
3188 ast_mutex_unlock(&c1->lock);
3189 return AST_BRIDGE_FAILED_NOWARN;
3192 oi0 = zt_get_index(c0, p0, 0);
3193 oi1 = zt_get_index(c1, p1, 0);
3194 if ((oi0 < 0) || (oi1 < 0)) {
3195 ast_mutex_unlock(&c0->lock);
3196 ast_mutex_unlock(&c1->lock);
3197 return AST_BRIDGE_FAILED;
3200 op0 = p0 = c0->tech_pvt;
3201 op1 = p1 = c1->tech_pvt;
3202 ofd0 = c0->fds[0];
3203 ofd1 = c1->fds[0];
3204 oc0 = p0->owner;
3205 oc1 = p1->owner;
3207 if (ast_mutex_trylock(&p0->lock)) {
3208 /* Don't block, due to potential for deadlock */
3209 ast_mutex_unlock(&c0->lock);
3210 ast_mutex_unlock(&c1->lock);
3211 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
3212 return AST_BRIDGE_RETRY;
3214 if (ast_mutex_trylock(&p1->lock)) {
3215 /* Don't block, due to potential for deadlock */
3216 ast_mutex_unlock(&p0->lock);
3217 ast_mutex_unlock(&c0->lock);
3218 ast_mutex_unlock(&c1->lock);
3219 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
3220 return AST_BRIDGE_RETRY;
3223 if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3224 if (p0->owner && p1->owner) {
3225 /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
3226 if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
3227 master = p0;
3228 slave = p1;
3229 inconf = 1;
3230 } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
3231 master = p1;
3232 slave = p0;
3233 inconf = 1;
3234 } else {
3235 ast_log(LOG_WARNING, "Huh? Both calls are callwaits or 3-ways? That's clever...?\n");
3236 ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
3237 p0->channel,
3238 oi0, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3239 p0->subs[SUB_REAL].inthreeway, p0->channel,
3240 oi0, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3241 p1->subs[SUB_REAL].inthreeway);
3243 nothingok = 0;
3245 } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
3246 if (p1->subs[SUB_THREEWAY].inthreeway) {
3247 master = p1;
3248 slave = p0;
3249 nothingok = 0;
3251 } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
3252 if (p0->subs[SUB_THREEWAY].inthreeway) {
3253 master = p0;
3254 slave = p1;
3255 nothingok = 0;
3257 } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
3258 /* We have a real and a call wait. If we're in a three way call, put us in it, otherwise,
3259 don't put us in anything */
3260 if (p1->subs[SUB_CALLWAIT].inthreeway) {
3261 master = p1;
3262 slave = p0;
3263 nothingok = 0;
3265 } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
3266 /* Same as previous */
3267 if (p0->subs[SUB_CALLWAIT].inthreeway) {
3268 master = p0;
3269 slave = p1;
3270 nothingok = 0;
3273 ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
3274 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
3275 if (master && slave) {
3276 /* Stop any tones, or play ringtone as appropriate. If they're bridged
3277 in an active threeway call with a channel that is ringing, we should
3278 indicate ringing. */
3279 if ((oi1 == SUB_THREEWAY) &&
3280 p1->subs[SUB_THREEWAY].inthreeway &&
3281 p1->subs[SUB_REAL].owner &&
3282 p1->subs[SUB_REAL].inthreeway &&
3283 (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
3284 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
3285 tone_zone_play_tone(p0->subs[oi0].zfd, ZT_TONE_RINGTONE);
3286 os1 = p1->subs[SUB_REAL].owner->_state;
3287 } else {
3288 ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p0->channel, oi0, p1->channel, oi1);
3289 tone_zone_play_tone(p0->subs[oi0].zfd, -1);
3291 if ((oi0 == SUB_THREEWAY) &&
3292 p0->subs[SUB_THREEWAY].inthreeway &&
3293 p0->subs[SUB_REAL].owner &&
3294 p0->subs[SUB_REAL].inthreeway &&
3295 (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
3296 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
3297 tone_zone_play_tone(p1->subs[oi1].zfd, ZT_TONE_RINGTONE);
3298 os0 = p0->subs[SUB_REAL].owner->_state;
3299 } else {
3300 ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p1->channel, oi1, p0->channel, oi0);
3301 tone_zone_play_tone(p1->subs[oi0].zfd, -1);
3303 if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3304 if (!p0->echocanbridged || !p1->echocanbridged) {
3305 /* Disable echo cancellation if appropriate */
3306 zt_disable_ec(p0);
3307 zt_disable_ec(p1);
3310 zt_link(slave, master);
3311 master->inconference = inconf;
3312 } else if (!nothingok)
3313 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
3315 update_conf(p0);
3316 update_conf(p1);
3317 t0 = p0->subs[SUB_REAL].inthreeway;
3318 t1 = p1->subs[SUB_REAL].inthreeway;
3320 ast_mutex_unlock(&p0->lock);
3321 ast_mutex_unlock(&p1->lock);
3323 ast_mutex_unlock(&c0->lock);
3324 ast_mutex_unlock(&c1->lock);
3326 /* Native bridge failed */
3327 if ((!master || !slave) && !nothingok) {
3328 zt_enable_ec(p0);
3329 zt_enable_ec(p1);
3330 return AST_BRIDGE_FAILED;
3333 if (option_verbose > 2)
3334 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
3336 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
3337 disable_dtmf_detect(op0);
3339 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
3340 disable_dtmf_detect(op1);
3342 for (;;) {
3343 struct ast_channel *c0_priority[2] = {c0, c1};
3344 struct ast_channel *c1_priority[2] = {c1, c0};
3346 /* Here's our main loop... Start by locking things, looking for private parts,
3347 and then balking if anything is wrong */
3348 ast_mutex_lock(&c0->lock);
3349 ast_mutex_lock(&c1->lock);
3350 p0 = c0->tech_pvt;
3351 p1 = c1->tech_pvt;
3353 if (op0 == p0)
3354 i0 = zt_get_index(c0, p0, 1);
3355 if (op1 == p1)
3356 i1 = zt_get_index(c1, p1, 1);
3357 ast_mutex_unlock(&c0->lock);
3358 ast_mutex_unlock(&c1->lock);
3360 if (!timeoutms ||
3361 (op0 != p0) ||
3362 (op1 != p1) ||
3363 (ofd0 != c0->fds[0]) ||
3364 (ofd1 != c1->fds[0]) ||
3365 (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) ||
3366 (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) ||
3367 (oc0 != p0->owner) ||
3368 (oc1 != p1->owner) ||
3369 (t0 != p0->subs[SUB_REAL].inthreeway) ||
3370 (t1 != p1->subs[SUB_REAL].inthreeway) ||
3371 (oi0 != i0) ||
3372 (oi1 != i1)) {
3373 ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
3374 op0->channel, oi0, op1->channel, oi1);
3375 res = AST_BRIDGE_RETRY;
3376 goto return_from_bridge;
3379 #ifdef PRI_2BCT
3380 q931c0 = p0->call;
3381 q931c1 = p1->call;
3382 if (p0->transfer && p1->transfer
3383 && q931c0 && q931c1
3384 && !triedtopribridge) {
3385 pri_channel_bridge(q931c0, q931c1);
3386 triedtopribridge = 1;
3388 #endif
3390 who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
3391 if (!who) {
3392 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
3393 continue;
3395 f = ast_read(who);
3396 if (!f || (f->frametype == AST_FRAME_CONTROL)) {
3397 *fo = f;
3398 *rc = who;
3399 res = AST_BRIDGE_COMPLETE;
3400 goto return_from_bridge;
3402 if (f->frametype == AST_FRAME_DTMF) {
3403 if ((who == c0) && p0->pulsedial) {
3404 ast_write(c1, f);
3405 } else if ((who == c1) && p1->pulsedial) {
3406 ast_write(c0, f);
3407 } else {
3408 *fo = f;
3409 *rc = who;
3410 res = AST_BRIDGE_COMPLETE;
3411 goto return_from_bridge;
3414 ast_frfree(f);
3416 /* Swap who gets priority */
3417 priority = !priority;
3420 return_from_bridge:
3421 if (op0 == p0)
3422 zt_enable_ec(p0);
3424 if (op1 == p1)
3425 zt_enable_ec(p1);
3427 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
3428 enable_dtmf_detect(op0);
3430 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
3431 enable_dtmf_detect(op1);
3433 zt_unlink(slave, master, 1);
3435 return res;
3438 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3440 struct zt_pvt *p = newchan->tech_pvt;
3441 int x;
3442 ast_mutex_lock(&p->lock);
3443 ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
3444 if (p->owner == oldchan) {
3445 p->owner = newchan;
3447 for (x = 0; x < 3; x++)
3448 if (p->subs[x].owner == oldchan) {
3449 if (!x)
3450 zt_unlink(NULL, p, 0);
3451 p->subs[x].owner = newchan;
3453 if (newchan->_state == AST_STATE_RINGING)
3454 zt_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
3455 update_conf(p);
3456 ast_mutex_unlock(&p->lock);
3457 return 0;
3460 static int zt_ring_phone(struct zt_pvt *p)
3462 int x;
3463 int res;
3464 /* Make sure our transmit state is on hook */
3465 x = 0;
3466 x = ZT_ONHOOK;
3467 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3468 do {
3469 x = ZT_RING;
3470 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3471 if (res) {
3472 switch (errno) {
3473 case EBUSY:
3474 case EINTR:
3475 /* Wait just in case */
3476 usleep(10000);
3477 continue;
3478 case EINPROGRESS:
3479 res = 0;
3480 break;
3481 default:
3482 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
3483 res = 0;
3486 } while (res);
3487 return res;
3490 static void *ss_thread(void *data);
3492 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
3494 static int attempt_transfer(struct zt_pvt *p)
3496 /* In order to transfer, we need at least one of the channels to
3497 actually be in a call bridge. We can't conference two applications
3498 together (but then, why would we want to?) */
3499 if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
3500 /* The three-way person we're about to transfer to could still be in MOH, so
3501 stop if now if appropriate */
3502 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
3503 ast_queue_control(p->subs[SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
3504 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
3505 ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
3507 if (p->subs[SUB_REAL].owner->cdr) {
3508 /* Move CDR from second channel to current one */
3509 p->subs[SUB_THREEWAY].owner->cdr =
3510 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, p->subs[SUB_REAL].owner->cdr);
3511 p->subs[SUB_REAL].owner->cdr = NULL;
3513 if (ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr) {
3514 /* Move CDR from second channel's bridge to current one */
3515 p->subs[SUB_THREEWAY].owner->cdr =
3516 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr);
3517 ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr = NULL;
3519 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
3520 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3521 ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
3522 return -1;
3524 /* Orphan the channel after releasing the lock */
3525 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3526 unalloc_sub(p, SUB_THREEWAY);
3527 } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
3528 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
3529 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)
3530 ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
3531 if (p->subs[SUB_THREEWAY].owner->cdr) {
3532 /* Move CDR from second channel to current one */
3533 p->subs[SUB_REAL].owner->cdr =
3534 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, p->subs[SUB_THREEWAY].owner->cdr);
3535 p->subs[SUB_THREEWAY].owner->cdr = NULL;
3537 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr) {
3538 /* Move CDR from second channel's bridge to current one */
3539 p->subs[SUB_REAL].owner->cdr =
3540 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr);
3541 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr = NULL;
3543 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
3544 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3545 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
3546 return -1;
3548 /* Three-way is now the REAL */
3549 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3550 ast_mutex_unlock(&p->subs[SUB_REAL].owner->lock);
3551 unalloc_sub(p, SUB_THREEWAY);
3552 /* Tell the caller not to hangup */
3553 return 1;
3554 } else {
3555 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
3556 p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
3557 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3558 return -1;
3560 return 0;
3563 static int check_for_conference(struct zt_pvt *p)
3565 ZT_CONFINFO ci;
3566 /* Fine if we already have a master, etc */
3567 if (p->master || (p->confno > -1))
3568 return 0;
3569 memset(&ci, 0, sizeof(ci));
3570 if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
3571 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
3572 return 0;
3574 /* If we have no master and don't have a confno, then
3575 if we're in a conference, it's probably a MeetMe room or
3576 some such, so don't let us 3-way out! */
3577 if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
3578 if (option_verbose > 2)
3579 ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
3580 return 1;
3582 return 0;
3585 static int get_alarms(struct zt_pvt *p)
3587 int res;
3588 ZT_SPANINFO zi;
3589 memset(&zi, 0, sizeof(zi));
3590 zi.spanno = p->span;
3591 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
3592 if (res < 0) {
3593 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
3594 return 0;
3596 return zi.alarms;
3599 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
3601 int res, x;
3602 int index, mysig;
3603 char *c;
3604 struct zt_pvt *p = ast->tech_pvt;
3605 pthread_t threadid;
3606 pthread_attr_t attr;
3607 struct ast_channel *chan;
3609 pthread_attr_init(&attr);
3610 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
3612 index = zt_get_index(ast, p, 0);
3613 mysig = p->sig;
3614 if (p->outsigmod > -1)
3615 mysig = p->outsigmod;
3616 p->subs[index].f.frametype = AST_FRAME_NULL;
3617 p->subs[index].f.subclass = 0;
3618 p->subs[index].f.datalen = 0;
3619 p->subs[index].f.samples = 0;
3620 p->subs[index].f.mallocd = 0;
3621 p->subs[index].f.offset = 0;
3622 p->subs[index].f.src = "zt_handle_event";
3623 p->subs[index].f.data = NULL;
3624 if (index < 0)
3625 return &p->subs[index].f;
3626 if (p->fake_event) {
3627 res = p->fake_event;
3628 p->fake_event = 0;
3629 } else
3630 res = zt_get_event(p->subs[index].zfd);
3632 ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
3634 if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFUP)) {
3635 p->pulsedial = (res & ZT_EVENT_PULSEDIGIT) ? 1 : 0;
3636 ast_log(LOG_DEBUG, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
3637 #ifdef HAVE_PRI
3638 if (!p->proceeding && p->sig == SIG_PRI && p->pri && p->pri->overlapdial) {
3639 /* absorb event */
3640 } else {
3641 #endif
3642 p->subs[index].f.frametype = AST_FRAME_DTMF_END;
3643 p->subs[index].f.subclass = res & 0xff;
3644 #ifdef HAVE_PRI
3646 #endif
3647 /* Unmute conference, return the captured digit */
3648 zt_confmute(p, 0);
3649 return &p->subs[index].f;
3652 if (res & ZT_EVENT_DTMFDOWN) {
3653 ast_log(LOG_DEBUG, "DTMF Down '%c'\n", res & 0xff);
3654 /* Mute conference */
3655 zt_confmute(p, 1);
3656 p->subs[index].f.frametype = AST_FRAME_DTMF_BEGIN;
3657 p->subs[index].f.subclass = res & 0xff;
3658 return &p->subs[index].f;
3661 switch (res) {
3662 #ifdef ZT_EVENT_EC_DISABLED
3663 case ZT_EVENT_EC_DISABLED:
3664 if (option_verbose > 2)
3665 ast_verbose(VERBOSE_PREFIX_3 "Channel %d echo canceler disabled due to CED detection\n", p->channel);
3666 p->echocanon = 0;
3667 break;
3668 #endif
3669 case ZT_EVENT_BITSCHANGED:
3670 ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
3671 case ZT_EVENT_PULSE_START:
3672 /* Stop tone if there's a pulse start and the PBX isn't started */
3673 if (!ast->pbx)
3674 tone_zone_play_tone(p->subs[index].zfd, -1);
3675 break;
3676 case ZT_EVENT_DIALCOMPLETE:
3677 if (p->inalarm) break;
3678 if ((p->radio || (p->oprmode < 0))) break;
3679 if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
3680 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
3681 return NULL;
3683 if (!x) { /* if not still dialing in driver */
3684 zt_enable_ec(p);
3685 if (p->echobreak) {
3686 zt_train_ec(p);
3687 ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
3688 p->dop.op = ZT_DIAL_OP_REPLACE;
3689 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
3690 p->echobreak = 0;
3691 } else {
3692 p->dialing = 0;
3693 if ((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) {
3694 /* if thru with dialing after offhook */
3695 if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
3696 ast_setstate(ast, AST_STATE_UP);
3697 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3698 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3699 break;
3700 } else { /* if to state wait for offhook to dial rest */
3701 /* we now wait for off hook */
3702 ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
3705 if (ast->_state == AST_STATE_DIALING) {
3706 if ((p->callprogress & 1) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
3707 ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
3708 } else if (p->confirmanswer || (!p->dialednone && ((mysig == SIG_EM) || (mysig == SIG_EM_E1) || (mysig == SIG_EMWINK) || (mysig == SIG_FEATD) || (mysig == SIG_FEATDMF_TA) || (mysig == SIG_FEATDMF) || (mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF) || (mysig == SIG_FEATB) || (mysig == SIG_SF) || (mysig == SIG_SFWINK) || (mysig == SIG_SF_FEATD) || (mysig == SIG_SF_FEATDMF) || (mysig == SIG_SF_FEATB)))) {
3709 ast_setstate(ast, AST_STATE_RINGING);
3710 } else if (!p->answeronpolarityswitch) {
3711 ast_setstate(ast, AST_STATE_UP);
3712 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3713 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3718 break;
3719 case ZT_EVENT_ALARM:
3720 #ifdef HAVE_PRI
3721 if (!p->pri || !p->pri->pri || (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0)) {
3722 /* T309 is not enabled : hangup calls when alarm occurs */
3723 if (p->call) {
3724 if (p->pri && p->pri->pri) {
3725 if (!pri_grab(p, p->pri)) {
3726 pri_hangup(p->pri->pri, p->call, -1);
3727 pri_destroycall(p->pri->pri, p->call);
3728 p->call = NULL;
3729 pri_rel(p->pri);
3730 } else
3731 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
3732 } else
3733 ast_log(LOG_WARNING, "The PRI Call has not been destroyed\n");
3735 if (p->owner)
3736 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3738 if (p->bearer)
3739 p->bearer->inalarm = 1;
3740 else
3741 #endif
3742 p->inalarm = 1;
3743 res = get_alarms(p);
3744 ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm2str(res));
3745 manager_event(EVENT_FLAG_SYSTEM, "Alarm",
3746 "Alarm: %s\r\n"
3747 "Channel: %d\r\n",
3748 alarm2str(res), p->channel);
3749 #ifdef HAVE_LIBPRI
3750 if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
3751 /* fall through intentionally */
3752 } else {
3753 break;
3755 #endif
3756 case ZT_EVENT_ONHOOK:
3757 if (p->radio) {
3758 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3759 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
3760 break;
3762 if (p->oprmode < 0)
3764 if (p->oprmode != -1) break;
3765 if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
3767 /* Make sure it starts ringing */
3768 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RINGOFF);
3769 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RING);
3770 save_conference(p->oprpeer);
3771 tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
3773 break;
3775 switch (p->sig) {
3776 case SIG_FXOLS:
3777 case SIG_FXOGS:
3778 case SIG_FXOKS:
3779 p->onhooktime = time(NULL);
3780 p->msgstate = -1;
3781 /* Check for some special conditions regarding call waiting */
3782 if (index == SUB_REAL) {
3783 /* The normal line was hung up */
3784 if (p->subs[SUB_CALLWAIT].owner) {
3785 /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
3786 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
3787 if (option_verbose > 2)
3788 ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
3789 unalloc_sub(p, SUB_CALLWAIT);
3790 #if 0
3791 p->subs[index].needanswer = 0;
3792 p->subs[index].needringing = 0;
3793 #endif
3794 p->callwaitingrepeat = 0;
3795 p->cidcwexpire = 0;
3796 p->owner = NULL;
3797 /* Don't start streaming audio yet if the incoming call isn't up yet */
3798 if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
3799 p->dialing = 1;
3800 zt_ring_phone(p);
3801 } else if (p->subs[SUB_THREEWAY].owner) {
3802 unsigned int mssinceflash;
3803 /* Here we have to retain the lock on both the main channel, the 3-way channel, and
3804 the private structure -- not especially easy or clean */
3805 while (p->subs[SUB_THREEWAY].owner && ast_mutex_trylock(&p->subs[SUB_THREEWAY].owner->lock)) {
3806 /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
3807 ast_mutex_unlock(&p->lock);
3808 ast_mutex_unlock(&ast->lock);
3809 usleep(1);
3810 /* We can grab ast and p in that order, without worry. We should make sure
3811 nothing seriously bad has happened though like some sort of bizarre double
3812 masquerade! */
3813 ast_mutex_lock(&ast->lock);
3814 ast_mutex_lock(&p->lock);
3815 if (p->owner != ast) {
3816 ast_log(LOG_WARNING, "This isn't good...\n");
3817 return NULL;
3820 if (!p->subs[SUB_THREEWAY].owner) {
3821 ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
3822 return NULL;
3824 mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
3825 ast_log(LOG_DEBUG, "Last flash was %d ms ago\n", mssinceflash);
3826 if (mssinceflash < MIN_MS_SINCE_FLASH) {
3827 /* It hasn't been long enough since the last flashook. This is probably a bounce on
3828 hanging up. Hangup both channels now */
3829 if (p->subs[SUB_THREEWAY].owner)
3830 ast_queue_hangup(p->subs[SUB_THREEWAY].owner);
3831 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3832 ast_log(LOG_DEBUG, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
3833 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3834 } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
3835 if (p->transfer) {
3836 /* In any case this isn't a threeway call anymore */
3837 p->subs[SUB_REAL].inthreeway = 0;
3838 p->subs[SUB_THREEWAY].inthreeway = 0;
3839 /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
3840 if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
3841 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3842 /* Swap subs and dis-own channel */
3843 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3844 p->owner = NULL;
3845 /* Ring the phone */
3846 zt_ring_phone(p);
3847 } else {
3848 if ((res = attempt_transfer(p)) < 0) {
3849 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3850 if (p->subs[SUB_THREEWAY].owner)
3851 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3852 } else if (res) {
3853 /* Don't actually hang up at this point */
3854 if (p->subs[SUB_THREEWAY].owner)
3855 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3856 break;
3859 } else {
3860 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3861 if (p->subs[SUB_THREEWAY].owner)
3862 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3864 } else {
3865 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3866 /* Swap subs and dis-own channel */
3867 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3868 p->owner = NULL;
3869 /* Ring the phone */
3870 zt_ring_phone(p);
3873 } else {
3874 ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
3876 /* Fall through */
3877 default:
3878 zt_disable_ec(p);
3879 return NULL;
3881 break;
3882 case ZT_EVENT_RINGOFFHOOK:
3883 if (p->inalarm) break;
3884 if (p->oprmode < 0)
3886 if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
3888 /* Make sure it stops ringing */
3889 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RINGOFF);
3890 tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].zfd, -1);
3891 restore_conference(p->oprpeer);
3893 break;
3895 if (p->radio)
3897 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3898 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
3899 break;
3901 /* for E911, its supposed to wait for offhook then dial
3902 the second half of the dial string */
3903 if (((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
3904 c = strchr(p->dialdest, '/');
3905 if (c)
3906 c++;
3907 else
3908 c = p->dialdest;
3909 if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
3910 else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
3911 if (strlen(p->dop.dialstr) > 4) {
3912 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
3913 strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
3914 p->echorest[sizeof(p->echorest) - 1] = '\0';
3915 p->echobreak = 1;
3916 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
3917 } else
3918 p->echobreak = 0;
3919 if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
3920 x = ZT_ONHOOK;
3921 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3922 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
3923 return NULL;
3925 p->dialing = 1;
3926 return &p->subs[index].f;
3928 switch (p->sig) {
3929 case SIG_FXOLS:
3930 case SIG_FXOGS:
3931 case SIG_FXOKS:
3932 switch (ast->_state) {
3933 case AST_STATE_RINGING:
3934 zt_enable_ec(p);
3935 zt_train_ec(p);
3936 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3937 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3938 /* Make sure it stops ringing */
3939 zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
3940 ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
3941 if (p->cidspill) {
3942 /* Cancel any running CallerID spill */
3943 free(p->cidspill);
3944 p->cidspill = NULL;
3946 p->dialing = 0;
3947 p->callwaitcas = 0;
3948 if (p->confirmanswer) {
3949 /* Ignore answer if "confirm answer" is enabled */
3950 p->subs[index].f.frametype = AST_FRAME_NULL;
3951 p->subs[index].f.subclass = 0;
3952 } else if (!ast_strlen_zero(p->dop.dialstr)) {
3953 /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
3954 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
3955 if (res < 0) {
3956 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
3957 p->dop.dialstr[0] = '\0';
3958 return NULL;
3959 } else {
3960 ast_log(LOG_DEBUG, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
3961 p->subs[index].f.frametype = AST_FRAME_NULL;
3962 p->subs[index].f.subclass = 0;
3963 p->dialing = 1;
3965 p->dop.dialstr[0] = '\0';
3966 ast_setstate(ast, AST_STATE_DIALING);
3967 } else
3968 ast_setstate(ast, AST_STATE_UP);
3969 return &p->subs[index].f;
3970 case AST_STATE_DOWN:
3971 ast_setstate(ast, AST_STATE_RING);
3972 ast->rings = 1;
3973 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3974 p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
3975 ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
3976 return &p->subs[index].f;
3977 case AST_STATE_UP:
3978 /* Make sure it stops ringing */
3979 zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
3980 /* Okay -- probably call waiting*/
3981 if (ast_bridged_channel(p->owner))
3982 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
3983 p->subs[index].needunhold = 1;
3984 break;
3985 case AST_STATE_RESERVED:
3986 /* Start up dialtone */
3987 if (has_voicemail(p))
3988 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_STUTTER);
3989 else
3990 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALTONE);
3991 break;
3992 default:
3993 ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
3995 break;
3996 case SIG_FXSLS:
3997 case SIG_FXSGS:
3998 case SIG_FXSKS:
3999 if (ast->_state == AST_STATE_RING) {
4000 p->ringt = p->ringt_base;
4003 /* If we get a ring then we cannot be in
4004 * reversed polarity. So we reset to idle */
4005 ast_log(LOG_DEBUG, "Setting IDLE polarity due "
4006 "to ring. Old polarity was %d\n",
4007 p->polarity);
4008 p->polarity = POLARITY_IDLE;
4010 /* Fall through */
4011 case SIG_EM:
4012 case SIG_EM_E1:
4013 case SIG_EMWINK:
4014 case SIG_FEATD:
4015 case SIG_FEATDMF:
4016 case SIG_FEATDMF_TA:
4017 case SIG_E911:
4018 case SIG_FGC_CAMA:
4019 case SIG_FGC_CAMAMF:
4020 case SIG_FEATB:
4021 case SIG_SF:
4022 case SIG_SFWINK:
4023 case SIG_SF_FEATD:
4024 case SIG_SF_FEATDMF:
4025 case SIG_SF_FEATB:
4026 if (ast->_state == AST_STATE_PRERING)
4027 ast_setstate(ast, AST_STATE_RING);
4028 if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
4029 if (option_debug)
4030 ast_log(LOG_DEBUG, "Ring detected\n");
4031 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4032 p->subs[index].f.subclass = AST_CONTROL_RING;
4033 } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
4034 if (option_debug)
4035 ast_log(LOG_DEBUG, "Line answered\n");
4036 if (p->confirmanswer) {
4037 p->subs[index].f.frametype = AST_FRAME_NULL;
4038 p->subs[index].f.subclass = 0;
4039 } else {
4040 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4041 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
4042 ast_setstate(ast, AST_STATE_UP);
4044 } else if (ast->_state != AST_STATE_RING)
4045 ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
4046 break;
4047 default:
4048 ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
4050 break;
4051 #ifdef ZT_EVENT_RINGBEGIN
4052 case ZT_EVENT_RINGBEGIN:
4053 switch (p->sig) {
4054 case SIG_FXSLS:
4055 case SIG_FXSGS:
4056 case SIG_FXSKS:
4057 if (ast->_state == AST_STATE_RING) {
4058 p->ringt = p->ringt_base;
4060 break;
4062 break;
4063 #endif
4064 case ZT_EVENT_RINGEROFF:
4065 if (p->inalarm) break;
4066 if ((p->radio || (p->oprmode < 0))) break;
4067 ast->rings++;
4068 if ((ast->rings > p->cidrings) && (p->cidspill)) {
4069 ast_log(LOG_WARNING, "Didn't finish Caller-ID spill. Cancelling.\n");
4070 free(p->cidspill);
4071 p->cidspill = NULL;
4072 p->callwaitcas = 0;
4074 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4075 p->subs[index].f.subclass = AST_CONTROL_RINGING;
4076 break;
4077 case ZT_EVENT_RINGERON:
4078 break;
4079 case ZT_EVENT_NOALARM:
4080 p->inalarm = 0;
4081 #ifdef HAVE_PRI
4082 /* Extremely unlikely but just in case */
4083 if (p->bearer)
4084 p->bearer->inalarm = 0;
4085 #endif
4086 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
4087 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
4088 "Channel: %d\r\n", p->channel);
4089 break;
4090 case ZT_EVENT_WINKFLASH:
4091 if (p->inalarm) break;
4092 if (p->radio) break;
4093 if (p->oprmode < 0) break;
4094 if (p->oprmode > 1)
4096 struct zt_params par;
4098 if (ioctl(p->oprpeer->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par) != -1)
4100 if (!par.rxisoffhook)
4102 /* Make sure it stops ringing */
4103 zt_set_hook(p->oprpeer->subs[SUB_REAL].zfd, ZT_RINGOFF);
4104 zt_set_hook(p->oprpeer->subs[SUB_REAL].zfd, ZT_RING);
4105 save_conference(p);
4106 tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
4109 break;
4111 /* Remember last time we got a flash-hook */
4112 gettimeofday(&p->flashtime, NULL);
4113 switch (mysig) {
4114 case SIG_FXOLS:
4115 case SIG_FXOGS:
4116 case SIG_FXOKS:
4117 ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
4118 index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
4119 p->callwaitcas = 0;
4121 if (index != SUB_REAL) {
4122 ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", index, p->channel);
4123 goto winkflashdone;
4126 if (p->subs[SUB_CALLWAIT].owner) {
4127 /* Swap to call-wait */
4128 swap_subs(p, SUB_REAL, SUB_CALLWAIT);
4129 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
4130 p->owner = p->subs[SUB_REAL].owner;
4131 ast_log(LOG_DEBUG, "Making %s the new owner\n", p->owner->name);
4132 if (p->owner->_state == AST_STATE_RINGING) {
4133 ast_setstate(p->owner, AST_STATE_UP);
4134 p->subs[SUB_REAL].needanswer = 1;
4136 p->callwaitingrepeat = 0;
4137 p->cidcwexpire = 0;
4138 /* Start music on hold if appropriate */
4139 if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
4140 ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
4141 S_OR(p->mohsuggest, NULL),
4142 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4144 p->subs[SUB_CALLWAIT].needhold = 1;
4145 if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
4146 ast_queue_control_data(p->subs[SUB_REAL].owner, AST_CONTROL_HOLD,
4147 S_OR(p->mohsuggest, NULL),
4148 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4150 p->subs[SUB_REAL].needunhold = 1;
4151 } else if (!p->subs[SUB_THREEWAY].owner) {
4152 char cid_num[256];
4153 char cid_name[256];
4155 if (!p->threewaycalling) {
4156 /* Just send a flash if no 3-way calling */
4157 p->subs[SUB_REAL].needflash = 1;
4158 goto winkflashdone;
4159 } else if (!check_for_conference(p)) {
4160 if (p->zaptrcallerid && p->owner) {
4161 if (p->owner->cid.cid_num)
4162 ast_copy_string(cid_num, p->owner->cid.cid_num, sizeof(cid_num));
4163 if (p->owner->cid.cid_name)
4164 ast_copy_string(cid_name, p->owner->cid.cid_name, sizeof(cid_name));
4166 /* XXX This section needs much more error checking!!! XXX */
4167 /* Start a 3-way call if feasible */
4168 if (!((ast->pbx) ||
4169 (ast->_state == AST_STATE_UP) ||
4170 (ast->_state == AST_STATE_RING))) {
4171 ast_log(LOG_DEBUG, "Flash when call not up or ringing\n");
4172 goto winkflashdone;
4174 if (alloc_sub(p, SUB_THREEWAY)) {
4175 ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
4176 goto winkflashdone;
4178 /* Make new channel */
4179 chan = zt_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, 0);
4180 if (p->zaptrcallerid) {
4181 if (!p->origcid_num)
4182 p->origcid_num = ast_strdup(p->cid_num);
4183 if (!p->origcid_name)
4184 p->origcid_name = ast_strdup(p->cid_name);
4185 ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
4186 ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
4188 /* Swap things around between the three-way and real call */
4189 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4190 /* Disable echo canceller for better dialing */
4191 zt_disable_ec(p);
4192 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALRECALL);
4193 if (res)
4194 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
4195 p->owner = chan;
4196 if (!chan) {
4197 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
4198 } else if (ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
4199 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
4200 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
4201 zt_enable_ec(p);
4202 ast_hangup(chan);
4203 } else {
4204 if (option_verbose > 2)
4205 ast_verbose(VERBOSE_PREFIX_3 "Started three way call on channel %d\n", p->channel);
4206 /* Start music on hold if appropriate */
4207 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
4208 ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
4209 S_OR(p->mohsuggest, NULL),
4210 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4212 p->subs[SUB_THREEWAY].needhold = 1;
4215 } else {
4216 /* Already have a 3 way call */
4217 if (p->subs[SUB_THREEWAY].inthreeway) {
4218 /* Call is already up, drop the last person */
4219 if (option_debug)
4220 ast_log(LOG_DEBUG, "Got flash with three way call up, dropping last call on %d\n", p->channel);
4221 /* If the primary call isn't answered yet, use it */
4222 if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
4223 /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
4224 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4225 p->owner = p->subs[SUB_REAL].owner;
4227 /* Drop the last call and stop the conference */
4228 if (option_verbose > 2)
4229 ast_verbose(VERBOSE_PREFIX_3 "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
4230 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
4231 p->subs[SUB_REAL].inthreeway = 0;
4232 p->subs[SUB_THREEWAY].inthreeway = 0;
4233 } else {
4234 /* Lets see what we're up to */
4235 if (((ast->pbx) || (ast->_state == AST_STATE_UP)) &&
4236 (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
4237 int otherindex = SUB_THREEWAY;
4239 if (option_verbose > 2)
4240 ast_verbose(VERBOSE_PREFIX_3 "Building conference on call on %s and %s\n", p->subs[SUB_THREEWAY].owner->name, p->subs[SUB_REAL].owner->name);
4241 /* Put them in the threeway, and flip */
4242 p->subs[SUB_THREEWAY].inthreeway = 1;
4243 p->subs[SUB_REAL].inthreeway = 1;
4244 if (ast->_state == AST_STATE_UP) {
4245 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4246 otherindex = SUB_REAL;
4248 if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
4249 ast_queue_control(p->subs[otherindex].owner, AST_CONTROL_UNHOLD);
4250 p->subs[otherindex].needunhold = 1;
4251 p->owner = p->subs[SUB_REAL].owner;
4252 if (ast->_state == AST_STATE_RINGING) {
4253 ast_log(LOG_DEBUG, "Enabling ringtone on real and threeway\n");
4254 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
4255 res = tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, ZT_TONE_RINGTONE);
4257 } else {
4258 if (option_verbose > 2)
4259 ast_verbose(VERBOSE_PREFIX_3 "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
4260 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4261 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
4262 p->owner = p->subs[SUB_REAL].owner;
4263 if (p->subs[SUB_REAL].owner && ast_bridged_channel(p->subs[SUB_REAL].owner))
4264 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
4265 p->subs[SUB_REAL].needunhold = 1;
4266 zt_enable_ec(p);
4271 winkflashdone:
4272 update_conf(p);
4273 break;
4274 case SIG_EM:
4275 case SIG_EM_E1:
4276 case SIG_EMWINK:
4277 case SIG_FEATD:
4278 case SIG_SF:
4279 case SIG_SFWINK:
4280 case SIG_SF_FEATD:
4281 case SIG_FXSLS:
4282 case SIG_FXSGS:
4283 if (p->dialing)
4284 ast_log(LOG_DEBUG, "Ignoring wink on channel %d\n", p->channel);
4285 else
4286 ast_log(LOG_DEBUG, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
4287 break;
4288 case SIG_FEATDMF_TA:
4289 switch (p->whichwink) {
4290 case 0:
4291 ast_log(LOG_DEBUG, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
4292 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
4293 break;
4294 case 1:
4295 ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
4296 break;
4297 case 2:
4298 ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
4299 return NULL;
4301 p->whichwink++;
4302 /* Fall through */
4303 case SIG_FEATDMF:
4304 case SIG_E911:
4305 case SIG_FGC_CAMAMF:
4306 case SIG_FGC_CAMA:
4307 case SIG_FEATB:
4308 case SIG_SF_FEATDMF:
4309 case SIG_SF_FEATB:
4310 /* FGD MF *Must* wait for wink */
4311 if (!ast_strlen_zero(p->dop.dialstr))
4312 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
4313 else if (res < 0) {
4314 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
4315 p->dop.dialstr[0] = '\0';
4316 return NULL;
4317 } else
4318 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
4319 p->dop.dialstr[0] = '\0';
4320 break;
4321 default:
4322 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
4324 break;
4325 case ZT_EVENT_HOOKCOMPLETE:
4326 if (p->inalarm) break;
4327 if ((p->radio || (p->oprmode < 0))) break;
4328 switch (mysig) {
4329 case SIG_FXSLS: /* only interesting for FXS */
4330 case SIG_FXSGS:
4331 case SIG_FXSKS:
4332 case SIG_EM:
4333 case SIG_EM_E1:
4334 case SIG_EMWINK:
4335 case SIG_FEATD:
4336 case SIG_SF:
4337 case SIG_SFWINK:
4338 case SIG_SF_FEATD:
4339 if (!ast_strlen_zero(p->dop.dialstr))
4340 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
4341 else if (res < 0) {
4342 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
4343 p->dop.dialstr[0] = '\0';
4344 return NULL;
4345 } else
4346 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
4347 p->dop.dialstr[0] = '\0';
4348 p->dop.op = ZT_DIAL_OP_REPLACE;
4349 break;
4350 case SIG_FEATDMF:
4351 case SIG_FEATDMF_TA:
4352 case SIG_E911:
4353 case SIG_FGC_CAMA:
4354 case SIG_FGC_CAMAMF:
4355 case SIG_FEATB:
4356 case SIG_SF_FEATDMF:
4357 case SIG_SF_FEATB:
4358 ast_log(LOG_DEBUG, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
4359 break;
4360 default:
4361 break;
4363 break;
4364 case ZT_EVENT_POLARITY:
4366 * If we get a Polarity Switch event, check to see
4367 * if we should change the polarity state and
4368 * mark the channel as UP or if this is an indication
4369 * of remote end disconnect.
4371 if (p->polarity == POLARITY_IDLE) {
4372 p->polarity = POLARITY_REV;
4373 if (p->answeronpolarityswitch &&
4374 ((ast->_state == AST_STATE_DIALING) ||
4375 (ast->_state == AST_STATE_RINGING))) {
4376 ast_log(LOG_DEBUG, "Answering on polarity switch!\n");
4377 ast_setstate(p->owner, AST_STATE_UP);
4378 if (p->hanguponpolarityswitch) {
4379 gettimeofday(&p->polaritydelaytv, NULL);
4381 } else
4382 ast_log(LOG_DEBUG, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
4384 /* Removed else statement from here as it was preventing hangups from ever happening*/
4385 /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
4386 if (p->hanguponpolarityswitch &&
4387 (p->polarityonanswerdelay > 0) &&
4388 (p->polarity == POLARITY_REV) &&
4389 ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
4390 /* Added log_debug information below to provide a better indication of what is going on */
4391 ast_log(LOG_DEBUG, "Polarity Reversal event occured - DEBUG 1: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %d\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
4393 if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
4394 ast_log(LOG_DEBUG, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
4395 ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
4396 p->polarity = POLARITY_IDLE;
4397 } else {
4398 ast_log(LOG_DEBUG, "Polarity Reversal detected but NOT hanging up (too close to answer event) on channel %d, state %d\n", p->channel, ast->_state);
4400 } else {
4401 p->polarity = POLARITY_IDLE;
4402 ast_log(LOG_DEBUG, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
4404 /* Added more log_debug information below to provide a better indication of what is going on */
4405 ast_log(LOG_DEBUG, "Polarity Reversal event occured - DEBUG 2: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %d\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
4406 break;
4407 default:
4408 ast_log(LOG_DEBUG, "Dunno what to do with event %d on channel %d\n", res, p->channel);
4410 return &p->subs[index].f;
4413 static struct ast_frame *__zt_exception(struct ast_channel *ast)
4415 struct zt_pvt *p = ast->tech_pvt;
4416 int res;
4417 int usedindex=-1;
4418 int index;
4419 struct ast_frame *f;
4422 index = zt_get_index(ast, p, 1);
4424 p->subs[index].f.frametype = AST_FRAME_NULL;
4425 p->subs[index].f.datalen = 0;
4426 p->subs[index].f.samples = 0;
4427 p->subs[index].f.mallocd = 0;
4428 p->subs[index].f.offset = 0;
4429 p->subs[index].f.subclass = 0;
4430 p->subs[index].f.delivery = ast_tv(0,0);
4431 p->subs[index].f.src = "zt_exception";
4432 p->subs[index].f.data = NULL;
4435 if ((!p->owner) && (!(p->radio || (p->oprmode < 0)))) {
4436 /* If nobody owns us, absorb the event appropriately, otherwise
4437 we loop indefinitely. This occurs when, during call waiting, the
4438 other end hangs up our channel so that it no longer exists, but we
4439 have neither FLASH'd nor ONHOOK'd to signify our desire to
4440 change to the other channel. */
4441 if (p->fake_event) {
4442 res = p->fake_event;
4443 p->fake_event = 0;
4444 } else
4445 res = zt_get_event(p->subs[SUB_REAL].zfd);
4446 /* Switch to real if there is one and this isn't something really silly... */
4447 if ((res != ZT_EVENT_RINGEROFF) && (res != ZT_EVENT_RINGERON) &&
4448 (res != ZT_EVENT_HOOKCOMPLETE)) {
4449 ast_log(LOG_DEBUG, "Restoring owner of channel %d on event %d\n", p->channel, res);
4450 p->owner = p->subs[SUB_REAL].owner;
4451 if (p->owner && ast_bridged_channel(p->owner))
4452 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4453 p->subs[SUB_REAL].needunhold = 1;
4455 switch (res) {
4456 case ZT_EVENT_ONHOOK:
4457 zt_disable_ec(p);
4458 if (p->owner) {
4459 if (option_verbose > 2)
4460 ast_verbose(VERBOSE_PREFIX_3 "Channel %s still has call, ringing phone\n", p->owner->name);
4461 zt_ring_phone(p);
4462 p->callwaitingrepeat = 0;
4463 p->cidcwexpire = 0;
4464 } else
4465 ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
4466 update_conf(p);
4467 break;
4468 case ZT_EVENT_RINGOFFHOOK:
4469 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
4470 if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
4471 p->subs[SUB_REAL].needanswer = 1;
4472 p->dialing = 0;
4474 break;
4475 case ZT_EVENT_HOOKCOMPLETE:
4476 case ZT_EVENT_RINGERON:
4477 case ZT_EVENT_RINGEROFF:
4478 /* Do nothing */
4479 break;
4480 case ZT_EVENT_WINKFLASH:
4481 gettimeofday(&p->flashtime, NULL);
4482 if (p->owner) {
4483 if (option_verbose > 2)
4484 ast_verbose(VERBOSE_PREFIX_3 "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
4485 if (p->owner->_state != AST_STATE_UP) {
4486 /* Answer if necessary */
4487 usedindex = zt_get_index(p->owner, p, 0);
4488 if (usedindex > -1) {
4489 p->subs[usedindex].needanswer = 1;
4491 ast_setstate(p->owner, AST_STATE_UP);
4493 p->callwaitingrepeat = 0;
4494 p->cidcwexpire = 0;
4495 if (ast_bridged_channel(p->owner))
4496 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4497 p->subs[SUB_REAL].needunhold = 1;
4498 } else
4499 ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
4500 update_conf(p);
4501 break;
4502 default:
4503 ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
4505 f = &p->subs[index].f;
4506 return f;
4508 if (!(p->radio || (p->oprmode < 0))) ast_log(LOG_DEBUG, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
4509 /* If it's not us, return NULL immediately */
4510 if (ast != p->owner) {
4511 ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
4512 f = &p->subs[index].f;
4513 return f;
4515 f = zt_handle_event(ast);
4516 return f;
4519 static struct ast_frame *zt_exception(struct ast_channel *ast)
4521 struct zt_pvt *p = ast->tech_pvt;
4522 struct ast_frame *f;
4523 ast_mutex_lock(&p->lock);
4524 f = __zt_exception(ast);
4525 ast_mutex_unlock(&p->lock);
4526 return f;
4529 static struct ast_frame *zt_read(struct ast_channel *ast)
4531 struct zt_pvt *p = ast->tech_pvt;
4532 int res;
4533 int index;
4534 void *readbuf;
4535 struct ast_frame *f;
4538 ast_mutex_lock(&p->lock);
4540 index = zt_get_index(ast, p, 0);
4542 /* Hang up if we don't really exist */
4543 if (index < 0) {
4544 ast_log(LOG_WARNING, "We dont exist?\n");
4545 ast_mutex_unlock(&p->lock);
4546 return NULL;
4549 if ((p->radio || (p->oprmode < 0)) && p->inalarm) return NULL;
4551 p->subs[index].f.frametype = AST_FRAME_NULL;
4552 p->subs[index].f.datalen = 0;
4553 p->subs[index].f.samples = 0;
4554 p->subs[index].f.mallocd = 0;
4555 p->subs[index].f.offset = 0;
4556 p->subs[index].f.subclass = 0;
4557 p->subs[index].f.delivery = ast_tv(0,0);
4558 p->subs[index].f.src = "zt_read";
4559 p->subs[index].f.data = NULL;
4561 /* make sure it sends initial key state as first frame */
4562 if ((p->radio || (p->oprmode < 0)) && (!p->firstradio))
4564 ZT_PARAMS ps;
4566 ps.channo = p->channel;
4567 if (ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps) < 0) {
4568 ast_mutex_unlock(&p->lock);
4569 return NULL;
4571 p->firstradio = 1;
4572 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4573 if (ps.rxisoffhook)
4575 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
4577 else
4579 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
4581 ast_mutex_unlock(&p->lock);
4582 return &p->subs[index].f;
4584 if (p->ringt == 1) {
4585 ast_mutex_unlock(&p->lock);
4586 return NULL;
4588 else if (p->ringt > 0)
4589 p->ringt--;
4591 if (p->subs[index].needringing) {
4592 /* Send ringing frame if requested */
4593 p->subs[index].needringing = 0;
4594 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4595 p->subs[index].f.subclass = AST_CONTROL_RINGING;
4596 ast_setstate(ast, AST_STATE_RINGING);
4597 ast_mutex_unlock(&p->lock);
4598 return &p->subs[index].f;
4601 if (p->subs[index].needbusy) {
4602 /* Send busy frame if requested */
4603 p->subs[index].needbusy = 0;
4604 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4605 p->subs[index].f.subclass = AST_CONTROL_BUSY;
4606 ast_mutex_unlock(&p->lock);
4607 return &p->subs[index].f;
4610 if (p->subs[index].needcongestion) {
4611 /* Send congestion frame if requested */
4612 p->subs[index].needcongestion = 0;
4613 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4614 p->subs[index].f.subclass = AST_CONTROL_CONGESTION;
4615 ast_mutex_unlock(&p->lock);
4616 return &p->subs[index].f;
4619 if (p->subs[index].needcallerid) {
4620 ast_set_callerid(ast, S_OR(p->lastcid_num, NULL),
4621 S_OR(p->lastcid_name, NULL),
4622 S_OR(p->lastcid_num, NULL)
4624 p->subs[index].needcallerid = 0;
4627 if (p->subs[index].needanswer) {
4628 /* Send answer frame if requested */
4629 p->subs[index].needanswer = 0;
4630 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4631 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
4632 ast_mutex_unlock(&p->lock);
4633 return &p->subs[index].f;
4636 if (p->subs[index].needflash) {
4637 /* Send answer frame if requested */
4638 p->subs[index].needflash = 0;
4639 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4640 p->subs[index].f.subclass = AST_CONTROL_FLASH;
4641 ast_mutex_unlock(&p->lock);
4642 return &p->subs[index].f;
4645 if (p->subs[index].needhold) {
4646 /* Send answer frame if requested */
4647 p->subs[index].needhold = 0;
4648 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4649 p->subs[index].f.subclass = AST_CONTROL_HOLD;
4650 ast_mutex_unlock(&p->lock);
4651 ast_log(LOG_DEBUG, "Sending hold on '%s'\n", ast->name);
4652 return &p->subs[index].f;
4655 if (p->subs[index].needunhold) {
4656 /* Send answer frame if requested */
4657 p->subs[index].needunhold = 0;
4658 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4659 p->subs[index].f.subclass = AST_CONTROL_UNHOLD;
4660 ast_mutex_unlock(&p->lock);
4661 ast_log(LOG_DEBUG, "Sending unhold on '%s'\n", ast->name);
4662 return &p->subs[index].f;
4665 if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
4666 if (!p->subs[index].linear) {
4667 p->subs[index].linear = 1;
4668 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4669 if (res)
4670 ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, index);
4672 } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
4673 (ast->rawreadformat == AST_FORMAT_ALAW)) {
4674 if (p->subs[index].linear) {
4675 p->subs[index].linear = 0;
4676 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4677 if (res)
4678 ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, index);
4680 } else {
4681 ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
4682 ast_mutex_unlock(&p->lock);
4683 return NULL;
4685 readbuf = ((unsigned char *)p->subs[index].buffer) + AST_FRIENDLY_OFFSET;
4686 CHECK_BLOCKING(ast);
4687 res = read(p->subs[index].zfd, readbuf, p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE);
4688 ast_clear_flag(ast, AST_FLAG_BLOCKING);
4689 /* Check for hangup */
4690 if (res < 0) {
4691 f = NULL;
4692 if (res == -1) {
4693 if (errno == EAGAIN) {
4694 /* Return "NULL" frame if there is nobody there */
4695 ast_mutex_unlock(&p->lock);
4696 return &p->subs[index].f;
4697 } else if (errno == ELAST) {
4698 f = __zt_exception(ast);
4699 } else
4700 ast_log(LOG_WARNING, "zt_rec: %s\n", strerror(errno));
4702 ast_mutex_unlock(&p->lock);
4703 return f;
4705 if (res != (p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE)) {
4706 ast_log(LOG_DEBUG, "Short read (%d/%d), must be an event...\n", res, p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE);
4707 f = __zt_exception(ast);
4708 ast_mutex_unlock(&p->lock);
4709 return f;
4711 if (p->tdd) { /* if in TDD mode, see if we receive that */
4712 int c;
4714 c = tdd_feed(p->tdd,readbuf,READ_SIZE);
4715 if (c < 0) {
4716 ast_log(LOG_DEBUG,"tdd_feed failed\n");
4717 ast_mutex_unlock(&p->lock);
4718 return NULL;
4720 if (c) { /* if a char to return */
4721 p->subs[index].f.subclass = 0;
4722 p->subs[index].f.frametype = AST_FRAME_TEXT;
4723 p->subs[index].f.mallocd = 0;
4724 p->subs[index].f.offset = AST_FRIENDLY_OFFSET;
4725 p->subs[index].f.data = p->subs[index].buffer + AST_FRIENDLY_OFFSET;
4726 p->subs[index].f.datalen = 1;
4727 *((char *) p->subs[index].f.data) = c;
4728 ast_mutex_unlock(&p->lock);
4729 return &p->subs[index].f;
4732 if (p->callwaitingrepeat)
4733 p->callwaitingrepeat--;
4734 if (p->cidcwexpire)
4735 p->cidcwexpire--;
4736 /* Repeat callwaiting */
4737 if (p->callwaitingrepeat == 1) {
4738 p->callwaitrings++;
4739 zt_callwait(ast);
4741 /* Expire CID/CW */
4742 if (p->cidcwexpire == 1) {
4743 if (option_verbose > 2)
4744 ast_verbose(VERBOSE_PREFIX_3 "CPE does not support Call Waiting Caller*ID.\n");
4745 restore_conference(p);
4747 if (p->subs[index].linear) {
4748 p->subs[index].f.datalen = READ_SIZE * 2;
4749 } else
4750 p->subs[index].f.datalen = READ_SIZE;
4752 /* Handle CallerID Transmission */
4753 if ((p->owner == ast) && p->cidspill &&((ast->_state == AST_STATE_UP) || (ast->rings == p->cidrings))) {
4754 send_callerid(p);
4757 p->subs[index].f.frametype = AST_FRAME_VOICE;
4758 p->subs[index].f.subclass = ast->rawreadformat;
4759 p->subs[index].f.samples = READ_SIZE;
4760 p->subs[index].f.mallocd = 0;
4761 p->subs[index].f.offset = AST_FRIENDLY_OFFSET;
4762 p->subs[index].f.data = p->subs[index].buffer + AST_FRIENDLY_OFFSET/2;
4763 #if 0
4764 ast_log(LOG_DEBUG, "Read %d of voice on %s\n", p->subs[index].f.datalen, ast->name);
4765 #endif
4766 if (p->dialing || /* Transmitting something */
4767 (index && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
4768 ((index == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
4770 /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
4771 don't send anything */
4772 p->subs[index].f.frametype = AST_FRAME_NULL;
4773 p->subs[index].f.subclass = 0;
4774 p->subs[index].f.samples = 0;
4775 p->subs[index].f.mallocd = 0;
4776 p->subs[index].f.offset = 0;
4777 p->subs[index].f.data = NULL;
4778 p->subs[index].f.datalen= 0;
4780 if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect || p->callprogress) && !index) {
4781 /* Perform busy detection. etc on the zap line */
4782 f = ast_dsp_process(ast, p->dsp, &p->subs[index].f);
4783 if (f) {
4784 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_BUSY)) {
4785 if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
4786 /* Treat this as a "hangup" instead of a "busy" on the assumption that
4787 a busy */
4788 f = NULL;
4790 } else if (f->frametype == AST_FRAME_DTMF) {
4791 #ifdef HAVE_PRI
4792 if (!p->proceeding && p->sig==SIG_PRI && p->pri && p->pri->overlapdial) {
4793 /* Don't accept in-band DTMF when in overlap dial mode */
4794 f->frametype = AST_FRAME_NULL;
4795 f->subclass = 0;
4797 #endif
4798 /* DSP clears us of being pulse */
4799 p->pulsedial = 0;
4802 } else
4803 f = &p->subs[index].f;
4804 if (f && (f->frametype == AST_FRAME_DTMF)) {
4805 ast_log(LOG_DEBUG, "DTMF digit: %c on %s\n", f->subclass, ast->name);
4806 if (p->confirmanswer) {
4807 ast_log(LOG_DEBUG, "Confirm answer on %s!\n", ast->name);
4808 /* Upon receiving a DTMF digit, consider this an answer confirmation instead
4809 of a DTMF digit */
4810 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4811 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
4812 f = &p->subs[index].f;
4813 /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
4814 p->confirmanswer = 0;
4815 } else if (p->callwaitcas) {
4816 if ((f->subclass == 'A') || (f->subclass == 'D')) {
4817 ast_log(LOG_DEBUG, "Got some DTMF, but it's for the CAS\n");
4818 if (p->cidspill)
4819 free(p->cidspill);
4820 send_cwcidspill(p);
4822 if ((f->subclass != 'm') && (f->subclass != 'u'))
4823 p->callwaitcas = 0;
4824 p->subs[index].f.frametype = AST_FRAME_NULL;
4825 p->subs[index].f.subclass = 0;
4826 f = &p->subs[index].f;
4827 } else if (f->subclass == 'f') {
4828 /* Fax tone -- Handle and return NULL */
4829 if (!p->faxhandled) {
4830 p->faxhandled++;
4831 if (strcmp(ast->exten, "fax")) {
4832 const char *target_context = S_OR(ast->macrocontext, ast->context);
4834 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
4835 if (option_verbose > 2)
4836 ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
4837 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
4838 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
4839 if (ast_async_goto(ast, target_context, "fax", 1))
4840 ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
4841 } else
4842 ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
4843 } else
4844 ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
4845 } else
4846 ast_log(LOG_DEBUG, "Fax already handled\n");
4847 zt_confmute(p, 0);
4848 p->subs[index].f.frametype = AST_FRAME_NULL;
4849 p->subs[index].f.subclass = 0;
4850 f = &p->subs[index].f;
4851 } else if (f->subclass == 'm') {
4852 /* Confmute request */
4853 zt_confmute(p, 1);
4854 p->subs[index].f.frametype = AST_FRAME_NULL;
4855 p->subs[index].f.subclass = 0;
4856 f = &p->subs[index].f;
4857 } else if (f->subclass == 'u') {
4858 /* Unmute */
4859 zt_confmute(p, 0);
4860 p->subs[index].f.frametype = AST_FRAME_NULL;
4861 p->subs[index].f.subclass = 0;
4862 f = &p->subs[index].f;
4863 } else
4864 zt_confmute(p, 0);
4867 /* If we have a fake_event, trigger exception to handle it */
4868 if (p->fake_event)
4869 ast_set_flag(ast, AST_FLAG_EXCEPTION);
4871 ast_mutex_unlock(&p->lock);
4872 return f;
4875 static int my_zt_write(struct zt_pvt *p, unsigned char *buf, int len, int index, int linear)
4877 int sent=0;
4878 int size;
4879 int res;
4880 int fd;
4881 fd = p->subs[index].zfd;
4882 while (len) {
4883 size = len;
4884 if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
4885 size = (linear ? READ_SIZE * 2 : READ_SIZE);
4886 res = write(fd, buf, size);
4887 if (res != size) {
4888 if (option_debug)
4889 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
4890 return sent;
4892 len -= size;
4893 buf += size;
4895 return sent;
4898 static int zt_write(struct ast_channel *ast, struct ast_frame *frame)
4900 struct zt_pvt *p = ast->tech_pvt;
4901 int res;
4902 unsigned char outbuf[4096];
4903 int index;
4904 index = zt_get_index(ast, p, 0);
4905 if (index < 0) {
4906 ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
4907 return -1;
4910 #if 0
4911 #ifdef HAVE_PRI
4912 ast_mutex_lock(&p->lock);
4913 if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
4914 if (p->pri->pri) {
4915 if (!pri_grab(p, p->pri)) {
4916 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
4917 pri_rel(p->pri);
4918 } else
4919 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
4921 p->proceeding=1;
4923 ast_mutex_unlock(&p->lock);
4924 #endif
4925 #endif
4926 /* Write a frame of (presumably voice) data */
4927 if (frame->frametype != AST_FRAME_VOICE) {
4928 if (frame->frametype != AST_FRAME_IMAGE)
4929 ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
4930 return 0;
4932 if ((frame->subclass != AST_FORMAT_SLINEAR) &&
4933 (frame->subclass != AST_FORMAT_ULAW) &&
4934 (frame->subclass != AST_FORMAT_ALAW)) {
4935 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
4936 return -1;
4938 if (p->dialing) {
4939 if (option_debug)
4940 ast_log(LOG_DEBUG, "Dropping frame since I'm still dialing on %s...\n",ast->name);
4941 return 0;
4943 if (!p->owner) {
4944 if (option_debug)
4945 ast_log(LOG_DEBUG, "Dropping frame since there is no active owner on %s...\n",ast->name);
4946 return 0;
4948 if (p->cidspill) {
4949 if (option_debug)
4950 ast_log(LOG_DEBUG, "Dropping frame since I've still got a callerid spill\n");
4951 return 0;
4953 /* Return if it's not valid data */
4954 if (!frame->data || !frame->datalen)
4955 return 0;
4956 if (frame->datalen > sizeof(outbuf) * 2) {
4957 ast_log(LOG_WARNING, "Frame too large\n");
4958 return 0;
4961 if (frame->subclass == AST_FORMAT_SLINEAR) {
4962 if (!p->subs[index].linear) {
4963 p->subs[index].linear = 1;
4964 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4965 if (res)
4966 ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
4968 res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, index, 1);
4969 } else {
4970 /* x-law already */
4971 if (p->subs[index].linear) {
4972 p->subs[index].linear = 0;
4973 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4974 if (res)
4975 ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
4977 res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, index, 0);
4979 if (res < 0) {
4980 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
4981 return -1;
4983 return 0;
4986 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
4988 struct zt_pvt *p = chan->tech_pvt;
4989 int res=-1;
4990 int index;
4991 int func = ZT_FLASH;
4992 ast_mutex_lock(&p->lock);
4993 index = zt_get_index(chan, p, 0);
4994 ast_log(LOG_DEBUG, "Requested indication %d on channel %s\n", condition, chan->name);
4995 if (index == SUB_REAL) {
4996 switch (condition) {
4997 case AST_CONTROL_BUSY:
4998 #ifdef HAVE_PRI
4999 if (p->priindication_oob && p->sig == SIG_PRI) {
5000 chan->hangupcause = AST_CAUSE_USER_BUSY;
5001 chan->_softhangup |= AST_SOFTHANGUP_DEV;
5002 res = 0;
5003 } else if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5004 if (p->pri->pri) {
5005 if (!pri_grab(p, p->pri)) {
5006 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5007 pri_rel(p->pri);
5009 else
5010 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5012 p->progress = 1;
5013 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_BUSY);
5014 } else
5015 #endif
5016 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_BUSY);
5017 break;
5018 case AST_CONTROL_RINGING:
5019 #ifdef HAVE_PRI
5020 if ((!p->alerting) && p->sig==SIG_PRI && p->pri && !p->outgoing && (chan->_state != AST_STATE_UP)) {
5021 if (p->pri->pri) {
5022 if (!pri_grab(p, p->pri)) {
5023 pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
5024 pri_rel(p->pri);
5026 else
5027 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5029 p->alerting = 1;
5031 #endif
5032 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_RINGTONE);
5033 if (chan->_state != AST_STATE_UP) {
5034 if ((chan->_state != AST_STATE_RING) ||
5035 ((p->sig != SIG_FXSKS) &&
5036 (p->sig != SIG_FXSLS) &&
5037 (p->sig != SIG_FXSGS)))
5038 ast_setstate(chan, AST_STATE_RINGING);
5040 break;
5041 case AST_CONTROL_PROCEEDING:
5042 ast_log(LOG_DEBUG,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
5043 #ifdef HAVE_PRI
5044 if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5045 if (p->pri->pri) {
5046 if (!pri_grab(p, p->pri)) {
5047 pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
5048 pri_rel(p->pri);
5050 else
5051 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5053 p->proceeding = 1;
5055 #endif
5056 /* don't continue in ast_indicate */
5057 res = 0;
5058 break;
5059 case AST_CONTROL_PROGRESS:
5060 ast_log(LOG_DEBUG,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
5061 #ifdef HAVE_PRI
5062 p->digital = 0; /* Digital-only calls isn't allows any inband progress messages */
5063 if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5064 if (p->pri->pri) {
5065 if (!pri_grab(p, p->pri)) {
5066 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5067 pri_rel(p->pri);
5069 else
5070 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5072 p->progress = 1;
5074 #endif
5075 /* don't continue in ast_indicate */
5076 res = 0;
5077 break;
5078 case AST_CONTROL_CONGESTION:
5079 chan->hangupcause = AST_CAUSE_CONGESTION;
5080 #ifdef HAVE_PRI
5081 if (p->priindication_oob && p->sig == SIG_PRI) {
5082 chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
5083 chan->_softhangup |= AST_SOFTHANGUP_DEV;
5084 res = 0;
5085 } else if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5086 if (p->pri) {
5087 if (!pri_grab(p, p->pri)) {
5088 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5089 pri_rel(p->pri);
5090 } else
5091 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5093 p->progress = 1;
5094 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5095 } else
5096 #endif
5097 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5098 break;
5099 case AST_CONTROL_HOLD:
5100 #ifdef HAVE_PRI
5101 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
5102 if (!pri_grab(p, p->pri)) {
5103 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
5104 pri_rel(p->pri);
5105 } else
5106 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5107 } else
5108 #endif
5109 ast_moh_start(chan, data, p->mohinterpret);
5110 break;
5111 case AST_CONTROL_UNHOLD:
5112 #ifdef HAVE_PRI
5113 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
5114 if (!pri_grab(p, p->pri)) {
5115 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
5116 pri_rel(p->pri);
5117 } else
5118 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5119 } else
5120 #endif
5121 ast_moh_stop(chan);
5122 break;
5123 case AST_CONTROL_RADIO_KEY:
5124 if (p->radio)
5125 res = zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
5126 res = 0;
5127 break;
5128 case AST_CONTROL_RADIO_UNKEY:
5129 if (p->radio)
5130 res = zt_set_hook(p->subs[index].zfd, ZT_RINGOFF);
5131 res = 0;
5132 break;
5133 case AST_CONTROL_FLASH:
5134 /* flash hookswitch */
5135 if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
5136 /* Clear out the dial buffer */
5137 p->dop.dialstr[0] = '\0';
5138 if ((ioctl(p->subs[SUB_REAL].zfd,ZT_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
5139 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
5140 chan->name, strerror(errno));
5141 } else
5142 res = 0;
5143 } else
5144 res = 0;
5145 break;
5146 case -1:
5147 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5148 break;
5150 } else
5151 res = 0;
5152 ast_mutex_unlock(&p->lock);
5153 return res;
5156 static struct ast_channel *zt_new(struct zt_pvt *i, int state, int startpbx, int index, int law, int transfercapability)
5158 struct ast_channel *tmp;
5159 int deflaw;
5160 int res;
5161 int x,y;
5162 int features;
5163 ZT_PARAMS ps;
5164 if (i->subs[index].owner) {
5165 ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[index]);
5166 return NULL;
5168 if (!(tmp = ast_channel_alloc(0)))
5169 return NULL;
5170 tmp->tech = &zap_tech;
5171 ps.channo = i->channel;
5172 res = ioctl(i->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps);
5173 if (res) {
5174 ast_log(LOG_WARNING, "Unable to get parameters, assuming MULAW\n");
5175 ps.curlaw = ZT_LAW_MULAW;
5177 if (ps.curlaw == ZT_LAW_ALAW)
5178 deflaw = AST_FORMAT_ALAW;
5179 else
5180 deflaw = AST_FORMAT_ULAW;
5181 if (law) {
5182 if (law == ZT_LAW_ALAW)
5183 deflaw = AST_FORMAT_ALAW;
5184 else
5185 deflaw = AST_FORMAT_ULAW;
5187 y = 1;
5188 do {
5189 #ifdef HAVE_PRI
5190 if (i->bearer || (i->pri && (i->sig == SIG_FXSKS)))
5191 ast_string_field_build(tmp, name, "Zap/%d:%d-%d", i->pri->trunkgroup, i->channel, y);
5192 else
5193 #endif
5194 if (i->channel == CHAN_PSEUDO)
5195 ast_string_field_build(tmp, name, "Zap/pseudo-%d", ast_random());
5196 else
5197 ast_string_field_build(tmp, name, "Zap/%d-%d", i->channel, y);
5198 for (x = 0; x < 3; x++) {
5199 if ((index != x) && i->subs[x].owner && !strcasecmp(tmp->name, i->subs[x].owner->name))
5200 break;
5202 y++;
5203 } while (x < 3);
5204 tmp->fds[0] = i->subs[index].zfd;
5205 tmp->nativeformats = AST_FORMAT_SLINEAR | deflaw;
5206 /* Start out assuming ulaw since it's smaller :) */
5207 tmp->rawreadformat = deflaw;
5208 tmp->readformat = deflaw;
5209 tmp->rawwriteformat = deflaw;
5210 tmp->writeformat = deflaw;
5211 i->subs[index].linear = 0;
5212 zt_setlinear(i->subs[index].zfd, i->subs[index].linear);
5213 features = 0;
5214 if (i->busydetect && CANBUSYDETECT(i))
5215 features |= DSP_FEATURE_BUSY_DETECT;
5216 if ((i->callprogress & 1) && CANPROGRESSDETECT(i))
5217 features |= DSP_FEATURE_CALL_PROGRESS;
5218 if ((!i->outgoing && (i->callprogress & 4)) ||
5219 (i->outgoing && (i->callprogress & 2))) {
5220 features |= DSP_FEATURE_FAX_DETECT;
5222 #ifdef ZT_TONEDETECT
5223 x = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
5224 if (ioctl(i->subs[index].zfd, ZT_TONEDETECT, &x)) {
5225 #endif
5226 i->hardwaredtmf = 0;
5227 features |= DSP_FEATURE_DTMF_DETECT;
5228 #ifdef ZT_TONEDETECT
5229 } else if (NEED_MFDETECT(i)) {
5230 i->hardwaredtmf = 1;
5231 features |= DSP_FEATURE_DTMF_DETECT;
5233 #endif
5234 if (features) {
5235 if (i->dsp) {
5236 ast_log(LOG_DEBUG, "Already have a dsp on %s?\n", tmp->name);
5237 } else {
5238 if (i->channel != CHAN_PSEUDO)
5239 i->dsp = ast_dsp_new();
5240 else
5241 i->dsp = NULL;
5242 if (i->dsp) {
5243 i->dsp_features = features & ~DSP_PROGRESS_TALK;
5244 #ifdef HAVE_PRI
5245 /* We cannot do progress detection until receives PROGRESS message */
5246 if (i->outgoing && (i->sig == SIG_PRI)) {
5247 /* Remember requested DSP features, don't treat
5248 talking as ANSWER */
5249 features = 0;
5251 #endif
5252 ast_dsp_set_features(i->dsp, features);
5253 ast_dsp_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
5254 if (!ast_strlen_zero(progzone))
5255 ast_dsp_set_call_progress_zone(i->dsp, progzone);
5256 if (i->busydetect && CANBUSYDETECT(i)) {
5257 ast_dsp_set_busy_count(i->dsp, i->busycount);
5258 ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
5264 if (state == AST_STATE_RING)
5265 tmp->rings = 1;
5266 tmp->tech_pvt = i;
5267 if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
5268 /* Only FXO signalled stuff can be picked up */
5269 tmp->callgroup = i->callgroup;
5270 tmp->pickupgroup = i->pickupgroup;
5272 if (!ast_strlen_zero(i->language))
5273 ast_string_field_set(tmp, language, i->language);
5274 if (!i->owner)
5275 i->owner = tmp;
5276 if (!ast_strlen_zero(i->accountcode))
5277 ast_string_field_set(tmp, accountcode, i->accountcode);
5278 if (i->amaflags)
5279 tmp->amaflags = i->amaflags;
5280 i->subs[index].owner = tmp;
5281 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
5282 ast_string_field_set(tmp, call_forward, i->call_forward);
5283 /* If we've been told "no ADSI" then enforce it */
5284 if (!i->adsi)
5285 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
5286 if (!ast_strlen_zero(i->exten))
5287 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
5288 if (!ast_strlen_zero(i->rdnis))
5289 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
5290 if (!ast_strlen_zero(i->dnid))
5291 tmp->cid.cid_dnid = ast_strdup(i->dnid);
5293 #ifdef PRI_ANI
5294 /* Don't use ast_set_callerid() here because it will
5295 * generate a NewCallerID event before the NewChannel event */
5296 tmp->cid.cid_num = ast_strdup(i->cid_num);
5297 tmp->cid.cid_name = ast_strdup(i->cid_name);
5298 if (!ast_strlen_zero(i->cid_ani))
5299 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5300 else
5301 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5302 #else
5303 tmp->cid.cid_num = ast_strdup(i->cid_num);
5304 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5305 tmp->cid.cid_name = ast_strdup(i->cid_name);
5306 #endif
5307 tmp->cid.cid_pres = i->callingpres;
5308 tmp->cid.cid_ton = i->cid_ton;
5309 #ifdef HAVE_PRI
5310 tmp->transfercapability = transfercapability;
5311 pbx_builtin_setvar_helper(tmp, "TRANSFERCAPABILITY", ast_transfercapability2str(transfercapability));
5312 if (transfercapability & PRI_TRANS_CAP_DIGITAL)
5313 i->digital = 1;
5314 /* Assume calls are not idle calls unless we're told differently */
5315 i->isidlecall = 0;
5316 i->alreadyhungup = 0;
5317 #endif
5318 /* clear the fake event in case we posted one before we had ast_channel */
5319 i->fake_event = 0;
5320 /* Assure there is no confmute on this channel */
5321 zt_confmute(i, 0);
5322 ast_setstate(tmp, state);
5323 /* Configure the new channel jb */
5324 ast_jb_configure(tmp, &global_jbconf);
5325 if (startpbx) {
5326 if (ast_pbx_start(tmp)) {
5327 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
5328 ast_hangup(tmp);
5329 i->owner = NULL;
5330 return NULL;
5334 ast_atomic_fetchadd_int(&usecnt, 1);
5335 ast_update_use_count();
5337 return tmp;
5341 static int my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
5343 char c;
5345 *str = 0; /* start with empty output buffer */
5346 for (;;)
5348 /* Wait for the first digit (up to specified ms). */
5349 c = ast_waitfordigit(chan, ms);
5350 /* if timeout, hangup or error, return as such */
5351 if (c < 1)
5352 return c;
5353 *str++ = c;
5354 *str = 0;
5355 if (strchr(term, c))
5356 return 1;
5360 static int zt_wink(struct zt_pvt *p, int index)
5362 int j;
5363 zt_set_hook(p->subs[index].zfd, ZT_WINK);
5364 for (;;)
5366 /* set bits of interest */
5367 j = ZT_IOMUX_SIGEVENT;
5368 /* wait for some happening */
5369 if (ioctl(p->subs[index].zfd,ZT_IOMUX,&j) == -1) return(-1);
5370 /* exit loop if we have it */
5371 if (j & ZT_IOMUX_SIGEVENT) break;
5373 /* get the event info */
5374 if (ioctl(p->subs[index].zfd,ZT_GETEVENT,&j) == -1) return(-1);
5375 return 0;
5378 static void *ss_thread(void *data)
5380 struct ast_channel *chan = data;
5381 struct zt_pvt *p = chan->tech_pvt;
5382 char exten[AST_MAX_EXTENSION] = "";
5383 char exten2[AST_MAX_EXTENSION] = "";
5384 unsigned char buf[256];
5385 char dtmfcid[300];
5386 char dtmfbuf[300];
5387 struct callerid_state *cs = NULL;
5388 char *name = NULL, *number = NULL;
5389 int distMatches;
5390 int curRingData[3];
5391 int receivedRingT;
5392 int counter1;
5393 int counter;
5394 int samples = 0;
5395 struct ast_smdi_md_message *smdi_msg = NULL;
5396 int flags;
5397 int i;
5398 int timeout;
5399 int getforward = 0;
5400 char *s1, *s2;
5401 int len = 0;
5402 int res;
5403 int index;
5405 if (option_verbose > 2)
5406 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s'\n", chan->name);
5407 index = zt_get_index(chan, p, 1);
5408 if (index < 0) {
5409 ast_log(LOG_WARNING, "Huh?\n");
5410 ast_hangup(chan);
5411 return NULL;
5413 if (p->dsp)
5414 ast_dsp_digitreset(p->dsp);
5415 switch (p->sig) {
5416 #ifdef HAVE_PRI
5417 case SIG_PRI:
5418 /* Now loop looking for an extension */
5419 ast_copy_string(exten, p->exten, sizeof(exten));
5420 len = strlen(exten);
5421 res = 0;
5422 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
5423 if (len && !ast_ignore_pattern(chan->context, exten))
5424 tone_zone_play_tone(p->subs[index].zfd, -1);
5425 else
5426 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5427 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
5428 timeout = matchdigittimeout;
5429 else
5430 timeout = gendigittimeout;
5431 res = ast_waitfordigit(chan, timeout);
5432 if (res < 0) {
5433 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5434 ast_hangup(chan);
5435 return NULL;
5436 } else if (res) {
5437 exten[len++] = res;
5438 exten[len] = '\0';
5439 } else
5440 break;
5442 /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
5443 if (ast_strlen_zero(exten)) {
5444 if (option_verbose > 2)
5445 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of empty extension received on overlap call\n");
5446 exten[0] = 's';
5447 exten[1] = '\0';
5449 tone_zone_play_tone(p->subs[index].zfd, -1);
5450 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
5451 /* Start the real PBX */
5452 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5453 if (p->dsp) ast_dsp_digitreset(p->dsp);
5454 zt_enable_ec(p);
5455 ast_setstate(chan, AST_STATE_RING);
5456 res = ast_pbx_run(chan);
5457 if (res) {
5458 ast_log(LOG_WARNING, "PBX exited non-zero!\n");
5460 } else {
5461 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
5462 chan->hangupcause = AST_CAUSE_UNALLOCATED;
5463 ast_hangup(chan);
5464 p->exten[0] = '\0';
5465 /* Since we send release complete here, we won't get one */
5466 p->call = NULL;
5468 return NULL;
5469 break;
5470 #endif
5471 case SIG_FEATD:
5472 case SIG_FEATDMF:
5473 case SIG_FEATDMF_TA:
5474 case SIG_E911:
5475 case SIG_FGC_CAMAMF:
5476 case SIG_FEATB:
5477 case SIG_EMWINK:
5478 case SIG_SF_FEATD:
5479 case SIG_SF_FEATDMF:
5480 case SIG_SF_FEATB:
5481 case SIG_SFWINK:
5482 if (zt_wink(p, index))
5483 return NULL;
5484 /* Fall through */
5485 case SIG_EM:
5486 case SIG_EM_E1:
5487 case SIG_SF:
5488 case SIG_FGC_CAMA:
5489 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5490 if (p->dsp)
5491 ast_dsp_digitreset(p->dsp);
5492 /* set digit mode appropriately */
5493 if (p->dsp) {
5494 if (NEED_MFDETECT(p))
5495 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MF | p->dtmfrelax);
5496 else
5497 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5499 memset(dtmfbuf, 0, sizeof(dtmfbuf));
5500 /* Wait for the first digit only if immediate=no */
5501 if (!p->immediate)
5502 /* Wait for the first digit (up to 5 seconds). */
5503 res = ast_waitfordigit(chan, 5000);
5504 else
5505 res = 0;
5506 if (res > 0) {
5507 /* save first char */
5508 dtmfbuf[0] = res;
5509 switch (p->sig) {
5510 case SIG_FEATD:
5511 case SIG_SF_FEATD:
5512 res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
5513 if (res > 0)
5514 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
5515 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5516 break;
5517 case SIG_FEATDMF_TA:
5518 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5519 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5520 if (zt_wink(p, index)) return NULL;
5521 dtmfbuf[0] = 0;
5522 /* Wait for the first digit (up to 5 seconds). */
5523 res = ast_waitfordigit(chan, 5000);
5524 if (res <= 0) break;
5525 dtmfbuf[0] = res;
5526 /* fall through intentionally */
5527 case SIG_FEATDMF:
5528 case SIG_E911:
5529 case SIG_FGC_CAMAMF:
5530 case SIG_SF_FEATDMF:
5531 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5532 /* if international caca, do it again to get real ANO */
5533 if ((p->sig == SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
5535 if (zt_wink(p, index)) return NULL;
5536 dtmfbuf[0] = 0;
5537 /* Wait for the first digit (up to 5 seconds). */
5538 res = ast_waitfordigit(chan, 5000);
5539 if (res <= 0) break;
5540 dtmfbuf[0] = res;
5541 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5543 if (res > 0) {
5544 /* if E911, take off hook */
5545 if (p->sig == SIG_E911)
5546 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
5547 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
5549 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5550 break;
5551 case SIG_FEATB:
5552 case SIG_SF_FEATB:
5553 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5554 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5555 break;
5556 case SIG_EMWINK:
5557 /* if we received a '*', we are actually receiving Feature Group D
5558 dial syntax, so use that mode; otherwise, fall through to normal
5559 mode
5561 if (res == '*') {
5562 res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
5563 if (res > 0)
5564 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
5565 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5566 break;
5568 default:
5569 /* If we got the first digit, get the rest */
5570 len = 1;
5571 dtmfbuf[len] = '\0';
5572 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
5573 if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
5574 timeout = matchdigittimeout;
5575 } else {
5576 timeout = gendigittimeout;
5578 res = ast_waitfordigit(chan, timeout);
5579 if (res < 0) {
5580 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5581 ast_hangup(chan);
5582 return NULL;
5583 } else if (res) {
5584 dtmfbuf[len++] = res;
5585 dtmfbuf[len] = '\0';
5586 } else {
5587 break;
5590 break;
5593 if (res == -1) {
5594 ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
5595 ast_hangup(chan);
5596 return NULL;
5597 } else if (res < 0) {
5598 ast_log(LOG_DEBUG, "Got hung up before digits finished\n");
5599 ast_hangup(chan);
5600 return NULL;
5603 if (p->sig == SIG_FGC_CAMA) {
5604 char anibuf[100];
5606 if (ast_safe_sleep(chan,1000) == -1) {
5607 ast_hangup(chan);
5608 return NULL;
5610 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
5611 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MF | p->dtmfrelax);
5612 res = my_getsigstr(chan, anibuf, "#", 10000);
5613 if ((res > 0) && (strlen(anibuf) > 2)) {
5614 if (anibuf[strlen(anibuf) - 1] == '#')
5615 anibuf[strlen(anibuf) - 1] = 0;
5616 ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
5618 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5621 ast_copy_string(exten, dtmfbuf, sizeof(exten));
5622 if (ast_strlen_zero(exten))
5623 ast_copy_string(exten, "s", sizeof(exten));
5624 if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
5625 /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
5626 if (exten[0] == '*') {
5627 char *stringp=NULL;
5628 ast_copy_string(exten2, exten, sizeof(exten2));
5629 /* Parse out extension and callerid */
5630 stringp=exten2 +1;
5631 s1 = strsep(&stringp, "*");
5632 s2 = strsep(&stringp, "*");
5633 if (s2) {
5634 if (!ast_strlen_zero(p->cid_num))
5635 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5636 else
5637 ast_set_callerid(chan, s1, NULL, s1);
5638 ast_copy_string(exten, s2, sizeof(exten));
5639 } else
5640 ast_copy_string(exten, s1, sizeof(exten));
5641 } else if (p->sig == SIG_FEATD)
5642 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d. Assuming E&M Wink instead\n", p->channel);
5644 if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
5645 if (exten[0] == '*') {
5646 char *stringp=NULL;
5647 ast_copy_string(exten2, exten, sizeof(exten2));
5648 /* Parse out extension and callerid */
5649 stringp=exten2 +1;
5650 s1 = strsep(&stringp, "#");
5651 s2 = strsep(&stringp, "#");
5652 if (s2) {
5653 if (!ast_strlen_zero(p->cid_num))
5654 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5655 else
5656 if (*(s1 + 2))
5657 ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
5658 ast_copy_string(exten, s2 + 1, sizeof(exten));
5659 } else
5660 ast_copy_string(exten, s1 + 2, sizeof(exten));
5661 } else
5662 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d. Assuming E&M Wink instead\n", p->channel);
5664 if ((p->sig == SIG_E911) || (p->sig == SIG_FGC_CAMAMF)) {
5665 if (exten[0] == '*') {
5666 char *stringp=NULL;
5667 ast_copy_string(exten2, exten, sizeof(exten2));
5668 /* Parse out extension and callerid */
5669 stringp=exten2 +1;
5670 s1 = strsep(&stringp, "#");
5671 s2 = strsep(&stringp, "#");
5672 if (s2 && (*(s2 + 1) == '0')) {
5673 if (*(s2 + 2))
5674 ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
5676 if (s1) ast_copy_string(exten, s1, sizeof(exten));
5677 else ast_copy_string(exten, "911", sizeof(exten));
5678 } else
5679 ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d. Assuming E&M Wink instead\n", p->channel);
5681 if (p->sig == SIG_FEATB) {
5682 if (exten[0] == '*') {
5683 char *stringp=NULL;
5684 ast_copy_string(exten2, exten, sizeof(exten2));
5685 /* Parse out extension and callerid */
5686 stringp=exten2 +1;
5687 s1 = strsep(&stringp, "#");
5688 ast_copy_string(exten, exten2 + 1, sizeof(exten));
5689 } else
5690 ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d. Assuming E&M Wink instead\n", p->channel);
5692 if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
5693 zt_wink(p, index);
5694 /* some switches require a minimum guard time between
5695 the last FGD wink and something that answers
5696 immediately. This ensures it */
5697 if (ast_safe_sleep(chan,100)) return NULL;
5699 zt_enable_ec(p);
5700 if (NEED_MFDETECT(p)) {
5701 if (p->dsp) {
5702 if (!p->hardwaredtmf)
5703 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5704 else {
5705 ast_dsp_free(p->dsp);
5706 p->dsp = NULL;
5711 if (ast_exists_extension(chan, chan->context, exten, 1, chan->cid.cid_num)) {
5712 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5713 if (p->dsp) ast_dsp_digitreset(p->dsp);
5714 res = ast_pbx_run(chan);
5715 if (res) {
5716 ast_log(LOG_WARNING, "PBX exited non-zero\n");
5717 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5719 return NULL;
5720 } else {
5721 if (option_verbose > 2)
5722 ast_verbose(VERBOSE_PREFIX_2 "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
5723 sleep(2);
5724 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_INFO);
5725 if (res < 0)
5726 ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
5727 else
5728 sleep(1);
5729 res = ast_streamfile(chan, "ss-noservice", chan->language);
5730 if (res >= 0)
5731 ast_waitstream(chan, "");
5732 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5733 ast_hangup(chan);
5734 return NULL;
5736 break;
5737 case SIG_FXOLS:
5738 case SIG_FXOGS:
5739 case SIG_FXOKS:
5740 /* Read the first digit */
5741 timeout = firstdigittimeout;
5742 /* If starting a threeway call, never timeout on the first digit so someone
5743 can use flash-hook as a "hold" feature */
5744 if (p->subs[SUB_THREEWAY].owner)
5745 timeout = 999999;
5746 while (len < AST_MAX_EXTENSION-1) {
5747 /* Read digit unless it's supposed to be immediate, in which case the
5748 only answer is 's' */
5749 if (p->immediate)
5750 res = 's';
5751 else
5752 res = ast_waitfordigit(chan, timeout);
5753 timeout = 0;
5754 if (res < 0) {
5755 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5756 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5757 ast_hangup(chan);
5758 return NULL;
5759 } else if (res) {
5760 exten[len++]=res;
5761 exten[len] = '\0';
5763 if (!ast_ignore_pattern(chan->context, exten))
5764 tone_zone_play_tone(p->subs[index].zfd, -1);
5765 else
5766 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5767 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && strcmp(exten, ast_parking_ext())) {
5768 if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
5769 if (getforward) {
5770 /* Record this as the forwarding extension */
5771 ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
5772 if (option_verbose > 2)
5773 ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
5774 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5775 if (res)
5776 break;
5777 usleep(500000);
5778 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5779 sleep(1);
5780 memset(exten, 0, sizeof(exten));
5781 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5782 len = 0;
5783 getforward = 0;
5784 } else {
5785 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5786 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5787 if (!ast_strlen_zero(p->cid_num)) {
5788 if (!p->hidecallerid)
5789 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5790 else
5791 ast_set_callerid(chan, NULL, NULL, p->cid_num);
5793 if (!ast_strlen_zero(p->cid_name)) {
5794 if (!p->hidecallerid)
5795 ast_set_callerid(chan, NULL, p->cid_name, NULL);
5797 ast_setstate(chan, AST_STATE_RING);
5798 zt_enable_ec(p);
5799 res = ast_pbx_run(chan);
5800 if (res) {
5801 ast_log(LOG_WARNING, "PBX exited non-zero\n");
5802 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5804 return NULL;
5806 } else {
5807 /* It's a match, but they just typed a digit, and there is an ambiguous match,
5808 so just set the timeout to matchdigittimeout and wait some more */
5809 timeout = matchdigittimeout;
5811 } else if (res == 0) {
5812 ast_log(LOG_DEBUG, "not enough digits (and no ambiguous match)...\n");
5813 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5814 zt_wait_event(p->subs[index].zfd);
5815 ast_hangup(chan);
5816 return NULL;
5817 } else if (p->callwaiting && !strcmp(exten, "*70")) {
5818 if (option_verbose > 2)
5819 ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
5820 /* Disable call waiting if enabled */
5821 p->callwaiting = 0;
5822 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5823 if (res) {
5824 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
5825 chan->name, strerror(errno));
5827 len = 0;
5828 ioctl(p->subs[index].zfd,ZT_CONFDIAG,&len);
5829 memset(exten, 0, sizeof(exten));
5830 timeout = firstdigittimeout;
5832 } else if (!strcmp(exten,ast_pickup_ext())) {
5833 /* Scan all channels and see if any there
5834 * ringing channqels with that have call groups
5835 * that equal this channels pickup group
5837 if (index == SUB_REAL) {
5838 /* Switch us from Third call to Call Wait */
5839 if (p->subs[SUB_THREEWAY].owner) {
5840 /* If you make a threeway call and the *8# a call, it should actually
5841 look like a callwait */
5842 alloc_sub(p, SUB_CALLWAIT);
5843 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
5844 unalloc_sub(p, SUB_THREEWAY);
5846 zt_enable_ec(p);
5847 if (ast_pickup_call(chan)) {
5848 ast_log(LOG_DEBUG, "No call pickup possible...\n");
5849 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5850 zt_wait_event(p->subs[index].zfd);
5852 ast_hangup(chan);
5853 return NULL;
5854 } else {
5855 ast_log(LOG_WARNING, "Huh? Got *8# on call not on real\n");
5856 ast_hangup(chan);
5857 return NULL;
5860 } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
5861 if (option_verbose > 2)
5862 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
5863 /* Disable Caller*ID if enabled */
5864 p->hidecallerid = 1;
5865 if (chan->cid.cid_num)
5866 free(chan->cid.cid_num);
5867 chan->cid.cid_num = NULL;
5868 if (chan->cid.cid_name)
5869 free(chan->cid.cid_name);
5870 chan->cid.cid_name = NULL;
5871 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5872 if (res) {
5873 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
5874 chan->name, strerror(errno));
5876 len = 0;
5877 memset(exten, 0, sizeof(exten));
5878 timeout = firstdigittimeout;
5879 } else if (p->callreturn && !strcmp(exten, "*69")) {
5880 res = 0;
5881 if (!ast_strlen_zero(p->lastcid_num)) {
5882 res = ast_say_digit_str(chan, p->lastcid_num, "", chan->language);
5884 if (!res)
5885 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5886 break;
5887 } else if (!strcmp(exten, "*78")) {
5888 /* Do not disturb */
5889 if (option_verbose > 2)
5890 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %d\n", p->channel);
5891 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
5892 "Channel: Zap/%d\r\n"
5893 "Status: enabled\r\n", p->channel);
5894 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5895 p->dnd = 1;
5896 getforward = 0;
5897 memset(exten, 0, sizeof(exten));
5898 len = 0;
5899 } else if (!strcmp(exten, "*79")) {
5900 /* Do not disturb */
5901 if (option_verbose > 2)
5902 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %d\n", p->channel);
5903 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
5904 "Channel: Zap/%d\r\n"
5905 "Status: disabled\r\n", p->channel);
5906 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5907 p->dnd = 0;
5908 getforward = 0;
5909 memset(exten, 0, sizeof(exten));
5910 len = 0;
5911 } else if (p->cancallforward && !strcmp(exten, "*72")) {
5912 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5913 getforward = 1;
5914 memset(exten, 0, sizeof(exten));
5915 len = 0;
5916 } else if (p->cancallforward && !strcmp(exten, "*73")) {
5917 if (option_verbose > 2)
5918 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %d\n", p->channel);
5919 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5920 memset(p->call_forward, 0, sizeof(p->call_forward));
5921 getforward = 0;
5922 memset(exten, 0, sizeof(exten));
5923 len = 0;
5924 } else if ((p->transfer || p->canpark) && !strcmp(exten, ast_parking_ext()) &&
5925 p->subs[SUB_THREEWAY].owner &&
5926 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
5927 /* This is a three way call, the main call being a real channel,
5928 and we're parking the first call. */
5929 ast_masq_park_call(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), chan, 0, NULL);
5930 if (option_verbose > 2)
5931 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
5932 break;
5933 } else if (!ast_strlen_zero(p->lastcid_num) && !strcmp(exten, "*60")) {
5934 if (option_verbose > 2)
5935 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", p->lastcid_num);
5936 res = ast_db_put("blacklist", p->lastcid_num, "1");
5937 if (!res) {
5938 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5939 memset(exten, 0, sizeof(exten));
5940 len = 0;
5942 } else if (p->hidecallerid && !strcmp(exten, "*82")) {
5943 if (option_verbose > 2)
5944 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
5945 /* Enable Caller*ID if enabled */
5946 p->hidecallerid = 0;
5947 if (chan->cid.cid_num)
5948 free(chan->cid.cid_num);
5949 chan->cid.cid_num = NULL;
5950 if (chan->cid.cid_name)
5951 free(chan->cid.cid_name);
5952 chan->cid.cid_name = NULL;
5953 ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
5954 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5955 if (res) {
5956 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
5957 chan->name, strerror(errno));
5959 len = 0;
5960 memset(exten, 0, sizeof(exten));
5961 timeout = firstdigittimeout;
5962 } else if (!strcmp(exten, "*0")) {
5963 struct ast_channel *nbridge =
5964 p->subs[SUB_THREEWAY].owner;
5965 struct zt_pvt *pbridge = NULL;
5966 /* set up the private struct of the bridged one, if any */
5967 if (nbridge && ast_bridged_channel(nbridge))
5968 pbridge = ast_bridged_channel(nbridge)->tech_pvt;
5969 if (nbridge && pbridge &&
5970 (nbridge->tech == &zap_tech) &&
5971 (ast_bridged_channel(nbridge)->tech == &zap_tech) &&
5972 ISTRUNK(pbridge)) {
5973 int func = ZT_FLASH;
5974 /* Clear out the dial buffer */
5975 p->dop.dialstr[0] = '\0';
5976 /* flash hookswitch */
5977 if ((ioctl(pbridge->subs[SUB_REAL].zfd,ZT_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
5978 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
5979 nbridge->name, strerror(errno));
5981 swap_subs(p, SUB_REAL, SUB_THREEWAY);
5982 unalloc_sub(p, SUB_THREEWAY);
5983 p->owner = p->subs[SUB_REAL].owner;
5984 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
5985 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
5986 ast_hangup(chan);
5987 return NULL;
5988 } else {
5989 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5990 zt_wait_event(p->subs[index].zfd);
5991 tone_zone_play_tone(p->subs[index].zfd, -1);
5992 swap_subs(p, SUB_REAL, SUB_THREEWAY);
5993 unalloc_sub(p, SUB_THREEWAY);
5994 p->owner = p->subs[SUB_REAL].owner;
5995 ast_hangup(chan);
5996 return NULL;
5998 } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
5999 ((exten[0] != '*') || (strlen(exten) > 2))) {
6000 if (option_debug)
6001 ast_log(LOG_DEBUG, "Can't match %s from '%s' in context %s\n", exten, chan->cid.cid_num ? chan->cid.cid_num : "<Unknown Caller>", chan->context);
6002 break;
6004 if (!timeout)
6005 timeout = gendigittimeout;
6006 if (len && !ast_ignore_pattern(chan->context, exten))
6007 tone_zone_play_tone(p->subs[index].zfd, -1);
6009 break;
6010 case SIG_FXSLS:
6011 case SIG_FXSGS:
6012 case SIG_FXSKS:
6013 #ifdef HAVE_PRI
6014 if (p->pri) {
6015 /* This is a GR-303 trunk actually. Wait for the first ring... */
6016 struct ast_frame *f;
6017 int res;
6018 time_t start;
6020 time(&start);
6021 ast_setstate(chan, AST_STATE_RING);
6022 while (time(NULL) < start + 3) {
6023 res = ast_waitfor(chan, 1000);
6024 if (res) {
6025 f = ast_read(chan);
6026 if (!f) {
6027 ast_log(LOG_WARNING, "Whoa, hangup while waiting for first ring!\n");
6028 ast_hangup(chan);
6029 return NULL;
6030 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_RING)) {
6031 res = 1;
6032 } else
6033 res = 0;
6034 ast_frfree(f);
6035 if (res) {
6036 ast_log(LOG_DEBUG, "Got ring!\n");
6037 res = 0;
6038 break;
6043 #endif
6044 /* check for SMDI messages */
6045 if (p->use_smdi && p->smdi_iface) {
6046 smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, SMDI_MD_WAIT_TIMEOUT);
6048 if (smdi_msg != NULL) {
6049 ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
6051 if (smdi_msg->type == 'B')
6052 pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
6053 else if (smdi_msg->type == 'N')
6054 pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
6056 ast_log(LOG_DEBUG, "Recieved SMDI message on %s\n", chan->name);
6057 } else {
6058 ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
6062 if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
6063 number = smdi_msg->calling_st;
6065 /* If we want caller id, we're in a prering state due to a polarity reversal
6066 * and we're set to use a polarity reversal to trigger the start of caller id,
6067 * grab the caller id and wait for ringing to start... */
6068 } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING && p->cid_start == CID_START_POLARITY)) {
6069 /* If set to use DTMF CID signalling, listen for DTMF */
6070 if (p->cid_signalling == CID_SIG_DTMF) {
6071 int i = 0;
6072 cs = NULL;
6073 ast_log(LOG_DEBUG, "Receiving DTMF cid on "
6074 "channel %s\n", chan->name);
6075 zt_setlinear(p->subs[index].zfd, 0);
6076 res = 2000;
6077 for (;;) {
6078 struct ast_frame *f;
6079 res = ast_waitfor(chan, res);
6080 if (res <= 0) {
6081 ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
6082 "Exiting simple switch\n");
6083 ast_hangup(chan);
6084 return NULL;
6086 f = ast_read(chan);
6087 if (f->frametype == AST_FRAME_DTMF) {
6088 dtmfbuf[i++] = f->subclass;
6089 ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass);
6090 res = 2000;
6092 ast_frfree(f);
6093 if (chan->_state == AST_STATE_RING ||
6094 chan->_state == AST_STATE_RINGING)
6095 break; /* Got ring */
6097 dtmfbuf[i] = '\0';
6098 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6099 /* Got cid and ring. */
6100 ast_log(LOG_DEBUG, "CID got string '%s'\n", dtmfbuf);
6101 callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
6102 ast_log(LOG_DEBUG, "CID is '%s', flags %d\n",
6103 dtmfcid, flags);
6104 /* If first byte is NULL, we have no cid */
6105 if (!ast_strlen_zero(dtmfcid))
6106 number = dtmfcid;
6107 else
6108 number = NULL;
6109 /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
6110 } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
6111 cs = callerid_new(p->cid_signalling);
6112 if (cs) {
6113 samples = 0;
6114 #if 1
6115 bump_gains(p);
6116 #endif
6117 /* Take out of linear mode for Caller*ID processing */
6118 zt_setlinear(p->subs[index].zfd, 0);
6120 /* First we wait and listen for the Caller*ID */
6121 for (;;) {
6122 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6123 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6124 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6125 callerid_free(cs);
6126 ast_hangup(chan);
6127 return NULL;
6129 if (i & ZT_IOMUX_SIGEVENT) {
6130 res = zt_get_event(p->subs[index].zfd);
6131 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6133 if (p->cid_signalling == CID_SIG_V23_JP) {
6134 #ifdef ZT_EVENT_RINGBEGIN
6135 if (res == ZT_EVENT_RINGBEGIN) {
6136 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6137 usleep(1);
6139 #endif
6140 } else {
6141 res = 0;
6142 break;
6144 } else if (i & ZT_IOMUX_READ) {
6145 res = read(p->subs[index].zfd, buf, sizeof(buf));
6146 if (res < 0) {
6147 if (errno != ELAST) {
6148 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6149 callerid_free(cs);
6150 ast_hangup(chan);
6151 return NULL;
6153 break;
6155 samples += res;
6157 if (p->cid_signalling == CID_SIG_V23_JP) {
6158 res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
6159 } else {
6160 res = callerid_feed(cs, buf, res, AST_LAW(p));
6163 if (res < 0) {
6164 ast_log(LOG_WARNING, "CallerID feed failed: %s\n", strerror(errno));
6165 break;
6166 } else if (res)
6167 break;
6168 else if (samples > (8000 * 10))
6169 break;
6172 if (res == 1) {
6173 callerid_get(cs, &name, &number, &flags);
6174 ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
6176 if (res < 0) {
6177 ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
6180 if (p->cid_signalling == CID_SIG_V23_JP) {
6181 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
6182 usleep(1);
6183 res = 4000;
6184 } else {
6186 /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
6187 res = 2000;
6190 for (;;) {
6191 struct ast_frame *f;
6192 res = ast_waitfor(chan, res);
6193 if (res <= 0) {
6194 ast_log(LOG_WARNING, "CID timed out waiting for ring. "
6195 "Exiting simple switch\n");
6196 ast_hangup(chan);
6197 return NULL;
6199 f = ast_read(chan);
6200 ast_frfree(f);
6201 if (chan->_state == AST_STATE_RING ||
6202 chan->_state == AST_STATE_RINGING)
6203 break; /* Got ring */
6206 /* We must have a ring by now, so, if configured, lets try to listen for
6207 * distinctive ringing */
6208 if (p->usedistinctiveringdetection == 1) {
6209 len = 0;
6210 distMatches = 0;
6211 /* Clear the current ring data array so we dont have old data in it. */
6212 for (receivedRingT = 0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
6213 curRingData[receivedRingT] = 0;
6214 receivedRingT = 0;
6215 counter = 0;
6216 counter1 = 0;
6217 /* Check to see if context is what it should be, if not set to be. */
6218 if (strcmp(p->context,p->defcontext) != 0) {
6219 ast_copy_string(p->context, p->defcontext, sizeof(p->context));
6220 ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
6223 for (;;) {
6224 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6225 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6226 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6227 callerid_free(cs);
6228 ast_hangup(chan);
6229 return NULL;
6231 if (i & ZT_IOMUX_SIGEVENT) {
6232 res = zt_get_event(p->subs[index].zfd);
6233 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6234 res = 0;
6235 /* Let us detect distinctive ring */
6237 curRingData[receivedRingT] = p->ringt;
6239 if (p->ringt < p->ringt_base/2)
6240 break;
6241 /* Increment the ringT counter so we can match it against
6242 values in zapata.conf for distinctive ring */
6243 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6244 break;
6245 } else if (i & ZT_IOMUX_READ) {
6246 res = read(p->subs[index].zfd, buf, sizeof(buf));
6247 if (res < 0) {
6248 if (errno != ELAST) {
6249 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6250 callerid_free(cs);
6251 ast_hangup(chan);
6252 return NULL;
6254 break;
6256 if (p->ringt)
6257 p->ringt--;
6258 if (p->ringt == 1) {
6259 res = -1;
6260 break;
6264 if (option_verbose > 2)
6265 /* this only shows up if you have n of the dring patterns filled in */
6266 ast_verbose( VERBOSE_PREFIX_3 "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
6268 for (counter = 0; counter < 3; counter++) {
6269 /* Check to see if the rings we received match any of the ones in zapata.conf for this
6270 channel */
6271 distMatches = 0;
6272 for (counter1 = 0; counter1 < 3; counter1++) {
6273 if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1]+10) && curRingData[counter1] >=
6274 (p->drings.ringnum[counter].ring[counter1]-10)) {
6275 distMatches++;
6278 if (distMatches == 3) {
6279 /* The ring matches, set the context to whatever is for distinctive ring.. */
6280 ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
6281 ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
6282 if (option_verbose > 2)
6283 ast_verbose( VERBOSE_PREFIX_3 "Distinctive Ring matched context %s\n",p->context);
6284 break;
6288 /* Restore linear mode (if appropriate) for Caller*ID processing */
6289 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6290 #if 1
6291 restore_gains(p);
6292 #endif
6293 } else
6294 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
6295 } else {
6296 ast_log(LOG_WARNING, "Channel %s in prering "
6297 "state, but I have nothing to do. "
6298 "Terminating simple switch, should be "
6299 "restarted by the actual ring.\n",
6300 chan->name);
6301 ast_hangup(chan);
6302 return NULL;
6304 } else if (p->use_callerid && p->cid_start == CID_START_RING) {
6305 /* FSK Bell202 callerID */
6306 cs = callerid_new(p->cid_signalling);
6307 if (cs) {
6308 #if 1
6309 bump_gains(p);
6310 #endif
6311 samples = 0;
6312 len = 0;
6313 distMatches = 0;
6314 /* Clear the current ring data array so we dont have old data in it. */
6315 for (receivedRingT = 0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
6316 curRingData[receivedRingT] = 0;
6317 receivedRingT = 0;
6318 counter = 0;
6319 counter1 = 0;
6320 /* Check to see if context is what it should be, if not set to be. */
6321 if (strcmp(p->context,p->defcontext) != 0) {
6322 ast_copy_string(p->context, p->defcontext, sizeof(p->context));
6323 ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
6326 /* Take out of linear mode for Caller*ID processing */
6327 zt_setlinear(p->subs[index].zfd, 0);
6328 for (;;) {
6329 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6330 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6331 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6332 callerid_free(cs);
6333 ast_hangup(chan);
6334 return NULL;
6336 if (i & ZT_IOMUX_SIGEVENT) {
6337 res = zt_get_event(p->subs[index].zfd);
6338 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6339 res = 0;
6340 /* Let us detect callerid when the telco uses distinctive ring */
6342 curRingData[receivedRingT] = p->ringt;
6344 if (p->ringt < p->ringt_base/2)
6345 break;
6346 /* Increment the ringT counter so we can match it against
6347 values in zapata.conf for distinctive ring */
6348 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6349 break;
6350 } else if (i & ZT_IOMUX_READ) {
6351 res = read(p->subs[index].zfd, buf, sizeof(buf));
6352 if (res < 0) {
6353 if (errno != ELAST) {
6354 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6355 callerid_free(cs);
6356 ast_hangup(chan);
6357 return NULL;
6359 break;
6361 if (p->ringt)
6362 p->ringt--;
6363 if (p->ringt == 1) {
6364 res = -1;
6365 break;
6367 samples += res;
6368 res = callerid_feed(cs, buf, res, AST_LAW(p));
6369 if (res < 0) {
6370 ast_log(LOG_WARNING, "CallerID feed failed: %s\n", strerror(errno));
6371 break;
6372 } else if (res)
6373 break;
6374 else if (samples > (8000 * 10))
6375 break;
6378 if (res == 1) {
6379 callerid_get(cs, &name, &number, &flags);
6380 if (option_debug)
6381 ast_log(LOG_DEBUG, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
6383 if (distinctiveringaftercid == 1) {
6384 /* Clear the current ring data array so we dont have old data in it. */
6385 for (receivedRingT = 0; receivedRingT < 3; receivedRingT++) {
6386 curRingData[receivedRingT] = 0;
6388 receivedRingT = 0;
6389 if (option_verbose > 2)
6390 ast_verbose( VERBOSE_PREFIX_3 "Detecting post-CID distinctive ring\n");
6391 for (;;) {
6392 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6393 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6394 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6395 callerid_free(cs);
6396 ast_hangup(chan);
6397 return NULL;
6399 if (i & ZT_IOMUX_SIGEVENT) {
6400 res = zt_get_event(p->subs[index].zfd);
6401 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6402 res = 0;
6403 /* Let us detect callerid when the telco uses distinctive ring */
6405 curRingData[receivedRingT] = p->ringt;
6407 if (p->ringt < p->ringt_base/2)
6408 break;
6409 /* Increment the ringT counter so we can match it against
6410 values in zapata.conf for distinctive ring */
6411 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6412 break;
6413 } else if (i & ZT_IOMUX_READ) {
6414 res = read(p->subs[index].zfd, buf, sizeof(buf));
6415 if (res < 0) {
6416 if (errno != ELAST) {
6417 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6418 callerid_free(cs);
6419 ast_hangup(chan);
6420 return NULL;
6422 break;
6424 if (p->ringt)
6425 p->ringt--;
6426 if (p->ringt == 1) {
6427 res = -1;
6428 break;
6433 if (p->usedistinctiveringdetection == 1) {
6434 if (option_verbose > 2)
6435 /* this only shows up if you have n of the dring patterns filled in */
6436 ast_verbose( VERBOSE_PREFIX_3 "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
6438 for (counter = 0; counter < 3; counter++) {
6439 /* Check to see if the rings we received match any of the ones in zapata.conf for this
6440 channel */
6441 if (option_verbose > 2)
6442 /* this only shows up if you have n of the dring patterns filled in */
6443 ast_verbose( VERBOSE_PREFIX_3 "Checking %d,%d,%d\n",
6444 p->drings.ringnum[counter].ring[0],
6445 p->drings.ringnum[counter].ring[1],
6446 p->drings.ringnum[counter].ring[2]);
6447 distMatches = 0;
6448 for (counter1 = 0; counter1 < 3; counter1++) {
6449 if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1]+10) && curRingData[counter1] >=
6450 (p->drings.ringnum[counter].ring[counter1]-10)) {
6451 distMatches++;
6454 if (distMatches == 3) {
6455 /* The ring matches, set the context to whatever is for distinctive ring.. */
6456 ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
6457 ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
6458 if (option_verbose > 2)
6459 ast_verbose( VERBOSE_PREFIX_3 "Distinctive Ring matched context %s\n",p->context);
6460 break;
6464 /* Restore linear mode (if appropriate) for Caller*ID processing */
6465 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6466 #if 1
6467 restore_gains(p);
6468 #endif
6469 if (res < 0) {
6470 ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
6472 } else
6473 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
6475 else
6476 cs = NULL;
6478 if (number)
6479 ast_shrink_phone_number(number);
6480 ast_set_callerid(chan, number, name, number);
6482 if (smdi_msg)
6483 ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
6485 if (cs)
6486 callerid_free(cs);
6488 ast_setstate(chan, AST_STATE_RING);
6489 chan->rings = 1;
6490 p->ringt = p->ringt_base;
6491 res = ast_pbx_run(chan);
6492 if (res) {
6493 ast_hangup(chan);
6494 ast_log(LOG_WARNING, "PBX exited non-zero\n");
6496 return NULL;
6497 default:
6498 ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", sig2str(p->sig), p->channel);
6499 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
6500 if (res < 0)
6501 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
6503 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
6504 if (res < 0)
6505 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
6506 ast_hangup(chan);
6507 return NULL;
6510 static int handle_init_event(struct zt_pvt *i, int event)
6512 int res;
6513 pthread_t threadid;
6514 pthread_attr_t attr;
6515 struct ast_channel *chan;
6516 pthread_attr_init(&attr);
6517 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6518 /* Handle an event on a given channel for the monitor thread. */
6519 switch (event) {
6520 case ZT_EVENT_NONE:
6521 case ZT_EVENT_BITSCHANGED:
6522 break;
6523 case ZT_EVENT_WINKFLASH:
6524 case ZT_EVENT_RINGOFFHOOK:
6525 if (i->inalarm) break;
6526 if (i->radio) break;
6527 /* Got a ring/answer. What kind of channel are we? */
6528 switch (i->sig) {
6529 case SIG_FXOLS:
6530 case SIG_FXOGS:
6531 case SIG_FXOKS:
6532 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6533 if (i->cidspill) {
6534 /* Cancel VMWI spill */
6535 free(i->cidspill);
6536 i->cidspill = NULL;
6538 if (i->immediate) {
6539 zt_enable_ec(i);
6540 /* The channel is immediately up. Start right away */
6541 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
6542 chan = zt_new(i, AST_STATE_RING, 1, SUB_REAL, 0, 0);
6543 if (!chan) {
6544 ast_log(LOG_WARNING, "Unable to start PBX on channel %d\n", i->channel);
6545 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6546 if (res < 0)
6547 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6549 } else {
6550 /* Check for callerid, digits, etc */
6551 chan = zt_new(i, AST_STATE_RESERVED, 0, SUB_REAL, 0, 0);
6552 if (chan) {
6553 if (has_voicemail(i))
6554 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_STUTTER);
6555 else
6556 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_DIALTONE);
6557 if (res < 0)
6558 ast_log(LOG_WARNING, "Unable to play dialtone on channel %d\n", i->channel);
6559 if (ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6560 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6561 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6562 if (res < 0)
6563 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6564 ast_hangup(chan);
6566 } else
6567 ast_log(LOG_WARNING, "Unable to create channel\n");
6569 break;
6570 case SIG_FXSLS:
6571 case SIG_FXSGS:
6572 case SIG_FXSKS:
6573 i->ringt = i->ringt_base;
6574 /* Fall through */
6575 case SIG_EMWINK:
6576 case SIG_FEATD:
6577 case SIG_FEATDMF:
6578 case SIG_FEATDMF_TA:
6579 case SIG_E911:
6580 case SIG_FGC_CAMA:
6581 case SIG_FGC_CAMAMF:
6582 case SIG_FEATB:
6583 case SIG_EM:
6584 case SIG_EM_E1:
6585 case SIG_SFWINK:
6586 case SIG_SF_FEATD:
6587 case SIG_SF_FEATDMF:
6588 case SIG_SF_FEATB:
6589 case SIG_SF:
6590 /* Check for callerid, digits, etc */
6591 chan = zt_new(i, AST_STATE_RING, 0, SUB_REAL, 0, 0);
6592 if (chan && ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6593 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6594 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6595 if (res < 0)
6596 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6597 ast_hangup(chan);
6598 } else if (!chan) {
6599 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
6601 break;
6602 default:
6603 ast_log(LOG_WARNING, "Don't know how to handle ring/answer with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
6604 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6605 if (res < 0)
6606 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6607 return -1;
6609 break;
6610 case ZT_EVENT_NOALARM:
6611 i->inalarm = 0;
6612 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", i->channel);
6613 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
6614 "Channel: %d\r\n", i->channel);
6615 break;
6616 case ZT_EVENT_ALARM:
6617 i->inalarm = 1;
6618 res = get_alarms(i);
6619 ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", i->channel, alarm2str(res));
6620 manager_event(EVENT_FLAG_SYSTEM, "Alarm",
6621 "Alarm: %s\r\n"
6622 "Channel: %d\r\n",
6623 alarm2str(res), i->channel);
6624 /* fall thru intentionally */
6625 case ZT_EVENT_ONHOOK:
6626 if (i->radio)
6627 break;
6628 /* Back on hook. Hang up. */
6629 switch (i->sig) {
6630 case SIG_FXOLS:
6631 case SIG_FXOGS:
6632 case SIG_FEATD:
6633 case SIG_FEATDMF:
6634 case SIG_FEATDMF_TA:
6635 case SIG_E911:
6636 case SIG_FGC_CAMA:
6637 case SIG_FGC_CAMAMF:
6638 case SIG_FEATB:
6639 case SIG_EM:
6640 case SIG_EM_E1:
6641 case SIG_EMWINK:
6642 case SIG_SF_FEATD:
6643 case SIG_SF_FEATDMF:
6644 case SIG_SF_FEATB:
6645 case SIG_SF:
6646 case SIG_SFWINK:
6647 case SIG_FXSLS:
6648 case SIG_FXSGS:
6649 case SIG_FXSKS:
6650 case SIG_GR303FXSKS:
6651 zt_disable_ec(i);
6652 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6653 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_ONHOOK);
6654 break;
6655 case SIG_GR303FXOKS:
6656 case SIG_FXOKS:
6657 zt_disable_ec(i);
6658 /* Diddle the battery for the zhone */
6659 #ifdef ZHONE_HACK
6660 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6661 usleep(1);
6662 #endif
6663 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6664 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_ONHOOK);
6665 break;
6666 case SIG_PRI:
6667 zt_disable_ec(i);
6668 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6669 break;
6670 default:
6671 ast_log(LOG_WARNING, "Don't know how to handle on hook with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
6672 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6673 return -1;
6675 break;
6676 case ZT_EVENT_POLARITY:
6677 switch (i->sig) {
6678 case SIG_FXSLS:
6679 case SIG_FXSKS:
6680 case SIG_FXSGS:
6681 if (i->cid_start == CID_START_POLARITY) {
6682 i->polarity = POLARITY_REV;
6683 ast_verbose(VERBOSE_PREFIX_2 "Starting post polarity "
6684 "CID detection on channel %d\n",
6685 i->channel);
6686 chan = zt_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, 0);
6687 if (chan && ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6688 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6691 break;
6692 default:
6693 ast_log(LOG_WARNING, "handle_init_event detected "
6694 "polarity reversal on non-FXO (SIG_FXS) "
6695 "interface %d\n", i->channel);
6698 return 0;
6701 static void *do_monitor(void *data)
6703 int count, res, res2, spoint, pollres=0;
6704 struct zt_pvt *i;
6705 struct zt_pvt *last = NULL;
6706 time_t thispass = 0, lastpass = 0;
6707 int found;
6708 char buf[1024];
6709 struct pollfd *pfds=NULL;
6710 int lastalloc = -1;
6711 /* This thread monitors all the frame relay interfaces which are not yet in use
6712 (and thus do not have a separate thread) indefinitely */
6713 /* From here on out, we die whenever asked */
6714 #if 0
6715 if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
6716 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
6717 return NULL;
6719 ast_log(LOG_DEBUG, "Monitor starting...\n");
6720 #endif
6721 for (;;) {
6722 /* Lock the interface list */
6723 ast_mutex_lock(&iflock);
6724 if (!pfds || (lastalloc != ifcount)) {
6725 if (pfds)
6726 free(pfds);
6727 if (ifcount) {
6728 if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
6729 ast_mutex_unlock(&iflock);
6730 return NULL;
6733 lastalloc = ifcount;
6735 /* Build the stuff we're going to poll on, that is the socket of every
6736 zt_pvt that does not have an associated owner channel */
6737 count = 0;
6738 i = iflist;
6739 while (i) {
6740 if ((i->subs[SUB_REAL].zfd > -1) && i->sig && (!i->radio)) {
6741 if (!i->owner && !i->subs[SUB_REAL].owner) {
6742 /* This needs to be watched, as it lacks an owner */
6743 pfds[count].fd = i->subs[SUB_REAL].zfd;
6744 pfds[count].events = POLLPRI;
6745 pfds[count].revents = 0;
6746 /* Message waiting or r2 channels also get watched for reading */
6747 if (i->cidspill)
6748 pfds[count].events |= POLLIN;
6749 count++;
6752 i = i->next;
6754 /* Okay, now that we know what to do, release the interface lock */
6755 ast_mutex_unlock(&iflock);
6757 pthread_testcancel();
6758 /* Wait at least a second for something to happen */
6759 res = poll(pfds, count, 1000);
6760 pthread_testcancel();
6761 /* Okay, poll has finished. Let's see what happened. */
6762 if (res < 0) {
6763 if ((errno != EAGAIN) && (errno != EINTR))
6764 ast_log(LOG_WARNING, "poll return %d: %s\n", res, strerror(errno));
6765 continue;
6767 /* Alright, lock the interface list again, and let's look and see what has
6768 happened */
6769 ast_mutex_lock(&iflock);
6770 found = 0;
6771 spoint = 0;
6772 lastpass = thispass;
6773 thispass = time(NULL);
6774 i = iflist;
6775 while (i) {
6776 if (thispass != lastpass) {
6777 if (!found && ((i == last) || ((i == iflist) && !last))) {
6778 last = i;
6779 if (last) {
6780 if (!last->cidspill && !last->owner && !ast_strlen_zero(last->mailbox) && (thispass - last->onhooktime > 3) &&
6781 (last->sig & __ZT_SIG_FXO)) {
6782 res = ast_app_has_voicemail(last->mailbox, NULL);
6783 if (last->msgstate != res) {
6784 int x;
6785 ast_log(LOG_DEBUG, "Message status for %s changed from %d to %d on %d\n", last->mailbox, last->msgstate, res, last->channel);
6786 x = ZT_FLUSH_BOTH;
6787 res2 = ioctl(last->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
6788 if (res2)
6789 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", last->channel);
6790 if ((last->cidspill = ast_calloc(1, MAX_CALLERID_SIZE))) {
6791 /* Turn on on hook transfer for 4 seconds */
6792 x = 4000;
6793 ioctl(last->subs[SUB_REAL].zfd, ZT_ONHOOKTRANSFER, &x);
6794 last->cidlen = vmwi_generate(last->cidspill, res, 1, AST_LAW(last));
6795 last->cidpos = 0;
6796 last->msgstate = res;
6797 last->onhooktime = thispass;
6799 found ++;
6802 last = last->next;
6806 if ((i->subs[SUB_REAL].zfd > -1) && i->sig) {
6807 if (i->radio && !i->owner)
6809 res = zt_get_event(i->subs[SUB_REAL].zfd);
6810 if (res)
6812 if (option_debug)
6813 ast_log(LOG_DEBUG, "Monitor doohicky got event %s on radio channel %d\n", event2str(res), i->channel);
6814 /* Don't hold iflock while handling init events */
6815 ast_mutex_unlock(&iflock);
6816 handle_init_event(i, res);
6817 ast_mutex_lock(&iflock);
6819 i = i->next;
6820 continue;
6822 pollres = ast_fdisset(pfds, i->subs[SUB_REAL].zfd, count, &spoint);
6823 if (pollres & POLLIN) {
6824 if (i->owner || i->subs[SUB_REAL].owner) {
6825 #ifdef HAVE_PRI
6826 if (!i->pri)
6827 #endif
6828 ast_log(LOG_WARNING, "Whoa.... I'm owned but found (%d) in read...\n", i->subs[SUB_REAL].zfd);
6829 i = i->next;
6830 continue;
6832 if (!i->cidspill) {
6833 ast_log(LOG_WARNING, "Whoa.... I'm reading but have no cidspill (%d)...\n", i->subs[SUB_REAL].zfd);
6834 i = i->next;
6835 continue;
6837 res = read(i->subs[SUB_REAL].zfd, buf, sizeof(buf));
6838 if (res > 0) {
6839 /* We read some number of bytes. Write an equal amount of data */
6840 if (res > i->cidlen - i->cidpos)
6841 res = i->cidlen - i->cidpos;
6842 res2 = write(i->subs[SUB_REAL].zfd, i->cidspill + i->cidpos, res);
6843 if (res2 > 0) {
6844 i->cidpos += res2;
6845 if (i->cidpos >= i->cidlen) {
6846 free(i->cidspill);
6847 i->cidspill = 0;
6848 i->cidpos = 0;
6849 i->cidlen = 0;
6851 } else {
6852 ast_log(LOG_WARNING, "Write failed: %s\n", strerror(errno));
6853 i->msgstate = -1;
6855 } else {
6856 ast_log(LOG_WARNING, "Read failed with %d: %s\n", res, strerror(errno));
6858 if (option_debug)
6859 ast_log(LOG_DEBUG, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
6860 /* Don't hold iflock while handling init events -- race with chlock */
6861 ast_mutex_unlock(&iflock);
6862 handle_init_event(i, res);
6863 ast_mutex_lock(&iflock);
6865 if (pollres & POLLPRI) {
6866 if (i->owner || i->subs[SUB_REAL].owner) {
6867 #ifdef HAVE_PRI
6868 if (!i->pri)
6869 #endif
6870 ast_log(LOG_WARNING, "Whoa.... I'm owned but found (%d)...\n", i->subs[SUB_REAL].zfd);
6871 i = i->next;
6872 continue;
6874 res = zt_get_event(i->subs[SUB_REAL].zfd);
6875 if (option_debug)
6876 ast_log(LOG_DEBUG, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
6877 /* Don't hold iflock while handling init events */
6878 ast_mutex_unlock(&iflock);
6879 handle_init_event(i, res);
6880 ast_mutex_lock(&iflock);
6883 i=i->next;
6885 ast_mutex_unlock(&iflock);
6887 /* Never reached */
6888 return NULL;
6892 static int restart_monitor(void)
6894 pthread_attr_t attr;
6895 pthread_attr_init(&attr);
6896 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6897 /* If we're supposed to be stopped -- stay stopped */
6898 if (monitor_thread == AST_PTHREADT_STOP)
6899 return 0;
6900 ast_mutex_lock(&monlock);
6901 if (monitor_thread == pthread_self()) {
6902 ast_mutex_unlock(&monlock);
6903 ast_log(LOG_WARNING, "Cannot kill myself\n");
6904 return -1;
6906 if (monitor_thread != AST_PTHREADT_NULL) {
6907 /* Just signal it to be sure it wakes up */
6908 #if 0
6909 pthread_cancel(monitor_thread);
6910 #endif
6911 pthread_kill(monitor_thread, SIGURG);
6912 #if 0
6913 pthread_join(monitor_thread, NULL);
6914 #endif
6915 } else {
6916 /* Start a new monitor */
6917 if (ast_pthread_create_background(&monitor_thread, &attr, do_monitor, NULL) < 0) {
6918 ast_mutex_unlock(&monlock);
6919 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
6920 return -1;
6923 ast_mutex_unlock(&monlock);
6924 return 0;
6927 #ifdef HAVE_PRI
6928 static int pri_resolve_span(int *span, int channel, int offset, struct zt_spaninfo *si)
6930 int x;
6931 int trunkgroup;
6932 /* Get appropriate trunk group if there is one */
6933 trunkgroup = pris[*span].mastertrunkgroup;
6934 if (trunkgroup) {
6935 /* Select a specific trunk group */
6936 for (x = 0; x < NUM_SPANS; x++) {
6937 if (pris[x].trunkgroup == trunkgroup) {
6938 *span = x;
6939 return 0;
6942 ast_log(LOG_WARNING, "Channel %d on span %d configured to use nonexistent trunk group %d\n", channel, *span, trunkgroup);
6943 *span = -1;
6944 } else {
6945 if (pris[*span].trunkgroup) {
6946 ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is trunk group %d (please use spanmap)\n", *span, pris[*span].trunkgroup);
6947 *span = -1;
6948 } else if (pris[*span].mastertrunkgroup) {
6949 ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is already part of trunk group %d\n", *span, pris[*span].mastertrunkgroup);
6950 *span = -1;
6951 } else {
6952 if (si->totalchans == 31) { /* if it's an E1 */
6953 pris[*span].dchannels[0] = 16 + offset;
6954 } else {
6955 pris[*span].dchannels[0] = 24 + offset;
6957 pris[*span].dchanavail[0] |= DCHAN_PROVISIONED;
6958 pris[*span].offset = offset;
6959 pris[*span].span = *span + 1;
6962 return 0;
6965 static int pri_create_trunkgroup(int trunkgroup, int *channels)
6967 struct zt_spaninfo si;
6968 ZT_PARAMS p;
6969 int fd;
6970 int span;
6971 int ospan=0;
6972 int x,y;
6973 for (x = 0; x < NUM_SPANS; x++) {
6974 if (pris[x].trunkgroup == trunkgroup) {
6975 ast_log(LOG_WARNING, "Trunk group %d already exists on span %d, Primary d-channel %d\n", trunkgroup, x + 1, pris[x].dchannels[0]);
6976 return -1;
6979 for (y = 0; y < NUM_DCHANS; y++) {
6980 if (!channels[y])
6981 break;
6982 memset(&si, 0, sizeof(si));
6983 memset(&p, 0, sizeof(p));
6984 fd = open("/dev/zap/channel", O_RDWR);
6985 if (fd < 0) {
6986 ast_log(LOG_WARNING, "Failed to open channel: %s\n", strerror(errno));
6987 return -1;
6989 x = channels[y];
6990 if (ioctl(fd, ZT_SPECIFY, &x)) {
6991 ast_log(LOG_WARNING, "Failed to specify channel %d: %s\n", channels[y], strerror(errno));
6992 zt_close(fd);
6993 return -1;
6995 if (ioctl(fd, ZT_GET_PARAMS, &p)) {
6996 ast_log(LOG_WARNING, "Failed to get channel parameters for channel %d: %s\n", channels[y], strerror(errno));
6997 return -1;
6999 if (ioctl(fd, ZT_SPANSTAT, &si)) {
7000 ast_log(LOG_WARNING, "Failed go get span information on channel %d (span %d)\n", channels[y], p.spanno);
7001 zt_close(fd);
7002 return -1;
7004 span = p.spanno - 1;
7005 if (pris[span].trunkgroup) {
7006 ast_log(LOG_WARNING, "Span %d is already provisioned for trunk group %d\n", span + 1, pris[span].trunkgroup);
7007 zt_close(fd);
7008 return -1;
7010 if (pris[span].pvts[0]) {
7011 ast_log(LOG_WARNING, "Span %d is already provisioned with channels (implicit PRI maybe?)\n", span + 1);
7012 zt_close(fd);
7013 return -1;
7015 if (!y) {
7016 pris[span].trunkgroup = trunkgroup;
7017 pris[span].offset = channels[y] - p.chanpos;
7018 ospan = span;
7020 pris[ospan].dchannels[y] = channels[y];
7021 pris[ospan].dchanavail[y] |= DCHAN_PROVISIONED;
7022 pris[span].span = span + 1;
7023 zt_close(fd);
7025 return 0;
7028 static int pri_create_spanmap(int span, int trunkgroup, int logicalspan)
7030 if (pris[span].mastertrunkgroup) {
7031 ast_log(LOG_WARNING, "Span %d is already part of trunk group %d, cannot add to trunk group %d\n", span + 1, pris[span].mastertrunkgroup, trunkgroup);
7032 return -1;
7034 pris[span].mastertrunkgroup = trunkgroup;
7035 pris[span].prilogicalspan = logicalspan;
7036 return 0;
7039 #endif
7041 static struct zt_pvt *mkintf(int channel, int signalling, int outsignalling, int radio, struct zt_pri *pri, int reloading)
7043 /* Make a zt_pvt structure for this interface (or CRV if "pri" is specified) */
7044 struct zt_pvt *tmp = NULL, *tmp2, *prev = NULL;
7045 char fn[80];
7046 #if 1
7047 struct zt_bufferinfo bi;
7048 #endif
7049 struct zt_spaninfo si;
7050 int res;
7051 int span=0;
7052 int here = 0;
7053 int x;
7054 struct zt_pvt **wlist;
7055 struct zt_pvt **wend;
7056 ZT_PARAMS p;
7058 wlist = &iflist;
7059 wend = &ifend;
7061 #ifdef HAVE_PRI
7062 if (pri) {
7063 wlist = &pri->crvs;
7064 wend = &pri->crvend;
7066 #endif
7068 tmp2 = *wlist;
7069 prev = NULL;
7071 while (tmp2) {
7072 if (!tmp2->destroy) {
7073 if (tmp2->channel == channel) {
7074 tmp = tmp2;
7075 here = 1;
7076 break;
7078 if (tmp2->channel > channel) {
7079 break;
7082 prev = tmp2;
7083 tmp2 = tmp2->next;
7086 if (!here && !reloading) {
7087 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
7088 destroy_zt_pvt(&tmp);
7089 return NULL;
7091 ast_mutex_init(&tmp->lock);
7092 ifcount++;
7093 for (x = 0; x < 3; x++)
7094 tmp->subs[x].zfd = -1;
7095 tmp->channel = channel;
7098 if (tmp) {
7099 if (!here) {
7100 if ((channel != CHAN_PSEUDO) && !pri) {
7101 snprintf(fn, sizeof(fn), "%d", channel);
7102 /* Open non-blocking */
7103 if (!here)
7104 tmp->subs[SUB_REAL].zfd = zt_open(fn);
7105 /* Allocate a zapata structure */
7106 if (tmp->subs[SUB_REAL].zfd < 0) {
7107 ast_log(LOG_ERROR, "Unable to open channel %d: %s\nhere = %d, tmp->channel = %d, channel = %d\n", channel, strerror(errno), here, tmp->channel, channel);
7108 destroy_zt_pvt(&tmp);
7109 return NULL;
7111 memset(&p, 0, sizeof(p));
7112 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &p);
7113 if (res < 0) {
7114 ast_log(LOG_ERROR, "Unable to get parameters\n");
7115 destroy_zt_pvt(&tmp);
7116 return NULL;
7118 if (p.sigtype != (signalling & 0x3ffff)) {
7119 ast_log(LOG_ERROR, "Signalling requested on channel %d is %s but line is in %s signalling\n", channel, sig2str(signalling), sig2str(p.sigtype));
7120 destroy_zt_pvt(&tmp);
7121 return NULL;
7123 tmp->law = p.curlaw;
7124 tmp->span = p.spanno;
7125 span = p.spanno - 1;
7126 } else {
7127 if (channel == CHAN_PSEUDO)
7128 signalling = 0;
7129 else if ((signalling != SIG_FXOKS) && (signalling != SIG_FXSKS)) {
7130 ast_log(LOG_ERROR, "CRV's must use FXO/FXS Kewl Start (fxo_ks/fxs_ks) signalling only.\n");
7131 return NULL;
7134 #ifdef HAVE_PRI
7135 if ((signalling == SIG_PRI) || (signalling == SIG_GR303FXOKS) || (signalling == SIG_GR303FXSKS)) {
7136 int offset;
7137 int myswitchtype;
7138 int matchesdchan;
7139 int x,y;
7140 offset = 0;
7141 if ((signalling == SIG_PRI) && ioctl(tmp->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &offset)) {
7142 ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
7143 destroy_zt_pvt(&tmp);
7144 return NULL;
7146 if (span >= NUM_SPANS) {
7147 ast_log(LOG_ERROR, "Channel %d does not lie on a span I know of (%d)\n", channel, span);
7148 destroy_zt_pvt(&tmp);
7149 return NULL;
7150 } else {
7151 si.spanno = 0;
7152 if (ioctl(tmp->subs[SUB_REAL].zfd,ZT_SPANSTAT,&si) == -1) {
7153 ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
7154 destroy_zt_pvt(&tmp);
7155 return NULL;
7157 /* Store the logical span first based upon the real span */
7158 tmp->logicalspan = pris[span].prilogicalspan;
7159 pri_resolve_span(&span, channel, (channel - p.chanpos), &si);
7160 if (span < 0) {
7161 ast_log(LOG_WARNING, "Channel %d: Unable to find locate channel/trunk group!\n", channel);
7162 destroy_zt_pvt(&tmp);
7163 return NULL;
7165 if (signalling == SIG_PRI)
7166 myswitchtype = switchtype;
7167 else
7168 myswitchtype = PRI_SWITCH_GR303_TMC;
7169 /* Make sure this isn't a d-channel */
7170 matchesdchan=0;
7171 for (x = 0; x < NUM_SPANS; x++) {
7172 for (y = 0; y < NUM_DCHANS; y++) {
7173 if (pris[x].dchannels[y] == tmp->channel) {
7174 matchesdchan = 1;
7175 break;
7179 offset = p.chanpos;
7180 if (!matchesdchan) {
7181 if (pris[span].nodetype && (pris[span].nodetype != pritype)) {
7182 ast_log(LOG_ERROR, "Span %d is already a %s node\n", span + 1, pri_node2str(pris[span].nodetype));
7183 destroy_zt_pvt(&tmp);
7184 return NULL;
7186 if (pris[span].switchtype && (pris[span].switchtype != myswitchtype)) {
7187 ast_log(LOG_ERROR, "Span %d is already a %s switch\n", span + 1, pri_switch2str(pris[span].switchtype));
7188 destroy_zt_pvt(&tmp);
7189 return NULL;
7191 if ((pris[span].dialplan) && (pris[span].dialplan != dialplan)) {
7192 ast_log(LOG_ERROR, "Span %d is already a %s dialing plan\n", span + 1, dialplan2str(pris[span].dialplan));
7193 destroy_zt_pvt(&tmp);
7194 return NULL;
7196 if (!ast_strlen_zero(pris[span].idledial) && strcmp(pris[span].idledial, idledial)) {
7197 ast_log(LOG_ERROR, "Span %d already has idledial '%s'.\n", span + 1, idledial);
7198 destroy_zt_pvt(&tmp);
7199 return NULL;
7201 if (!ast_strlen_zero(pris[span].idleext) && strcmp(pris[span].idleext, idleext)) {
7202 ast_log(LOG_ERROR, "Span %d already has idleext '%s'.\n", span + 1, idleext);
7203 destroy_zt_pvt(&tmp);
7204 return NULL;
7206 if (pris[span].minunused && (pris[span].minunused != minunused)) {
7207 ast_log(LOG_ERROR, "Span %d already has minunused of %d.\n", span + 1, minunused);
7208 destroy_zt_pvt(&tmp);
7209 return NULL;
7211 if (pris[span].minidle && (pris[span].minidle != minidle)) {
7212 ast_log(LOG_ERROR, "Span %d already has minidle of %d.\n", span + 1, minidle);
7213 destroy_zt_pvt(&tmp);
7214 return NULL;
7216 if (pris[span].numchans >= MAX_CHANNELS) {
7217 ast_log(LOG_ERROR, "Unable to add channel %d: Too many channels in trunk group %d!\n", channel,
7218 pris[span].trunkgroup);
7219 destroy_zt_pvt(&tmp);
7220 return NULL;
7222 pris[span].nodetype = pritype;
7223 pris[span].switchtype = myswitchtype;
7224 pris[span].nsf = nsf;
7225 pris[span].dialplan = dialplan;
7226 pris[span].localdialplan = localdialplan;
7227 pris[span].pvts[pris[span].numchans++] = tmp;
7228 pris[span].minunused = minunused;
7229 pris[span].minidle = minidle;
7230 pris[span].overlapdial = overlapdial;
7231 pris[span].facilityenable = facilityenable;
7232 ast_copy_string(pris[span].idledial, idledial, sizeof(pris[span].idledial));
7233 ast_copy_string(pris[span].idleext, idleext, sizeof(pris[span].idleext));
7234 ast_copy_string(pris[span].internationalprefix, internationalprefix, sizeof(pris[span].internationalprefix));
7235 ast_copy_string(pris[span].nationalprefix, nationalprefix, sizeof(pris[span].nationalprefix));
7236 ast_copy_string(pris[span].localprefix, localprefix, sizeof(pris[span].localprefix));
7237 ast_copy_string(pris[span].privateprefix, privateprefix, sizeof(pris[span].privateprefix));
7238 ast_copy_string(pris[span].unknownprefix, unknownprefix, sizeof(pris[span].unknownprefix));
7239 pris[span].resetinterval = resetinterval;
7241 tmp->pri = &pris[span];
7242 tmp->prioffset = offset;
7243 tmp->call = NULL;
7244 } else {
7245 ast_log(LOG_ERROR, "Channel %d is reserved for D-channel.\n", offset);
7246 destroy_zt_pvt(&tmp);
7247 return NULL;
7250 } else {
7251 tmp->prioffset = 0;
7253 #endif
7254 } else {
7255 signalling = tmp->sig;
7256 radio = tmp->radio;
7257 memset(&p, 0, sizeof(p));
7258 if (tmp->subs[SUB_REAL].zfd > -1)
7259 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &p);
7261 /* Adjust starttime on loopstart and kewlstart trunks to reasonable values */
7262 if ((signalling == SIG_FXSKS) || (signalling == SIG_FXSLS) ||
7263 (signalling == SIG_EM) || (signalling == SIG_EM_E1) || (signalling == SIG_EMWINK) ||
7264 (signalling == SIG_FEATD) || (signalling == SIG_FEATDMF) || (signalling == SIG_FEATDMF_TA) ||
7265 (signalling == SIG_FEATB) || (signalling == SIG_E911) ||
7266 (signalling == SIG_SF) || (signalling == SIG_SFWINK) || (signalling == SIG_FGC_CAMA) || (signalling == SIG_FGC_CAMAMF) ||
7267 (signalling == SIG_SF_FEATD) || (signalling == SIG_SF_FEATDMF) ||
7268 (signalling == SIG_SF_FEATB)) {
7269 p.starttime = 250;
7271 if (radio) {
7272 /* XXX Waiting to hear back from Jim if these should be adjustable XXX */
7273 p.channo = channel;
7274 p.rxwinktime = 1;
7275 p.rxflashtime = 1;
7276 p.starttime = 1;
7277 p.debouncetime = 5;
7279 if (!radio) {
7280 p.channo = channel;
7281 /* Override timing settings based on config file */
7282 if (cur_prewink >= 0)
7283 p.prewinktime = cur_prewink;
7284 if (cur_preflash >= 0)
7285 p.preflashtime = cur_preflash;
7286 if (cur_wink >= 0)
7287 p.winktime = cur_wink;
7288 if (cur_flash >= 0)
7289 p.flashtime = cur_flash;
7290 if (cur_start >= 0)
7291 p.starttime = cur_start;
7292 if (cur_rxwink >= 0)
7293 p.rxwinktime = cur_rxwink;
7294 if (cur_rxflash >= 0)
7295 p.rxflashtime = cur_rxflash;
7296 if (cur_debounce >= 0)
7297 p.debouncetime = cur_debounce;
7300 /* dont set parms on a pseudo-channel (or CRV) */
7301 if (tmp->subs[SUB_REAL].zfd >= 0)
7303 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_SET_PARAMS, &p);
7304 if (res < 0) {
7305 ast_log(LOG_ERROR, "Unable to set parameters\n");
7306 destroy_zt_pvt(&tmp);
7307 return NULL;
7310 #if 1
7311 if (!here && (tmp->subs[SUB_REAL].zfd > -1)) {
7312 memset(&bi, 0, sizeof(bi));
7313 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_BUFINFO, &bi);
7314 if (!res) {
7315 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
7316 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
7317 bi.numbufs = numbufs;
7318 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_SET_BUFINFO, &bi);
7319 if (res < 0) {
7320 ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", channel);
7322 } else
7323 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", channel);
7325 #endif
7326 tmp->immediate = immediate;
7327 tmp->transfertobusy = transfertobusy;
7328 tmp->sig = signalling;
7329 tmp->outsigmod = outsignalling;
7330 tmp->radio = radio;
7331 tmp->ringt_base = ringt_base;
7332 tmp->firstradio = 0;
7333 if ((signalling == SIG_FXOKS) || (signalling == SIG_FXOLS) || (signalling == SIG_FXOGS))
7334 tmp->permcallwaiting = callwaiting;
7335 else
7336 tmp->permcallwaiting = 0;
7337 /* Flag to destroy the channel must be cleared on new mkif. Part of changes for reload to work */
7338 tmp->destroy = 0;
7339 tmp->drings = drings;
7340 tmp->usedistinctiveringdetection = usedistinctiveringdetection;
7341 tmp->callwaitingcallerid = callwaitingcallerid;
7342 tmp->threewaycalling = threewaycalling;
7343 tmp->adsi = adsi;
7344 tmp->use_smdi = use_smdi;
7345 tmp->permhidecallerid = hidecallerid;
7346 tmp->callreturn = callreturn;
7347 tmp->echocancel = echocancel;
7348 tmp->echotraining = echotraining;
7349 tmp->pulse = pulse;
7350 tmp->echocanbridged = echocanbridged;
7351 tmp->busydetect = busydetect;
7352 tmp->busycount = busycount;
7353 tmp->busy_tonelength = busy_tonelength;
7354 tmp->busy_quietlength = busy_quietlength;
7355 tmp->callprogress = callprogress;
7356 tmp->cancallforward = cancallforward;
7357 tmp->dtmfrelax = relaxdtmf;
7358 tmp->callwaiting = tmp->permcallwaiting;
7359 tmp->hidecallerid = tmp->permhidecallerid;
7360 tmp->channel = channel;
7361 tmp->stripmsd = stripmsd;
7362 tmp->use_callerid = use_callerid;
7363 tmp->cid_signalling = cid_signalling;
7364 tmp->cid_start = cid_start;
7365 tmp->zaptrcallerid = zaptrcallerid;
7366 tmp->restrictcid = restrictcid;
7367 tmp->use_callingpres = use_callingpres;
7368 tmp->priindication_oob = priindication_oob;
7369 tmp->priexclusive = cur_priexclusive;
7370 if (tmp->usedistinctiveringdetection) {
7371 if (!tmp->use_callerid) {
7372 ast_log(LOG_NOTICE, "Distinctive Ring detect requires 'usecallerid' be on\n");
7373 tmp->use_callerid = 1;
7377 if (tmp->cid_signalling == CID_SIG_SMDI) {
7378 if (!tmp->use_smdi) {
7379 ast_log(LOG_WARNING, "SMDI callerid requires SMDI to be enabled, enabling...\n");
7380 tmp->use_smdi = 1;
7383 if (tmp->use_smdi) {
7384 tmp->smdi_iface = ast_smdi_interface_find(smdi_port);
7385 if (!(tmp->smdi_iface)) {
7386 ast_log(LOG_ERROR, "Invalid SMDI port specfied, disabling SMDI support\n");
7387 tmp->use_smdi = 0;
7391 ast_copy_string(tmp->accountcode, accountcode, sizeof(tmp->accountcode));
7392 tmp->amaflags = amaflags;
7393 if (!here) {
7394 tmp->confno = -1;
7395 tmp->propconfno = -1;
7397 tmp->canpark = canpark;
7398 tmp->transfer = transfer;
7399 ast_copy_string(tmp->defcontext,context,sizeof(tmp->defcontext));
7400 ast_copy_string(tmp->language, language, sizeof(tmp->language));
7401 ast_copy_string(tmp->mohinterpret, mohinterpret, sizeof(tmp->mohinterpret));
7402 ast_copy_string(tmp->mohsuggest, mohsuggest, sizeof(tmp->mohsuggest));
7403 ast_copy_string(tmp->context, context, sizeof(tmp->context));
7404 ast_copy_string(tmp->cid_num, cid_num, sizeof(tmp->cid_num));
7405 tmp->cid_ton = 0;
7406 ast_copy_string(tmp->cid_name, cid_name, sizeof(tmp->cid_name));
7407 ast_copy_string(tmp->mailbox, mailbox, sizeof(tmp->mailbox));
7408 tmp->msgstate = -1;
7409 tmp->group = cur_group;
7410 tmp->callgroup=cur_callergroup;
7411 tmp->pickupgroup=cur_pickupgroup;
7412 tmp->rxgain = rxgain;
7413 tmp->txgain = txgain;
7414 tmp->tonezone = tonezone;
7415 tmp->onhooktime = time(NULL);
7416 if (tmp->subs[SUB_REAL].zfd > -1) {
7417 set_actual_gain(tmp->subs[SUB_REAL].zfd, 0, tmp->rxgain, tmp->txgain, tmp->law);
7418 if (tmp->dsp)
7419 ast_dsp_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
7420 update_conf(tmp);
7421 if (!here) {
7422 if (signalling != SIG_PRI)
7423 /* Hang it up to be sure it's good */
7424 zt_set_hook(tmp->subs[SUB_REAL].zfd, ZT_ONHOOK);
7426 ioctl(tmp->subs[SUB_REAL].zfd,ZT_SETTONEZONE,&tmp->tonezone);
7427 #ifdef HAVE_PRI
7428 /* the dchannel is down so put the channel in alarm */
7429 if (tmp->pri && !pri_is_up(tmp->pri))
7430 tmp->inalarm = 1;
7431 else
7432 tmp->inalarm = 0;
7433 #endif
7434 memset(&si, 0, sizeof(si));
7435 if (ioctl(tmp->subs[SUB_REAL].zfd,ZT_SPANSTAT,&si) == -1) {
7436 ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
7437 destroy_zt_pvt(&tmp);
7438 return NULL;
7440 if (si.alarms) tmp->inalarm = 1;
7443 tmp->polarityonanswerdelay = polarityonanswerdelay;
7444 tmp->answeronpolarityswitch = answeronpolarityswitch;
7445 tmp->hanguponpolarityswitch = hanguponpolarityswitch;
7446 tmp->sendcalleridafter = sendcalleridafter;
7449 if (tmp && !here) {
7450 /* nothing on the iflist */
7451 if (!*wlist) {
7452 *wlist = tmp;
7453 tmp->prev = NULL;
7454 tmp->next = NULL;
7455 *wend = tmp;
7456 } else {
7457 /* at least one member on the iflist */
7458 struct zt_pvt *working = *wlist;
7460 /* check if we maybe have to put it on the begining */
7461 if (working->channel > tmp->channel) {
7462 tmp->next = *wlist;
7463 tmp->prev = NULL;
7464 (*wlist)->prev = tmp;
7465 *wlist = tmp;
7466 } else {
7467 /* go through all the members and put the member in the right place */
7468 while (working) {
7469 /* in the middle */
7470 if (working->next) {
7471 if (working->channel < tmp->channel && working->next->channel > tmp->channel) {
7472 tmp->next = working->next;
7473 tmp->prev = working;
7474 working->next->prev = tmp;
7475 working->next = tmp;
7476 break;
7478 } else {
7479 /* the last */
7480 if (working->channel < tmp->channel) {
7481 working->next = tmp;
7482 tmp->next = NULL;
7483 tmp->prev = working;
7484 *wend = tmp;
7485 break;
7488 working = working->next;
7493 return tmp;
7496 static inline int available(struct zt_pvt *p, int channelmatch, int groupmatch, int *busy, int *channelmatched, int *groupmatched)
7498 int res;
7499 ZT_PARAMS par;
7501 /* First, check group matching */
7502 if (groupmatch) {
7503 if ((p->group & groupmatch) != groupmatch)
7504 return 0;
7505 *groupmatched = 1;
7507 /* Check to see if we have a channel match */
7508 if (channelmatch != -1) {
7509 if (p->channel != channelmatch)
7510 return 0;
7511 *channelmatched = 1;
7513 /* We're at least busy at this point */
7514 if (busy) {
7515 if ((p->sig == SIG_FXOKS) || (p->sig == SIG_FXOLS) || (p->sig == SIG_FXOGS))
7516 *busy = 1;
7518 /* If do not disturb, definitely not */
7519 if (p->dnd)
7520 return 0;
7521 /* If guard time, definitely not */
7522 if (p->guardtime && (time(NULL) < p->guardtime))
7523 return 0;
7525 /* If no owner definitely available */
7526 if (!p->owner) {
7527 #ifdef HAVE_PRI
7528 /* Trust PRI */
7529 if (p->pri) {
7530 if (p->resetting || p->call)
7531 return 0;
7532 else
7533 return 1;
7535 #endif
7536 if (!(p->radio || (p->oprmode < 0)))
7538 if (!p->sig || (p->sig == SIG_FXSLS))
7539 return 1;
7540 /* Check hook state */
7541 if (p->subs[SUB_REAL].zfd > -1)
7542 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
7543 else {
7544 /* Assume not off hook on CVRS */
7545 res = 0;
7546 par.rxisoffhook = 0;
7548 if (res) {
7549 ast_log(LOG_WARNING, "Unable to check hook state on channel %d\n", p->channel);
7550 } else if ((p->sig == SIG_FXSKS) || (p->sig == SIG_FXSGS)) {
7551 /* When "onhook" that means no battery on the line, and thus
7552 it is out of service..., if it's on a TDM card... If it's a channel
7553 bank, there is no telling... */
7554 if (par.rxbits > -1)
7555 return 1;
7556 if (par.rxisoffhook)
7557 return 1;
7558 else
7559 #ifdef ZAP_CHECK_HOOKSTATE
7560 return 0;
7561 #else
7562 return 1;
7563 #endif
7564 } else if (par.rxisoffhook) {
7565 ast_log(LOG_DEBUG, "Channel %d off hook, can't use\n", p->channel);
7566 /* Not available when the other end is off hook */
7567 return 0;
7570 return 1;
7573 /* If it's not an FXO, forget about call wait */
7574 if ((p->sig != SIG_FXOKS) && (p->sig != SIG_FXOLS) && (p->sig != SIG_FXOGS))
7575 return 0;
7577 if (!p->callwaiting) {
7578 /* If they don't have call waiting enabled, then for sure they're unavailable at this point */
7579 return 0;
7582 if (p->subs[SUB_CALLWAIT].zfd > -1) {
7583 /* If there is already a call waiting call, then we can't take a second one */
7584 return 0;
7587 if ((p->owner->_state != AST_STATE_UP) &&
7588 ((p->owner->_state != AST_STATE_RINGING) || p->outgoing)) {
7589 /* If the current call is not up, then don't allow the call */
7590 return 0;
7592 if ((p->subs[SUB_THREEWAY].owner) && (!p->subs[SUB_THREEWAY].inthreeway)) {
7593 /* Can't take a call wait when the three way calling hasn't been merged yet. */
7594 return 0;
7596 /* We're cool */
7597 return 1;
7600 static struct zt_pvt *chandup(struct zt_pvt *src)
7602 struct zt_pvt *p;
7603 ZT_BUFFERINFO bi;
7604 int res;
7606 if ((p = ast_malloc(sizeof(*p)))) {
7607 memcpy(p, src, sizeof(struct zt_pvt));
7608 ast_mutex_init(&p->lock);
7609 p->subs[SUB_REAL].zfd = zt_open("/dev/zap/pseudo");
7610 /* Allocate a zapata structure */
7611 if (p->subs[SUB_REAL].zfd < 0) {
7612 ast_log(LOG_ERROR, "Unable to dup channel: %s\n", strerror(errno));
7613 destroy_zt_pvt(&p);
7614 return NULL;
7616 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_BUFINFO, &bi);
7617 if (!res) {
7618 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
7619 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
7620 bi.numbufs = numbufs;
7621 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SET_BUFINFO, &bi);
7622 if (res < 0) {
7623 ast_log(LOG_WARNING, "Unable to set buffer policy on dup channel\n");
7625 } else
7626 ast_log(LOG_WARNING, "Unable to check buffer policy on dup channel\n");
7628 p->destroy = 1;
7629 p->next = iflist;
7630 iflist = p;
7631 return p;
7635 #ifdef HAVE_PRI
7636 static int pri_find_empty_chan(struct zt_pri *pri, int backwards)
7638 int x;
7639 if (backwards)
7640 x = pri->numchans;
7641 else
7642 x = 0;
7643 for (;;) {
7644 if (backwards && (x < 0))
7645 break;
7646 if (!backwards && (x >= pri->numchans))
7647 break;
7648 if (pri->pvts[x] && !pri->pvts[x]->inalarm && !pri->pvts[x]->owner) {
7649 ast_log(LOG_DEBUG, "Found empty available channel %d/%d\n",
7650 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
7651 return x;
7653 if (backwards)
7654 x--;
7655 else
7656 x++;
7658 return -1;
7660 #endif
7662 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause)
7664 int groupmatch = 0;
7665 int channelmatch = -1;
7666 int roundrobin = 0;
7667 int callwait = 0;
7668 int busy = 0;
7669 struct zt_pvt *p;
7670 struct ast_channel *tmp = NULL;
7671 char *dest=NULL;
7672 int x;
7673 char *s;
7674 char opt=0;
7675 int res=0, y=0;
7676 int backwards = 0;
7677 #ifdef HAVE_PRI
7678 int crv;
7679 int bearer = -1;
7680 int trunkgroup;
7681 struct zt_pri *pri=NULL;
7682 #endif
7683 struct zt_pvt *exit, *start, *end;
7684 ast_mutex_t *lock;
7685 int channelmatched = 0;
7686 int groupmatched = 0;
7688 /* Assume we're locking the iflock */
7689 lock = &iflock;
7690 start = iflist;
7691 end = ifend;
7692 if (data) {
7693 dest = ast_strdupa((char *)data);
7694 } else {
7695 ast_log(LOG_WARNING, "Channel requested with no data\n");
7696 return NULL;
7698 if (toupper(dest[0]) == 'G' || toupper(dest[0])=='R') {
7699 /* Retrieve the group number */
7700 char *stringp=NULL;
7701 stringp=dest + 1;
7702 s = strsep(&stringp, "/");
7703 if ((res = sscanf(s, "%d%c%d", &x, &opt, &y)) < 1) {
7704 ast_log(LOG_WARNING, "Unable to determine group for data %s\n", (char *)data);
7705 return NULL;
7707 groupmatch = 1 << x;
7708 if (toupper(dest[0]) == 'G') {
7709 if (dest[0] == 'G') {
7710 backwards = 1;
7711 p = ifend;
7712 } else
7713 p = iflist;
7714 } else {
7715 if (dest[0] == 'R') {
7716 backwards = 1;
7717 p = round_robin[x]?round_robin[x]->prev:ifend;
7718 if (!p)
7719 p = ifend;
7720 } else {
7721 p = round_robin[x]?round_robin[x]->next:iflist;
7722 if (!p)
7723 p = iflist;
7725 roundrobin = 1;
7727 } else {
7728 char *stringp=NULL;
7729 stringp=dest;
7730 s = strsep(&stringp, "/");
7731 p = iflist;
7732 if (!strcasecmp(s, "pseudo")) {
7733 /* Special case for pseudo */
7734 x = CHAN_PSEUDO;
7735 channelmatch = x;
7737 #ifdef HAVE_PRI
7738 else if ((res = sscanf(s, "%d:%d%c%d", &trunkgroup, &crv, &opt, &y)) > 1) {
7739 if ((trunkgroup < 1) || (crv < 1)) {
7740 ast_log(LOG_WARNING, "Unable to determine trunk group and CRV for data %s\n", (char *)data);
7741 return NULL;
7743 res--;
7744 for (x = 0; x < NUM_SPANS; x++) {
7745 if (pris[x].trunkgroup == trunkgroup) {
7746 pri = pris + x;
7747 lock = &pri->lock;
7748 start = pri->crvs;
7749 end = pri->crvend;
7750 break;
7753 if (!pri) {
7754 ast_log(LOG_WARNING, "Unable to find trunk group %d\n", trunkgroup);
7755 return NULL;
7757 channelmatch = crv;
7758 p = pris[x].crvs;
7760 #endif
7761 else if ((res = sscanf(s, "%d%c%d", &x, &opt, &y)) < 1) {
7762 ast_log(LOG_WARNING, "Unable to determine channel for data %s\n", (char *)data);
7763 return NULL;
7764 } else {
7765 channelmatch = x;
7768 /* Search for an unowned channel */
7769 ast_mutex_lock(lock);
7770 exit = p;
7771 while (p && !tmp) {
7772 if (roundrobin)
7773 round_robin[x] = p;
7774 #if 0
7775 ast_verbose("name = %s, %d, %d, %d\n",p->owner ? p->owner->name : "<none>", p->channel, channelmatch, groupmatch);
7776 #endif
7778 if (p && available(p, channelmatch, groupmatch, &busy, &channelmatched, &groupmatched)) {
7779 if (option_debug)
7780 ast_log(LOG_DEBUG, "Using channel %d\n", p->channel);
7781 if (p->inalarm)
7782 goto next;
7784 callwait = (p->owner != NULL);
7785 #ifdef HAVE_PRI
7786 if (pri && (p->subs[SUB_REAL].zfd < 0)) {
7787 if (p->sig != SIG_FXSKS) {
7788 /* Gotta find an actual channel to use for this
7789 CRV if this isn't a callwait */
7790 bearer = pri_find_empty_chan(pri, 0);
7791 if (bearer < 0) {
7792 ast_log(LOG_NOTICE, "Out of bearer channels on span %d for call to CRV %d:%d\n", pri->span, trunkgroup, crv);
7793 p = NULL;
7794 break;
7796 pri_assign_bearer(p, pri, pri->pvts[bearer]);
7797 } else {
7798 if (alloc_sub(p, 0)) {
7799 ast_log(LOG_NOTICE, "Failed to allocate place holder pseudo channel!\n");
7800 p = NULL;
7801 break;
7802 } else
7803 ast_log(LOG_DEBUG, "Allocated placeholder pseudo channel\n");
7804 p->pri = pri;
7807 #endif
7808 if (p->channel == CHAN_PSEUDO) {
7809 p = chandup(p);
7810 if (!p) {
7811 break;
7814 if (p->owner) {
7815 if (alloc_sub(p, SUB_CALLWAIT)) {
7816 p = NULL;
7817 break;
7820 p->outgoing = 1;
7821 tmp = zt_new(p, AST_STATE_RESERVED, 0, p->owner ? SUB_CALLWAIT : SUB_REAL, 0, 0);
7822 #ifdef HAVE_PRI
7823 if (p->bearer) {
7824 /* Log owner to bearer channel, too */
7825 p->bearer->owner = tmp;
7827 #endif
7828 /* Make special notes */
7829 if (res > 1) {
7830 if (opt == 'c') {
7831 /* Confirm answer */
7832 p->confirmanswer = 1;
7833 } else if (opt == 'r') {
7834 /* Distinctive ring */
7835 if (res < 3)
7836 ast_log(LOG_WARNING, "Distinctive ring missing identifier in '%s'\n", (char *)data);
7837 else
7838 p->distinctivering = y;
7839 } else if (opt == 'd') {
7840 /* If this is an ISDN call, make it digital */
7841 p->digital = 1;
7842 if (tmp)
7843 tmp->transfercapability = AST_TRANS_CAP_DIGITAL;
7844 } else {
7845 ast_log(LOG_WARNING, "Unknown option '%c' in '%s'\n", opt, (char *)data);
7848 /* Note if the call is a call waiting call */
7849 if (tmp && callwait)
7850 tmp->cdrflags |= AST_CDR_CALLWAIT;
7851 break;
7853 next:
7854 if (backwards) {
7855 p = p->prev;
7856 if (!p)
7857 p = end;
7858 } else {
7859 p = p->next;
7860 if (!p)
7861 p = start;
7863 /* stop when you roll to the one that we started from */
7864 if (p == exit)
7865 break;
7867 ast_mutex_unlock(lock);
7868 restart_monitor();
7869 if (callwait)
7870 *cause = AST_CAUSE_BUSY;
7871 else if (!tmp) {
7872 if (channelmatched) {
7873 if (busy)
7874 *cause = AST_CAUSE_BUSY;
7875 } else if (groupmatched) {
7876 *cause = AST_CAUSE_CONGESTION;
7880 return tmp;
7884 #ifdef HAVE_PRI
7885 static struct zt_pvt *pri_find_crv(struct zt_pri *pri, int crv)
7887 struct zt_pvt *p;
7888 p = pri->crvs;
7889 while (p) {
7890 if (p->channel == crv)
7891 return p;
7892 p = p->next;
7894 return NULL;
7898 static int pri_find_principle(struct zt_pri *pri, int channel)
7900 int x;
7901 int span = PRI_SPAN(channel);
7902 int spanfd;
7903 ZT_PARAMS param;
7904 int principle = -1;
7905 int explicit = PRI_EXPLICIT(channel);
7906 channel = PRI_CHANNEL(channel);
7908 if (!explicit) {
7909 spanfd = pri_active_dchan_fd(pri);
7910 if (ioctl(spanfd, ZT_GET_PARAMS, &param))
7911 return -1;
7912 span = pris[param.spanno - 1].prilogicalspan;
7915 for (x = 0; x < pri->numchans; x++) {
7916 if (pri->pvts[x] && (pri->pvts[x]->prioffset == channel) && (pri->pvts[x]->logicalspan == span)) {
7917 principle = x;
7918 break;
7922 return principle;
7925 static int pri_fixup_principle(struct zt_pri *pri, int principle, q931_call *c)
7927 int x;
7928 struct zt_pvt *crv;
7929 if (!c) {
7930 if (principle < 0)
7931 return -1;
7932 return principle;
7934 if ((principle > -1) &&
7935 (principle < pri->numchans) &&
7936 (pri->pvts[principle]) &&
7937 (pri->pvts[principle]->call == c))
7938 return principle;
7939 /* First, check for other bearers */
7940 for (x = 0; x < pri->numchans; x++) {
7941 if (!pri->pvts[x])
7942 continue;
7943 if (pri->pvts[x]->call == c) {
7944 /* Found our call */
7945 if (principle != x) {
7946 if (option_verbose > 2)
7947 ast_verbose(VERBOSE_PREFIX_3 "Moving call from channel %d to channel %d\n",
7948 pri->pvts[x]->channel, pri->pvts[principle]->channel);
7949 if (pri->pvts[principle]->owner) {
7950 ast_log(LOG_WARNING, "Can't fix up channel from %d to %d because %d is already in use\n",
7951 pri->pvts[x]->channel, pri->pvts[principle]->channel, pri->pvts[principle]->channel);
7952 return -1;
7954 /* Fix it all up now */
7955 pri->pvts[principle]->owner = pri->pvts[x]->owner;
7956 if (pri->pvts[principle]->owner) {
7957 ast_string_field_build(pri->pvts[principle]->owner, name,
7958 "Zap/%d:%d-%d", pri->trunkgroup,
7959 pri->pvts[principle]->channel, 1);
7960 pri->pvts[principle]->owner->tech_pvt = pri->pvts[principle];
7961 pri->pvts[principle]->owner->fds[0] = pri->pvts[principle]->subs[SUB_REAL].zfd;
7962 pri->pvts[principle]->subs[SUB_REAL].owner = pri->pvts[x]->subs[SUB_REAL].owner;
7963 } else
7964 ast_log(LOG_WARNING, "Whoa, there's no owner, and we're having to fix up channel %d to channel %d\n", pri->pvts[x]->channel, pri->pvts[principle]->channel);
7965 pri->pvts[principle]->call = pri->pvts[x]->call;
7966 /* Free up the old channel, now not in use */
7967 pri->pvts[x]->subs[SUB_REAL].owner = NULL;
7968 pri->pvts[x]->owner = NULL;
7969 pri->pvts[x]->call = NULL;
7971 return principle;
7974 /* Now check for a CRV with no bearer */
7975 crv = pri->crvs;
7976 while (crv) {
7977 if (crv->call == c) {
7978 /* This is our match... Perform some basic checks */
7979 if (crv->bearer)
7980 ast_log(LOG_WARNING, "Trying to fix up call which already has a bearer which isn't the one we think it is\n");
7981 else if (pri->pvts[principle]->owner)
7982 ast_log(LOG_WARNING, "Tring to fix up a call to a bearer which already has an owner!\n");
7983 else {
7984 /* Looks good. Drop the pseudo channel now, clear up the assignment, and
7985 wakeup the potential sleeper */
7986 zt_close(crv->subs[SUB_REAL].zfd);
7987 pri->pvts[principle]->call = crv->call;
7988 pri_assign_bearer(crv, pri, pri->pvts[principle]);
7989 ast_log(LOG_DEBUG, "Assigning bearer %d/%d to CRV %d:%d\n",
7990 pri->pvts[principle]->logicalspan, pri->pvts[principle]->prioffset,
7991 pri->trunkgroup, crv->channel);
7992 wakeup_sub(crv, SUB_REAL, pri);
7994 return principle;
7996 crv = crv->next;
7998 ast_log(LOG_WARNING, "Call specified, but not found?\n");
7999 return -1;
8002 static void *do_idle_thread(void *vchan)
8004 struct ast_channel *chan = vchan;
8005 struct zt_pvt *pvt = chan->tech_pvt;
8006 struct ast_frame *f;
8007 char ex[80];
8008 /* Wait up to 30 seconds for an answer */
8009 int newms, ms = 30000;
8010 if (option_verbose > 2)
8011 ast_verbose(VERBOSE_PREFIX_3 "Initiating idle call on channel %s\n", chan->name);
8012 snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
8013 if (ast_call(chan, ex, 0)) {
8014 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
8015 ast_hangup(chan);
8016 return NULL;
8018 while ((newms = ast_waitfor(chan, ms)) > 0) {
8019 f = ast_read(chan);
8020 if (!f) {
8021 /* Got hangup */
8022 break;
8024 if (f->frametype == AST_FRAME_CONTROL) {
8025 switch (f->subclass) {
8026 case AST_CONTROL_ANSWER:
8027 /* Launch the PBX */
8028 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
8029 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
8030 chan->priority = 1;
8031 if (option_verbose > 3)
8032 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
8033 ast_pbx_run(chan);
8034 /* It's already hungup, return immediately */
8035 return NULL;
8036 case AST_CONTROL_BUSY:
8037 if (option_verbose > 3)
8038 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' busy, waiting...\n", chan->name);
8039 break;
8040 case AST_CONTROL_CONGESTION:
8041 if (option_verbose > 3)
8042 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' congested, waiting...\n", chan->name);
8043 break;
8046 ast_frfree(f);
8047 ms = newms;
8049 /* Hangup the channel since nothing happend */
8050 ast_hangup(chan);
8051 return NULL;
8054 #ifndef PRI_RESTART
8055 #error "Upgrade your libpri"
8056 #endif
8057 static void zt_pri_message(struct pri *pri, char *s)
8059 int x, y;
8060 int dchan = -1, span = -1;
8061 int dchancount = 0;
8063 if (pri) {
8064 for (x = 0; x < NUM_SPANS; x++) {
8065 for (y = 0; y < NUM_DCHANS; y++) {
8066 if (pris[x].dchans[y])
8067 dchancount++;
8069 if (pris[x].dchans[y] == pri)
8070 dchan = y;
8072 if (dchan >= 0) {
8073 span = x;
8074 break;
8076 dchancount = 0;
8078 if ((dchan >= 0) && (span >= 0)) {
8079 if (dchancount > 1)
8080 ast_verbose("[Span %d D-Channel %d]%s", span, dchan, s);
8081 else
8082 ast_verbose("%s", s);
8083 } else
8084 ast_log(LOG_ERROR, "PRI debug error: could not find pri associated it with debug message output\n");
8085 } else
8086 ast_verbose("%s", s);
8088 ast_mutex_lock(&pridebugfdlock);
8090 if (pridebugfd >= 0)
8091 write(pridebugfd, s, strlen(s));
8093 ast_mutex_unlock(&pridebugfdlock);
8096 static void zt_pri_error(struct pri *pri, char *s)
8098 int x, y;
8099 int dchan = -1, span = -1;
8100 int dchancount = 0;
8102 if (pri) {
8103 for (x = 0; x < NUM_SPANS; x++) {
8104 for (y = 0; y < NUM_DCHANS; y++) {
8105 if (pris[x].dchans[y])
8106 dchancount++;
8108 if (pris[x].dchans[y] == pri)
8109 dchan = y;
8111 if (dchan >= 0) {
8112 span = x;
8113 break;
8115 dchancount = 0;
8117 if ((dchan >= 0) && (span >= 0)) {
8118 if (dchancount > 1)
8119 ast_log(LOG_ERROR, "[Span %d D-Channel %d] PRI: %s", span, dchan, s);
8120 else
8121 ast_log(LOG_ERROR, "%s", s);
8122 } else
8123 ast_log(LOG_ERROR, "PRI debug error: could not find pri associated it with debug message output\n");
8124 } else
8125 ast_log(LOG_ERROR, "%s", s);
8127 ast_mutex_lock(&pridebugfdlock);
8129 if (pridebugfd >= 0)
8130 write(pridebugfd, s, strlen(s));
8132 ast_mutex_unlock(&pridebugfdlock);
8135 static int pri_check_restart(struct zt_pri *pri)
8137 do {
8138 pri->resetpos++;
8139 } while ((pri->resetpos < pri->numchans) &&
8140 (!pri->pvts[pri->resetpos] ||
8141 pri->pvts[pri->resetpos]->call ||
8142 pri->pvts[pri->resetpos]->resetting));
8143 if (pri->resetpos < pri->numchans) {
8144 /* Mark the channel as resetting and restart it */
8145 pri->pvts[pri->resetpos]->resetting = 1;
8146 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
8147 } else {
8148 pri->resetting = 0;
8149 time(&pri->lastreset);
8151 return 0;
8154 static int pri_hangup_all(struct zt_pvt *p, struct zt_pri *pri)
8156 int x;
8157 int redo;
8158 ast_mutex_unlock(&pri->lock);
8159 ast_mutex_lock(&p->lock);
8160 do {
8161 redo = 0;
8162 for (x = 0; x < 3; x++) {
8163 while (p->subs[x].owner && ast_mutex_trylock(&p->subs[x].owner->lock)) {
8164 redo++;
8165 ast_mutex_unlock(&p->lock);
8166 usleep(1);
8167 ast_mutex_lock(&p->lock);
8169 if (p->subs[x].owner) {
8170 ast_queue_hangup(p->subs[x].owner);
8171 ast_mutex_unlock(&p->subs[x].owner->lock);
8174 } while (redo);
8175 ast_mutex_unlock(&p->lock);
8176 ast_mutex_lock(&pri->lock);
8177 return 0;
8180 static char * redirectingreason2str(int redirectingreason)
8182 switch (redirectingreason) {
8183 case 0:
8184 return "UNKNOWN";
8185 case 1:
8186 return "BUSY";
8187 case 2:
8188 return "NO_REPLY";
8189 case 0xF:
8190 return "UNCONDITIONAL";
8191 default:
8192 return "NOREDIRECT";
8196 static void apply_plan_to_number(char *buf, size_t size, const struct zt_pri *pri, const char *number, const int plan)
8198 switch (plan) {
8199 case PRI_INTERNATIONAL_ISDN: /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
8200 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
8201 break;
8202 case PRI_NATIONAL_ISDN: /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
8203 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
8204 break;
8205 case PRI_LOCAL_ISDN: /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
8206 snprintf(buf, size, "%s%s", pri->localprefix, number);
8207 break;
8208 case PRI_PRIVATE: /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
8209 snprintf(buf, size, "%s%s", pri->privateprefix, number);
8210 break;
8211 case PRI_UNKNOWN: /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
8212 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
8213 break;
8214 default: /* other Q.931 dialplan => don't twiddle with callingnum */
8215 snprintf(buf, size, "%s", number);
8216 break;
8220 static int zt_setlaw(int zfd, int law)
8222 int res;
8223 res = ioctl(zfd, ZT_SETLAW, &law);
8224 if (res)
8225 return res;
8226 return 0;
8229 static void *pri_dchannel(void *vpri)
8231 struct zt_pri *pri = vpri;
8232 pri_event *e;
8233 struct pollfd fds[NUM_DCHANS];
8234 int res;
8235 int chanpos = 0;
8236 int x;
8237 int haveidles;
8238 int activeidles;
8239 int nextidle = -1;
8240 struct ast_channel *c;
8241 struct timeval tv, lowest, *next;
8242 struct timeval lastidle = { 0, 0 };
8243 int doidling=0;
8244 char *cc;
8245 char idlen[80];
8246 struct ast_channel *idle;
8247 pthread_t p;
8248 time_t t;
8249 int i, which=-1;
8250 int numdchans;
8251 int cause=0;
8252 struct zt_pvt *crv;
8253 pthread_t threadid;
8254 pthread_attr_t attr;
8255 char ani2str[6];
8256 char plancallingnum[256];
8257 char plancallingani[256];
8258 char calledtonstr[10];
8260 pthread_attr_init(&attr);
8261 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
8263 gettimeofday(&lastidle, NULL);
8264 if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
8265 /* Need to do idle dialing, check to be sure though */
8266 cc = strchr(pri->idleext, '@');
8267 if (cc) {
8268 *cc = '\0';
8269 cc++;
8270 ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
8271 #if 0
8272 /* Extensions may not be loaded yet */
8273 if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
8274 ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
8275 else
8276 #endif
8277 doidling = 1;
8278 } else
8279 ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
8281 for (;;) {
8282 for (i = 0; i < NUM_DCHANS; i++) {
8283 if (!pri->dchannels[i])
8284 break;
8285 fds[i].fd = pri->fds[i];
8286 fds[i].events = POLLIN | POLLPRI;
8287 fds[i].revents = 0;
8289 numdchans = i;
8290 time(&t);
8291 ast_mutex_lock(&pri->lock);
8292 if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->resetinterval > 0)) {
8293 if (pri->resetting && pri_is_up(pri)) {
8294 if (pri->resetpos < 0)
8295 pri_check_restart(pri);
8296 } else {
8297 if (!pri->resetting && (t - pri->lastreset) >= pri->resetinterval) {
8298 pri->resetting = 1;
8299 pri->resetpos = -1;
8303 /* Look for any idle channels if appropriate */
8304 if (doidling && pri_is_up(pri)) {
8305 nextidle = -1;
8306 haveidles = 0;
8307 activeidles = 0;
8308 for (x = pri->numchans; x >= 0; x--) {
8309 if (pri->pvts[x] && !pri->pvts[x]->owner &&
8310 !pri->pvts[x]->call) {
8311 if (haveidles < pri->minunused) {
8312 haveidles++;
8313 } else if (!pri->pvts[x]->resetting) {
8314 nextidle = x;
8315 break;
8317 } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
8318 activeidles++;
8320 if (nextidle > -1) {
8321 if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
8322 /* Don't create a new idle call more than once per second */
8323 snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
8324 idle = zt_request("Zap", AST_FORMAT_ULAW, idlen, &cause);
8325 if (idle) {
8326 pri->pvts[nextidle]->isidlecall = 1;
8327 if (ast_pthread_create_background(&p, NULL, do_idle_thread, idle)) {
8328 ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
8329 zt_hangup(idle);
8331 } else
8332 ast_log(LOG_WARNING, "Unable to request channel 'Zap/%s' for idle call\n", idlen);
8333 gettimeofday(&lastidle, NULL);
8335 } else if ((haveidles < pri->minunused) &&
8336 (activeidles > pri->minidle)) {
8337 /* Mark something for hangup if there is something
8338 that can be hungup */
8339 for (x = pri->numchans; x >= 0; x--) {
8340 /* find a candidate channel */
8341 if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
8342 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8343 haveidles++;
8344 /* Stop if we have enough idle channels or
8345 can't spare any more active idle ones */
8346 if ((haveidles >= pri->minunused) ||
8347 (activeidles <= pri->minidle))
8348 break;
8353 /* Start with reasonable max */
8354 lowest = ast_tv(60, 0);
8355 for (i = 0; i < NUM_DCHANS; i++) {
8356 /* Find lowest available d-channel */
8357 if (!pri->dchannels[i])
8358 break;
8359 if ((next = pri_schedule_next(pri->dchans[i]))) {
8360 /* We need relative time here */
8361 tv = ast_tvsub(*next, ast_tvnow());
8362 if (tv.tv_sec < 0) {
8363 tv = ast_tv(0,0);
8365 if (doidling || pri->resetting) {
8366 if (tv.tv_sec > 1) {
8367 tv = ast_tv(1, 0);
8369 } else {
8370 if (tv.tv_sec > 60) {
8371 tv = ast_tv(60, 0);
8374 } else if (doidling || pri->resetting) {
8375 /* Make sure we stop at least once per second if we're
8376 monitoring idle channels */
8377 tv = ast_tv(1,0);
8378 } else {
8379 /* Don't poll for more than 60 seconds */
8380 tv = ast_tv(60, 0);
8382 if (!i || ast_tvcmp(tv, lowest) < 0) {
8383 lowest = tv;
8386 ast_mutex_unlock(&pri->lock);
8388 e = NULL;
8389 res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
8391 ast_mutex_lock(&pri->lock);
8392 if (!res) {
8393 for (which = 0; which < NUM_DCHANS; which++) {
8394 if (!pri->dchans[which])
8395 break;
8396 /* Just a timeout, run the scheduler */
8397 e = pri_schedule_run(pri->dchans[which]);
8398 if (e)
8399 break;
8401 } else if (res > -1) {
8402 for (which = 0; which < NUM_DCHANS; which++) {
8403 if (!pri->dchans[which])
8404 break;
8405 if (fds[which].revents & POLLPRI) {
8406 /* Check for an event */
8407 x = 0;
8408 res = ioctl(pri->fds[which], ZT_GETEVENT, &x);
8409 if (x)
8410 ast_log(LOG_NOTICE, "PRI got event: %s (%d) on %s D-channel of span %d\n", event2str(x), x, pri_order(which), pri->span);
8411 /* Keep track of alarm state */
8412 if (x == ZT_EVENT_ALARM) {
8413 pri->dchanavail[which] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
8414 pri_find_dchan(pri);
8415 } else if (x == ZT_EVENT_NOALARM) {
8416 pri->dchanavail[which] |= DCHAN_NOTINALARM;
8417 pri_restart(pri->dchans[which]);
8420 if (option_debug)
8421 ast_log(LOG_DEBUG, "Got event %s (%d) on D-channel for span %d\n", event2str(x), x, pri->span);
8422 } else if (fds[which].revents & POLLIN) {
8423 e = pri_check_event(pri->dchans[which]);
8425 if (e)
8426 break;
8428 } else if (errno != EINTR)
8429 ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
8431 if (e) {
8432 if (pri->debug)
8433 pri_dump_event(pri->dchans[which], e);
8434 if (e->e != PRI_EVENT_DCHAN_DOWN)
8435 pri->dchanavail[which] |= DCHAN_UP;
8436 switch (e->e) {
8437 case PRI_EVENT_DCHAN_UP:
8438 if (option_verbose > 1)
8439 ast_verbose(VERBOSE_PREFIX_2 "%s D-Channel on span %d up\n", pri_order(which), pri->span);
8440 pri->dchanavail[which] |= DCHAN_UP;
8441 if (!pri->pri) pri_find_dchan(pri);
8443 /* Note presense of D-channel */
8444 time(&pri->lastreset);
8446 /* Restart in 5 seconds */
8447 if (pri->resetinterval > -1) {
8448 pri->lastreset -= pri->resetinterval;
8449 pri->lastreset += 5;
8451 pri->resetting = 0;
8452 /* Take the channels from inalarm condition */
8453 for (i = 0; i < pri->numchans; i++)
8454 if (pri->pvts[i]) {
8455 pri->pvts[i]->inalarm = 0;
8457 break;
8458 case PRI_EVENT_DCHAN_DOWN:
8459 if (option_verbose > 1)
8460 ast_verbose(VERBOSE_PREFIX_2 "%s D-Channel on span %d down\n", pri_order(which), pri->span);
8461 pri->dchanavail[which] &= ~DCHAN_UP;
8462 pri_find_dchan(pri);
8463 if (!pri_is_up(pri)) {
8464 pri->resetting = 0;
8465 /* Hangup active channels and put them in alarm mode */
8466 for (i = 0; i < pri->numchans; i++) {
8467 struct zt_pvt *p = pri->pvts[i];
8468 if (p) {
8469 if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
8470 /* T309 is not enabled : hangup calls when alarm occurs */
8471 if (p->call) {
8472 if (p->pri && p->pri->pri) {
8473 pri_hangup(p->pri->pri, p->call, -1);
8474 pri_destroycall(p->pri->pri, p->call);
8475 p->call = NULL;
8476 } else
8477 ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
8479 if (p->realcall) {
8480 pri_hangup_all(p->realcall, pri);
8481 } else if (p->owner)
8482 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8484 p->inalarm = 1;
8488 break;
8489 case PRI_EVENT_RESTART:
8490 if (e->restart.channel > -1) {
8491 chanpos = pri_find_principle(pri, e->restart.channel);
8492 if (chanpos < 0)
8493 ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
8494 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
8495 else {
8496 if (option_verbose > 2)
8497 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d restarted on span %d\n",
8498 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
8499 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8500 if (pri->pvts[chanpos]->call) {
8501 pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
8502 pri->pvts[chanpos]->call = NULL;
8504 /* Force soft hangup if appropriate */
8505 if (pri->pvts[chanpos]->realcall)
8506 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
8507 else if (pri->pvts[chanpos]->owner)
8508 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8509 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8511 } else {
8512 if (option_verbose > 2)
8513 ast_verbose(VERBOSE_PREFIX_2 "Restart on requested on entire span %d\n", pri->span);
8514 for (x = 0; x < pri->numchans; x++)
8515 if (pri->pvts[x]) {
8516 ast_mutex_lock(&pri->pvts[x]->lock);
8517 if (pri->pvts[x]->call) {
8518 pri_destroycall(pri->pri, pri->pvts[x]->call);
8519 pri->pvts[x]->call = NULL;
8521 if (pri->pvts[chanpos]->realcall)
8522 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
8523 else if (pri->pvts[x]->owner)
8524 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8525 ast_mutex_unlock(&pri->pvts[x]->lock);
8528 break;
8529 case PRI_EVENT_KEYPAD_DIGIT:
8530 chanpos = pri_find_principle(pri, e->digit.channel);
8531 if (chanpos < 0) {
8532 ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
8533 PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
8534 } else {
8535 chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
8536 if (chanpos > -1) {
8537 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8538 /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
8539 if (pri->overlapdial && pri->pvts[chanpos]->call==e->digit.call && pri->pvts[chanpos]->owner) {
8540 /* how to do that */
8541 int digitlen = strlen(e->digit.digits);
8542 char digit;
8543 int i;
8544 for (i = 0; i < digitlen; i++) {
8545 digit = e->digit.digits[i];
8547 struct ast_frame f = { AST_FRAME_DTMF, digit, };
8548 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8552 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8555 break;
8557 case PRI_EVENT_INFO_RECEIVED:
8558 chanpos = pri_find_principle(pri, e->ring.channel);
8559 if (chanpos < 0) {
8560 ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
8561 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8562 } else {
8563 chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
8564 if (chanpos > -1) {
8565 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8566 /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
8567 if (pri->overlapdial && pri->pvts[chanpos]->call==e->ring.call && pri->pvts[chanpos]->owner) {
8568 /* how to do that */
8569 int digitlen = strlen(e->ring.callednum);
8570 char digit;
8571 int i;
8572 for (i = 0; i < digitlen; i++) {
8573 digit = e->ring.callednum[i];
8575 struct ast_frame f = { AST_FRAME_DTMF, digit, };
8576 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8580 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8583 break;
8584 case PRI_EVENT_RING:
8585 crv = NULL;
8586 if (e->ring.channel == -1)
8587 chanpos = pri_find_empty_chan(pri, 1);
8588 else
8589 chanpos = pri_find_principle(pri, e->ring.channel);
8590 /* if no channel specified find one empty */
8591 if (chanpos < 0) {
8592 ast_log(LOG_WARNING, "Ring requested on unconfigured channel %d/%d span %d\n",
8593 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8594 } else {
8595 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8596 if (pri->pvts[chanpos]->owner) {
8597 if (pri->pvts[chanpos]->call == e->ring.call) {
8598 ast_log(LOG_WARNING, "Duplicate setup requested on channel %d/%d already in use on span %d\n",
8599 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8600 break;
8601 } else {
8602 ast_log(LOG_WARNING, "Ring requested on channel %d/%d already in use on span %d. Hanging up owner.\n",
8603 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8604 if (pri->pvts[chanpos]->realcall)
8605 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
8606 else
8607 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8608 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8609 chanpos = -1;
8612 if (chanpos > -1)
8613 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8615 if ((chanpos < 0) && (e->ring.flexible))
8616 chanpos = pri_find_empty_chan(pri, 1);
8617 if (chanpos > -1) {
8618 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8619 if (pri->switchtype == PRI_SWITCH_GR303_TMC) {
8620 /* Should be safe to lock CRV AFAIK while bearer is still locked */
8621 crv = pri_find_crv(pri, pri_get_crv(pri->pri, e->ring.call, NULL));
8622 if (crv)
8623 ast_mutex_lock(&crv->lock);
8624 if (!crv || crv->owner) {
8625 pri->pvts[chanpos]->call = NULL;
8626 if (crv) {
8627 if (crv->owner)
8628 crv->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8629 ast_log(LOG_WARNING, "Call received for busy CRV %d on span %d\n", pri_get_crv(pri->pri, e->ring.call, NULL), pri->span);
8630 } else
8631 ast_log(LOG_NOTICE, "Call received for unconfigured CRV %d on span %d\n", pri_get_crv(pri->pri, e->ring.call, NULL), pri->span);
8632 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_INVALID_CALL_REFERENCE);
8633 if (crv)
8634 ast_mutex_unlock(&crv->lock);
8635 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8636 break;
8639 pri->pvts[chanpos]->call = e->ring.call;
8640 apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri, e->ring.callingnum, e->ring.callingplan);
8641 if (pri->pvts[chanpos]->use_callerid) {
8642 ast_shrink_phone_number(plancallingnum);
8643 ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
8644 #ifdef PRI_ANI
8645 if (!ast_strlen_zero(e->ring.callingani)) {
8646 apply_plan_to_number(plancallingani, sizeof(plancallingani), pri, e->ring.callingani, e->ring.callingplanani);
8647 ast_shrink_phone_number(plancallingani);
8648 ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani, sizeof(pri->pvts[chanpos]->cid_ani));
8649 } else {
8650 pri->pvts[chanpos]->cid_ani[0] = '\0';
8652 #endif
8653 ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
8654 pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
8655 } else {
8656 pri->pvts[chanpos]->cid_num[0] = '\0';
8657 pri->pvts[chanpos]->cid_ani[0] = '\0';
8658 pri->pvts[chanpos]->cid_name[0] = '\0';
8659 pri->pvts[chanpos]->cid_ton = 0;
8661 apply_plan_to_number(pri->pvts[chanpos]->rdnis, sizeof(pri->pvts[chanpos]->rdnis), pri,
8662 e->ring.redirectingnum, e->ring.callingplanrdnis);
8663 /* If immediate=yes go to s|1 */
8664 if (pri->pvts[chanpos]->immediate) {
8665 if (option_verbose > 2)
8666 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of immediate=yes\n");
8667 pri->pvts[chanpos]->exten[0] = 's';
8668 pri->pvts[chanpos]->exten[1] = '\0';
8670 /* Get called number */
8671 else if (!ast_strlen_zero(e->ring.callednum)) {
8672 ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
8673 ast_copy_string(pri->pvts[chanpos]->dnid, e->ring.callednum, sizeof(pri->pvts[chanpos]->dnid));
8674 } else
8675 pri->pvts[chanpos]->exten[0] = '\0';
8676 /* Set DNID on all incoming calls -- even immediate */
8677 if (!ast_strlen_zero(e->ring.callednum))
8678 ast_copy_string(pri->pvts[chanpos]->dnid, e->ring.callednum, sizeof(pri->pvts[chanpos]->dnid));
8679 /* No number yet, but received "sending complete"? */
8680 if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
8681 if (option_verbose > 2)
8682 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of Complete received\n");
8683 pri->pvts[chanpos]->exten[0] = 's';
8684 pri->pvts[chanpos]->exten[1] = '\0';
8686 /* Make sure extension exists (or in overlap dial mode, can exist) */
8687 if ((pri->overlapdial && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
8688 ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
8689 /* Setup law */
8690 int law;
8691 if (pri->switchtype != PRI_SWITCH_GR303_TMC) {
8692 /* Set to audio mode at this point */
8693 law = 1;
8694 if (ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &law) == -1)
8695 ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", pri->pvts[chanpos]->channel, law);
8697 if (e->ring.layer1 == PRI_LAYER_1_ALAW)
8698 law = ZT_LAW_ALAW;
8699 else
8700 law = ZT_LAW_MULAW;
8701 res = zt_setlaw(pri->pvts[chanpos]->subs[SUB_REAL].zfd, law);
8702 if (res < 0)
8703 ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pri->pvts[chanpos]->channel);
8704 res = set_actual_gain(pri->pvts[chanpos]->subs[SUB_REAL].zfd, 0, pri->pvts[chanpos]->rxgain, pri->pvts[chanpos]->txgain, law);
8705 if (res < 0)
8706 ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pri->pvts[chanpos]->channel);
8707 if (e->ring.complete || !pri->overlapdial) {
8708 /* Just announce proceeding */
8709 pri->pvts[chanpos]->proceeding = 1;
8710 pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
8711 } else {
8712 if (pri->switchtype != PRI_SWITCH_GR303_TMC)
8713 pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
8714 else
8715 pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
8717 /* Get the use_callingpres state */
8718 pri->pvts[chanpos]->callingpres = e->ring.callingpres;
8720 /* Start PBX */
8721 if (pri->overlapdial && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
8722 /* Release the PRI lock while we create the channel */
8723 ast_mutex_unlock(&pri->lock);
8724 if (crv) {
8725 /* Set bearer and such */
8726 pri_assign_bearer(crv, pri, pri->pvts[chanpos]);
8727 c = zt_new(crv, AST_STATE_RESERVED, 0, SUB_REAL, law, e->ring.ctype);
8728 pri->pvts[chanpos]->owner = &inuse;
8729 ast_log(LOG_DEBUG, "Started up crv %d:%d on bearer channel %d\n", pri->trunkgroup, crv->channel, crv->bearer->channel);
8730 } else {
8731 c = zt_new(pri->pvts[chanpos], AST_STATE_RESERVED, 0, SUB_REAL, law, e->ring.ctype);
8733 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
8734 pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
8736 if (e->ring.ani2 >= 0) {
8737 snprintf(ani2str, 5, "%.2d", e->ring.ani2);
8738 pbx_builtin_setvar_helper(c, "ANI2", ani2str);
8741 #ifdef SUPPORT_USERUSER
8742 if (!ast_strlen_zero(e->ring.useruserinfo)) {
8743 pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
8745 #endif
8747 snprintf(calledtonstr, sizeof(calledtonstr)-1, "%d", e->ring.calledplan);
8748 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
8749 if (e->ring.redirectingreason >= 0)
8750 pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
8752 ast_mutex_lock(&pri->lock);
8753 if (c && !ast_pthread_create(&threadid, &attr, ss_thread, c)) {
8754 if (option_verbose > 2)
8755 ast_verbose(VERBOSE_PREFIX_3 "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
8756 plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
8757 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8758 } else {
8759 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
8760 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8761 if (c)
8762 ast_hangup(c);
8763 else {
8764 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
8765 pri->pvts[chanpos]->call = NULL;
8768 } else {
8769 ast_mutex_unlock(&pri->lock);
8770 /* Release PRI lock while we create the channel */
8771 c = zt_new(pri->pvts[chanpos], AST_STATE_RING, 1, SUB_REAL, law, e->ring.ctype);
8772 ast_mutex_lock(&pri->lock);
8773 if (c) {
8774 char calledtonstr[10];
8775 if (e->ring.ani2 >= 0) {
8776 snprintf(ani2str, 5, "%d", e->ring.ani2);
8777 pbx_builtin_setvar_helper(c, "ANI2", ani2str);
8780 #ifdef SUPPORT_USERUSER
8781 if (!ast_strlen_zero(e->ring.useruserinfo)) {
8782 pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
8784 #endif
8786 if (e->ring.redirectingreason >= 0)
8787 pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
8789 snprintf(calledtonstr, sizeof(calledtonstr)-1, "%d", e->ring.calledplan);
8790 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
8791 if (option_verbose > 2)
8792 ast_verbose(VERBOSE_PREFIX_3 "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
8793 plancallingnum, pri->pvts[chanpos]->exten,
8794 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8795 zt_enable_ec(pri->pvts[chanpos]);
8796 } else {
8797 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
8798 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8799 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
8800 pri->pvts[chanpos]->call = NULL;
8803 } else {
8804 if (option_verbose > 2)
8805 ast_verbose(VERBOSE_PREFIX_3 "Extension '%s' in context '%s' from '%s' does not exist. Rejecting call on channel %d/%d, span %d\n",
8806 pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context, pri->pvts[chanpos]->cid_num, pri->pvts[chanpos]->logicalspan,
8807 pri->pvts[chanpos]->prioffset, pri->span);
8808 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
8809 pri->pvts[chanpos]->call = NULL;
8810 pri->pvts[chanpos]->exten[0] = '\0';
8812 if (crv)
8813 ast_mutex_unlock(&crv->lock);
8814 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8815 } else
8816 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
8817 break;
8818 case PRI_EVENT_RINGING:
8819 chanpos = pri_find_principle(pri, e->ringing.channel);
8820 if (chanpos < 0) {
8821 ast_log(LOG_WARNING, "Ringing requested on unconfigured channel %d/%d span %d\n",
8822 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
8823 } else {
8824 chanpos = pri_fixup_principle(pri, chanpos, e->ringing.call);
8825 if (chanpos < 0) {
8826 ast_log(LOG_WARNING, "Ringing requested on channel %d/%d not in use on span %d\n",
8827 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
8828 } else {
8829 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8830 if (ast_strlen_zero(pri->pvts[chanpos]->dop.dialstr)) {
8831 zt_enable_ec(pri->pvts[chanpos]);
8832 pri->pvts[chanpos]->subs[SUB_REAL].needringing = 1;
8833 pri->pvts[chanpos]->alerting = 1;
8834 } else
8835 ast_log(LOG_DEBUG, "Deferring ringing notification because of extra digits to dial...\n");
8836 #ifdef PRI_PROGRESS_MASK
8837 if (e->ringing.progressmask & PRI_PROG_INBAND_AVAILABLE) {
8838 #else
8839 if (e->ringing.progress == 8) {
8840 #endif
8841 /* Now we can do call progress detection */
8842 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
8843 /* RINGING detection isn't required because we got ALERTING signal */
8844 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features & ~DSP_PROGRESS_RINGING);
8845 pri->pvts[chanpos]->dsp_features = 0;
8849 #ifdef SUPPORT_USERUSER
8850 if (!ast_strlen_zero(e->ringing.useruserinfo)) {
8851 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->ringing.useruserinfo);
8853 #endif
8855 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8858 break;
8859 case PRI_EVENT_PROGRESS:
8860 /* Get chan value if e->e is not PRI_EVNT_RINGING */
8861 chanpos = pri_find_principle(pri, e->proceeding.channel);
8862 if (chanpos > -1) {
8863 #ifdef PRI_PROGRESS_MASK
8864 if ((!pri->pvts[chanpos]->progress) || (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE)) {
8865 #else
8866 if ((!pri->pvts[chanpos]->progress) || (e->proceeding.progress == 8)) {
8867 #endif
8868 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, };
8870 if (e->proceeding.cause > -1) {
8871 if (option_verbose > 2)
8872 ast_verbose(VERBOSE_PREFIX_3 "PROGRESS with cause code %d received\n", e->proceeding.cause);
8874 /* Work around broken, out of spec USER_BUSY cause in a progress message */
8875 if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
8876 if (pri->pvts[chanpos]->owner) {
8877 if (option_verbose > 2)
8878 ast_verbose(VERBOSE_PREFIX_3 "PROGRESS with 'user busy' received, signaling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
8880 pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
8881 f.subclass = AST_CONTROL_BUSY;
8886 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8887 ast_log(LOG_DEBUG, "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
8888 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
8889 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8890 #ifdef PRI_PROGRESS_MASK
8891 if (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE) {
8892 #else
8893 if (e->proceeding.progress == 8) {
8894 #endif
8895 /* Now we can do call progress detection */
8896 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
8897 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
8898 pri->pvts[chanpos]->dsp_features = 0;
8901 pri->pvts[chanpos]->progress = 1;
8902 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8905 break;
8906 case PRI_EVENT_PROCEEDING:
8907 chanpos = pri_find_principle(pri, e->proceeding.channel);
8908 if (chanpos > -1) {
8909 if (!pri->pvts[chanpos]->proceeding) {
8910 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROCEEDING, };
8912 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8913 ast_log(LOG_DEBUG, "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
8914 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
8915 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8916 #ifdef PRI_PROGRESS_MASK
8917 if (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE) {
8918 #else
8919 if (e->proceeding.progress == 8) {
8920 #endif
8921 /* Now we can do call progress detection */
8922 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
8923 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
8924 pri->pvts[chanpos]->dsp_features = 0;
8926 /* Bring voice path up */
8927 f.subclass = AST_CONTROL_PROGRESS;
8928 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8930 pri->pvts[chanpos]->proceeding = 1;
8931 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8934 break;
8935 case PRI_EVENT_FACNAME:
8936 chanpos = pri_find_principle(pri, e->facname.channel);
8937 if (chanpos < 0) {
8938 ast_log(LOG_WARNING, "Facility Name requested on unconfigured channel %d/%d span %d\n",
8939 PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
8940 } else {
8941 chanpos = pri_fixup_principle(pri, chanpos, e->facname.call);
8942 if (chanpos < 0) {
8943 ast_log(LOG_WARNING, "Facility Name requested on channel %d/%d not in use on span %d\n",
8944 PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
8945 } else {
8946 /* Re-use *69 field for PRI */
8947 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8948 ast_copy_string(pri->pvts[chanpos]->lastcid_num, e->facname.callingnum, sizeof(pri->pvts[chanpos]->lastcid_num));
8949 ast_copy_string(pri->pvts[chanpos]->lastcid_name, e->facname.callingname, sizeof(pri->pvts[chanpos]->lastcid_name));
8950 pri->pvts[chanpos]->subs[SUB_REAL].needcallerid =1;
8951 zt_enable_ec(pri->pvts[chanpos]);
8952 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8955 break;
8956 case PRI_EVENT_ANSWER:
8957 chanpos = pri_find_principle(pri, e->answer.channel);
8958 if (chanpos < 0) {
8959 ast_log(LOG_WARNING, "Answer on unconfigured channel %d/%d span %d\n",
8960 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
8961 } else {
8962 chanpos = pri_fixup_principle(pri, chanpos, e->answer.call);
8963 if (chanpos < 0) {
8964 ast_log(LOG_WARNING, "Answer requested on channel %d/%d not in use on span %d\n",
8965 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
8966 } else {
8967 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8968 /* Now we can do call progress detection */
8970 /* We changed this so it turns on the DSP no matter what... progress or no progress.
8971 * By this time, we need DTMF detection and other features that were previously disabled
8972 * -- Matt F */
8973 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
8974 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
8975 pri->pvts[chanpos]->dsp_features = 0;
8977 if (pri->pvts[chanpos]->realcall && (pri->pvts[chanpos]->realcall->sig == SIG_FXSKS)) {
8978 ast_log(LOG_DEBUG, "Starting up GR-303 trunk now that we got CONNECT...\n");
8979 x = ZT_START;
8980 res = ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_HOOK, &x);
8981 if (res < 0) {
8982 if (errno != EINPROGRESS) {
8983 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
8986 } else if (!ast_strlen_zero(pri->pvts[chanpos]->dop.dialstr)) {
8987 pri->pvts[chanpos]->dialing = 1;
8988 /* Send any "w" waited stuff */
8989 res = ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_DIAL, &pri->pvts[chanpos]->dop);
8990 if (res < 0) {
8991 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", pri->pvts[chanpos]->channel);
8992 pri->pvts[chanpos]->dop.dialstr[0] = '\0';
8993 } else
8994 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", pri->pvts[chanpos]->dop.dialstr);
8995 pri->pvts[chanpos]->dop.dialstr[0] = '\0';
8996 } else if (pri->pvts[chanpos]->confirmanswer) {
8997 ast_log(LOG_DEBUG, "Waiting on answer confirmation on channel %d!\n", pri->pvts[chanpos]->channel);
8998 } else {
8999 pri->pvts[chanpos]->subs[SUB_REAL].needanswer =1;
9000 /* Enable echo cancellation if it's not on already */
9001 zt_enable_ec(pri->pvts[chanpos]);
9004 #ifdef SUPPORT_USERUSER
9005 if (!ast_strlen_zero(e->answer.useruserinfo)) {
9006 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->answer.useruserinfo);
9008 #endif
9010 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9013 break;
9014 case PRI_EVENT_HANGUP:
9015 chanpos = pri_find_principle(pri, e->hangup.channel);
9016 if (chanpos < 0) {
9017 ast_log(LOG_WARNING, "Hangup requested on unconfigured channel %d/%d span %d\n",
9018 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9019 } else {
9020 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9021 if (chanpos > -1) {
9022 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9023 if (!pri->pvts[chanpos]->alreadyhungup) {
9024 /* we're calling here zt_hangup so once we get there we need to clear p->call after calling pri_hangup */
9025 pri->pvts[chanpos]->alreadyhungup = 1;
9026 if (pri->pvts[chanpos]->realcall)
9027 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9028 else if (pri->pvts[chanpos]->owner) {
9029 /* Queue a BUSY instead of a hangup if our cause is appropriate */
9030 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
9031 switch (e->hangup.cause) {
9032 case PRI_CAUSE_USER_BUSY:
9033 pri->pvts[chanpos]->subs[SUB_REAL].needbusy =1;
9034 break;
9035 case PRI_CAUSE_CALL_REJECTED:
9036 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
9037 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
9038 case PRI_CAUSE_SWITCH_CONGESTION:
9039 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
9040 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
9041 pri->pvts[chanpos]->subs[SUB_REAL].needcongestion =1;
9042 break;
9043 default:
9044 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9047 if (option_verbose > 2)
9048 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d got hangup\n",
9049 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
9050 } else {
9051 pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
9052 pri->pvts[chanpos]->call = NULL;
9054 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
9055 if (option_verbose > 2)
9056 ast_verbose(VERBOSE_PREFIX_3 "Forcing restart of channel %d/%d on span %d since channel reported in use\n",
9057 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9058 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
9059 pri->pvts[chanpos]->resetting = 1;
9061 if (e->hangup.aoc_units > -1)
9062 if (option_verbose > 2)
9063 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
9064 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
9066 #ifdef SUPPORT_USERUSER
9067 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
9068 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->hangup.useruserinfo);
9070 #endif
9072 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9073 } else {
9074 ast_log(LOG_WARNING, "Hangup on bad channel %d/%d on span %d\n",
9075 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9078 break;
9079 #ifndef PRI_EVENT_HANGUP_REQ
9080 #error please update libpri
9081 #endif
9082 case PRI_EVENT_HANGUP_REQ:
9083 chanpos = pri_find_principle(pri, e->hangup.channel);
9084 if (chanpos < 0) {
9085 ast_log(LOG_WARNING, "Hangup REQ requested on unconfigured channel %d/%d span %d\n",
9086 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9087 } else {
9088 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9089 if (chanpos > -1) {
9090 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9091 if (pri->pvts[chanpos]->realcall)
9092 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9093 else if (pri->pvts[chanpos]->owner) {
9094 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
9095 switch (e->hangup.cause) {
9096 case PRI_CAUSE_USER_BUSY:
9097 pri->pvts[chanpos]->subs[SUB_REAL].needbusy =1;
9098 break;
9099 case PRI_CAUSE_CALL_REJECTED:
9100 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
9101 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
9102 case PRI_CAUSE_SWITCH_CONGESTION:
9103 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
9104 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
9105 pri->pvts[chanpos]->subs[SUB_REAL].needcongestion =1;
9106 break;
9107 default:
9108 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9110 if (option_verbose > 2)
9111 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d got hangup request\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9112 if (e->hangup.aoc_units > -1)
9113 if (option_verbose > 2)
9114 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
9115 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
9116 } else {
9117 pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
9118 pri->pvts[chanpos]->call = NULL;
9120 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
9121 if (option_verbose > 2)
9122 ast_verbose(VERBOSE_PREFIX_3 "Forcing restart of channel %d/%d span %d since channel reported in use\n",
9123 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9124 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
9125 pri->pvts[chanpos]->resetting = 1;
9128 #ifdef SUPPORT_USERUSER
9129 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
9130 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->hangup.useruserinfo);
9132 #endif
9134 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9135 } else {
9136 ast_log(LOG_WARNING, "Hangup REQ on bad channel %d/%d on span %d\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9139 break;
9140 case PRI_EVENT_HANGUP_ACK:
9141 chanpos = pri_find_principle(pri, e->hangup.channel);
9142 if (chanpos < 0) {
9143 ast_log(LOG_WARNING, "Hangup ACK requested on unconfigured channel number %d/%d span %d\n",
9144 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9145 } else {
9146 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9147 if (chanpos > -1) {
9148 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9149 pri->pvts[chanpos]->call = NULL;
9150 pri->pvts[chanpos]->resetting = 0;
9151 if (pri->pvts[chanpos]->owner) {
9152 if (option_verbose > 2)
9153 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d got hangup ACK\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9156 #ifdef SUPPORT_USERUSER
9157 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
9158 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->hangup.useruserinfo);
9160 #endif
9162 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9165 break;
9166 case PRI_EVENT_CONFIG_ERR:
9167 ast_log(LOG_WARNING, "PRI Error on span %d: %s\n", pri->trunkgroup, e->err.err);
9168 break;
9169 case PRI_EVENT_RESTART_ACK:
9170 chanpos = pri_find_principle(pri, e->restartack.channel);
9171 if (chanpos < 0) {
9172 /* Sometime switches (e.g. I421 / British Telecom) don't give us the
9173 channel number, so we have to figure it out... This must be why
9174 everybody resets exactly a channel at a time. */
9175 for (x = 0; x < pri->numchans; x++) {
9176 if (pri->pvts[x] && pri->pvts[x]->resetting) {
9177 chanpos = x;
9178 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9179 ast_log(LOG_DEBUG, "Assuming restart ack is really for channel %d/%d span %d\n", pri->pvts[chanpos]->logicalspan,
9180 pri->pvts[chanpos]->prioffset, pri->span);
9181 if (pri->pvts[chanpos]->realcall)
9182 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9183 else if (pri->pvts[chanpos]->owner) {
9184 ast_log(LOG_WARNING, "Got restart ack on channel %d/%d with owner on span %d\n", pri->pvts[chanpos]->logicalspan,
9185 pri->pvts[chanpos]->prioffset, pri->span);
9186 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9188 pri->pvts[chanpos]->resetting = 0;
9189 if (option_verbose > 2)
9190 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
9191 pri->pvts[chanpos]->prioffset, pri->span);
9192 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9193 if (pri->resetting)
9194 pri_check_restart(pri);
9195 break;
9198 if (chanpos < 0) {
9199 ast_log(LOG_WARNING, "Restart ACK requested on strange channel %d/%d span %d\n",
9200 PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
9202 } else {
9203 if (pri->pvts[chanpos]) {
9204 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9205 if (pri->pvts[chanpos]->realcall)
9206 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9207 else if (pri->pvts[chanpos]->owner) {
9208 ast_log(LOG_WARNING, "Got restart ack on channel %d/%d span %d with owner\n",
9209 PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
9210 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9212 pri->pvts[chanpos]->resetting = 0;
9213 if (option_verbose > 2)
9214 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
9215 pri->pvts[chanpos]->prioffset, pri->span);
9216 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9217 if (pri->resetting)
9218 pri_check_restart(pri);
9221 break;
9222 case PRI_EVENT_SETUP_ACK:
9223 chanpos = pri_find_principle(pri, e->setup_ack.channel);
9224 if (chanpos < 0) {
9225 ast_log(LOG_WARNING, "Received SETUP_ACKNOWLEDGE on unconfigured channel %d/%d span %d\n",
9226 PRI_SPAN(e->setup_ack.channel), PRI_CHANNEL(e->setup_ack.channel), pri->span);
9227 } else {
9228 chanpos = pri_fixup_principle(pri, chanpos, e->setup_ack.call);
9229 if (chanpos > -1) {
9230 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9231 pri->pvts[chanpos]->setup_ack = 1;
9232 /* Send any queued digits */
9233 for (x = 0;x < strlen(pri->pvts[chanpos]->dialdest); x++) {
9234 ast_log(LOG_DEBUG, "Sending pending digit '%c'\n", pri->pvts[chanpos]->dialdest[x]);
9235 pri_information(pri->pri, pri->pvts[chanpos]->call,
9236 pri->pvts[chanpos]->dialdest[x]);
9238 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9239 } else
9240 ast_log(LOG_WARNING, "Unable to move channel %d!\n", e->setup_ack.channel);
9242 break;
9243 case PRI_EVENT_NOTIFY:
9244 chanpos = pri_find_principle(pri, e->notify.channel);
9245 if (chanpos < 0) {
9246 ast_log(LOG_WARNING, "Received NOTIFY on unconfigured channel %d/%d span %d\n",
9247 PRI_SPAN(e->notify.channel), PRI_CHANNEL(e->notify.channel), pri->span);
9248 } else {
9249 struct ast_frame f = { AST_FRAME_CONTROL, };
9250 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9251 switch (e->notify.info) {
9252 case PRI_NOTIFY_REMOTE_HOLD:
9253 f.subclass = AST_CONTROL_HOLD;
9254 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9255 break;
9256 case PRI_NOTIFY_REMOTE_RETRIEVAL:
9257 f.subclass = AST_CONTROL_UNHOLD;
9258 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9259 break;
9261 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9263 break;
9264 default:
9265 ast_log(LOG_DEBUG, "Event: %d\n", e->e);
9268 ast_mutex_unlock(&pri->lock);
9270 /* Never reached */
9271 return NULL;
9274 static int start_pri(struct zt_pri *pri)
9276 int res, x;
9277 ZT_PARAMS p;
9278 ZT_BUFFERINFO bi;
9279 struct zt_spaninfo si;
9280 int i;
9282 for (i = 0; i < NUM_DCHANS; i++) {
9283 if (!pri->dchannels[i])
9284 break;
9285 pri->fds[i] = open("/dev/zap/channel", O_RDWR, 0600);
9286 x = pri->dchannels[i];
9287 if ((pri->fds[i] < 0) || (ioctl(pri->fds[i],ZT_SPECIFY,&x) == -1)) {
9288 ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
9289 return -1;
9291 res = ioctl(pri->fds[i], ZT_GET_PARAMS, &p);
9292 if (res) {
9293 zt_close(pri->fds[i]);
9294 pri->fds[i] = -1;
9295 ast_log(LOG_ERROR, "Unable to get parameters for D-channel %d (%s)\n", x, strerror(errno));
9296 return -1;
9298 if ((p.sigtype != ZT_SIG_HDLCFCS) && (p.sigtype != ZT_SIG_HARDHDLC)) {
9299 zt_close(pri->fds[i]);
9300 pri->fds[i] = -1;
9301 ast_log(LOG_ERROR, "D-channel %d is not in HDLC/FCS mode. See /etc/zaptel.conf\n", x);
9302 return -1;
9304 memset(&si, 0, sizeof(si));
9305 res = ioctl(pri->fds[i], ZT_SPANSTAT, &si);
9306 if (res) {
9307 zt_close(pri->fds[i]);
9308 pri->fds[i] = -1;
9309 ast_log(LOG_ERROR, "Unable to get span state for D-channel %d (%s)\n", x, strerror(errno));
9311 if (!si.alarms)
9312 pri->dchanavail[i] |= DCHAN_NOTINALARM;
9313 else
9314 pri->dchanavail[i] &= ~DCHAN_NOTINALARM;
9315 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
9316 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
9317 bi.numbufs = 32;
9318 bi.bufsize = 1024;
9319 if (ioctl(pri->fds[i], ZT_SET_BUFINFO, &bi)) {
9320 ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d\n", x);
9321 zt_close(pri->fds[i]);
9322 pri->fds[i] = -1;
9323 return -1;
9325 pri->dchans[i] = pri_new(pri->fds[i], pri->nodetype, pri->switchtype);
9326 /* Force overlap dial if we're doing GR-303! */
9327 if (pri->switchtype == PRI_SWITCH_GR303_TMC)
9328 pri->overlapdial = 1;
9329 pri_set_overlapdial(pri->dchans[i],pri->overlapdial);
9330 /* Enslave to master if appropriate */
9331 if (i)
9332 pri_enslave(pri->dchans[0], pri->dchans[i]);
9333 if (!pri->dchans[i]) {
9334 zt_close(pri->fds[i]);
9335 pri->fds[i] = -1;
9336 ast_log(LOG_ERROR, "Unable to create PRI structure\n");
9337 return -1;
9339 pri_set_debug(pri->dchans[i], DEFAULT_PRI_DEBUG);
9340 pri_set_nsf(pri->dchans[i], pri->nsf);
9341 #ifdef PRI_GETSET_TIMERS
9342 for (x = 0; x < PRI_MAX_TIMERS; x++) {
9343 if (pritimers[x] != 0)
9344 pri_set_timer(pri->dchans[i], x, pritimers[x]);
9346 #endif
9348 /* Assume primary is the one we use */
9349 pri->pri = pri->dchans[0];
9350 pri->resetpos = -1;
9351 if (ast_pthread_create_background(&pri->master, NULL, pri_dchannel, pri)) {
9352 for (i = 0; i < NUM_DCHANS; i++) {
9353 if (!pri->dchannels[i])
9354 break;
9355 zt_close(pri->fds[i]);
9356 pri->fds[i] = -1;
9358 ast_log(LOG_ERROR, "Unable to spawn D-channel: %s\n", strerror(errno));
9359 return -1;
9361 return 0;
9364 static char *complete_span_helper(const char *line, const char *word, int pos, int state, int rpos)
9366 int which, span;
9367 char *ret = NULL;
9369 if (pos != rpos)
9370 return ret;
9372 for (which = span = 0; span < NUM_SPANS; span++) {
9373 if (pris[span].pri && ++which > state) {
9374 asprintf(&ret, "%d", span + 1); /* user indexes start from 1 */
9375 break;
9378 return ret;
9381 static char *complete_span_4(const char *line, const char *word, int pos, int state)
9383 return complete_span_helper(line,word,pos,state,3);
9386 static char *complete_span_5(const char *line, const char *word, int pos, int state)
9388 return complete_span_helper(line,word,pos,state,4);
9391 static int handle_pri_set_debug_file(int fd, int argc, char **argv)
9393 int myfd;
9395 if (!strncasecmp(argv[1], "set", 3)) {
9396 if (argc < 5)
9397 return RESULT_SHOWUSAGE;
9399 if (ast_strlen_zero(argv[4]))
9400 return RESULT_SHOWUSAGE;
9402 myfd = open(argv[4], O_CREAT|O_WRONLY);
9403 if (myfd < 0) {
9404 ast_cli(fd, "Unable to open '%s' for writing\n", argv[4]);
9405 return RESULT_SUCCESS;
9408 ast_mutex_lock(&pridebugfdlock);
9410 if (pridebugfd >= 0)
9411 close(pridebugfd);
9413 pridebugfd = myfd;
9414 ast_copy_string(pridebugfilename,argv[4],sizeof(pridebugfilename));
9416 ast_mutex_unlock(&pridebugfdlock);
9418 ast_cli(fd, "PRI debug output will be sent to '%s'\n", argv[4]);
9419 } else {
9420 /* Assume it is unset */
9421 ast_mutex_lock(&pridebugfdlock);
9422 close(pridebugfd);
9423 pridebugfd = -1;
9424 ast_cli(fd, "PRI debug output to file disabled\n");
9425 ast_mutex_unlock(&pridebugfdlock);
9428 return RESULT_SUCCESS;
9431 static int handle_pri_debug(int fd, int argc, char *argv[])
9433 int span;
9434 int x;
9435 if (argc < 4) {
9436 return RESULT_SHOWUSAGE;
9438 span = atoi(argv[3]);
9439 if ((span < 1) || (span > NUM_SPANS)) {
9440 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[3], 1, NUM_SPANS);
9441 return RESULT_SUCCESS;
9443 if (!pris[span-1].pri) {
9444 ast_cli(fd, "No PRI running on span %d\n", span);
9445 return RESULT_SUCCESS;
9447 for (x = 0; x < NUM_DCHANS; x++) {
9448 if (pris[span-1].dchans[x])
9449 pri_set_debug(pris[span-1].dchans[x], PRI_DEBUG_APDU |
9450 PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q931_STATE |
9451 PRI_DEBUG_Q921_STATE);
9453 ast_cli(fd, "Enabled debugging on span %d\n", span);
9454 return RESULT_SUCCESS;
9459 static int handle_pri_no_debug(int fd, int argc, char *argv[])
9461 int span;
9462 int x;
9463 if (argc < 5)
9464 return RESULT_SHOWUSAGE;
9465 span = atoi(argv[4]);
9466 if ((span < 1) || (span > NUM_SPANS)) {
9467 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[4], 1, NUM_SPANS);
9468 return RESULT_SUCCESS;
9470 if (!pris[span-1].pri) {
9471 ast_cli(fd, "No PRI running on span %d\n", span);
9472 return RESULT_SUCCESS;
9474 for (x = 0; x < NUM_DCHANS; x++) {
9475 if (pris[span-1].dchans[x])
9476 pri_set_debug(pris[span-1].dchans[x], 0);
9478 ast_cli(fd, "Disabled debugging on span %d\n", span);
9479 return RESULT_SUCCESS;
9482 static int handle_pri_really_debug(int fd, int argc, char *argv[])
9484 int span;
9485 int x;
9486 if (argc < 5)
9487 return RESULT_SHOWUSAGE;
9488 span = atoi(argv[4]);
9489 if ((span < 1) || (span > NUM_SPANS)) {
9490 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[4], 1, NUM_SPANS);
9491 return RESULT_SUCCESS;
9493 if (!pris[span-1].pri) {
9494 ast_cli(fd, "No PRI running on span %d\n", span);
9495 return RESULT_SUCCESS;
9497 for (x = 0; x < NUM_DCHANS; x++) {
9498 if (pris[span-1].dchans[x])
9499 pri_set_debug(pris[span-1].dchans[x], PRI_DEBUG_APDU |
9500 PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q931_STATE |
9501 PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_STATE);
9503 ast_cli(fd, "Enabled EXTENSIVE debugging on span %d\n", span);
9504 return RESULT_SUCCESS;
9507 static void build_status(char *s, size_t len, int status, int active)
9509 if (!s || len < 1) {
9510 return;
9512 s[0] = '\0';
9513 if (status & DCHAN_PROVISIONED)
9514 strncat(s, "Provisioned, ", len - strlen(s) - 1);
9515 if (!(status & DCHAN_NOTINALARM))
9516 strncat(s, "In Alarm, ", len - strlen(s) - 1);
9517 if (status & DCHAN_UP)
9518 strncat(s, "Up", len - strlen(s) - 1);
9519 else
9520 strncat(s, "Down", len - strlen(s) - 1);
9521 if (active)
9522 strncat(s, ", Active", len - strlen(s) - 1);
9523 else
9524 strncat(s, ", Standby", len - strlen(s) - 1);
9525 s[len - 1] = '\0';
9528 static int handle_pri_show_spans(int fd, int argc, char *argv[])
9530 int span;
9531 int x;
9532 char status[256];
9533 if (argc != 3)
9534 return RESULT_SHOWUSAGE;
9536 for (span = 0; span < NUM_SPANS; span++) {
9537 if (pris[span].pri) {
9538 for (x = 0; x < NUM_DCHANS; x++) {
9539 if (pris[span].dchannels[x]) {
9540 build_status(status, sizeof(status), pris[span].dchanavail[x], pris[span].dchans[x] == pris[span].pri);
9541 ast_cli(fd, "PRI span %d/%d: %s\n", span + 1, x, status);
9546 return RESULT_SUCCESS;
9549 static int handle_pri_show_span(int fd, int argc, char *argv[])
9551 int span;
9552 int x;
9553 char status[256];
9554 if (argc < 4)
9555 return RESULT_SHOWUSAGE;
9556 span = atoi(argv[3]);
9557 if ((span < 1) || (span > NUM_SPANS)) {
9558 ast_cli(fd, "Invalid span '%s'. Should be a number from %d to %d\n", argv[3], 1, NUM_SPANS);
9559 return RESULT_SUCCESS;
9561 if (!pris[span-1].pri) {
9562 ast_cli(fd, "No PRI running on span %d\n", span);
9563 return RESULT_SUCCESS;
9565 for (x = 0; x < NUM_DCHANS; x++) {
9566 if (pris[span-1].dchannels[x]) {
9567 #ifdef PRI_DUMP_INFO_STR
9568 char *info_str = NULL;
9569 #endif
9570 ast_cli(fd, "%s D-channel: %d\n", pri_order(x), pris[span-1].dchannels[x]);
9571 build_status(status, sizeof(status), pris[span-1].dchanavail[x], pris[span-1].dchans[x] == pris[span-1].pri);
9572 ast_cli(fd, "Status: %s\n", status);
9573 #ifdef PRI_DUMP_INFO_STR
9574 info_str = pri_dump_info_str(pris[span-1].pri);
9575 if (info_str) {
9576 ast_cli(fd, "%s", info_str);
9577 free(info_str);
9579 #else
9580 pri_dump_info(pris[span-1].pri);
9581 #endif
9582 ast_cli(fd, "\n");
9585 return RESULT_SUCCESS;
9588 static int handle_pri_show_debug(int fd, int argc, char *argv[])
9590 int x;
9591 int span;
9592 int count=0;
9593 int debug=0;
9595 for (span = 0; span < NUM_SPANS; span++) {
9596 if (pris[span].pri) {
9597 for (x = 0; x < NUM_DCHANS; x++) {
9598 debug = 0;
9599 if (pris[span].dchans[x]) {
9600 debug = pri_get_debug(pris[span].dchans[x]);
9601 ast_cli(fd, "Span %d: Debug: %s\tIntense: %s\n", span+1, (debug&PRI_DEBUG_Q931_STATE)? "Yes" : "No" ,(debug&PRI_DEBUG_Q921_RAW)? "Yes" : "No" );
9602 count++;
9608 ast_mutex_lock(&pridebugfdlock);
9609 if (pridebugfd >= 0)
9610 ast_cli(fd, "Logging PRI debug to file %s\n", pridebugfilename);
9611 ast_mutex_unlock(&pridebugfdlock);
9613 if (!count)
9614 ast_cli(fd, "No debug set or no PRI running\n");
9615 return RESULT_SUCCESS;
9618 static const char pri_debug_help[] =
9619 "Usage: pri debug span <span>\n"
9620 " Enables debugging on a given PRI span\n";
9622 static const char pri_no_debug_help[] =
9623 "Usage: pri no debug span <span>\n"
9624 " Disables debugging on a given PRI span\n";
9626 static const char pri_really_debug_help[] =
9627 "Usage: pri intensive debug span <span>\n"
9628 " Enables debugging down to the Q.921 level\n";
9630 static const char pri_show_span_help[] =
9631 "Usage: pri show span <span>\n"
9632 " Displays PRI Information on a given PRI span\n";
9634 static const char pri_show_spans_help[] =
9635 "Usage: pri show spans\n"
9636 " Displays PRI Information\n";
9638 static struct ast_cli_entry zap_pri_cli[] = {
9639 { { "pri", "debug", "span", NULL },
9640 handle_pri_debug, "Enables PRI debugging on a span",
9641 pri_debug_help, complete_span_4 },
9643 { { "pri", "no", "debug", "span", NULL },
9644 handle_pri_no_debug, "Disables PRI debugging on a span",
9645 pri_no_debug_help, complete_span_5 },
9647 { { "pri", "intense", "debug", "span", NULL },
9648 handle_pri_really_debug, "Enables REALLY INTENSE PRI debugging",
9649 pri_really_debug_help, complete_span_5 },
9651 { { "pri", "show", "spans", NULL },
9652 handle_pri_show_spans, "Displays PRI Information",
9653 pri_show_spans_help },
9655 { { "pri", "show", "span", NULL },
9656 handle_pri_show_span, "Displays PRI Information",
9657 pri_show_span_help, complete_span_4 },
9659 { { "pri", "show", "debug", NULL },
9660 handle_pri_show_debug, "Displays current PRI debug settings" },
9662 { { "pri", "set", "debug", "file", NULL },
9663 handle_pri_set_debug_file, "Sends PRI debug output to the specified file" },
9665 { { "pri", "unset", "debug", "file", NULL },
9666 handle_pri_set_debug_file, "Ends PRI debug output to file" },
9669 #endif /* HAVE_PRI */
9671 static int zap_destroy_channel(int fd, int argc, char **argv)
9673 int channel = 0;
9674 struct zt_pvt *tmp = NULL;
9675 struct zt_pvt *prev = NULL;
9677 if (argc != 4) {
9678 return RESULT_SHOWUSAGE;
9680 channel = atoi(argv[3]);
9682 tmp = iflist;
9683 while (tmp) {
9684 if (tmp->channel == channel) {
9685 destroy_channel(prev, tmp, 1);
9686 return RESULT_SUCCESS;
9688 prev = tmp;
9689 tmp = tmp->next;
9691 return RESULT_FAILURE;
9694 static int setup_zap(int reload);
9695 static int zap_restart(void)
9697 if (option_verbose > 0)
9698 ast_verbose(VERBOSE_PREFIX_1 "Destroying channels and reloading zaptel configuration.\n");
9699 while (iflist) {
9700 if (option_debug)
9701 ast_log(LOG_DEBUG, "Destroying zaptel channel no. %d\n", iflist->channel);
9702 /* Also updates iflist: */
9703 destroy_channel(NULL, iflist, 1);
9705 if (option_debug)
9706 ast_log(LOG_DEBUG, "Channels destroyed. Now re-reading config.\n");
9707 if (setup_zap(0) != 0) {
9708 ast_log(LOG_WARNING, "Reload channels from zap config failed!\n");
9709 return 1;
9711 return 0;
9714 static int zap_restart_cmd(int fd, int argc, char **argv)
9716 if (argc != 2) {
9717 return RESULT_SHOWUSAGE;
9720 if (zap_restart() != 0)
9721 return RESULT_FAILURE;
9722 return RESULT_SUCCESS;
9725 static int action_zaprestart(struct mansession *s, struct message *m)
9727 if (zap_restart() != 0) {
9728 astman_send_error(s, m, "Failed rereading zaptel configuration");
9729 return 1;
9731 astman_send_ack(s, m, "ZapRestart: Success");
9732 return 0;
9735 static int zap_show_channels(int fd, int argc, char **argv)
9737 #define FORMAT "%7s %-10.10s %-15.15s %-10.10s %-20.20s\n"
9738 #define FORMAT2 "%7s %-10.10s %-15.15s %-10.10s %-20.20s\n"
9739 struct zt_pvt *tmp = NULL;
9740 char tmps[20] = "";
9741 ast_mutex_t *lock;
9742 struct zt_pvt *start;
9743 #ifdef HAVE_PRI
9744 int trunkgroup;
9745 struct zt_pri *pri = NULL;
9746 int x;
9747 #endif
9749 lock = &iflock;
9750 start = iflist;
9752 #ifdef HAVE_PRI
9753 if (argc == 4) {
9754 if ((trunkgroup = atoi(argv[3])) < 1)
9755 return RESULT_SHOWUSAGE;
9756 for (x = 0; x < NUM_SPANS; x++) {
9757 if (pris[x].trunkgroup == trunkgroup) {
9758 pri = pris + x;
9759 break;
9762 if (pri) {
9763 start = pri->crvs;
9764 lock = &pri->lock;
9765 } else {
9766 ast_cli(fd, "No such trunk group %d\n", trunkgroup);
9767 return RESULT_FAILURE;
9769 } else
9770 #endif
9771 if (argc != 3)
9772 return RESULT_SHOWUSAGE;
9774 ast_mutex_lock(lock);
9775 #ifdef HAVE_PRI
9776 ast_cli(fd, FORMAT2, pri ? "CRV" : "Chan", "Extension", "Context", "Language", "MOH Interpret");
9777 #else
9778 ast_cli(fd, FORMAT2, "Chan", "Extension", "Context", "Language", "MOH Interpret");
9779 #endif
9781 tmp = start;
9782 while (tmp) {
9783 if (tmp->channel > 0) {
9784 snprintf(tmps, sizeof(tmps), "%d", tmp->channel);
9785 } else
9786 ast_copy_string(tmps, "pseudo", sizeof(tmps));
9787 ast_cli(fd, FORMAT, tmps, tmp->exten, tmp->context, tmp->language, tmp->mohinterpret);
9788 tmp = tmp->next;
9790 ast_mutex_unlock(lock);
9791 return RESULT_SUCCESS;
9792 #undef FORMAT
9793 #undef FORMAT2
9796 static int zap_show_channel(int fd, int argc, char **argv)
9798 int channel;
9799 struct zt_pvt *tmp = NULL;
9800 ZT_CONFINFO ci;
9801 ZT_PARAMS ps;
9802 int x;
9803 ast_mutex_t *lock;
9804 struct zt_pvt *start;
9805 #ifdef HAVE_PRI
9806 char *c;
9807 int trunkgroup;
9808 struct zt_pri *pri=NULL;
9809 #endif
9811 lock = &iflock;
9812 start = iflist;
9814 if (argc != 4)
9815 return RESULT_SHOWUSAGE;
9816 #ifdef HAVE_PRI
9817 if ((c = strchr(argv[3], ':'))) {
9818 if (sscanf(argv[3], "%d:%d", &trunkgroup, &channel) != 2)
9819 return RESULT_SHOWUSAGE;
9820 if ((trunkgroup < 1) || (channel < 1))
9821 return RESULT_SHOWUSAGE;
9822 for (x = 0; x < NUM_SPANS; x++) {
9823 if (pris[x].trunkgroup == trunkgroup) {
9824 pri = pris + x;
9825 break;
9828 if (pri) {
9829 start = pri->crvs;
9830 lock = &pri->lock;
9831 } else {
9832 ast_cli(fd, "No such trunk group %d\n", trunkgroup);
9833 return RESULT_FAILURE;
9835 } else
9836 #endif
9837 channel = atoi(argv[3]);
9839 ast_mutex_lock(lock);
9840 tmp = start;
9841 while (tmp) {
9842 if (tmp->channel == channel) {
9843 #ifdef HAVE_PRI
9844 if (pri)
9845 ast_cli(fd, "Trunk/CRV: %d/%d\n", trunkgroup, tmp->channel);
9846 else
9847 #endif
9848 ast_cli(fd, "Channel: %d\n", tmp->channel);
9849 ast_cli(fd, "File Descriptor: %d\n", tmp->subs[SUB_REAL].zfd);
9850 ast_cli(fd, "Span: %d\n", tmp->span);
9851 ast_cli(fd, "Extension: %s\n", tmp->exten);
9852 ast_cli(fd, "Dialing: %s\n", tmp->dialing ? "yes" : "no");
9853 ast_cli(fd, "Context: %s\n", tmp->context);
9854 ast_cli(fd, "Caller ID: %s\n", tmp->cid_num);
9855 ast_cli(fd, "Calling TON: %d\n", tmp->cid_ton);
9856 ast_cli(fd, "Caller ID name: %s\n", tmp->cid_name);
9857 ast_cli(fd, "Destroy: %d\n", tmp->destroy);
9858 ast_cli(fd, "InAlarm: %d\n", tmp->inalarm);
9859 ast_cli(fd, "Signalling Type: %s\n", sig2str(tmp->sig));
9860 ast_cli(fd, "Radio: %d\n", tmp->radio);
9861 ast_cli(fd, "Owner: %s\n", tmp->owner ? tmp->owner->name : "<None>");
9862 ast_cli(fd, "Real: %s%s%s\n", tmp->subs[SUB_REAL].owner ? tmp->subs[SUB_REAL].owner->name : "<None>", tmp->subs[SUB_REAL].inthreeway ? " (Confed)" : "", tmp->subs[SUB_REAL].linear ? " (Linear)" : "");
9863 ast_cli(fd, "Callwait: %s%s%s\n", tmp->subs[SUB_CALLWAIT].owner ? tmp->subs[SUB_CALLWAIT].owner->name : "<None>", tmp->subs[SUB_CALLWAIT].inthreeway ? " (Confed)" : "", tmp->subs[SUB_CALLWAIT].linear ? " (Linear)" : "");
9864 ast_cli(fd, "Threeway: %s%s%s\n", tmp->subs[SUB_THREEWAY].owner ? tmp->subs[SUB_THREEWAY].owner->name : "<None>", tmp->subs[SUB_THREEWAY].inthreeway ? " (Confed)" : "", tmp->subs[SUB_THREEWAY].linear ? " (Linear)" : "");
9865 ast_cli(fd, "Confno: %d\n", tmp->confno);
9866 ast_cli(fd, "Propagated Conference: %d\n", tmp->propconfno);
9867 ast_cli(fd, "Real in conference: %d\n", tmp->inconference);
9868 ast_cli(fd, "DSP: %s\n", tmp->dsp ? "yes" : "no");
9869 ast_cli(fd, "Relax DTMF: %s\n", tmp->dtmfrelax ? "yes" : "no");
9870 ast_cli(fd, "Dialing/CallwaitCAS: %d/%d\n", tmp->dialing, tmp->callwaitcas);
9871 ast_cli(fd, "Default law: %s\n", tmp->law == ZT_LAW_MULAW ? "ulaw" : tmp->law == ZT_LAW_ALAW ? "alaw" : "unknown");
9872 ast_cli(fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
9873 ast_cli(fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
9874 ast_cli(fd, "Echo Cancellation: %d taps%s, currently %s\n", tmp->echocancel, tmp->echocanbridged ? "" : " unless TDM bridged", tmp->echocanon ? "ON" : "OFF");
9875 if (tmp->master)
9876 ast_cli(fd, "Master Channel: %d\n", tmp->master->channel);
9877 for (x = 0; x < MAX_SLAVES; x++) {
9878 if (tmp->slaves[x])
9879 ast_cli(fd, "Slave Channel: %d\n", tmp->slaves[x]->channel);
9881 #ifdef HAVE_PRI
9882 if (tmp->pri) {
9883 ast_cli(fd, "PRI Flags: ");
9884 if (tmp->resetting)
9885 ast_cli(fd, "Resetting ");
9886 if (tmp->call)
9887 ast_cli(fd, "Call ");
9888 if (tmp->bearer)
9889 ast_cli(fd, "Bearer ");
9890 ast_cli(fd, "\n");
9891 if (tmp->logicalspan)
9892 ast_cli(fd, "PRI Logical Span: %d\n", tmp->logicalspan);
9893 else
9894 ast_cli(fd, "PRI Logical Span: Implicit\n");
9897 #endif
9898 memset(&ci, 0, sizeof(ci));
9899 ps.channo = tmp->channel;
9900 if (tmp->subs[SUB_REAL].zfd > -1) {
9901 if (!ioctl(tmp->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
9902 ast_cli(fd, "Actual Confinfo: Num/%d, Mode/0x%04x\n", ci.confno, ci.confmode);
9904 #ifdef ZT_GETCONFMUTE
9905 if (!ioctl(tmp->subs[SUB_REAL].zfd, ZT_GETCONFMUTE, &x)) {
9906 ast_cli(fd, "Actual Confmute: %s\n", x ? "Yes" : "No");
9908 #endif
9909 if (ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps) < 0) {
9910 ast_log(LOG_WARNING, "Failed to get parameters on channel %d\n", tmp->channel);
9911 } else {
9912 ast_cli(fd, "Hookstate (FXS only): %s\n", ps.rxisoffhook ? "Offhook" : "Onhook");
9915 ast_mutex_unlock(lock);
9916 return RESULT_SUCCESS;
9918 tmp = tmp->next;
9921 ast_cli(fd, "Unable to find given channel %d\n", channel);
9922 ast_mutex_unlock(lock);
9923 return RESULT_FAILURE;
9926 static char zap_show_cadences_help[] =
9927 "Usage: zap show cadences\n"
9928 " Shows all cadences currently defined\n";
9930 static int handle_zap_show_cadences(int fd, int argc, char *argv[])
9932 int i, j;
9933 for (i = 0; i < num_cadence; i++) {
9934 char output[1024];
9935 char tmp[16], tmp2[64];
9936 snprintf(tmp, sizeof(tmp), "r%d: ", i + 1);
9937 term_color(output, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(output));
9939 for (j = 0; j < 16; j++) {
9940 if (cadences[i].ringcadence[j] == 0)
9941 break;
9942 snprintf(tmp, sizeof(tmp), "%d", cadences[i].ringcadence[j]);
9943 if (cidrings[i] * 2 - 1 == j)
9944 term_color(tmp2, tmp, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp2) - 1);
9945 else
9946 term_color(tmp2, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(tmp2) - 1);
9947 if (j != 0)
9948 strncat(output, ",", sizeof(output) - strlen(output) - 1);
9949 strncat(output, tmp2, sizeof(output) - strlen(output) - 1);
9951 ast_cli(fd,"%s\n",output);
9953 return 0;
9956 /* Based on irqmiss.c */
9957 static int zap_show_status(int fd, int argc, char *argv[]) {
9958 #define FORMAT "%-40.40s %-10.10s %-10d %-10d %-10d\n"
9959 #define FORMAT2 "%-40.40s %-10.10s %-10.10s %-10.10s %-10.10s\n"
9961 int span;
9962 int res;
9963 char alarms[50];
9965 int ctl;
9966 ZT_SPANINFO s;
9968 ctl = open("/dev/zap/ctl", O_RDWR);
9969 if (ctl < 0) {
9970 ast_log(LOG_WARNING, "Unable to open /dev/zap/ctl: %s\n", strerror(errno));
9971 ast_cli(fd, "No Zaptel interface found.\n");
9972 return RESULT_FAILURE;
9974 ast_cli(fd, FORMAT2, "Description", "Alarms", "IRQ", "bpviol", "CRC4");
9976 for (span = 1; span < ZT_MAX_SPANS; ++span) {
9977 s.spanno = span;
9978 res = ioctl(ctl, ZT_SPANSTAT, &s);
9979 if (res) {
9980 continue;
9982 alarms[0] = '\0';
9983 if (s.alarms > 0) {
9984 if (s.alarms & ZT_ALARM_BLUE)
9985 strcat(alarms, "BLU/");
9986 if (s.alarms & ZT_ALARM_YELLOW)
9987 strcat(alarms, "YEL/");
9988 if (s.alarms & ZT_ALARM_RED)
9989 strcat(alarms, "RED/");
9990 if (s.alarms & ZT_ALARM_LOOPBACK)
9991 strcat(alarms, "LB/");
9992 if (s.alarms & ZT_ALARM_RECOVER)
9993 strcat(alarms, "REC/");
9994 if (s.alarms & ZT_ALARM_NOTOPEN)
9995 strcat(alarms, "NOP/");
9996 if (!strlen(alarms))
9997 strcat(alarms, "UUU/");
9998 if (strlen(alarms)) {
9999 /* Strip trailing / */
10000 alarms[strlen(alarms) - 1] = '\0';
10002 } else {
10003 if (s.numchans)
10004 strcpy(alarms, "OK");
10005 else
10006 strcpy(alarms, "UNCONFIGURED");
10009 ast_cli(fd, FORMAT, s.desc, alarms, s.irqmisses, s.bpvcount, s.crc4count);
10011 close(ctl);
10013 return RESULT_SUCCESS;
10014 #undef FORMAT
10015 #undef FORMAT2
10018 static char show_channels_usage[] =
10019 "Usage: zap show channels\n"
10020 " Shows a list of available channels\n";
10022 static char show_channel_usage[] =
10023 "Usage: zap show channel <chan num>\n"
10024 " Detailed information about a given channel\n";
10026 static char zap_show_status_usage[] =
10027 "Usage: zap show status\n"
10028 " Shows a list of Zaptel cards with status\n";
10030 static char destroy_channel_usage[] =
10031 "Usage: zap destroy channel <chan num>\n"
10032 " DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING. Immediately removes a given channel, whether it is in use or not\n";
10034 static char zap_restart_usage[] =
10035 "Usage: zap restart\n"
10036 " Restarts the zaptel channels: destroys them all and then\n"
10037 " re-reads them from zapata.conf.\n"
10038 " Note that this will STOP any running CALL on zaptel channels.\n"
10041 static struct ast_cli_entry zap_cli[] = {
10042 { { "zap", "show", "cadences", NULL },
10043 handle_zap_show_cadences, "List cadences",
10044 zap_show_cadences_help },
10046 { { "zap", "show", "channels", NULL},
10047 zap_show_channels, "Show active zapata channels",
10048 show_channels_usage },
10050 { { "zap", "show", "channel", NULL},
10051 zap_show_channel, "Show information on a channel",
10052 show_channel_usage },
10054 { { "zap", "destroy", "channel", NULL},
10055 zap_destroy_channel, "Destroy a channel",
10056 destroy_channel_usage },
10058 { { "zap", "restart", NULL},
10059 zap_restart_cmd, "Fully restart zaptel channels",
10060 zap_restart_usage },
10062 { { "zap", "show", "status", NULL},
10063 zap_show_status, "Show all Zaptel cards status",
10064 zap_show_status_usage },
10067 #define TRANSFER 0
10068 #define HANGUP 1
10070 static int zap_fake_event(struct zt_pvt *p, int mode)
10072 if (p) {
10073 switch (mode) {
10074 case TRANSFER:
10075 p->fake_event = ZT_EVENT_WINKFLASH;
10076 break;
10077 case HANGUP:
10078 p->fake_event = ZT_EVENT_ONHOOK;
10079 break;
10080 default:
10081 ast_log(LOG_WARNING, "I don't know how to handle transfer event with this: %d on channel %s\n",mode, p->owner->name);
10084 return 0;
10086 static struct zt_pvt *find_channel(int channel)
10088 struct zt_pvt *p = iflist;
10089 while (p) {
10090 if (p->channel == channel) {
10091 break;
10093 p = p->next;
10095 return p;
10098 static int action_zapdndon(struct mansession *s, struct message *m)
10100 struct zt_pvt *p = NULL;
10101 char *channel = astman_get_header(m, "ZapChannel");
10102 if (ast_strlen_zero(channel)) {
10103 astman_send_error(s, m, "No channel specified");
10104 return 0;
10106 p = find_channel(atoi(channel));
10107 if (!p) {
10108 astman_send_error(s, m, "No such channel");
10109 return 0;
10111 p->dnd = 1;
10112 astman_send_ack(s, m, "DND Enabled");
10113 return 0;
10116 static int action_zapdndoff(struct mansession *s, struct message *m)
10118 struct zt_pvt *p = NULL;
10119 char *channel = astman_get_header(m, "ZapChannel");
10120 if (ast_strlen_zero(channel)) {
10121 astman_send_error(s, m, "No channel specified");
10122 return 0;
10124 p = find_channel(atoi(channel));
10125 if (!p) {
10126 astman_send_error(s, m, "No such channel");
10127 return 0;
10129 p->dnd = 0;
10130 astman_send_ack(s, m, "DND Disabled");
10131 return 0;
10134 static int action_transfer(struct mansession *s, struct message *m)
10136 struct zt_pvt *p = NULL;
10137 char *channel = astman_get_header(m, "ZapChannel");
10138 if (ast_strlen_zero(channel)) {
10139 astman_send_error(s, m, "No channel specified");
10140 return 0;
10142 p = find_channel(atoi(channel));
10143 if (!p) {
10144 astman_send_error(s, m, "No such channel");
10145 return 0;
10147 zap_fake_event(p,TRANSFER);
10148 astman_send_ack(s, m, "ZapTransfer");
10149 return 0;
10152 static int action_transferhangup(struct mansession *s, struct message *m)
10154 struct zt_pvt *p = NULL;
10155 char *channel = astman_get_header(m, "ZapChannel");
10156 if (ast_strlen_zero(channel)) {
10157 astman_send_error(s, m, "No channel specified");
10158 return 0;
10160 p = find_channel(atoi(channel));
10161 if (!p) {
10162 astman_send_error(s, m, "No such channel");
10163 return 0;
10165 zap_fake_event(p,HANGUP);
10166 astman_send_ack(s, m, "ZapHangup");
10167 return 0;
10170 static int action_zapdialoffhook(struct mansession *s, struct message *m)
10172 struct zt_pvt *p = NULL;
10173 char *channel = astman_get_header(m, "ZapChannel");
10174 char *number = astman_get_header(m, "Number");
10175 int i;
10176 if (ast_strlen_zero(channel)) {
10177 astman_send_error(s, m, "No channel specified");
10178 return 0;
10180 if (ast_strlen_zero(number)) {
10181 astman_send_error(s, m, "No number specified");
10182 return 0;
10184 p = find_channel(atoi(channel));
10185 if (!p) {
10186 astman_send_error(s, m, "No such channel");
10187 return 0;
10189 if (!p->owner) {
10190 astman_send_error(s, m, "Channel does not have it's owner");
10191 return 0;
10193 for (i = 0; i < strlen(number); i++) {
10194 struct ast_frame f = { AST_FRAME_DTMF, number[i] };
10195 zap_queue_frame(p, &f, NULL);
10197 astman_send_ack(s, m, "ZapDialOffhook");
10198 return 0;
10201 static int action_zapshowchannels(struct mansession *s, struct message *m)
10203 struct zt_pvt *tmp = NULL;
10204 char *id = astman_get_header(m, "ActionID");
10205 char idText[256] = "";
10207 astman_send_ack(s, m, "Zapata channel status will follow");
10208 if (!ast_strlen_zero(id))
10209 snprintf(idText, sizeof(idText) - 1, "ActionID: %s\r\n", id);
10211 ast_mutex_lock(&iflock);
10213 tmp = iflist;
10214 while (tmp) {
10215 if (tmp->channel > 0) {
10216 int alarm = get_alarms(tmp);
10217 astman_append(s,
10218 "Event: ZapShowChannels\r\n"
10219 "Channel: %d\r\n"
10220 "Signalling: %s\r\n"
10221 "Context: %s\r\n"
10222 "DND: %s\r\n"
10223 "Alarm: %s\r\n"
10224 "%s"
10225 "\r\n",
10226 tmp->channel, sig2str(tmp->sig), tmp->context,
10227 tmp->dnd ? "Enabled" : "Disabled",
10228 alarm2str(alarm), idText);
10231 tmp = tmp->next;
10234 ast_mutex_unlock(&iflock);
10236 astman_append(s,
10237 "Event: ZapShowChannelsComplete\r\n"
10238 "%s"
10239 "\r\n",
10240 idText);
10241 return 0;
10244 static int __unload_module(void)
10246 int x = 0;
10247 struct zt_pvt *p, *pl;
10248 #ifdef HAVE_PRI
10249 int i;
10250 for (i = 0; i < NUM_SPANS; i++) {
10251 if (pris[i].master != AST_PTHREADT_NULL)
10252 pthread_cancel(pris[i].master);
10254 ast_cli_unregister_multiple(zap_pri_cli, sizeof(zap_pri_cli) / sizeof(struct ast_cli_entry));
10255 ast_unregister_application(zap_send_keypad_facility_app);
10256 #endif
10257 ast_cli_unregister_multiple(zap_cli, sizeof(zap_cli) / sizeof(struct ast_cli_entry));
10258 ast_manager_unregister( "ZapDialOffhook" );
10259 ast_manager_unregister( "ZapHangup" );
10260 ast_manager_unregister( "ZapTransfer" );
10261 ast_manager_unregister( "ZapDNDoff" );
10262 ast_manager_unregister( "ZapDNDon" );
10263 ast_manager_unregister("ZapShowChannels");
10264 ast_manager_unregister("ZapRestart");
10265 ast_channel_unregister(&zap_tech);
10266 ast_mutex_lock(&iflock);
10267 /* Hangup all interfaces if they have an owner */
10268 p = iflist;
10269 while (p) {
10270 if (p->owner)
10271 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
10272 p = p->next;
10274 ast_mutex_unlock(&iflock);
10275 ast_mutex_lock(&monlock);
10276 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
10277 pthread_cancel(monitor_thread);
10278 pthread_kill(monitor_thread, SIGURG);
10279 pthread_join(monitor_thread, NULL);
10281 monitor_thread = AST_PTHREADT_STOP;
10282 ast_mutex_unlock(&monlock);
10284 ast_mutex_lock(&iflock);
10285 /* Destroy all the interfaces and free their memory */
10286 p = iflist;
10287 while (p) {
10288 /* Free any callerid */
10289 if (p->cidspill)
10290 free(p->cidspill);
10291 /* Close the zapata thingy */
10292 if (p->subs[SUB_REAL].zfd > -1)
10293 zt_close(p->subs[SUB_REAL].zfd);
10294 pl = p;
10295 p = p->next;
10296 x++;
10297 /* Free associated memory */
10298 if (pl)
10299 destroy_zt_pvt(&pl);
10300 ast_verbose(VERBOSE_PREFIX_3 "Unregistered channel %d\n", x);
10302 iflist = NULL;
10303 ifcount = 0;
10304 ast_mutex_unlock(&iflock);
10305 #ifdef HAVE_PRI
10306 for (i = 0; i < NUM_SPANS; i++) {
10307 if (pris[i].master && (pris[i].master != AST_PTHREADT_NULL))
10308 pthread_join(pris[i].master, NULL);
10309 zt_close(pris[i].fds[i]);
10311 #endif
10312 return 0;
10315 static int unload_module(void)
10317 #ifdef HAVE_PRI
10318 int y;
10319 for (y = 0; y < NUM_SPANS; y++)
10320 ast_mutex_destroy(&pris[y].lock);
10321 #endif
10322 return __unload_module();
10325 static int build_channels(int iscrv, const char *value, int reload, int lineno, int *found_pseudo)
10327 char *c, *chan;
10328 int x, start, finish;
10329 struct zt_pvt *tmp;
10330 #ifdef HAVE_PRI
10331 struct zt_pri *pri;
10332 int trunkgroup, y;
10333 #endif
10335 if ((reload == 0) && (cur_signalling < 0)) {
10336 ast_log(LOG_ERROR, "Signalling must be specified before any channels are.\n");
10337 return -1;
10340 c = ast_strdupa(value);
10342 #ifdef HAVE_PRI
10343 pri = NULL;
10344 if (iscrv) {
10345 if (sscanf(c, "%d:%n", &trunkgroup, &y) != 1) {
10346 ast_log(LOG_WARNING, "CRV must begin with trunkgroup followed by a colon at line %d\n", lineno);
10347 return -1;
10349 if (trunkgroup < 1) {
10350 ast_log(LOG_WARNING, "CRV trunk group must be a positive number at line %d\n", lineno);
10351 return -1;
10353 c += y;
10354 for (y = 0; y < NUM_SPANS; y++) {
10355 if (pris[y].trunkgroup == trunkgroup) {
10356 pri = pris + y;
10357 break;
10360 if (!pri) {
10361 ast_log(LOG_WARNING, "No such trunk group %d at CRV declaration at line %d\n", trunkgroup, lineno);
10362 return -1;
10365 #endif
10367 while ((chan = strsep(&c, ","))) {
10368 if (sscanf(chan, "%d-%d", &start, &finish) == 2) {
10369 /* Range */
10370 } else if (sscanf(chan, "%d", &start)) {
10371 /* Just one */
10372 finish = start;
10373 } else if (!strcasecmp(chan, "pseudo")) {
10374 finish = start = CHAN_PSEUDO;
10375 if (found_pseudo)
10376 *found_pseudo = 1;
10377 } else {
10378 ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
10379 return -1;
10381 if (finish < start) {
10382 ast_log(LOG_WARNING, "Sillyness: %d < %d\n", start, finish);
10383 x = finish;
10384 finish = start;
10385 start = x;
10388 for (x = start; x <= finish; x++) {
10389 #ifdef HAVE_PRI
10390 tmp = mkintf(x, cur_signalling, cur_outsignalling, cur_radio, pri, reload);
10391 #else
10392 tmp = mkintf(x, cur_signalling, cur_outsignalling, cur_radio, NULL, reload);
10393 #endif
10395 if (tmp) {
10396 if (option_verbose > 2) {
10397 #ifdef HAVE_PRI
10398 if (pri)
10399 ast_verbose(VERBOSE_PREFIX_3 "%s CRV %d:%d, %s signalling\n", reload ? "Reconfigured" : "Registered", trunkgroup, x, sig2str(tmp->sig));
10400 else
10401 #endif
10402 ast_verbose(VERBOSE_PREFIX_3 "%s channel %d, %s signalling\n", reload ? "Reconfigured" : "Registered", x, sig2str(tmp->sig));
10404 } else {
10405 ast_log(LOG_ERROR, "Unable to %s channel '%s'\n",
10406 (reload == 1) ? "reconfigure" : "register", value);
10407 return -1;
10412 return 0;
10415 static int process_zap(struct ast_variable *v, int reload, int skipchannels)
10417 struct zt_pvt *tmp;
10418 char *ringc;
10419 int y;
10420 int found_pseudo = 0;
10422 while(v) {
10423 /* Create the interface list */
10424 if (!strcasecmp(v->name, "channel")
10425 #ifdef HAVE_PRI
10426 || !strcasecmp(v->name, "crv")
10427 #endif
10429 if (!skipchannels) {
10430 if (build_channels(!strcasecmp(v->name, "crv"), v->value, reload, v->lineno, &found_pseudo))
10431 return -1;
10433 } else if (!strcasecmp(v->name, "usedistinctiveringdetection")) {
10434 if (ast_true(v->value))
10435 usedistinctiveringdetection = 1;
10436 } else if (!strcasecmp(v->name, "distinctiveringaftercid")) {
10437 if (ast_true(v->value))
10438 distinctiveringaftercid = 1;
10439 } else if (!strcasecmp(v->name, "dring1context")) {
10440 ast_copy_string(drings.ringContext[0].contextData,v->value,sizeof(drings.ringContext[0].contextData));
10441 } else if (!strcasecmp(v->name, "dring2context")) {
10442 ast_copy_string(drings.ringContext[1].contextData,v->value,sizeof(drings.ringContext[1].contextData));
10443 } else if (!strcasecmp(v->name, "dring3context")) {
10444 ast_copy_string(drings.ringContext[2].contextData,v->value,sizeof(drings.ringContext[2].contextData));
10445 } else if (!strcasecmp(v->name, "dring1")) {
10446 ringc = v->value;
10447 sscanf(ringc, "%d,%d,%d", &drings.ringnum[0].ring[0], &drings.ringnum[0].ring[1], &drings.ringnum[0].ring[2]);
10448 } else if (!strcasecmp(v->name, "dring2")) {
10449 ringc = v->value;
10450 sscanf(ringc,"%d,%d,%d", &drings.ringnum[1].ring[0], &drings.ringnum[1].ring[1], &drings.ringnum[1].ring[2]);
10451 } else if (!strcasecmp(v->name, "dring3")) {
10452 ringc = v->value;
10453 sscanf(ringc, "%d,%d,%d", &drings.ringnum[2].ring[0], &drings.ringnum[2].ring[1], &drings.ringnum[2].ring[2]);
10454 } else if (!strcasecmp(v->name, "usecallerid")) {
10455 use_callerid = ast_true(v->value);
10456 } else if (!strcasecmp(v->name, "cidsignalling")) {
10457 if (!strcasecmp(v->value, "bell"))
10458 cid_signalling = CID_SIG_BELL;
10459 else if (!strcasecmp(v->value, "v23"))
10460 cid_signalling = CID_SIG_V23;
10461 else if (!strcasecmp(v->value, "dtmf"))
10462 cid_signalling = CID_SIG_DTMF;
10463 else if (!strcasecmp(v->value, "smdi"))
10464 cid_signalling = CID_SIG_SMDI;
10465 else if (!strcasecmp(v->value, "v23_jp"))
10466 cid_signalling = CID_SIG_V23_JP;
10467 else if (ast_true(v->value))
10468 cid_signalling = CID_SIG_BELL;
10469 } else if (!strcasecmp(v->name, "cidstart")) {
10470 if (!strcasecmp(v->value, "ring"))
10471 cid_start = CID_START_RING;
10472 else if (!strcasecmp(v->value, "polarity"))
10473 cid_start = CID_START_POLARITY;
10474 else if (ast_true(v->value))
10475 cid_start = CID_START_RING;
10476 } else if (!strcasecmp(v->name, "threewaycalling")) {
10477 threewaycalling = ast_true(v->value);
10478 } else if (!strcasecmp(v->name, "cancallforward")) {
10479 cancallforward = ast_true(v->value);
10480 } else if (!strcasecmp(v->name, "relaxdtmf")) {
10481 if (ast_true(v->value))
10482 relaxdtmf = DSP_DIGITMODE_RELAXDTMF;
10483 else
10484 relaxdtmf = 0;
10485 } else if (!strcasecmp(v->name, "mailbox")) {
10486 ast_copy_string(mailbox, v->value, sizeof(mailbox));
10487 } else if (!strcasecmp(v->name, "adsi")) {
10488 adsi = ast_true(v->value);
10489 } else if (!strcasecmp(v->name, "usesmdi")) {
10490 use_smdi = ast_true(v->value);
10491 } else if (!strcasecmp(v->name, "smdiport")) {
10492 ast_copy_string(smdi_port, v->value, sizeof(smdi_port));
10493 } else if (!strcasecmp(v->name, "transfer")) {
10494 transfer = ast_true(v->value);
10495 } else if (!strcasecmp(v->name, "canpark")) {
10496 canpark = ast_true(v->value);
10497 } else if (!strcasecmp(v->name, "echocancelwhenbridged")) {
10498 echocanbridged = ast_true(v->value);
10499 } else if (!strcasecmp(v->name, "busydetect")) {
10500 busydetect = ast_true(v->value);
10501 } else if (!strcasecmp(v->name, "busycount")) {
10502 busycount = atoi(v->value);
10503 } else if (!strcasecmp(v->name, "busypattern")) {
10504 if (sscanf(v->value, "%d,%d", &busy_tonelength, &busy_quietlength) != 2) {
10505 ast_log(LOG_ERROR, "busypattern= expects busypattern=tonelength,quietlength\n");
10507 } else if (!strcasecmp(v->name, "callprogress")) {
10508 if (ast_true(v->value))
10509 callprogress |= 1;
10510 else
10511 callprogress &= ~1;
10512 } else if (!strcasecmp(v->name, "faxdetect")) {
10513 if (!strcasecmp(v->value, "incoming")) {
10514 callprogress |= 4;
10515 callprogress &= ~2;
10516 } else if (!strcasecmp(v->value, "outgoing")) {
10517 callprogress &= ~4;
10518 callprogress |= 2;
10519 } else if (!strcasecmp(v->value, "both") || ast_true(v->value))
10520 callprogress |= 6;
10521 else
10522 callprogress &= ~6;
10523 } else if (!strcasecmp(v->name, "echocancel")) {
10524 if (!ast_strlen_zero(v->value)) {
10525 y = atoi(v->value);
10526 } else
10527 y = 0;
10528 if ((y == 32) || (y == 64) || (y == 128) || (y == 256) || (y == 512) || (y == 1024))
10529 echocancel = y;
10530 else {
10531 echocancel = ast_true(v->value);
10532 if (echocancel)
10533 echocancel=128;
10535 } else if (!strcasecmp(v->name, "echotraining")) {
10536 if (sscanf(v->value, "%d", &y) == 1) {
10537 if ((y < 10) || (y > 4000)) {
10538 ast_log(LOG_WARNING, "Echo training time must be within the range of 10 to 4000 ms at line %d\n", v->lineno);
10539 } else {
10540 echotraining = y;
10542 } else if (ast_true(v->value)) {
10543 echotraining = 400;
10544 } else
10545 echotraining = 0;
10546 } else if (!strcasecmp(v->name, "hidecallerid")) {
10547 hidecallerid = ast_true(v->value);
10548 } else if (!strcasecmp(v->name, "pulsedial")) {
10549 pulse = ast_true(v->value);
10550 } else if (!strcasecmp(v->name, "callreturn")) {
10551 callreturn = ast_true(v->value);
10552 } else if (!strcasecmp(v->name, "callwaiting")) {
10553 callwaiting = ast_true(v->value);
10554 } else if (!strcasecmp(v->name, "callwaitingcallerid")) {
10555 callwaitingcallerid = ast_true(v->value);
10556 } else if (!strcasecmp(v->name, "context")) {
10557 ast_copy_string(context, v->value, sizeof(context));
10558 } else if (!strcasecmp(v->name, "language")) {
10559 ast_copy_string(language, v->value, sizeof(language));
10560 } else if (!strcasecmp(v->name, "progzone")) {
10561 ast_copy_string(progzone, v->value, sizeof(progzone));
10562 } else if (!strcasecmp(v->name, "mohinterpret")
10563 ||!strcasecmp(v->name, "musiconhold") || !strcasecmp(v->name, "musicclass")) {
10564 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
10565 } else if (!strcasecmp(v->name, "mohsuggest")) {
10566 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
10567 } else if (!strcasecmp(v->name, "stripmsd")) {
10568 stripmsd = atoi(v->value);
10569 } else if (!strcasecmp(v->name, "jitterbuffers")) {
10570 numbufs = atoi(v->value);
10571 } else if (!strcasecmp(v->name, "group")) {
10572 cur_group = ast_get_group(v->value);
10573 } else if (!strcasecmp(v->name, "callgroup")) {
10574 cur_callergroup = ast_get_group(v->value);
10575 } else if (!strcasecmp(v->name, "pickupgroup")) {
10576 cur_pickupgroup = ast_get_group(v->value);
10577 } else if (!strcasecmp(v->name, "immediate")) {
10578 immediate = ast_true(v->value);
10579 } else if (!strcasecmp(v->name, "transfertobusy")) {
10580 transfertobusy = ast_true(v->value);
10581 } else if (!strcasecmp(v->name, "rxgain")) {
10582 if (sscanf(v->value, "%f", &rxgain) != 1) {
10583 ast_log(LOG_WARNING, "Invalid rxgain: %s\n", v->value);
10585 } else if (!strcasecmp(v->name, "txgain")) {
10586 if (sscanf(v->value, "%f", &txgain) != 1) {
10587 ast_log(LOG_WARNING, "Invalid txgain: %s\n", v->value);
10589 } else if (!strcasecmp(v->name, "tonezone")) {
10590 if (sscanf(v->value, "%d", &tonezone) != 1) {
10591 ast_log(LOG_WARNING, "Invalid tonezone: %s\n", v->value);
10593 } else if (!strcasecmp(v->name, "callerid")) {
10594 if (!strcasecmp(v->value, "asreceived")) {
10595 cid_num[0] = '\0';
10596 cid_name[0] = '\0';
10597 } else {
10598 ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
10600 } else if (!strcasecmp(v->name, "fullname")) {
10601 ast_copy_string(cid_name, v->value, sizeof(cid_name));
10602 } else if (!strcasecmp(v->name, "cid_number")) {
10603 ast_copy_string(cid_num, v->value, sizeof(cid_num));
10604 } else if (!strcasecmp(v->name, "useincomingcalleridonzaptransfer")) {
10605 zaptrcallerid = ast_true(v->value);
10606 } else if (!strcasecmp(v->name, "restrictcid")) {
10607 restrictcid = ast_true(v->value);
10608 } else if (!strcasecmp(v->name, "usecallingpres")) {
10609 use_callingpres = ast_true(v->value);
10610 } else if (!strcasecmp(v->name, "accountcode")) {
10611 ast_copy_string(accountcode, v->value, sizeof(accountcode));
10612 } else if (!strcasecmp(v->name, "amaflags")) {
10613 y = ast_cdr_amaflags2int(v->value);
10614 if (y < 0)
10615 ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
10616 else
10617 amaflags = y;
10618 } else if (!reload){
10619 if (!strcasecmp(v->name, "signalling")) {
10620 cur_outsignalling = -1;
10621 if (!strcasecmp(v->value, "em")) {
10622 cur_signalling = SIG_EM;
10623 } else if (!strcasecmp(v->value, "em_e1")) {
10624 cur_signalling = SIG_EM_E1;
10625 } else if (!strcasecmp(v->value, "em_w")) {
10626 cur_signalling = SIG_EMWINK;
10627 cur_radio = 0;
10628 } else if (!strcasecmp(v->value, "fxs_ls")) {
10629 cur_signalling = SIG_FXSLS;
10630 cur_radio = 0;
10631 } else if (!strcasecmp(v->value, "fxs_gs")) {
10632 cur_signalling = SIG_FXSGS;
10633 cur_radio = 0;
10634 } else if (!strcasecmp(v->value, "fxs_ks")) {
10635 cur_signalling = SIG_FXSKS;
10636 cur_radio = 0;
10637 } else if (!strcasecmp(v->value, "fxo_ls")) {
10638 cur_signalling = SIG_FXOLS;
10639 cur_radio = 0;
10640 } else if (!strcasecmp(v->value, "fxo_gs")) {
10641 cur_signalling = SIG_FXOGS;
10642 cur_radio = 0;
10643 } else if (!strcasecmp(v->value, "fxo_ks")) {
10644 cur_signalling = SIG_FXOKS;
10645 cur_radio = 0;
10646 } else if (!strcasecmp(v->value, "fxs_rx")) {
10647 cur_signalling = SIG_FXSKS;
10648 cur_radio = 1;
10649 } else if (!strcasecmp(v->value, "fxo_rx")) {
10650 cur_signalling = SIG_FXOLS;
10651 cur_radio = 1;
10652 } else if (!strcasecmp(v->value, "fxs_tx")) {
10653 cur_signalling = SIG_FXSLS;
10654 cur_radio = 1;
10655 } else if (!strcasecmp(v->value, "fxo_tx")) {
10656 cur_signalling = SIG_FXOGS;
10657 cur_radio = 1;
10658 } else if (!strcasecmp(v->value, "em_rx")) {
10659 cur_signalling = SIG_EM;
10660 cur_radio = 1;
10661 } else if (!strcasecmp(v->value, "em_tx")) {
10662 cur_signalling = SIG_EM;
10663 cur_radio = 1;
10664 } else if (!strcasecmp(v->value, "em_rxtx")) {
10665 cur_signalling = SIG_EM;
10666 cur_radio = 2;
10667 } else if (!strcasecmp(v->value, "em_txrx")) {
10668 cur_signalling = SIG_EM;
10669 cur_radio = 2;
10670 } else if (!strcasecmp(v->value, "sf")) {
10671 cur_signalling = SIG_SF;
10672 cur_radio = 0;
10673 } else if (!strcasecmp(v->value, "sf_w")) {
10674 cur_signalling = SIG_SFWINK;
10675 cur_radio = 0;
10676 } else if (!strcasecmp(v->value, "sf_featd")) {
10677 cur_signalling = SIG_FEATD;
10678 cur_radio = 0;
10679 } else if (!strcasecmp(v->value, "sf_featdmf")) {
10680 cur_signalling = SIG_FEATDMF;
10681 cur_radio = 0;
10682 } else if (!strcasecmp(v->value, "sf_featb")) {
10683 cur_signalling = SIG_SF_FEATB;
10684 cur_radio = 0;
10685 } else if (!strcasecmp(v->value, "sf")) {
10686 cur_signalling = SIG_SF;
10687 cur_radio = 0;
10688 } else if (!strcasecmp(v->value, "sf_rx")) {
10689 cur_signalling = SIG_SF;
10690 cur_radio = 1;
10691 } else if (!strcasecmp(v->value, "sf_tx")) {
10692 cur_signalling = SIG_SF;
10693 cur_radio = 1;
10694 } else if (!strcasecmp(v->value, "sf_rxtx")) {
10695 cur_signalling = SIG_SF;
10696 cur_radio = 2;
10697 } else if (!strcasecmp(v->value, "sf_txrx")) {
10698 cur_signalling = SIG_SF;
10699 cur_radio = 2;
10700 } else if (!strcasecmp(v->value, "featd")) {
10701 cur_signalling = SIG_FEATD;
10702 cur_radio = 0;
10703 } else if (!strcasecmp(v->value, "featdmf")) {
10704 cur_signalling = SIG_FEATDMF;
10705 cur_radio = 0;
10706 } else if (!strcasecmp(v->value, "featdmf_ta")) {
10707 cur_signalling = SIG_FEATDMF_TA;
10708 cur_radio = 0;
10709 } else if (!strcasecmp(v->value, "e911")) {
10710 cur_signalling = SIG_E911;
10711 cur_radio = 0;
10712 } else if (!strcasecmp(v->value, "fgccama")) {
10713 cur_signalling = SIG_FGC_CAMA;
10714 cur_radio = 0;
10715 } else if (!strcasecmp(v->value, "fgccamamf")) {
10716 cur_signalling = SIG_FGC_CAMAMF;
10717 cur_radio = 0;
10718 } else if (!strcasecmp(v->value, "featb")) {
10719 cur_signalling = SIG_FEATB;
10720 cur_radio = 0;
10721 #ifdef HAVE_PRI
10722 } else if (!strcasecmp(v->value, "pri_net")) {
10723 cur_radio = 0;
10724 cur_signalling = SIG_PRI;
10725 pritype = PRI_NETWORK;
10726 } else if (!strcasecmp(v->value, "pri_cpe")) {
10727 cur_signalling = SIG_PRI;
10728 cur_radio = 0;
10729 pritype = PRI_CPE;
10730 } else if (!strcasecmp(v->value, "gr303fxoks_net")) {
10731 cur_signalling = SIG_GR303FXOKS;
10732 cur_radio = 0;
10733 pritype = PRI_NETWORK;
10734 } else if (!strcasecmp(v->value, "gr303fxsks_cpe")) {
10735 cur_signalling = SIG_GR303FXSKS;
10736 cur_radio = 0;
10737 pritype = PRI_CPE;
10738 #endif
10739 } else {
10740 ast_log(LOG_ERROR, "Unknown signalling method '%s'\n", v->value);
10742 } else if (!strcasecmp(v->name, "outsignalling")) {
10743 if (!strcasecmp(v->value, "em")) {
10744 cur_outsignalling = SIG_EM;
10745 } else if (!strcasecmp(v->value, "em_e1")) {
10746 cur_outsignalling = SIG_EM_E1;
10747 } else if (!strcasecmp(v->value, "em_w")) {
10748 cur_outsignalling = SIG_EMWINK;
10749 } else if (!strcasecmp(v->value, "sf")) {
10750 cur_outsignalling = SIG_SF;
10751 } else if (!strcasecmp(v->value, "sf_w")) {
10752 cur_outsignalling = SIG_SFWINK;
10753 } else if (!strcasecmp(v->value, "sf_featd")) {
10754 cur_outsignalling = SIG_FEATD;
10755 } else if (!strcasecmp(v->value, "sf_featdmf")) {
10756 cur_outsignalling = SIG_FEATDMF;
10757 } else if (!strcasecmp(v->value, "sf_featb")) {
10758 cur_outsignalling = SIG_SF_FEATB;
10759 } else if (!strcasecmp(v->value, "sf")) {
10760 cur_outsignalling = SIG_SF;
10761 } else if (!strcasecmp(v->value, "featd")) {
10762 cur_outsignalling = SIG_FEATD;
10763 } else if (!strcasecmp(v->value, "featdmf")) {
10764 cur_outsignalling = SIG_FEATDMF;
10765 } else if (!strcasecmp(v->value, "featdmf_ta")) {
10766 cur_outsignalling = SIG_FEATDMF_TA;
10767 } else if (!strcasecmp(v->value, "e911")) {
10768 cur_outsignalling = SIG_E911;
10769 } else if (!strcasecmp(v->value, "fgccama")) {
10770 cur_outsignalling = SIG_FGC_CAMA;
10771 } else if (!strcasecmp(v->value, "fgccamamf")) {
10772 cur_outsignalling = SIG_FGC_CAMAMF;
10773 } else if (!strcasecmp(v->value, "featb")) {
10774 cur_outsignalling = SIG_FEATB;
10775 } else {
10776 ast_log(LOG_ERROR, "Unknown signalling method '%s'\n", v->value);
10778 #ifdef HAVE_PRI
10779 } else if (!strcasecmp(v->name, "pridialplan")) {
10780 if (!strcasecmp(v->value, "national")) {
10781 dialplan = PRI_NATIONAL_ISDN + 1;
10782 } else if (!strcasecmp(v->value, "unknown")) {
10783 dialplan = PRI_UNKNOWN + 1;
10784 } else if (!strcasecmp(v->value, "private")) {
10785 dialplan = PRI_PRIVATE + 1;
10786 } else if (!strcasecmp(v->value, "international")) {
10787 dialplan = PRI_INTERNATIONAL_ISDN + 1;
10788 } else if (!strcasecmp(v->value, "local")) {
10789 dialplan = PRI_LOCAL_ISDN + 1;
10790 } else if (!strcasecmp(v->value, "dynamic")) {
10791 dialplan = -1;
10792 } else {
10793 ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
10795 } else if (!strcasecmp(v->name, "prilocaldialplan")) {
10796 if (!strcasecmp(v->value, "national")) {
10797 localdialplan = PRI_NATIONAL_ISDN + 1;
10798 } else if (!strcasecmp(v->value, "unknown")) {
10799 localdialplan = PRI_UNKNOWN + 1;
10800 } else if (!strcasecmp(v->value, "private")) {
10801 localdialplan = PRI_PRIVATE + 1;
10802 } else if (!strcasecmp(v->value, "international")) {
10803 localdialplan = PRI_INTERNATIONAL_ISDN + 1;
10804 } else if (!strcasecmp(v->value, "local")) {
10805 localdialplan = PRI_LOCAL_ISDN + 1;
10806 } else if (!strcasecmp(v->value, "dynamic")) {
10807 localdialplan = -1;
10808 } else {
10809 ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
10811 } else if (!strcasecmp(v->name, "switchtype")) {
10812 if (!strcasecmp(v->value, "national"))
10813 switchtype = PRI_SWITCH_NI2;
10814 else if (!strcasecmp(v->value, "ni1"))
10815 switchtype = PRI_SWITCH_NI1;
10816 else if (!strcasecmp(v->value, "dms100"))
10817 switchtype = PRI_SWITCH_DMS100;
10818 else if (!strcasecmp(v->value, "4ess"))
10819 switchtype = PRI_SWITCH_ATT4ESS;
10820 else if (!strcasecmp(v->value, "5ess"))
10821 switchtype = PRI_SWITCH_LUCENT5E;
10822 else if (!strcasecmp(v->value, "euroisdn"))
10823 switchtype = PRI_SWITCH_EUROISDN_E1;
10824 else if (!strcasecmp(v->value, "qsig"))
10825 switchtype = PRI_SWITCH_QSIG;
10826 else {
10827 ast_log(LOG_ERROR, "Unknown switchtype '%s'\n", v->value);
10828 return -1;
10830 } else if (!strcasecmp(v->name, "nsf")) {
10831 if (!strcasecmp(v->value, "sdn"))
10832 nsf = PRI_NSF_SDN;
10833 else if (!strcasecmp(v->value, "megacom"))
10834 nsf = PRI_NSF_MEGACOM;
10835 else if (!strcasecmp(v->value, "tollfreemegacom"))
10836 nsf = PRI_NSF_TOLL_FREE_MEGACOM;
10837 else if (!strcasecmp(v->value, "accunet"))
10838 nsf = PRI_NSF_ACCUNET;
10839 else if (!strcasecmp(v->value, "none"))
10840 nsf = PRI_NSF_NONE;
10841 else {
10842 ast_log(LOG_WARNING, "Unknown network-specific facility '%s'\n", v->value);
10843 nsf = PRI_NSF_NONE;
10845 } else if (!strcasecmp(v->name, "priindication")) {
10846 if (!strcasecmp(v->value, "outofband"))
10847 priindication_oob = 1;
10848 else if (!strcasecmp(v->value, "inband"))
10849 priindication_oob = 0;
10850 else
10851 ast_log(LOG_WARNING, "'%s' is not a valid pri indication value, should be 'inband' or 'outofband' at line %d\n",
10852 v->value, v->lineno);
10853 } else if (!strcasecmp(v->name, "priexclusive")) {
10854 cur_priexclusive = ast_true(v->value);
10855 } else if (!strcasecmp(v->name, "internationalprefix")) {
10856 ast_copy_string(internationalprefix, v->value, sizeof(internationalprefix));
10857 } else if (!strcasecmp(v->name, "nationalprefix")) {
10858 ast_copy_string(nationalprefix, v->value, sizeof(nationalprefix));
10859 } else if (!strcasecmp(v->name, "localprefix")) {
10860 ast_copy_string(localprefix, v->value, sizeof(localprefix));
10861 } else if (!strcasecmp(v->name, "privateprefix")) {
10862 ast_copy_string(privateprefix, v->value, sizeof(privateprefix));
10863 } else if (!strcasecmp(v->name, "unknownprefix")) {
10864 ast_copy_string(unknownprefix, v->value, sizeof(unknownprefix));
10865 } else if (!strcasecmp(v->name, "resetinterval")) {
10866 if (!strcasecmp(v->value, "never"))
10867 resetinterval = -1;
10868 else if (atoi(v->value) >= 60)
10869 resetinterval = atoi(v->value);
10870 else
10871 ast_log(LOG_WARNING, "'%s' is not a valid reset interval, should be >= 60 seconds or 'never' at line %d\n",
10872 v->value, v->lineno);
10873 } else if (!strcasecmp(v->name, "minunused")) {
10874 minunused = atoi(v->value);
10875 } else if (!strcasecmp(v->name, "minidle")) {
10876 minidle = atoi(v->value);
10877 } else if (!strcasecmp(v->name, "idleext")) {
10878 ast_copy_string(idleext, v->value, sizeof(idleext));
10879 } else if (!strcasecmp(v->name, "idledial")) {
10880 ast_copy_string(idledial, v->value, sizeof(idledial));
10881 } else if (!strcasecmp(v->name, "overlapdial")) {
10882 overlapdial = ast_true(v->value);
10883 } else if (!strcasecmp(v->name, "pritimer")) {
10884 #ifdef PRI_GETSET_TIMERS
10885 char *timerc, *c;
10886 int timer, timeridx;
10887 c = v->value;
10888 timerc = strsep(&c, ",");
10889 if (timerc) {
10890 timer = atoi(c);
10891 if (!timer)
10892 ast_log(LOG_WARNING, "'%s' is not a valid value for an ISDN timer\n", timerc);
10893 else {
10894 if ((timeridx = pri_timer2idx(timerc)) >= 0)
10895 pritimers[timeridx] = timer;
10896 else
10897 ast_log(LOG_WARNING, "'%s' is not a valid ISDN timer\n", timerc);
10899 } else
10900 ast_log(LOG_WARNING, "'%s' is not a valid ISDN timer configuration string\n", v->value);
10902 } else if (!strcasecmp(v->name, "facilityenable")) {
10903 facilityenable = ast_true(v->value);
10904 #endif /* PRI_GETSET_TIMERS */
10905 #endif /* HAVE_PRI */
10906 } else if (!strcasecmp(v->name, "cadence")) {
10907 /* setup to scan our argument */
10908 int element_count, c[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
10909 int i;
10910 struct zt_ring_cadence new_cadence;
10911 int cid_location = -1;
10912 int firstcadencepos = 0;
10913 char original_args[80];
10914 int cadence_is_ok = 1;
10916 ast_copy_string(original_args, v->value, sizeof(original_args));
10917 /* 16 cadences allowed (8 pairs) */
10918 element_count = sscanf(v->value, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", &c[0], &c[1], &c[2], &c[3], &c[4], &c[5], &c[6], &c[7], &c[8], &c[9], &c[10], &c[11], &c[12], &c[13], &c[14], &c[15]);
10920 /* Cadence must be even (on/off) */
10921 if (element_count % 2 == 1) {
10922 ast_log(LOG_ERROR, "Must be a silence duration for each ring duration: %s\n",original_args);
10923 cadence_is_ok = 0;
10926 /* Ring cadences cannot be negative */
10927 for (i = 0; i < element_count; i++) {
10928 if (c[i] == 0) {
10929 ast_log(LOG_ERROR, "Ring or silence duration cannot be zero: %s\n", original_args);
10930 cadence_is_ok = 0;
10931 break;
10932 } else if (c[i] < 0) {
10933 if (i % 2 == 1) {
10934 /* Silence duration, negative possibly okay */
10935 if (cid_location == -1) {
10936 cid_location = i;
10937 c[i] *= -1;
10938 } else {
10939 ast_log(LOG_ERROR, "CID location specified twice: %s\n",original_args);
10940 cadence_is_ok = 0;
10941 break;
10943 } else {
10944 if (firstcadencepos == 0) {
10945 firstcadencepos = i; /* only recorded to avoid duplicate specification */
10946 /* duration will be passed negative to the zaptel driver */
10947 } else {
10948 ast_log(LOG_ERROR, "First cadence position specified twice: %s\n",original_args);
10949 cadence_is_ok = 0;
10950 break;
10956 /* Substitute our scanned cadence */
10957 for (i = 0; i < 16; i++) {
10958 new_cadence.ringcadence[i] = c[i];
10961 if (cadence_is_ok) {
10962 /* ---we scanned it without getting annoyed; now some sanity checks--- */
10963 if (element_count < 2) {
10964 ast_log(LOG_ERROR, "Minimum cadence is ring,pause: %s\n", original_args);
10965 } else {
10966 if (cid_location == -1) {
10967 /* user didn't say; default to first pause */
10968 cid_location = 1;
10969 } else {
10970 /* convert element_index to cidrings value */
10971 cid_location = (cid_location + 1) / 2;
10973 /* ---we like their cadence; try to install it--- */
10974 if (!user_has_defined_cadences++)
10975 /* this is the first user-defined cadence; clear the default user cadences */
10976 num_cadence = 0;
10977 if ((num_cadence+1) >= NUM_CADENCE_MAX)
10978 ast_log(LOG_ERROR, "Already %d cadences; can't add another: %s\n", NUM_CADENCE_MAX, original_args);
10979 else {
10980 cadences[num_cadence] = new_cadence;
10981 cidrings[num_cadence++] = cid_location;
10982 if (option_verbose > 2)
10983 ast_verbose(VERBOSE_PREFIX_3 "cadence 'r%d' added: %s\n",num_cadence,original_args);
10987 } else if (!strcasecmp(v->name, "ringtimeout")) {
10988 ringt_base = (atoi(v->value) * 8) / READ_SIZE;
10989 } else if (!strcasecmp(v->name, "prewink")) {
10990 cur_prewink = atoi(v->value);
10991 } else if (!strcasecmp(v->name, "preflash")) {
10992 cur_preflash = atoi(v->value);
10993 } else if (!strcasecmp(v->name, "wink")) {
10994 cur_wink = atoi(v->value);
10995 } else if (!strcasecmp(v->name, "flash")) {
10996 cur_flash = atoi(v->value);
10997 } else if (!strcasecmp(v->name, "start")) {
10998 cur_start = atoi(v->value);
10999 } else if (!strcasecmp(v->name, "rxwink")) {
11000 cur_rxwink = atoi(v->value);
11001 } else if (!strcasecmp(v->name, "rxflash")) {
11002 cur_rxflash = atoi(v->value);
11003 } else if (!strcasecmp(v->name, "debounce")) {
11004 cur_debounce = atoi(v->value);
11005 } else if (!strcasecmp(v->name, "toneduration")) {
11006 int toneduration;
11007 int ctlfd;
11008 int res;
11009 struct zt_dialparams dps;
11011 ctlfd = open("/dev/zap/ctl", O_RDWR);
11012 if (ctlfd == -1) {
11013 ast_log(LOG_ERROR, "Unable to open /dev/zap/ctl to set toneduration\n");
11014 return -1;
11017 toneduration = atoi(v->value);
11018 if (toneduration > -1) {
11019 dps.dtmf_tonelen = dps.mfv1_tonelen = toneduration;
11020 res = ioctl(ctlfd, ZT_SET_DIALPARAMS, &dps);
11021 if (res < 0) {
11022 ast_log(LOG_ERROR, "Invalid tone duration: %d ms\n", toneduration);
11023 return -1;
11026 close(ctlfd);
11027 } else if (!strcasecmp(v->name, "polarityonanswerdelay")) {
11028 polarityonanswerdelay = atoi(v->value);
11029 } else if (!strcasecmp(v->name, "answeronpolarityswitch")) {
11030 answeronpolarityswitch = ast_true(v->value);
11031 } else if (!strcasecmp(v->name, "hanguponpolarityswitch")) {
11032 hanguponpolarityswitch = ast_true(v->value);
11033 } else if (!strcasecmp(v->name, "sendcalleridafter")) {
11034 sendcalleridafter = atoi(v->value);
11035 } else if (!strcasecmp(v->name, "defaultcic")) {
11036 ast_copy_string(defaultcic, v->value, sizeof(defaultcic));
11037 } else if (!strcasecmp(v->name, "defaultozz")) {
11038 ast_copy_string(defaultozz, v->value, sizeof(defaultozz));
11040 } else if (!skipchannels)
11041 ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
11042 v = v->next;
11044 if (!found_pseudo && reload == 0) {
11045 /* Make sure pseudo isn't a member of any groups if
11046 we're automatically making it. */
11047 cur_group = 0;
11048 cur_callergroup = 0;
11049 cur_pickupgroup = 0;
11051 tmp = mkintf(CHAN_PSEUDO, cur_signalling, cur_signalling, cur_radio, NULL, reload);
11053 if (tmp) {
11054 if (option_verbose > 2)
11055 ast_verbose(VERBOSE_PREFIX_3 "Automatically generated pseudo channel\n");
11056 } else {
11057 ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
11060 return 0;
11063 static int setup_zap(int reload)
11065 struct ast_config *cfg;
11066 struct ast_variable *v;
11067 struct ast_variable *vjb;
11068 int res;
11070 #ifdef HAVE_PRI
11071 char *c;
11072 int spanno;
11073 int i, x;
11074 int logicalspan;
11075 int trunkgroup;
11076 int dchannels[NUM_DCHANS];
11077 #endif
11079 cfg = ast_config_load(config);
11081 /* Error if we have no config file */
11082 if (!cfg) {
11083 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
11084 return 0;
11087 /* It's a little silly to lock it, but we mind as well just to be sure */
11088 ast_mutex_lock(&iflock);
11089 #ifdef HAVE_PRI
11090 if (!reload) {
11091 /* Process trunkgroups first */
11092 v = ast_variable_browse(cfg, "trunkgroups");
11093 while (v) {
11094 if (!strcasecmp(v->name, "trunkgroup")) {
11095 trunkgroup = atoi(v->value);
11096 if (trunkgroup > 0) {
11097 if ((c = strchr(v->value, ','))) {
11098 i = 0;
11099 memset(dchannels, 0, sizeof(dchannels));
11100 while (c && (i < NUM_DCHANS)) {
11101 dchannels[i] = atoi(c + 1);
11102 if (dchannels[i] < 0) {
11103 ast_log(LOG_WARNING, "D-channel for trunk group %d must be a postiive number at line %d of zapata.conf\n", trunkgroup, v->lineno);
11104 } else
11105 i++;
11106 c = strchr(c + 1, ',');
11108 if (i) {
11109 if (pri_create_trunkgroup(trunkgroup, dchannels)) {
11110 ast_log(LOG_WARNING, "Unable to create trunk group %d with Primary D-channel %d at line %d of zapata.conf\n", trunkgroup, dchannels[0], v->lineno);
11111 } else if (option_verbose > 1)
11112 ast_verbose(VERBOSE_PREFIX_2 "Created trunk group %d with Primary D-channel %d and %d backup%s\n", trunkgroup, dchannels[0], i - 1, (i == 1) ? "" : "s");
11113 } else
11114 ast_log(LOG_WARNING, "Trunk group %d lacks any valid D-channels at line %d of zapata.conf\n", trunkgroup, v->lineno);
11115 } else
11116 ast_log(LOG_WARNING, "Trunk group %d lacks a primary D-channel at line %d of zapata.conf\n", trunkgroup, v->lineno);
11117 } else
11118 ast_log(LOG_WARNING, "Trunk group identifier must be a positive integer at line %d of zapata.conf\n", v->lineno);
11119 } else if (!strcasecmp(v->name, "spanmap")) {
11120 spanno = atoi(v->value);
11121 if (spanno > 0) {
11122 if ((c = strchr(v->value, ','))) {
11123 trunkgroup = atoi(c + 1);
11124 if (trunkgroup > 0) {
11125 if ((c = strchr(c + 1, ',')))
11126 logicalspan = atoi(c + 1);
11127 else
11128 logicalspan = 0;
11129 if (logicalspan >= 0) {
11130 if (pri_create_spanmap(spanno - 1, trunkgroup, logicalspan)) {
11131 ast_log(LOG_WARNING, "Failed to map span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
11132 } else if (option_verbose > 1)
11133 ast_verbose(VERBOSE_PREFIX_2 "Mapped span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
11134 } else
11135 ast_log(LOG_WARNING, "Logical span must be a postive number, or '0' (for unspecified) at line %d of zapata.conf\n", v->lineno);
11136 } else
11137 ast_log(LOG_WARNING, "Trunk group must be a postive number at line %d of zapata.conf\n", v->lineno);
11138 } else
11139 ast_log(LOG_WARNING, "Missing trunk group for span map at line %d of zapata.conf\n", v->lineno);
11140 } else
11141 ast_log(LOG_WARNING, "Span number must be a postive integer at line %d of zapata.conf\n", v->lineno);
11142 } else {
11143 ast_log(LOG_NOTICE, "Ignoring unknown keyword '%s' in trunkgroups\n", v->name);
11145 v = v->next;
11148 #endif
11149 v = ast_variable_browse(cfg, "channels");
11150 /* Copy the default jb config over global_jbconf */
11151 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
11152 /* Traverse all variables to handle jb conf */
11153 for (vjb = v; vjb; vjb = vjb->next)
11154 ast_jb_read_conf(&global_jbconf, vjb->name, vjb->value);
11155 res = process_zap(v, reload, 0);
11156 ast_mutex_unlock(&iflock);
11157 ast_config_destroy(cfg);
11158 if (res)
11159 return res;
11160 cfg = ast_config_load("users.conf");
11161 if (cfg) {
11162 char *cat;
11163 const char *chans;
11164 process_zap(ast_variable_browse(cfg, "general"), 1, 1);
11165 for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
11166 if (!strcasecmp(cat, "general"))
11167 continue;
11168 chans = ast_variable_retrieve(cfg, cat, "zapchan");
11169 if (!ast_strlen_zero(chans)) {
11170 process_zap(ast_variable_browse(cfg, cat), 1, 1);
11171 build_channels(0, chans, 1, 0, NULL);
11174 ast_config_destroy(cfg);
11176 #ifdef HAVE_PRI
11177 if (!reload) {
11178 for (x = 0; x < NUM_SPANS; x++) {
11179 if (pris[x].pvts[0]) {
11180 if (start_pri(pris + x)) {
11181 ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
11182 return -1;
11183 } else if (option_verbose > 1)
11184 ast_verbose(VERBOSE_PREFIX_2 "Starting D-Channel on span %d\n", x + 1);
11188 #endif
11189 /* And start the monitor for the first time */
11190 restart_monitor();
11191 return 0;
11194 static int load_module(void)
11196 int res;
11198 #ifdef HAVE_PRI
11199 int y,i;
11200 memset(pris, 0, sizeof(pris));
11201 for (y = 0; y < NUM_SPANS; y++) {
11202 ast_mutex_init(&pris[y].lock);
11203 pris[y].offset = -1;
11204 pris[y].master = AST_PTHREADT_NULL;
11205 for (i = 0; i < NUM_DCHANS; i++)
11206 pris[y].fds[i] = -1;
11208 pri_set_error(zt_pri_error);
11209 pri_set_message(zt_pri_message);
11210 ast_register_application(zap_send_keypad_facility_app, zap_send_keypad_facility_exec,
11211 zap_send_keypad_facility_synopsis, zap_send_keypad_facility_descrip);
11212 #endif
11213 res = setup_zap(0);
11214 /* Make sure we can register our Zap channel type */
11215 if (res)
11216 return AST_MODULE_LOAD_DECLINE;
11217 if (ast_channel_register(&zap_tech)) {
11218 ast_log(LOG_ERROR, "Unable to register channel class 'Zap'\n");
11219 __unload_module();
11220 return -1;
11222 #ifdef HAVE_PRI
11223 ast_string_field_init(&inuse, 16);
11224 ast_string_field_set(&inuse, name, "GR-303InUse");
11225 ast_cli_register_multiple(zap_pri_cli, sizeof(zap_pri_cli) / sizeof(struct ast_cli_entry));
11226 #endif
11227 ast_cli_register_multiple(zap_cli, sizeof(zap_cli) / sizeof(struct ast_cli_entry));
11229 memset(round_robin, 0, sizeof(round_robin));
11230 ast_manager_register( "ZapTransfer", 0, action_transfer, "Transfer Zap Channel" );
11231 ast_manager_register( "ZapHangup", 0, action_transferhangup, "Hangup Zap Channel" );
11232 ast_manager_register( "ZapDialOffhook", 0, action_zapdialoffhook, "Dial over Zap channel while offhook" );
11233 ast_manager_register( "ZapDNDon", 0, action_zapdndon, "Toggle Zap channel Do Not Disturb status ON" );
11234 ast_manager_register( "ZapDNDoff", 0, action_zapdndoff, "Toggle Zap channel Do Not Disturb status OFF" );
11235 ast_manager_register("ZapShowChannels", 0, action_zapshowchannels, "Show status zapata channels");
11236 ast_manager_register("ZapRestart", 0, action_zaprestart, "Fully Restart zaptel channels (terminates calls)");
11238 return res;
11241 static int zt_sendtext(struct ast_channel *c, const char *text)
11243 #define END_SILENCE_LEN 400
11244 #define HEADER_MS 50
11245 #define TRAILER_MS 5
11246 #define HEADER_LEN ((HEADER_MS + TRAILER_MS) * 8)
11247 #define ASCII_BYTES_PER_CHAR 80
11249 unsigned char *buf,*mybuf;
11250 struct zt_pvt *p = c->tech_pvt;
11251 struct pollfd fds[1];
11252 int size,res,fd,len,x;
11253 int bytes=0;
11254 /* Initial carrier (imaginary) */
11255 float cr = 1.0;
11256 float ci = 0.0;
11257 float scont = 0.0;
11258 int index;
11260 index = zt_get_index(c, p, 0);
11261 if (index < 0) {
11262 ast_log(LOG_WARNING, "Huh? I don't exist?\n");
11263 return -1;
11265 if (!text[0]) return(0); /* if nothing to send, dont */
11266 if ((!p->tdd) && (!p->mate)) return(0); /* if not in TDD mode, just return */
11267 if (p->mate)
11268 buf = ast_malloc(((strlen(text) + 1) * ASCII_BYTES_PER_CHAR) + END_SILENCE_LEN + HEADER_LEN);
11269 else
11270 buf = ast_malloc(((strlen(text) + 1) * TDD_BYTES_PER_CHAR) + END_SILENCE_LEN);
11271 if (!buf)
11272 return -1;
11273 mybuf = buf;
11274 if (p->mate) {
11275 int codec = AST_LAW(p);
11276 for (x = 0; x < HEADER_MS; x++) { /* 50 ms of Mark */
11277 PUT_CLID_MARKMS;
11279 /* Put actual message */
11280 for (x = 0; text[x]; x++) {
11281 PUT_CLID(text[x]);
11283 for (x = 0; x < TRAILER_MS; x++) { /* 5 ms of Mark */
11284 PUT_CLID_MARKMS;
11286 len = bytes;
11287 buf = mybuf;
11288 } else {
11289 len = tdd_generate(p->tdd, buf, text);
11290 if (len < 1) {
11291 ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
11292 free(mybuf);
11293 return -1;
11296 memset(buf + len, 0x7f, END_SILENCE_LEN);
11297 len += END_SILENCE_LEN;
11298 fd = p->subs[index].zfd;
11299 while (len) {
11300 if (ast_check_hangup(c)) {
11301 free(mybuf);
11302 return -1;
11304 size = len;
11305 if (size > READ_SIZE)
11306 size = READ_SIZE;
11307 fds[0].fd = fd;
11308 fds[0].events = POLLOUT | POLLPRI;
11309 fds[0].revents = 0;
11310 res = poll(fds, 1, -1);
11311 if (!res) {
11312 ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
11313 continue;
11315 /* if got exception */
11316 if (fds[0].revents & POLLPRI)
11317 return -1;
11318 if (!(fds[0].revents & POLLOUT)) {
11319 ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
11320 continue;
11322 res = write(fd, buf, size);
11323 if (res != size) {
11324 if (res == -1) {
11325 free(mybuf);
11326 return -1;
11328 if (option_debug)
11329 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
11330 break;
11332 len -= size;
11333 buf += size;
11335 free(mybuf);
11336 return(0);
11340 static int reload(void)
11342 int res = 0;
11344 res = setup_zap(1);
11345 if (res) {
11346 ast_log(LOG_WARNING, "Reload of chan_zap.so is unsuccessful!\n");
11347 return -1;
11349 return 0;
11352 #ifdef ZAPATA_PRI
11353 #define tdesc "Zapata Telephony w/PRI"
11354 #else
11355 #define tdesc "Zapata Telephony"
11356 #endif
11358 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, tdesc,
11359 .load = load_module,
11360 .unload = unload_module,
11361 .reload = reload,