Merged revisions 61913 via svnmerge from
[asterisk-bristuff.git] / channels / chan_zap.c
blob3a8301c5e25e553dc64906f33b98ca9e53ab5103
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_vldtmf</depend>
42 <depend>zaptel</depend>
43 <depend>tonezone</depend>
44 <use>pri</use>
45 ***/
47 #include "asterisk.h"
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
51 #include <stdio.h>
52 #include <string.h>
53 #ifdef __NetBSD__
54 #include <pthread.h>
55 #include <signal.h>
56 #else
57 #include <sys/signal.h>
58 #endif
59 #include <errno.h>
60 #include <stdlib.h>
61 #if !defined(SOLARIS) && !defined(__FreeBSD__)
62 #include <stdint.h>
63 #endif
64 #include <unistd.h>
65 #include <sys/ioctl.h>
66 #include <math.h>
67 #include <ctype.h>
68 #include <zaptel/zaptel.h>
69 #include <zaptel/tonezone.h>
71 #ifdef HAVE_PRI
72 #include <libpri.h>
73 #endif
75 #include "asterisk/lock.h"
76 #include "asterisk/channel.h"
77 #include "asterisk/config.h"
78 #include "asterisk/logger.h"
79 #include "asterisk/module.h"
80 #include "asterisk/pbx.h"
81 #include "asterisk/options.h"
82 #include "asterisk/file.h"
83 #include "asterisk/ulaw.h"
84 #include "asterisk/alaw.h"
85 #include "asterisk/callerid.h"
86 #include "asterisk/adsi.h"
87 #include "asterisk/cli.h"
88 #include "asterisk/cdr.h"
89 #include "asterisk/features.h"
90 #include "asterisk/musiconhold.h"
91 #include "asterisk/say.h"
92 #include "asterisk/tdd.h"
93 #include "asterisk/app.h"
94 #include "asterisk/dsp.h"
95 #include "asterisk/astdb.h"
96 #include "asterisk/manager.h"
97 #include "asterisk/causes.h"
98 #include "asterisk/term.h"
99 #include "asterisk/utils.h"
100 #include "asterisk/transcap.h"
101 #include "asterisk/stringfields.h"
102 #include "asterisk/abstract_jb.h"
103 #include "asterisk/smdi.h"
104 #include "asterisk/astobj.h"
105 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
107 /*! Global jitterbuffer configuration - by default, jb is disabled */
108 static struct ast_jb_conf default_jbconf =
110 .flags = 0,
111 .max_size = -1,
112 .resync_threshold = -1,
113 .impl = ""
115 static struct ast_jb_conf global_jbconf;
117 #if !defined(ZT_SIG_EM_E1) || (defined(HAVE_PRI) && !defined(ZT_SIG_HARDHDLC))
118 #error "Your zaptel is too old. Please update"
119 #endif
121 #ifndef ZT_TONEDETECT
122 /* Work around older code with no tone detect */
123 #define ZT_EVENT_DTMFDOWN 0
124 #define ZT_EVENT_DTMFUP 0
125 #endif
127 /* define this to send PRI user-user information elements */
128 #undef SUPPORT_USERUSER
130 /*!
131 * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
132 * the user hangs up to reset the state machine so ring works properly.
133 * This is used to be able to support kewlstart by putting the zhone in
134 * groundstart mode since their forward disconnect supervision is entirely
135 * broken even though their documentation says it isn't and their support
136 * is entirely unwilling to provide any assistance with their channel banks
137 * even though their web site says they support their products for life.
139 /* #define ZHONE_HACK */
141 /*! \note
142 * Define if you want to check the hook state for an FXO (FXS signalled) interface
143 * before dialing on it. Certain FXO interfaces always think they're out of
144 * service with this method however.
146 /* #define ZAP_CHECK_HOOKSTATE */
148 /*! \brief Typically, how many rings before we should send Caller*ID */
149 #define DEFAULT_CIDRINGS 1
151 #define CHANNEL_PSEUDO -12
153 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
155 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
156 #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))
158 static const char tdesc[] = "Zapata Telephony Driver"
159 #ifdef HAVE_PRI
160 " w/PRI"
161 #endif
164 static const char config[] = "zapata.conf";
166 #define SIG_EM ZT_SIG_EM
167 #define SIG_EMWINK (0x0100000 | ZT_SIG_EM)
168 #define SIG_FEATD (0x0200000 | ZT_SIG_EM)
169 #define SIG_FEATDMF (0x0400000 | ZT_SIG_EM)
170 #define SIG_FEATB (0x0800000 | ZT_SIG_EM)
171 #define SIG_E911 (0x1000000 | ZT_SIG_EM)
172 #define SIG_FEATDMF_TA (0x2000000 | ZT_SIG_EM)
173 #define SIG_FGC_CAMA (0x4000000 | ZT_SIG_EM)
174 #define SIG_FGC_CAMAMF (0x8000000 | ZT_SIG_EM)
175 #define SIG_FXSLS ZT_SIG_FXSLS
176 #define SIG_FXSGS ZT_SIG_FXSGS
177 #define SIG_FXSKS ZT_SIG_FXSKS
178 #define SIG_FXOLS ZT_SIG_FXOLS
179 #define SIG_FXOGS ZT_SIG_FXOGS
180 #define SIG_FXOKS ZT_SIG_FXOKS
181 #define SIG_PRI ZT_SIG_CLEAR
182 #define SIG_SF ZT_SIG_SF
183 #define SIG_SFWINK (0x0100000 | ZT_SIG_SF)
184 #define SIG_SF_FEATD (0x0200000 | ZT_SIG_SF)
185 #define SIG_SF_FEATDMF (0x0400000 | ZT_SIG_SF)
186 #define SIG_SF_FEATB (0x0800000 | ZT_SIG_SF)
187 #define SIG_EM_E1 ZT_SIG_EM_E1
188 #define SIG_GR303FXOKS (0x0100000 | ZT_SIG_FXOKS)
189 #define SIG_GR303FXSKS (0x0100000 | ZT_SIG_FXSKS)
191 #define NUM_SPANS 32
192 #define NUM_DCHANS 4 /*!< No more than 4 d-channels */
193 #define MAX_CHANNELS 672 /*!< No more than a DS3 per trunk group */
195 #define CHAN_PSEUDO -2
197 #define DCHAN_PROVISIONED (1 << 0)
198 #define DCHAN_NOTINALARM (1 << 1)
199 #define DCHAN_UP (1 << 2)
201 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
203 static char defaultcic[64] = "";
204 static char defaultozz[64] = "";
206 static char language[MAX_LANGUAGE] = "";
207 static char progzone[10] = "";
209 static int usedistinctiveringdetection = 0;
210 static int distinctiveringaftercid = 0;
212 static int numbufs = 4;
214 #ifdef HAVE_PRI
215 static struct ast_channel inuse;
216 #ifdef PRI_GETSET_TIMERS
217 static int pritimers[PRI_MAX_TIMERS];
218 #endif
219 static int pridebugfd = -1;
220 static char pridebugfilename[1024] = "";
221 #endif
223 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
224 static int firstdigittimeout = 16000;
226 /*! \brief How long to wait for following digits (FXO logic) */
227 static int gendigittimeout = 8000;
229 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
230 static int matchdigittimeout = 3000;
232 /*! \brief Protect the interface list (of zt_pvt's) */
233 AST_MUTEX_DEFINE_STATIC(iflock);
236 static int ifcount = 0;
238 #ifdef HAVE_PRI
239 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
240 #endif
242 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
243 when it's doing something critical. */
244 AST_MUTEX_DEFINE_STATIC(monlock);
246 /*! \brief This is the thread for the monitor which checks for input on the channels
247 which are not currently in use. */
248 static pthread_t monitor_thread = AST_PTHREADT_NULL;
250 static int restart_monitor(void);
252 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);
254 static int zt_sendtext(struct ast_channel *c, const char *text);
256 /*! \brief Avoid the silly zt_getevent which ignores a bunch of events */
257 static inline int zt_get_event(int fd)
259 int j;
260 if (ioctl(fd, ZT_GETEVENT, &j) == -1)
261 return -1;
262 return j;
265 /*! \brief Avoid the silly zt_waitevent which ignores a bunch of events */
266 static inline int zt_wait_event(int fd)
268 int i, j = 0;
269 i = ZT_IOMUX_SIGEVENT;
270 if (ioctl(fd, ZT_IOMUX, &i) == -1)
271 return -1;
272 if (ioctl(fd, ZT_GETEVENT, &j) == -1)
273 return -1;
274 return j;
277 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
278 #define READ_SIZE 160
280 #define MASK_AVAIL (1 << 0) /*!< Channel available for PRI use */
281 #define MASK_INUSE (1 << 1) /*!< Channel currently in use */
283 #define CALLWAITING_SILENT_SAMPLES ( (300 * 8) / READ_SIZE) /*!< 300 ms */
284 #define CALLWAITING_REPEAT_SAMPLES ( (10000 * 8) / READ_SIZE) /*!< 300 ms */
285 #define CIDCW_EXPIRE_SAMPLES ( (500 * 8) / READ_SIZE) /*!< 500 ms */
286 #define MIN_MS_SINCE_FLASH ( (2000) ) /*!< 2000 ms */
287 #define DEFAULT_RINGT ( (8000 * 8) / READ_SIZE)
289 struct zt_pvt;
291 static int ringt_base = DEFAULT_RINGT;
293 #ifdef HAVE_PRI
295 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
296 #define PRI_CHANNEL(p) ((p) & 0xff)
297 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
298 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
300 struct zt_pri {
301 pthread_t master; /*!< Thread of master */
302 ast_mutex_t lock; /*!< Mutex */
303 char idleext[AST_MAX_EXTENSION]; /*!< Where to idle extra calls */
304 char idlecontext[AST_MAX_CONTEXT]; /*!< What context to use for idle */
305 char idledial[AST_MAX_EXTENSION]; /*!< What to dial before dumping */
306 int minunused; /*!< Min # of channels to keep empty */
307 int minidle; /*!< Min # of "idling" calls to keep active */
308 int nodetype; /*!< Node type */
309 int switchtype; /*!< Type of switch to emulate */
310 int nsf; /*!< Network-Specific Facilities */
311 int dialplan; /*!< Dialing plan */
312 int localdialplan; /*!< Local dialing plan */
313 char internationalprefix[10]; /*!< country access code ('00' for european dialplans) */
314 char nationalprefix[10]; /*!< area access code ('0' for european dialplans) */
315 char localprefix[20]; /*!< area access code + area code ('0'+area code for european dialplans) */
316 char privateprefix[20]; /*!< for private dialplans */
317 char unknownprefix[20]; /*!< for unknown dialplans */
318 int dchannels[NUM_DCHANS]; /*!< What channel are the dchannels on */
319 int trunkgroup; /*!< What our trunkgroup is */
320 int mastertrunkgroup; /*!< What trunk group is our master */
321 int prilogicalspan; /*!< Logical span number within trunk group */
322 int numchans; /*!< Num of channels we represent */
323 int overlapdial; /*!< In overlap dialing mode */
324 int facilityenable; /*!< Enable facility IEs */
325 struct pri *dchans[NUM_DCHANS]; /*!< Actual d-channels */
326 int dchanavail[NUM_DCHANS]; /*!< Whether each channel is available */
327 struct pri *pri; /*!< Currently active D-channel */
328 int debug;
329 int fds[NUM_DCHANS]; /*!< FD's for d-channels */
330 int offset;
331 int span;
332 int resetting;
333 int resetpos;
334 time_t lastreset; /*!< time when unused channels were last reset */
335 long resetinterval; /*!< Interval (in seconds) for resetting unused channels */
336 struct zt_pvt *pvts[MAX_CHANNELS]; /*!< Member channel pvt structs */
337 struct zt_pvt *crvs; /*!< Member CRV structs */
338 struct zt_pvt *crvend; /*!< Pointer to end of CRV structs */
342 static struct zt_pri pris[NUM_SPANS];
344 #if 0
345 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
346 #else
347 #define DEFAULT_PRI_DEBUG 0
348 #endif
350 static inline void pri_rel(struct zt_pri *pri)
352 ast_mutex_unlock(&pri->lock);
355 #else
356 /*! Shut up the compiler */
357 struct zt_pri;
358 #endif
360 #define SUB_REAL 0 /*!< Active call */
361 #define SUB_CALLWAIT 1 /*!< Call-Waiting call on hold */
362 #define SUB_THREEWAY 2 /*!< Three-way call */
364 /* Polarity states */
365 #define POLARITY_IDLE 0
366 #define POLARITY_REV 1
369 static struct zt_distRings drings;
371 struct distRingData {
372 int ring[3];
374 struct ringContextData {
375 char contextData[AST_MAX_CONTEXT];
377 struct zt_distRings {
378 struct distRingData ringnum[3];
379 struct ringContextData ringContext[3];
382 static char *subnames[] = {
383 "Real",
384 "Callwait",
385 "Threeway"
388 struct zt_subchannel {
389 int zfd;
390 struct ast_channel *owner;
391 int chan;
392 short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
393 struct ast_frame f; /*!< One frame for each channel. How did this ever work before? */
394 unsigned int needringing:1;
395 unsigned int needbusy:1;
396 unsigned int needcongestion:1;
397 unsigned int needcallerid:1;
398 unsigned int needanswer:1;
399 unsigned int needflash:1;
400 unsigned int needhold:1;
401 unsigned int needunhold:1;
402 unsigned int linear:1;
403 unsigned int inthreeway:1;
404 ZT_CONFINFO curconf;
407 #define CONF_USER_REAL (1 << 0)
408 #define CONF_USER_THIRDCALL (1 << 1)
410 #define MAX_SLAVES 4
412 static struct zt_pvt {
413 ast_mutex_t lock;
414 struct ast_channel *owner; /*!< Our current active owner (if applicable) */
415 /*!< Up to three channels can be associated with this call */
417 struct zt_subchannel sub_unused; /*!< Just a safety precaution */
418 struct zt_subchannel subs[3]; /*!< Sub-channels */
419 struct zt_confinfo saveconf; /*!< Saved conference info */
421 struct zt_pvt *slaves[MAX_SLAVES]; /*!< Slave to us (follows our conferencing) */
422 struct zt_pvt *master; /*!< Master to us (we follow their conferencing) */
423 int inconference; /*!< If our real should be in the conference */
425 int sig; /*!< Signalling style */
426 int radio; /*!< radio type */
427 int outsigmod; /*!< Outbound Signalling style (modifier) */
428 int oprmode; /*!< "Operator Services" mode */
429 struct zt_pvt *oprpeer; /*!< "Operator Services" peer tech_pvt ptr */
430 float rxgain;
431 float txgain;
432 int tonezone; /*!< tone zone for this chan, or -1 for default */
433 struct zt_pvt *next; /*!< Next channel in list */
434 struct zt_pvt *prev; /*!< Prev channel in list */
436 /* flags */
437 unsigned int adsi:1;
438 unsigned int answeronpolarityswitch:1;
439 unsigned int busydetect:1;
440 unsigned int callreturn:1;
441 unsigned int callwaiting:1;
442 unsigned int callwaitingcallerid:1;
443 unsigned int cancallforward:1;
444 unsigned int canpark:1;
445 unsigned int confirmanswer:1; /*!< Wait for '#' to confirm answer */
446 unsigned int destroy:1;
447 unsigned int didtdd:1; /*!< flag to say its done it once */
448 unsigned int dialednone:1;
449 unsigned int dialing:1;
450 unsigned int digital:1;
451 unsigned int dnd:1;
452 unsigned int echobreak:1;
453 unsigned int echocanbridged:1;
454 unsigned int echocanon:1;
455 unsigned int faxhandled:1; /*!< Has a fax tone already been handled? */
456 unsigned int firstradio:1;
457 unsigned int hanguponpolarityswitch:1;
458 unsigned int hardwaredtmf:1;
459 unsigned int hidecallerid:1;
460 unsigned int hidecalleridname:1; /*!< Hide just the name not the number for legacy PBX use */
461 unsigned int ignoredtmf:1;
462 unsigned int immediate:1; /*!< Answer before getting digits? */
463 unsigned int inalarm:1;
464 unsigned int mate:1; /*!< flag to say its in MATE mode */
465 unsigned int outgoing:1;
466 unsigned int overlapdial:1;
467 unsigned int permcallwaiting:1;
468 unsigned int permhidecallerid:1; /*!< Whether to hide our outgoing caller ID or not */
469 unsigned int priindication_oob:1;
470 unsigned int priexclusive:1;
471 unsigned int pulse:1;
472 unsigned int pulsedial:1; /*!< whether a pulse dial phone is detected */
473 unsigned int restrictcid:1; /*!< Whether restrict the callerid -> only send ANI */
474 unsigned int threewaycalling:1;
475 unsigned int transfer:1;
476 unsigned int use_callerid:1; /*!< Whether or not to use caller id on this channel */
477 unsigned int use_callingpres:1; /*!< Whether to use the callingpres the calling switch sends */
478 unsigned int usedistinctiveringdetection:1;
479 unsigned int zaptrcallerid:1; /*!< should we use the callerid from incoming call on zap transfer or not */
480 unsigned int transfertobusy:1; /*!< allow flash-transfers to busy channels */
481 #if defined(HAVE_PRI)
482 unsigned int alerting:1;
483 unsigned int alreadyhungup:1;
484 unsigned int isidlecall:1;
485 unsigned int proceeding:1;
486 unsigned int progress:1;
487 unsigned int resetting:1;
488 unsigned int setup_ack:1;
489 #endif
490 unsigned int use_smdi:1; /* Whether to use SMDI on this channel */
491 struct ast_smdi_interface *smdi_iface; /* The serial port to listen for SMDI data on */
493 struct zt_distRings drings;
495 char context[AST_MAX_CONTEXT];
496 char defcontext[AST_MAX_CONTEXT];
497 char exten[AST_MAX_EXTENSION];
498 char language[MAX_LANGUAGE];
499 char mohinterpret[MAX_MUSICCLASS];
500 char mohsuggest[MAX_MUSICCLASS];
501 #ifdef PRI_ANI
502 char cid_ani[AST_MAX_EXTENSION];
503 #endif
504 char cid_num[AST_MAX_EXTENSION];
505 int cid_ton; /*!< Type Of Number (TON) */
506 char cid_name[AST_MAX_EXTENSION];
507 char lastcid_num[AST_MAX_EXTENSION];
508 char lastcid_name[AST_MAX_EXTENSION];
509 char *origcid_num; /*!< malloced original callerid */
510 char *origcid_name; /*!< malloced original callerid */
511 char callwait_num[AST_MAX_EXTENSION];
512 char callwait_name[AST_MAX_EXTENSION];
513 char rdnis[AST_MAX_EXTENSION];
514 char dnid[AST_MAX_EXTENSION];
515 unsigned int group;
516 int law;
517 int confno; /*!< Our conference */
518 int confusers; /*!< Who is using our conference */
519 int propconfno; /*!< Propagated conference number */
520 ast_group_t callgroup;
521 ast_group_t pickupgroup;
522 int channel; /*!< Channel Number or CRV */
523 int span; /*!< Span number */
524 time_t guardtime; /*!< Must wait this much time before using for new call */
525 int cid_signalling; /*!< CID signalling type bell202 or v23 */
526 int cid_start; /*!< CID start indicator, polarity or ring */
527 int callingpres; /*!< The value of callling presentation that we're going to use when placing a PRI call */
528 int callwaitingrepeat; /*!< How many samples to wait before repeating call waiting */
529 int cidcwexpire; /*!< When to expire our muting for CID/CW */
530 unsigned char *cidspill;
531 int cidpos;
532 int cidlen;
533 int ringt;
534 int ringt_base;
535 int stripmsd;
536 int callwaitcas;
537 int callwaitrings;
538 int echocancel;
539 int echotraining;
540 char echorest[20];
541 int busycount;
542 int busy_tonelength;
543 int busy_quietlength;
544 int callprogress;
545 struct timeval flashtime; /*!< Last flash-hook time */
546 struct ast_dsp *dsp;
547 int cref; /*!< Call reference number */
548 ZT_DIAL_OPERATION dop;
549 int whichwink; /*!< SIG_FEATDMF_TA Which wink are we on? */
550 char finaldial[64];
551 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
552 int amaflags; /*!< AMA Flags */
553 struct tdd_state *tdd; /*!< TDD flag */
554 char call_forward[AST_MAX_EXTENSION];
555 char mailbox[AST_MAX_EXTENSION];
556 char dialdest[256];
557 int onhooktime;
558 int msgstate;
559 int distinctivering; /*!< Which distinctivering to use */
560 int cidrings; /*!< Which ring to deliver CID on */
561 int dtmfrelax; /*!< whether to run in relaxed DTMF mode */
562 int fake_event;
563 int polarityonanswerdelay;
564 struct timeval polaritydelaytv;
565 int sendcalleridafter;
566 #ifdef HAVE_PRI
567 struct zt_pri *pri;
568 struct zt_pvt *bearer;
569 struct zt_pvt *realcall;
570 q931_call *call;
571 int prioffset;
572 int logicalspan;
573 #endif
574 int polarity;
575 int dsp_features;
576 char begindigit;
577 } *iflist = NULL, *ifend = NULL;
579 /*! \brief Channel configuration from zapata.conf .
580 * This struct is used for parsing the [channels] section of zapata.conf.
581 * Generally there is a field here for every possible configuration item.
583 * The state of fields is saved along the parsing and whenever a 'channel'
584 * statement is reached, the current zt_chan_conf is used to configure the
585 * channel (struct zt_pvt)
587 * @seealso zt_chan_init for the default values.
589 struct zt_chan_conf {
590 struct zt_pvt chan;
591 #ifdef HAVE_PRI
592 struct zt_pri pri;
593 #endif
594 ZT_PARAMS timing;
596 char smdi_port[SMDI_MAX_FILENAME_LEN];
599 /** returns a new zt_chan_conf with default values (by-value) */
600 static struct zt_chan_conf zt_chan_conf_default(void) {
601 /* recall that if a field is not included here it is initialized
602 * to 0 or equivalent
604 struct zt_chan_conf conf = {
605 #ifdef HAVE_PRI
606 .pri = {
607 .nsf = PRI_NSF_NONE,
608 .switchtype = PRI_SWITCH_NI2,
609 .dialplan = PRI_NATIONAL_ISDN + 1,
610 .localdialplan = PRI_NATIONAL_ISDN + 1,
611 .nodetype = PRI_CPE,
613 .minunused = 2,
614 .idleext = "",
615 .idledial = "",
616 .internationalprefix = "",
617 .nationalprefix = "",
618 .localprefix = "",
619 .privateprefix = "",
620 .unknownprefix = "",
622 .resetinterval = 3600
624 #endif
625 .chan = {
626 .context = "default",
627 .cid_num = "",
628 .cid_name = "",
629 .mohinterpret = "default",
630 .mohsuggest = "",
631 .transfertobusy = 1,
633 .cid_signalling = CID_SIG_BELL,
634 .cid_start = CID_START_RING,
635 .zaptrcallerid = 0,
636 .use_callerid = 1,
637 .sig = -1,
638 .outsigmod = -1,
640 .tonezone = -1,
642 .echocancel = 1,
644 .busycount = 3,
646 .accountcode = "",
648 .mailbox = "",
651 .polarityonanswerdelay = 600,
653 .sendcalleridafter = DEFAULT_CIDRINGS
655 .timing = {
656 .prewinktime = -1,
657 .preflashtime = -1,
658 .winktime = -1,
659 .flashtime = -1,
660 .starttime = -1,
661 .rxwinktime = -1,
662 .rxflashtime = -1,
663 .debouncetime = -1
665 .smdi_port = "/dev/ttyS0",
668 return conf;
672 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
673 static int zt_digit_begin(struct ast_channel *ast, char digit);
674 static int zt_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
675 static int zt_sendtext(struct ast_channel *c, const char *text);
676 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
677 static int zt_hangup(struct ast_channel *ast);
678 static int zt_answer(struct ast_channel *ast);
679 static struct ast_frame *zt_read(struct ast_channel *ast);
680 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
681 static struct ast_frame *zt_exception(struct ast_channel *ast);
682 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
683 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
684 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
685 static int zt_func_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
687 static const struct ast_channel_tech zap_tech = {
688 .type = "Zap",
689 .description = tdesc,
690 .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
691 .requester = zt_request,
692 .send_digit_begin = zt_digit_begin,
693 .send_digit_end = zt_digit_end,
694 .send_text = zt_sendtext,
695 .call = zt_call,
696 .hangup = zt_hangup,
697 .answer = zt_answer,
698 .read = zt_read,
699 .write = zt_write,
700 .bridge = zt_bridge,
701 .exception = zt_exception,
702 .indicate = zt_indicate,
703 .fixup = zt_fixup,
704 .setoption = zt_setoption,
705 .func_channel_read = zt_func_read,
708 #ifdef HAVE_PRI
709 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
710 #else
711 #define GET_CHANNEL(p) ((p)->channel)
712 #endif
714 struct zt_pvt *round_robin[32];
716 #ifdef HAVE_PRI
717 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
719 int res;
720 /* Grab the lock first */
721 do {
722 res = ast_mutex_trylock(&pri->lock);
723 if (res) {
724 ast_mutex_unlock(&pvt->lock);
725 /* Release the lock and try again */
726 usleep(1);
727 ast_mutex_lock(&pvt->lock);
729 } while (res);
730 /* Then break the poll */
731 pthread_kill(pri->master, SIGURG);
732 return 0;
734 #endif
736 #define NUM_CADENCE_MAX 25
737 static int num_cadence = 4;
738 static int user_has_defined_cadences = 0;
740 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
741 { { 125, 125, 2000, 4000 } }, /*!< Quick chirp followed by normal ring */
742 { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
743 { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
744 { { 1000, 500, 2500, 5000 } }, /*!< Long ring */
747 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
748 * is 1, the second pause is 2 and so on.
751 static int cidrings[NUM_CADENCE_MAX] = {
752 2, /*!< Right after first long ring */
753 4, /*!< Right after long part */
754 3, /*!< After third chirp */
755 2, /*!< Second spell */
758 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
759 (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
761 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
762 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
764 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
766 int res;
767 if (p->subs[0].owner == ast)
768 res = 0;
769 else if (p->subs[1].owner == ast)
770 res = 1;
771 else if (p->subs[2].owner == ast)
772 res = 2;
773 else {
774 res = -1;
775 if (!nullok)
776 ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
778 return res;
781 #ifdef HAVE_PRI
782 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
783 #else
784 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
785 #endif
787 #ifdef HAVE_PRI
788 if (pri)
789 ast_mutex_unlock(&pri->lock);
790 #endif
791 for (;;) {
792 if (p->subs[a].owner) {
793 if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
794 ast_mutex_unlock(&p->lock);
795 usleep(1);
796 ast_mutex_lock(&p->lock);
797 } else {
798 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
799 ast_mutex_unlock(&p->subs[a].owner->lock);
800 break;
802 } else
803 break;
805 #ifdef HAVE_PRI
806 if (pri)
807 ast_mutex_lock(&pri->lock);
808 #endif
811 #ifdef HAVE_PRI
812 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, struct zt_pri *pri)
813 #else
814 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *pri)
815 #endif
817 /* We must unlock the PRI to avoid the possibility of a deadlock */
818 #ifdef HAVE_PRI
819 if (pri)
820 ast_mutex_unlock(&pri->lock);
821 #endif
822 for (;;) {
823 if (p->owner) {
824 if (ast_mutex_trylock(&p->owner->lock)) {
825 ast_mutex_unlock(&p->lock);
826 usleep(1);
827 ast_mutex_lock(&p->lock);
828 } else {
829 ast_queue_frame(p->owner, f);
830 ast_mutex_unlock(&p->owner->lock);
831 break;
833 } else
834 break;
836 #ifdef HAVE_PRI
837 if (pri)
838 ast_mutex_lock(&pri->lock);
839 #endif
842 static int restore_gains(struct zt_pvt *p);
844 static void swap_subs(struct zt_pvt *p, int a, int b)
846 int tchan;
847 int tinthreeway;
848 struct ast_channel *towner;
850 ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
852 tchan = p->subs[a].chan;
853 towner = p->subs[a].owner;
854 tinthreeway = p->subs[a].inthreeway;
856 p->subs[a].chan = p->subs[b].chan;
857 p->subs[a].owner = p->subs[b].owner;
858 p->subs[a].inthreeway = p->subs[b].inthreeway;
860 p->subs[b].chan = tchan;
861 p->subs[b].owner = towner;
862 p->subs[b].inthreeway = tinthreeway;
864 if (p->subs[a].owner)
865 p->subs[a].owner->fds[0] = p->subs[a].zfd;
866 if (p->subs[b].owner)
867 p->subs[b].owner->fds[0] = p->subs[b].zfd;
868 wakeup_sub(p, a, NULL);
869 wakeup_sub(p, b, NULL);
872 static int zt_open(char *fn)
874 int fd;
875 int isnum;
876 int chan = 0;
877 int bs;
878 int x;
879 isnum = 1;
880 for (x = 0; x < strlen(fn); x++) {
881 if (!isdigit(fn[x])) {
882 isnum = 0;
883 break;
886 if (isnum) {
887 chan = atoi(fn);
888 if (chan < 1) {
889 ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
890 return -1;
892 fn = "/dev/zap/channel";
894 fd = open(fn, O_RDWR | O_NONBLOCK);
895 if (fd < 0) {
896 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
897 return -1;
899 if (chan) {
900 if (ioctl(fd, ZT_SPECIFY, &chan)) {
901 x = errno;
902 close(fd);
903 errno = x;
904 ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
905 return -1;
908 bs = READ_SIZE;
909 if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) return -1;
910 return fd;
913 static void zt_close(int fd)
915 if (fd > 0)
916 close(fd);
919 static int zt_setlinear(int zfd, int linear)
921 int res;
922 res = ioctl(zfd, ZT_SETLINEAR, &linear);
923 if (res)
924 return res;
925 return 0;
929 static int alloc_sub(struct zt_pvt *p, int x)
931 ZT_BUFFERINFO bi;
932 int res;
933 if (p->subs[x].zfd < 0) {
934 p->subs[x].zfd = zt_open("/dev/zap/pseudo");
935 if (p->subs[x].zfd > -1) {
936 res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
937 if (!res) {
938 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
939 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
940 bi.numbufs = numbufs;
941 res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
942 if (res < 0) {
943 ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
945 } else
946 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
947 if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
948 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d\n", p->subs[x].zfd);
949 zt_close(p->subs[x].zfd);
950 p->subs[x].zfd = -1;
951 return -1;
953 if (option_debug)
954 ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
955 return 0;
956 } else
957 ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
958 return -1;
960 ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
961 return -1;
964 static int unalloc_sub(struct zt_pvt *p, int x)
966 if (!x) {
967 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
968 return -1;
970 ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
971 if (p->subs[x].zfd > -1) {
972 zt_close(p->subs[x].zfd);
974 p->subs[x].zfd = -1;
975 p->subs[x].linear = 0;
976 p->subs[x].chan = 0;
977 p->subs[x].owner = NULL;
978 p->subs[x].inthreeway = 0;
979 p->polarity = POLARITY_IDLE;
980 memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
981 return 0;
984 static int digit_to_dtmfindex(char digit)
986 if (isdigit(digit))
987 return ZT_TONE_DTMF_BASE + (digit - '0');
988 else if (digit >= 'A' && digit <= 'D')
989 return ZT_TONE_DTMF_A + (digit - 'A');
990 else if (digit >= 'a' && digit <= 'd')
991 return ZT_TONE_DTMF_A + (digit - 'a');
992 else if (digit == '*')
993 return ZT_TONE_DTMF_s;
994 else if (digit == '#')
995 return ZT_TONE_DTMF_p;
996 else
997 return -1;
1000 static int zt_digit_begin(struct ast_channel *chan, char digit)
1002 struct zt_pvt *pvt;
1003 int index;
1004 int dtmf = -1;
1006 pvt = chan->tech_pvt;
1008 ast_mutex_lock(&pvt->lock);
1010 index = zt_get_index(chan, pvt, 0);
1012 if ((index != SUB_REAL) || !pvt->owner)
1013 goto out;
1015 #ifdef HAVE_PRI
1016 if ((pvt->sig == SIG_PRI) && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
1017 if (pvt->setup_ack) {
1018 if (!pri_grab(pvt, pvt->pri)) {
1019 pri_information(pvt->pri->pri, pvt->call, digit);
1020 pri_rel(pvt->pri);
1021 } else
1022 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
1023 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
1024 int res;
1025 ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
1026 res = strlen(pvt->dialdest);
1027 pvt->dialdest[res++] = digit;
1028 pvt->dialdest[res] = '\0';
1030 goto out;
1032 #endif
1033 if ((dtmf = digit_to_dtmfindex(digit)) == -1)
1034 goto out;
1036 if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &dtmf)) {
1037 int res;
1038 ZT_DIAL_OPERATION zo = {
1039 .op = ZT_DIAL_OP_APPEND,
1040 .dialstr[0] = 'T',
1041 .dialstr[1] = digit,
1042 .dialstr[2] = 0,
1044 if ((res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
1045 ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
1046 else
1047 pvt->dialing = 1;
1048 } else {
1049 ast_log(LOG_DEBUG, "Started VLDTMF digit '%c'\n", digit);
1050 pvt->dialing = 1;
1051 pvt->begindigit = digit;
1054 out:
1055 ast_mutex_unlock(&pvt->lock);
1057 return 0;
1060 static int zt_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1062 struct zt_pvt *pvt;
1063 int res = 0;
1064 int index;
1065 int x;
1067 pvt = chan->tech_pvt;
1069 ast_mutex_lock(&pvt->lock);
1071 index = zt_get_index(chan, pvt, 0);
1073 if ((index != SUB_REAL) || !pvt->owner || pvt->pulse)
1074 goto out;
1076 #ifdef HAVE_PRI
1077 /* This means that the digit was already sent via PRI signalling */
1078 if (pvt->sig == SIG_PRI && !pvt->begindigit)
1079 goto out;
1080 #endif
1082 if (pvt->begindigit) {
1083 x = -1;
1084 ast_log(LOG_DEBUG, "Ending VLDTMF digit '%c'\n", digit);
1085 res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &x);
1086 pvt->dialing = 0;
1087 pvt->begindigit = 0;
1090 out:
1091 ast_mutex_unlock(&pvt->lock);
1093 return res;
1096 static char *events[] = {
1097 "No event",
1098 "On hook",
1099 "Ring/Answered",
1100 "Wink/Flash",
1101 "Alarm",
1102 "No more alarm",
1103 "HDLC Abort",
1104 "HDLC Overrun",
1105 "HDLC Bad FCS",
1106 "Dial Complete",
1107 "Ringer On",
1108 "Ringer Off",
1109 "Hook Transition Complete",
1110 "Bits Changed",
1111 "Pulse Start",
1112 "Timer Expired",
1113 "Timer Ping",
1114 "Polarity Reversal",
1115 "Ring Begin",
1118 static struct {
1119 int alarm;
1120 char *name;
1121 } alarms[] = {
1122 { ZT_ALARM_RED, "Red Alarm" },
1123 { ZT_ALARM_YELLOW, "Yellow Alarm" },
1124 { ZT_ALARM_BLUE, "Blue Alarm" },
1125 { ZT_ALARM_RECOVER, "Recovering" },
1126 { ZT_ALARM_LOOPBACK, "Loopback" },
1127 { ZT_ALARM_NOTOPEN, "Not Open" },
1128 { ZT_ALARM_NONE, "None" },
1131 static char *alarm2str(int alarm)
1133 int x;
1134 for (x = 0; x < sizeof(alarms) / sizeof(alarms[0]); x++) {
1135 if (alarms[x].alarm & alarm)
1136 return alarms[x].name;
1138 return alarm ? "Unknown Alarm" : "No Alarm";
1141 static char *event2str(int event)
1143 static char buf[256];
1144 if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
1145 return events[event];
1146 sprintf(buf, "Event %d", event); /* safe */
1147 return buf;
1150 #ifdef HAVE_PRI
1151 static char *dialplan2str(int dialplan)
1153 if (dialplan == -1) {
1154 return("Dynamically set dialplan in ISDN");
1156 return (pri_plan2str(dialplan));
1158 #endif
1160 static char *zap_sig2str(int sig)
1162 static char buf[256];
1163 switch (sig) {
1164 case SIG_EM:
1165 return "E & M Immediate";
1166 case SIG_EMWINK:
1167 return "E & M Wink";
1168 case SIG_EM_E1:
1169 return "E & M E1";
1170 case SIG_FEATD:
1171 return "Feature Group D (DTMF)";
1172 case SIG_FEATDMF:
1173 return "Feature Group D (MF)";
1174 case SIG_FEATDMF_TA:
1175 return "Feature Groud D (MF) Tandem Access";
1176 case SIG_FEATB:
1177 return "Feature Group B (MF)";
1178 case SIG_E911:
1179 return "E911 (MF)";
1180 case SIG_FGC_CAMA:
1181 return "FGC/CAMA (Dialpulse)";
1182 case SIG_FGC_CAMAMF:
1183 return "FGC/CAMA (MF)";
1184 case SIG_FXSLS:
1185 return "FXS Loopstart";
1186 case SIG_FXSGS:
1187 return "FXS Groundstart";
1188 case SIG_FXSKS:
1189 return "FXS Kewlstart";
1190 case SIG_FXOLS:
1191 return "FXO Loopstart";
1192 case SIG_FXOGS:
1193 return "FXO Groundstart";
1194 case SIG_FXOKS:
1195 return "FXO Kewlstart";
1196 case SIG_PRI:
1197 return "PRI Signalling";
1198 case SIG_SF:
1199 return "SF (Tone) Signalling Immediate";
1200 case SIG_SFWINK:
1201 return "SF (Tone) Signalling Wink";
1202 case SIG_SF_FEATD:
1203 return "SF (Tone) Signalling with Feature Group D (DTMF)";
1204 case SIG_SF_FEATDMF:
1205 return "SF (Tone) Signalling with Feature Group D (MF)";
1206 case SIG_SF_FEATB:
1207 return "SF (Tone) Signalling with Feature Group B (MF)";
1208 case SIG_GR303FXOKS:
1209 return "GR-303 Signalling with FXOKS";
1210 case SIG_GR303FXSKS:
1211 return "GR-303 Signalling with FXSKS";
1212 case 0:
1213 return "Pseudo Signalling";
1214 default:
1215 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1216 return buf;
1220 #define sig2str zap_sig2str
1222 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1224 /* If the conference already exists, and we're already in it
1225 don't bother doing anything */
1226 ZT_CONFINFO zi;
1228 memset(&zi, 0, sizeof(zi));
1229 zi.chan = 0;
1231 if (slavechannel > 0) {
1232 /* If we have only one slave, do a digital mon */
1233 zi.confmode = ZT_CONF_DIGITALMON;
1234 zi.confno = slavechannel;
1235 } else {
1236 if (!index) {
1237 /* Real-side and pseudo-side both participate in conference */
1238 zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1239 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1240 } else
1241 zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1242 zi.confno = p->confno;
1244 if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1245 return 0;
1246 if (c->zfd < 0)
1247 return 0;
1248 if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1249 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1250 return -1;
1252 if (slavechannel < 1) {
1253 p->confno = zi.confno;
1255 memcpy(&c->curconf, &zi, sizeof(c->curconf));
1256 ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1257 return 0;
1260 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1262 /* If they're listening to our channel, they're ours */
1263 if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1264 return 1;
1265 /* If they're a talker on our (allocated) conference, they're ours */
1266 if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1267 return 1;
1268 return 0;
1271 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1273 ZT_CONFINFO zi;
1274 if (/* Can't delete if there's no zfd */
1275 (c->zfd < 0) ||
1276 /* Don't delete from the conference if it's not our conference */
1277 !isourconf(p, c)
1278 /* Don't delete if we don't think it's conferenced at all (implied) */
1279 ) return 0;
1280 memset(&zi, 0, sizeof(zi));
1281 zi.chan = 0;
1282 zi.confno = 0;
1283 zi.confmode = 0;
1284 if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1285 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1286 return -1;
1288 ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1289 memcpy(&c->curconf, &zi, sizeof(c->curconf));
1290 return 0;
1293 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1295 int x;
1296 int useslavenative;
1297 struct zt_pvt *slave = NULL;
1298 /* Start out optimistic */
1299 useslavenative = 1;
1300 /* Update conference state in a stateless fashion */
1301 for (x = 0; x < 3; x++) {
1302 /* Any three-way calling makes slave native mode *definitely* out
1303 of the question */
1304 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1305 useslavenative = 0;
1307 /* If we don't have any 3-way calls, check to see if we have
1308 precisely one slave */
1309 if (useslavenative) {
1310 for (x = 0; x < MAX_SLAVES; x++) {
1311 if (p->slaves[x]) {
1312 if (slave) {
1313 /* Whoops already have a slave! No
1314 slave native and stop right away */
1315 slave = NULL;
1316 useslavenative = 0;
1317 break;
1318 } else {
1319 /* We have one slave so far */
1320 slave = p->slaves[x];
1325 /* If no slave, slave native definitely out */
1326 if (!slave)
1327 useslavenative = 0;
1328 else if (slave->law != p->law) {
1329 useslavenative = 0;
1330 slave = NULL;
1332 if (out)
1333 *out = slave;
1334 return useslavenative;
1337 static int reset_conf(struct zt_pvt *p)
1339 ZT_CONFINFO zi;
1340 memset(&zi, 0, sizeof(zi));
1341 p->confno = -1;
1342 memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1343 if (p->subs[SUB_REAL].zfd > -1) {
1344 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1345 ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1347 return 0;
1350 static int update_conf(struct zt_pvt *p)
1352 int needconf = 0;
1353 int x;
1354 int useslavenative;
1355 struct zt_pvt *slave = NULL;
1357 useslavenative = isslavenative(p, &slave);
1358 /* Start with the obvious, general stuff */
1359 for (x = 0; x < 3; x++) {
1360 /* Look for three way calls */
1361 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1362 conf_add(p, &p->subs[x], x, 0);
1363 needconf++;
1364 } else {
1365 conf_del(p, &p->subs[x], x);
1368 /* If we have a slave, add him to our conference now. or DAX
1369 if this is slave native */
1370 for (x = 0; x < MAX_SLAVES; x++) {
1371 if (p->slaves[x]) {
1372 if (useslavenative)
1373 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1374 else {
1375 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1376 needconf++;
1380 /* If we're supposed to be in there, do so now */
1381 if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1382 if (useslavenative)
1383 conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1384 else {
1385 conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1386 needconf++;
1389 /* If we have a master, add ourselves to his conference */
1390 if (p->master) {
1391 if (isslavenative(p->master, NULL)) {
1392 conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1393 } else {
1394 conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1397 if (!needconf) {
1398 /* Nobody is left (or should be left) in our conference.
1399 Kill it. */
1400 p->confno = -1;
1402 ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1403 return 0;
1406 static void zt_enable_ec(struct zt_pvt *p)
1408 int x;
1409 int res;
1410 if (!p)
1411 return;
1412 if (p->echocanon) {
1413 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1414 return;
1416 if (p->digital) {
1417 ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
1418 return;
1420 if (p->echocancel) {
1421 if (p->sig == SIG_PRI) {
1422 x = 1;
1423 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1424 if (res)
1425 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1427 x = p->echocancel;
1428 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1429 if (res)
1430 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1431 else {
1432 p->echocanon = 1;
1433 ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1435 } else
1436 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1439 static void zt_train_ec(struct zt_pvt *p)
1441 int x;
1442 int res;
1443 if (p && p->echocancel && p->echotraining) {
1444 x = p->echotraining;
1445 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1446 if (res)
1447 ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1448 else {
1449 ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1451 } else
1452 ast_log(LOG_DEBUG, "No echo training requested\n");
1455 static void zt_disable_ec(struct zt_pvt *p)
1457 int x;
1458 int res;
1459 if (p->echocancel) {
1460 x = 0;
1461 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1462 if (res)
1463 ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1464 else
1465 ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1467 p->echocanon = 0;
1470 static void fill_txgain(struct zt_gains *g, float gain, int law)
1472 int j;
1473 int k;
1474 float linear_gain = pow(10.0, gain / 20.0);
1476 switch (law) {
1477 case ZT_LAW_ALAW:
1478 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1479 if (gain) {
1480 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1481 if (k > 32767) k = 32767;
1482 if (k < -32767) k = -32767;
1483 g->txgain[j] = AST_LIN2A(k);
1484 } else {
1485 g->txgain[j] = j;
1488 break;
1489 case ZT_LAW_MULAW:
1490 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1491 if (gain) {
1492 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1493 if (k > 32767) k = 32767;
1494 if (k < -32767) k = -32767;
1495 g->txgain[j] = AST_LIN2MU(k);
1496 } else {
1497 g->txgain[j] = j;
1500 break;
1504 static void fill_rxgain(struct zt_gains *g, float gain, int law)
1506 int j;
1507 int k;
1508 float linear_gain = pow(10.0, gain / 20.0);
1510 switch (law) {
1511 case ZT_LAW_ALAW:
1512 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1513 if (gain) {
1514 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1515 if (k > 32767) k = 32767;
1516 if (k < -32767) k = -32767;
1517 g->rxgain[j] = AST_LIN2A(k);
1518 } else {
1519 g->rxgain[j] = j;
1522 break;
1523 case ZT_LAW_MULAW:
1524 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1525 if (gain) {
1526 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1527 if (k > 32767) k = 32767;
1528 if (k < -32767) k = -32767;
1529 g->rxgain[j] = AST_LIN2MU(k);
1530 } else {
1531 g->rxgain[j] = j;
1534 break;
1538 static int set_actual_txgain(int fd, int chan, float gain, int law)
1540 struct zt_gains g;
1541 int res;
1543 memset(&g, 0, sizeof(g));
1544 g.chan = chan;
1545 res = ioctl(fd, ZT_GETGAINS, &g);
1546 if (res) {
1547 ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1548 return res;
1551 fill_txgain(&g, gain, law);
1553 return ioctl(fd, ZT_SETGAINS, &g);
1556 static int set_actual_rxgain(int fd, int chan, float gain, int law)
1558 struct zt_gains g;
1559 int res;
1561 memset(&g, 0, sizeof(g));
1562 g.chan = chan;
1563 res = ioctl(fd, ZT_GETGAINS, &g);
1564 if (res) {
1565 ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1566 return res;
1569 fill_rxgain(&g, gain, law);
1571 return ioctl(fd, ZT_SETGAINS, &g);
1574 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1576 return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
1579 static int bump_gains(struct zt_pvt *p)
1581 int res;
1583 /* Bump receive gain by 5.0db */
1584 res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + 5.0, p->txgain, p->law);
1585 if (res) {
1586 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
1587 return -1;
1590 return 0;
1593 static int restore_gains(struct zt_pvt *p)
1595 int res;
1597 res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1598 if (res) {
1599 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
1600 return -1;
1603 return 0;
1606 static inline int zt_set_hook(int fd, int hs)
1608 int x, res;
1609 x = hs;
1610 res = ioctl(fd, ZT_HOOK, &x);
1611 if (res < 0)
1613 if (errno == EINPROGRESS) return 0;
1614 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1616 return res;
1619 static inline int zt_confmute(struct zt_pvt *p, int muted)
1621 int x, y, res;
1622 x = muted;
1623 if (p->sig == SIG_PRI) {
1624 y = 1;
1625 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1626 if (res)
1627 ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1629 res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1630 if (res < 0)
1631 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1632 return res;
1635 static int save_conference(struct zt_pvt *p)
1637 struct zt_confinfo c;
1638 int res;
1639 if (p->saveconf.confmode) {
1640 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1641 return -1;
1643 p->saveconf.chan = 0;
1644 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1645 if (res) {
1646 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1647 p->saveconf.confmode = 0;
1648 return -1;
1650 c.chan = 0;
1651 c.confno = 0;
1652 c.confmode = ZT_CONF_NORMAL;
1653 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1654 if (res) {
1655 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1656 return -1;
1658 if (option_debug)
1659 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1660 return 0;
1663 static int restore_conference(struct zt_pvt *p)
1665 int res;
1666 if (p->saveconf.confmode) {
1667 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1668 p->saveconf.confmode = 0;
1669 if (res) {
1670 ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1671 return -1;
1674 if (option_debug)
1675 ast_log(LOG_DEBUG, "Restored conferencing\n");
1676 return 0;
1679 static int send_callerid(struct zt_pvt *p);
1681 static int send_cwcidspill(struct zt_pvt *p)
1683 p->callwaitcas = 0;
1684 p->cidcwexpire = 0;
1685 if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
1686 return -1;
1687 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1688 /* Make sure we account for the end */
1689 p->cidlen += READ_SIZE * 4;
1690 p->cidpos = 0;
1691 send_callerid(p);
1692 if (option_verbose > 2)
1693 ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID. Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1694 return 0;
1697 static int has_voicemail(struct zt_pvt *p)
1700 return ast_app_has_voicemail(p->mailbox, NULL);
1703 static int send_callerid(struct zt_pvt *p)
1705 /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1706 int res;
1707 /* Take out of linear mode if necessary */
1708 if (p->subs[SUB_REAL].linear) {
1709 p->subs[SUB_REAL].linear = 0;
1710 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1712 while (p->cidpos < p->cidlen) {
1713 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1714 if (res < 0) {
1715 if (errno == EAGAIN)
1716 return 0;
1717 else {
1718 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1719 return -1;
1722 if (!res)
1723 return 0;
1724 p->cidpos += res;
1726 free(p->cidspill);
1727 p->cidspill = NULL;
1728 if (p->callwaitcas) {
1729 /* Wait for CID/CW to expire */
1730 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1731 } else
1732 restore_conference(p);
1733 return 0;
1736 static int zt_callwait(struct ast_channel *ast)
1738 struct zt_pvt *p = ast->tech_pvt;
1739 p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1740 if (p->cidspill) {
1741 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1742 free(p->cidspill);
1744 if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
1745 return -1;
1746 save_conference(p);
1747 /* Silence */
1748 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1749 if (!p->callwaitrings && p->callwaitingcallerid) {
1750 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1751 p->callwaitcas = 1;
1752 p->cidlen = 2400 + 680 + READ_SIZE * 4;
1753 } else {
1754 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1755 p->callwaitcas = 0;
1756 p->cidlen = 2400 + READ_SIZE * 4;
1758 p->cidpos = 0;
1759 send_callerid(p);
1761 return 0;
1764 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1766 struct zt_pvt *p = ast->tech_pvt;
1767 int x, res, index,mysig;
1768 char *c, *n, *l;
1769 #ifdef HAVE_PRI
1770 char *s = NULL;
1771 #endif
1772 char dest[256]; /* must be same length as p->dialdest */
1773 ast_mutex_lock(&p->lock);
1774 ast_copy_string(dest, rdest, sizeof(dest));
1775 ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
1776 if ((ast->_state == AST_STATE_BUSY)) {
1777 p->subs[SUB_REAL].needbusy = 1;
1778 ast_mutex_unlock(&p->lock);
1779 return 0;
1781 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1782 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1783 ast_mutex_unlock(&p->lock);
1784 return -1;
1786 p->dialednone = 0;
1787 if ((p->radio || (p->oprmode < 0))) /* if a radio channel, up immediately */
1789 /* Special pseudo -- automatically up */
1790 ast_setstate(ast, AST_STATE_UP);
1791 ast_mutex_unlock(&p->lock);
1792 return 0;
1794 x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1795 res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1796 if (res)
1797 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1798 p->outgoing = 1;
1800 set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1802 mysig = p->sig;
1803 if (p->outsigmod > -1)
1804 mysig = p->outsigmod;
1806 switch (mysig) {
1807 case SIG_FXOLS:
1808 case SIG_FXOGS:
1809 case SIG_FXOKS:
1810 if (p->owner == ast) {
1811 /* Normal ring, on hook */
1813 /* Don't send audio while on hook, until the call is answered */
1814 p->dialing = 1;
1815 if (p->use_callerid) {
1816 /* Generate the Caller-ID spill if desired */
1817 if (p->cidspill) {
1818 ast_log(LOG_WARNING, "cidspill already exists??\n");
1819 free(p->cidspill);
1821 p->callwaitcas = 0;
1822 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
1823 p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1824 p->cidpos = 0;
1825 send_callerid(p);
1828 /* Choose proper cadence */
1829 if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1830 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering - 1]))
1831 ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1832 p->cidrings = cidrings[p->distinctivering - 1];
1833 } else {
1834 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1835 ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1836 p->cidrings = p->sendcalleridafter;
1839 /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1840 c = strchr(dest, '/');
1841 if (c)
1842 c++;
1843 if (c && (strlen(c) < p->stripmsd)) {
1844 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1845 c = NULL;
1847 if (c) {
1848 p->dop.op = ZT_DIAL_OP_REPLACE;
1849 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1850 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1851 } else {
1852 p->dop.dialstr[0] = '\0';
1854 x = ZT_RING;
1855 if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1856 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1857 ast_mutex_unlock(&p->lock);
1858 return -1;
1860 p->dialing = 1;
1861 } else {
1862 /* Call waiting call */
1863 p->callwaitrings = 0;
1864 if (ast->cid.cid_num)
1865 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
1866 else
1867 p->callwait_num[0] = '\0';
1868 if (ast->cid.cid_name)
1869 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
1870 else
1871 p->callwait_name[0] = '\0';
1872 /* Call waiting tone instead */
1873 if (zt_callwait(ast)) {
1874 ast_mutex_unlock(&p->lock);
1875 return -1;
1877 /* Make ring-back */
1878 if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1879 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1882 n = ast->cid.cid_name;
1883 l = ast->cid.cid_num;
1884 if (l)
1885 ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
1886 else
1887 p->lastcid_num[0] = '\0';
1888 if (n)
1889 ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
1890 else
1891 p->lastcid_name[0] = '\0';
1892 ast_setstate(ast, AST_STATE_RINGING);
1893 index = zt_get_index(ast, p, 0);
1894 if (index > -1) {
1895 p->subs[index].needringing = 1;
1897 break;
1898 case SIG_FXSLS:
1899 case SIG_FXSGS:
1900 case SIG_FXSKS:
1901 case SIG_EMWINK:
1902 case SIG_EM:
1903 case SIG_EM_E1:
1904 case SIG_FEATD:
1905 case SIG_FEATDMF:
1906 case SIG_E911:
1907 case SIG_FGC_CAMA:
1908 case SIG_FGC_CAMAMF:
1909 case SIG_FEATB:
1910 case SIG_SFWINK:
1911 case SIG_SF:
1912 case SIG_SF_FEATD:
1913 case SIG_SF_FEATDMF:
1914 case SIG_FEATDMF_TA:
1915 case SIG_SF_FEATB:
1916 c = strchr(dest, '/');
1917 if (c)
1918 c++;
1919 else
1920 c = "";
1921 if (strlen(c) < p->stripmsd) {
1922 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1923 ast_mutex_unlock(&p->lock);
1924 return -1;
1926 #ifdef HAVE_PRI
1927 /* Start the trunk, if not GR-303 */
1928 if (!p->pri) {
1929 #endif
1930 x = ZT_START;
1931 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1932 if (res < 0) {
1933 if (errno != EINPROGRESS) {
1934 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1935 ast_mutex_unlock(&p->lock);
1936 return -1;
1939 #ifdef HAVE_PRI
1941 #endif
1942 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1943 p->dop.op = ZT_DIAL_OP_REPLACE;
1945 c += p->stripmsd;
1947 switch (mysig) {
1948 case SIG_FEATD:
1949 l = ast->cid.cid_num;
1950 if (l)
1951 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
1952 else
1953 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
1954 break;
1955 case SIG_FEATDMF:
1956 l = ast->cid.cid_num;
1957 if (l)
1958 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
1959 else
1960 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
1961 break;
1962 case SIG_FEATDMF_TA:
1964 const char *cic, *ozz;
1966 /* If you have to go through a Tandem Access point you need to use this */
1967 ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
1968 if (!ozz)
1969 ozz = defaultozz;
1970 cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
1971 if (!cic)
1972 cic = defaultcic;
1973 if (!ozz || !cic) {
1974 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
1975 ast_mutex_unlock(&p->lock);
1976 return -1;
1978 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
1979 snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
1980 p->whichwink = 0;
1982 break;
1983 case SIG_E911:
1984 ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
1985 break;
1986 case SIG_FGC_CAMA:
1987 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
1988 break;
1989 case SIG_FGC_CAMAMF:
1990 case SIG_FEATB:
1991 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
1992 break;
1993 default:
1994 if (p->pulse)
1995 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
1996 else
1997 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
1998 break;
2001 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
2002 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2003 strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2004 p->echorest[sizeof(p->echorest) - 1] = '\0';
2005 p->echobreak = 1;
2006 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2007 } else
2008 p->echobreak = 0;
2009 if (!res) {
2010 if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
2011 x = ZT_ONHOOK;
2012 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2013 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
2014 ast_mutex_unlock(&p->lock);
2015 return -1;
2017 } else
2018 ast_log(LOG_DEBUG, "Deferring dialing...\n");
2019 p->dialing = 1;
2020 if (ast_strlen_zero(c))
2021 p->dialednone = 1;
2022 ast_setstate(ast, AST_STATE_DIALING);
2023 break;
2024 case 0:
2025 /* Special pseudo -- automatically up*/
2026 ast_setstate(ast, AST_STATE_UP);
2027 break;
2028 case SIG_PRI:
2029 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
2030 p->dialdest[0] = '\0';
2031 break;
2032 default:
2033 ast_log(LOG_DEBUG, "not yet implemented\n");
2034 ast_mutex_unlock(&p->lock);
2035 return -1;
2037 #ifdef HAVE_PRI
2038 if (p->pri) {
2039 struct pri_sr *sr;
2040 #ifdef SUPPORT_USERUSER
2041 const char *useruser;
2042 #endif
2043 int pridialplan;
2044 int dp_strip;
2045 int prilocaldialplan;
2046 int ldp_strip;
2047 int exclusive;
2048 const char *rr_str;
2049 int redirect_reason;
2051 c = strchr(dest, '/');
2052 if (c)
2053 c++;
2054 else
2055 c = dest;
2056 if (!p->hidecalleridname)
2057 n = ast->cid.cid_name;
2058 else
2059 n = NULL;
2060 if (!p->hidecallerid) {
2061 l = ast->cid.cid_num;
2062 n = ast->cid.cid_name;
2063 } else {
2064 l = NULL;
2065 n = NULL;
2067 if (strlen(c) < p->stripmsd) {
2068 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2069 ast_mutex_unlock(&p->lock);
2070 return -1;
2072 if (mysig != SIG_FXSKS) {
2073 p->dop.op = ZT_DIAL_OP_REPLACE;
2074 s = strchr(c + p->stripmsd, 'w');
2075 if (s) {
2076 if (strlen(s) > 1)
2077 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2078 else
2079 p->dop.dialstr[0] = '\0';
2080 *s = '\0';
2081 } else {
2082 p->dop.dialstr[0] = '\0';
2085 if (pri_grab(p, p->pri)) {
2086 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2087 ast_mutex_unlock(&p->lock);
2088 return -1;
2090 if (!(p->call = pri_new_call(p->pri->pri))) {
2091 ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2092 pri_rel(p->pri);
2093 ast_mutex_unlock(&p->lock);
2094 return -1;
2096 if (!(sr = pri_sr_new())) {
2097 ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2098 pri_rel(p->pri);
2099 ast_mutex_unlock(&p->lock);
2101 if (p->bearer || (mysig == SIG_FXSKS)) {
2102 if (p->bearer) {
2103 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);
2104 p->bearer->call = p->call;
2105 } else
2106 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
2107 pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2109 p->digital = IS_DIGITAL(ast->transfercapability);
2110 /* Add support for exclusive override */
2111 if (p->priexclusive)
2112 exclusive = 1;
2113 else {
2114 /* otherwise, traditional behavior */
2115 if (p->pri->nodetype == PRI_NETWORK)
2116 exclusive = 0;
2117 else
2118 exclusive = 1;
2121 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2122 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability,
2123 (p->digital ? -1 :
2124 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2125 if (p->pri->facilityenable)
2126 pri_facility_enable(p->pri->pri);
2128 if (option_verbose > 2)
2129 ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2130 dp_strip = 0;
2131 pridialplan = p->pri->dialplan - 1;
2132 if (pridialplan == -2) { /* compute dynamically */
2133 if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2134 dp_strip = strlen(p->pri->internationalprefix);
2135 pridialplan = PRI_INTERNATIONAL_ISDN;
2136 } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2137 dp_strip = strlen(p->pri->nationalprefix);
2138 pridialplan = PRI_NATIONAL_ISDN;
2139 } else {
2140 pridialplan = PRI_LOCAL_ISDN;
2143 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2145 ldp_strip = 0;
2146 prilocaldialplan = p->pri->localdialplan - 1;
2147 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
2148 if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2149 ldp_strip = strlen(p->pri->internationalprefix);
2150 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2151 } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2152 ldp_strip = strlen(p->pri->nationalprefix);
2153 prilocaldialplan = PRI_NATIONAL_ISDN;
2154 } else {
2155 prilocaldialplan = PRI_LOCAL_ISDN;
2158 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2159 p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2160 if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
2161 if (!strcasecmp(rr_str, "UNKNOWN"))
2162 redirect_reason = 0;
2163 else if (!strcasecmp(rr_str, "BUSY"))
2164 redirect_reason = 1;
2165 else if (!strcasecmp(rr_str, "NO_REPLY"))
2166 redirect_reason = 2;
2167 else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
2168 redirect_reason = 15;
2169 else
2170 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2171 } else
2172 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2173 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
2175 #ifdef SUPPORT_USERUSER
2176 /* User-user info */
2177 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2179 if (useruser)
2180 pri_sr_set_useruser(sr, useruser);
2181 #endif
2183 if (pri_setup(p->pri->pri, p->call, sr)) {
2184 ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n",
2185 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2186 pri_rel(p->pri);
2187 ast_mutex_unlock(&p->lock);
2188 pri_sr_free(sr);
2189 return -1;
2191 pri_sr_free(sr);
2192 ast_setstate(ast, AST_STATE_DIALING);
2193 pri_rel(p->pri);
2195 #endif
2196 ast_mutex_unlock(&p->lock);
2197 return 0;
2200 static void destroy_zt_pvt(struct zt_pvt **pvt)
2202 struct zt_pvt *p = *pvt;
2203 /* Remove channel from the list */
2204 if (p->prev)
2205 p->prev->next = p->next;
2206 if (p->next)
2207 p->next->prev = p->prev;
2208 if (p->use_smdi)
2209 ASTOBJ_UNREF(p->smdi_iface, ast_smdi_interface_destroy);
2210 ast_mutex_destroy(&p->lock);
2211 free(p);
2212 *pvt = NULL;
2215 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
2217 int owned = 0;
2218 int i = 0;
2220 if (!now) {
2221 if (cur->owner) {
2222 owned = 1;
2225 for (i = 0; i < 3; i++) {
2226 if (cur->subs[i].owner) {
2227 owned = 1;
2230 if (!owned) {
2231 if (prev) {
2232 prev->next = cur->next;
2233 if (prev->next)
2234 prev->next->prev = prev;
2235 else
2236 ifend = prev;
2237 } else {
2238 iflist = cur->next;
2239 if (iflist)
2240 iflist->prev = NULL;
2241 else
2242 ifend = NULL;
2244 if (cur->subs[SUB_REAL].zfd > -1) {
2245 zt_close(cur->subs[SUB_REAL].zfd);
2247 destroy_zt_pvt(&cur);
2249 } else {
2250 if (prev) {
2251 prev->next = cur->next;
2252 if (prev->next)
2253 prev->next->prev = prev;
2254 else
2255 ifend = prev;
2256 } else {
2257 iflist = cur->next;
2258 if (iflist)
2259 iflist->prev = NULL;
2260 else
2261 ifend = NULL;
2263 if (cur->subs[SUB_REAL].zfd > -1) {
2264 zt_close(cur->subs[SUB_REAL].zfd);
2266 destroy_zt_pvt(&cur);
2268 return 0;
2271 #ifdef HAVE_PRI
2272 static char *zap_send_keypad_facility_app = "ZapSendKeypadFacility";
2274 static char *zap_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
2276 static char *zap_send_keypad_facility_descrip =
2277 " ZapSendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
2278 " IE over the current channel.\n";
2280 static int zap_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2282 /* Data will be our digit string */
2283 struct zt_pvt *p;
2284 char *digits = (char *) data;
2286 if (ast_strlen_zero(digits)) {
2287 ast_log(LOG_DEBUG, "No digit string sent to application!\n");
2288 return -1;
2291 p = (struct zt_pvt *)chan->tech_pvt;
2293 if (!p) {
2294 ast_log(LOG_DEBUG, "Unable to find technology private\n");
2295 return -1;
2298 ast_mutex_lock(&p->lock);
2300 if (!p->pri || !p->call) {
2301 ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
2302 ast_mutex_unlock(&p->lock);
2303 return -1;
2306 if (!pri_grab(p, p->pri)) {
2307 pri_keypad_facility(p->pri->pri, p->call, digits);
2308 pri_rel(p->pri);
2309 } else {
2310 ast_log(LOG_DEBUG, "Unable to grab pri to send keypad facility!\n");
2311 ast_mutex_unlock(&p->lock);
2312 return -1;
2315 ast_mutex_unlock(&p->lock);
2317 return 0;
2320 static int pri_is_up(struct zt_pri *pri)
2322 int x;
2323 for (x = 0; x < NUM_DCHANS; x++) {
2324 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2325 return 1;
2327 return 0;
2330 static int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2332 bearer->owner = &inuse;
2333 bearer->realcall = crv;
2334 crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2335 if (crv->subs[SUB_REAL].owner)
2336 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2337 crv->bearer = bearer;
2338 crv->call = bearer->call;
2339 crv->pri = pri;
2340 return 0;
2343 static char *pri_order(int level)
2345 switch (level) {
2346 case 0:
2347 return "Primary";
2348 case 1:
2349 return "Secondary";
2350 case 2:
2351 return "Tertiary";
2352 case 3:
2353 return "Quaternary";
2354 default:
2355 return "<Unknown>";
2359 /* Returns fd of the active dchan */
2360 static int pri_active_dchan_fd(struct zt_pri *pri)
2362 int x = -1;
2364 for (x = 0; x < NUM_DCHANS; x++) {
2365 if ((pri->dchans[x] == pri->pri))
2366 break;
2369 return pri->fds[x];
2372 static int pri_find_dchan(struct zt_pri *pri)
2374 int oldslot = -1;
2375 struct pri *old;
2376 int newslot = -1;
2377 int x;
2378 old = pri->pri;
2379 for (x = 0; x < NUM_DCHANS; x++) {
2380 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2381 newslot = x;
2382 if (pri->dchans[x] == old) {
2383 oldslot = x;
2386 if (newslot < 0) {
2387 newslot = 0;
2388 ast_log(LOG_WARNING, "No D-channels available! Using Primary channel %d as D-channel anyway!\n",
2389 pri->dchannels[newslot]);
2391 if (old && (oldslot != newslot))
2392 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2393 pri->dchannels[oldslot], pri->dchannels[newslot]);
2394 pri->pri = pri->dchans[newslot];
2395 return 0;
2397 #endif
2399 static int zt_hangup(struct ast_channel *ast)
2401 int res;
2402 int index,x, law;
2403 /*static int restore_gains(struct zt_pvt *p);*/
2404 struct zt_pvt *p = ast->tech_pvt;
2405 struct zt_pvt *tmp = NULL;
2406 struct zt_pvt *prev = NULL;
2407 ZT_PARAMS par;
2409 if (option_debug)
2410 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2411 if (!ast->tech_pvt) {
2412 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2413 return 0;
2416 ast_mutex_lock(&p->lock);
2418 index = zt_get_index(ast, p, 1);
2420 if (p->sig == SIG_PRI) {
2421 x = 1;
2422 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2425 x = 0;
2426 zt_confmute(p, 0);
2427 restore_gains(p);
2428 if (p->origcid_num) {
2429 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2430 free(p->origcid_num);
2431 p->origcid_num = NULL;
2433 if (p->origcid_name) {
2434 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2435 free(p->origcid_name);
2436 p->origcid_name = NULL;
2438 if (p->dsp)
2439 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2440 if (p->exten)
2441 p->exten[0] = '\0';
2443 ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2444 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2445 p->ignoredtmf = 0;
2447 if (index > -1) {
2448 /* Real channel, do some fixup */
2449 p->subs[index].owner = NULL;
2450 p->subs[index].needanswer = 0;
2451 p->subs[index].needflash = 0;
2452 p->subs[index].needringing = 0;
2453 p->subs[index].needbusy = 0;
2454 p->subs[index].needcongestion = 0;
2455 p->subs[index].linear = 0;
2456 p->subs[index].needcallerid = 0;
2457 p->polarity = POLARITY_IDLE;
2458 zt_setlinear(p->subs[index].zfd, 0);
2459 if (index == SUB_REAL) {
2460 if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2461 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2462 if (p->subs[SUB_CALLWAIT].inthreeway) {
2463 /* We had flipped over to answer a callwait and now it's gone */
2464 ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2465 /* Move to the call-wait, but un-own us until they flip back. */
2466 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2467 unalloc_sub(p, SUB_CALLWAIT);
2468 p->owner = NULL;
2469 } else {
2470 /* The three way hung up, but we still have a call wait */
2471 ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still. Ditching the threeway.\n");
2472 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2473 unalloc_sub(p, SUB_THREEWAY);
2474 if (p->subs[SUB_REAL].inthreeway) {
2475 /* This was part of a three way call. Immediately make way for
2476 another call */
2477 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2478 p->owner = p->subs[SUB_REAL].owner;
2479 } else {
2480 /* This call hasn't been completed yet... Set owner to NULL */
2481 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2482 p->owner = NULL;
2484 p->subs[SUB_REAL].inthreeway = 0;
2486 } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2487 /* Move to the call-wait and switch back to them. */
2488 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2489 unalloc_sub(p, SUB_CALLWAIT);
2490 p->owner = p->subs[SUB_REAL].owner;
2491 if (p->owner->_state != AST_STATE_UP)
2492 p->subs[SUB_REAL].needanswer = 1;
2493 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2494 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
2495 } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2496 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2497 unalloc_sub(p, SUB_THREEWAY);
2498 if (p->subs[SUB_REAL].inthreeway) {
2499 /* This was part of a three way call. Immediately make way for
2500 another call */
2501 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2502 p->owner = p->subs[SUB_REAL].owner;
2503 } else {
2504 /* This call hasn't been completed yet... Set owner to NULL */
2505 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2506 p->owner = NULL;
2508 p->subs[SUB_REAL].inthreeway = 0;
2510 } else if (index == SUB_CALLWAIT) {
2511 /* Ditch the holding callwait call, and immediately make it availabe */
2512 if (p->subs[SUB_CALLWAIT].inthreeway) {
2513 /* This is actually part of a three way, placed on hold. Place the third part
2514 on music on hold now */
2515 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
2516 ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
2517 S_OR(p->mohsuggest, NULL),
2518 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2520 p->subs[SUB_THREEWAY].inthreeway = 0;
2521 /* Make it the call wait now */
2522 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2523 unalloc_sub(p, SUB_THREEWAY);
2524 } else
2525 unalloc_sub(p, SUB_CALLWAIT);
2526 } else if (index == SUB_THREEWAY) {
2527 if (p->subs[SUB_CALLWAIT].inthreeway) {
2528 /* The other party of the three way call is currently in a call-wait state.
2529 Start music on hold for them, and take the main guy out of the third call */
2530 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
2531 ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
2532 S_OR(p->mohsuggest, NULL),
2533 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2535 p->subs[SUB_CALLWAIT].inthreeway = 0;
2537 p->subs[SUB_REAL].inthreeway = 0;
2538 /* If this was part of a three way call index, let us make
2539 another three way call */
2540 unalloc_sub(p, SUB_THREEWAY);
2541 } else {
2542 /* This wasn't any sort of call, but how are we an index? */
2543 ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2547 if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2548 p->owner = NULL;
2549 p->ringt = 0;
2550 p->distinctivering = 0;
2551 p->confirmanswer = 0;
2552 p->cidrings = 1;
2553 p->outgoing = 0;
2554 p->digital = 0;
2555 p->faxhandled = 0;
2556 p->pulsedial = 0;
2557 p->onhooktime = time(NULL);
2558 #ifdef HAVE_PRI
2559 p->proceeding = 0;
2560 p->progress = 0;
2561 p->alerting = 0;
2562 p->setup_ack = 0;
2563 #endif
2564 if (p->dsp) {
2565 ast_dsp_free(p->dsp);
2566 p->dsp = NULL;
2569 law = ZT_LAW_DEFAULT;
2570 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2571 if (res < 0)
2572 ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2573 /* Perform low level hangup if no owner left */
2574 #ifdef HAVE_PRI
2575 if (p->pri) {
2576 #ifdef SUPPORT_USERUSER
2577 const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
2578 #endif
2580 /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2581 if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2582 if (!pri_grab(p, p->pri)) {
2583 if (p->alreadyhungup) {
2584 ast_log(LOG_DEBUG, "Already hungup... Calling hangup once, and clearing call\n");
2586 #ifdef SUPPORT_USERUSER
2587 pri_call_set_useruser(p->call, useruser);
2588 #endif
2590 pri_hangup(p->pri->pri, p->call, -1);
2591 p->call = NULL;
2592 if (p->bearer)
2593 p->bearer->call = NULL;
2594 } else {
2595 const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2596 int icause = ast->hangupcause ? ast->hangupcause : -1;
2597 ast_log(LOG_DEBUG, "Not yet hungup... Calling hangup once with icause, and clearing call\n");
2599 #ifdef SUPPORT_USERUSER
2600 pri_call_set_useruser(p->call, useruser);
2601 #endif
2603 p->alreadyhungup = 1;
2604 if (p->bearer)
2605 p->bearer->alreadyhungup = 1;
2606 if (cause) {
2607 if (atoi(cause))
2608 icause = atoi(cause);
2610 pri_hangup(p->pri->pri, p->call, icause);
2612 if (res < 0)
2613 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2614 pri_rel(p->pri);
2615 } else {
2616 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2617 res = -1;
2619 } else {
2620 if (p->bearer)
2621 ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2622 p->call = NULL;
2623 res = 0;
2626 #endif
2627 if (p->sig && (p->sig != SIG_PRI))
2628 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2629 if (res < 0) {
2630 ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2632 switch (p->sig) {
2633 case SIG_FXOGS:
2634 case SIG_FXOLS:
2635 case SIG_FXOKS:
2636 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2637 if (!res) {
2638 #if 0
2639 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2640 #endif
2641 /* If they're off hook, try playing congestion */
2642 if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
2643 tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2644 else
2645 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2647 break;
2648 case SIG_FXSGS:
2649 case SIG_FXSLS:
2650 case SIG_FXSKS:
2651 /* Make sure we're not made available for at least two seconds assuming
2652 we were actually used for an inbound or outbound call. */
2653 if (ast->_state != AST_STATE_RESERVED) {
2654 time(&p->guardtime);
2655 p->guardtime += 2;
2657 break;
2658 default:
2659 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2661 if (p->cidspill)
2662 free(p->cidspill);
2663 if (p->sig)
2664 zt_disable_ec(p);
2665 x = 0;
2666 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2667 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2668 p->didtdd = 0;
2669 p->cidspill = NULL;
2670 p->callwaitcas = 0;
2671 p->callwaiting = p->permcallwaiting;
2672 p->hidecallerid = p->permhidecallerid;
2673 p->dialing = 0;
2674 p->rdnis[0] = '\0';
2675 update_conf(p);
2676 reset_conf(p);
2677 /* Restore data mode */
2678 if (p->sig == SIG_PRI) {
2679 x = 0;
2680 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2682 #ifdef HAVE_PRI
2683 if (p->bearer) {
2684 ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2685 /* Free up the bearer channel as well, and
2686 don't use its file descriptor anymore */
2687 update_conf(p->bearer);
2688 reset_conf(p->bearer);
2689 p->bearer->owner = NULL;
2690 p->bearer->realcall = NULL;
2691 p->bearer = NULL;
2692 p->subs[SUB_REAL].zfd = -1;
2693 p->pri = NULL;
2695 #endif
2696 restart_monitor();
2699 p->callwaitingrepeat = 0;
2700 p->cidcwexpire = 0;
2701 p->oprmode = 0;
2702 ast->tech_pvt = NULL;
2703 ast_mutex_unlock(&p->lock);
2704 ast_module_unref(ast_module_info->self);
2705 if (option_verbose > 2)
2706 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2708 ast_mutex_lock(&iflock);
2709 tmp = iflist;
2710 prev = NULL;
2711 if (p->destroy) {
2712 while (tmp) {
2713 if (tmp == p) {
2714 destroy_channel(prev, tmp, 0);
2715 break;
2716 } else {
2717 prev = tmp;
2718 tmp = tmp->next;
2722 ast_mutex_unlock(&iflock);
2723 return 0;
2726 static int zt_answer(struct ast_channel *ast)
2728 struct zt_pvt *p = ast->tech_pvt;
2729 int res = 0;
2730 int index;
2731 int oldstate = ast->_state;
2732 ast_setstate(ast, AST_STATE_UP);
2733 ast_mutex_lock(&p->lock);
2734 index = zt_get_index(ast, p, 0);
2735 if (index < 0)
2736 index = SUB_REAL;
2737 /* nothing to do if a radio channel */
2738 if ((p->radio || (p->oprmode < 0))) {
2739 ast_mutex_unlock(&p->lock);
2740 return 0;
2742 switch (p->sig) {
2743 case SIG_FXSLS:
2744 case SIG_FXSGS:
2745 case SIG_FXSKS:
2746 p->ringt = 0;
2747 /* Fall through */
2748 case SIG_EM:
2749 case SIG_EM_E1:
2750 case SIG_EMWINK:
2751 case SIG_FEATD:
2752 case SIG_FEATDMF:
2753 case SIG_FEATDMF_TA:
2754 case SIG_E911:
2755 case SIG_FGC_CAMA:
2756 case SIG_FGC_CAMAMF:
2757 case SIG_FEATB:
2758 case SIG_SF:
2759 case SIG_SFWINK:
2760 case SIG_SF_FEATD:
2761 case SIG_SF_FEATDMF:
2762 case SIG_SF_FEATB:
2763 case SIG_FXOLS:
2764 case SIG_FXOGS:
2765 case SIG_FXOKS:
2766 /* Pick up the line */
2767 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2768 if (p->hanguponpolarityswitch) {
2769 gettimeofday(&p->polaritydelaytv, NULL);
2771 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2772 tone_zone_play_tone(p->subs[index].zfd, -1);
2773 p->dialing = 0;
2774 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2775 if (oldstate == AST_STATE_RINGING) {
2776 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2777 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2778 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2779 p->owner = p->subs[SUB_REAL].owner;
2782 if (p->sig & __ZT_SIG_FXS) {
2783 zt_enable_ec(p);
2784 zt_train_ec(p);
2786 break;
2787 #ifdef HAVE_PRI
2788 case SIG_PRI:
2789 /* Send a pri acknowledge */
2790 if (!pri_grab(p, p->pri)) {
2791 p->proceeding = 1;
2792 res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2793 pri_rel(p->pri);
2794 } else {
2795 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2796 res = -1;
2798 break;
2799 #endif
2800 case 0:
2801 ast_mutex_unlock(&p->lock);
2802 return 0;
2803 default:
2804 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2805 res = -1;
2807 ast_mutex_unlock(&p->lock);
2808 return res;
2811 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2813 char *cp;
2814 signed char *scp;
2815 int x;
2816 int index;
2817 struct zt_pvt *p = chan->tech_pvt, *pp;
2818 struct oprmode *oprmode;
2821 /* all supported options require data */
2822 if (!data || (datalen < 1)) {
2823 errno = EINVAL;
2824 return -1;
2827 switch (option) {
2828 case AST_OPTION_TXGAIN:
2829 scp = (signed char *) data;
2830 index = zt_get_index(chan, p, 0);
2831 if (index < 0) {
2832 ast_log(LOG_WARNING, "No index in TXGAIN?\n");
2833 return -1;
2835 ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
2836 return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
2837 case AST_OPTION_RXGAIN:
2838 scp = (signed char *) data;
2839 index = zt_get_index(chan, p, 0);
2840 if (index < 0) {
2841 ast_log(LOG_WARNING, "No index in RXGAIN?\n");
2842 return -1;
2844 ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
2845 return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
2846 case AST_OPTION_TONE_VERIFY:
2847 if (!p->dsp)
2848 break;
2849 cp = (char *) data;
2850 switch (*cp) {
2851 case 1:
2852 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2853 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax); /* set mute mode if desired */
2854 break;
2855 case 2:
2856 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2857 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax); /* set mute mode if desired */
2858 break;
2859 default:
2860 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2861 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax); /* set mute mode if desired */
2862 break;
2864 break;
2865 case AST_OPTION_TDD:
2866 /* turn on or off TDD */
2867 cp = (char *) data;
2868 p->mate = 0;
2869 if (!*cp) { /* turn it off */
2870 ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2871 if (p->tdd)
2872 tdd_free(p->tdd);
2873 p->tdd = 0;
2874 break;
2876 ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
2877 (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
2878 zt_disable_ec(p);
2879 /* otherwise, turn it on */
2880 if (!p->didtdd) { /* if havent done it yet */
2881 unsigned char mybuf[41000], *buf;
2882 int size, res, fd, len;
2883 struct pollfd fds[1];
2885 buf = mybuf;
2886 memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
2887 ast_tdd_gen_ecdisa(buf + 16000, 16000); /* put in tone */
2888 len = 40000;
2889 index = zt_get_index(chan, p, 0);
2890 if (index < 0) {
2891 ast_log(LOG_WARNING, "No index in TDD?\n");
2892 return -1;
2894 fd = p->subs[index].zfd;
2895 while (len) {
2896 if (ast_check_hangup(chan))
2897 return -1;
2898 size = len;
2899 if (size > READ_SIZE)
2900 size = READ_SIZE;
2901 fds[0].fd = fd;
2902 fds[0].events = POLLPRI | POLLOUT;
2903 fds[0].revents = 0;
2904 res = poll(fds, 1, -1);
2905 if (!res) {
2906 ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2907 continue;
2909 /* if got exception */
2910 if (fds[0].revents & POLLPRI)
2911 return -1;
2912 if (!(fds[0].revents & POLLOUT)) {
2913 ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2914 continue;
2916 res = write(fd, buf, size);
2917 if (res != size) {
2918 if (res == -1) return -1;
2919 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2920 break;
2922 len -= size;
2923 buf += size;
2925 p->didtdd = 1; /* set to have done it now */
2927 if (*cp == 2) { /* Mate mode */
2928 if (p->tdd)
2929 tdd_free(p->tdd);
2930 p->tdd = 0;
2931 p->mate = 1;
2932 break;
2934 if (!p->tdd) { /* if we dont have one yet */
2935 p->tdd = tdd_new(); /* allocate one */
2937 break;
2938 case AST_OPTION_RELAXDTMF: /* Relax DTMF decoding (or not) */
2939 if (!p->dsp)
2940 break;
2941 cp = (char *) data;
2942 ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
2943 *cp ? "ON" : "OFF", (int) *cp, chan->name);
2944 ast_dsp_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
2945 break;
2946 case AST_OPTION_AUDIO_MODE: /* Set AUDIO mode (or not) */
2947 cp = (char *) data;
2948 if (!*cp) {
2949 ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
2950 x = 0;
2951 zt_disable_ec(p);
2952 } else {
2953 ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
2954 x = 1;
2956 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2957 ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2958 break;
2959 case AST_OPTION_OPRMODE: /* Operator services mode */
2960 oprmode = (struct oprmode *) data;
2961 pp = oprmode->peer->tech_pvt;
2962 p->oprmode = pp->oprmode = 0;
2963 /* setup peers */
2964 p->oprpeer = pp;
2965 pp->oprpeer = p;
2966 /* setup modes, if any */
2967 if (oprmode->mode)
2969 pp->oprmode = oprmode->mode;
2970 p->oprmode = -oprmode->mode;
2972 ast_log(LOG_DEBUG, "Set Operator Services mode, value: %d on %s/%s\n",
2973 oprmode->mode, chan->name,oprmode->peer->name);;
2974 break;
2975 case AST_OPTION_ECHOCAN:
2976 cp = (char *) data;
2977 if (*cp) {
2978 ast_log(LOG_DEBUG, "Enabling echo cancelation on %s\n", chan->name);
2979 zt_enable_ec(p);
2980 } else {
2981 ast_log(LOG_DEBUG, "Disabling echo cancelation on %s\n", chan->name);
2982 zt_disable_ec(p);
2984 break;
2986 errno = 0;
2988 return 0;
2991 static int zt_func_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
2993 struct zt_pvt *p = chan->tech_pvt;
2995 if (!strcasecmp(data, "rxgain")) {
2996 ast_mutex_lock(&p->lock);
2997 snprintf(buf, len, "%f", p->rxgain);
2998 ast_mutex_unlock(&p->lock);
2999 } else if (!strcasecmp(data, "txgain")) {
3000 ast_mutex_lock(&p->lock);
3001 snprintf(buf, len, "%f", p->txgain);
3002 ast_mutex_unlock(&p->lock);
3003 } else {
3004 ast_copy_string(buf, "", len);
3006 return 0;
3010 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
3012 /* Unlink a specific slave or all slaves/masters from a given master */
3013 int x;
3014 int hasslaves;
3015 if (!master)
3016 return;
3017 if (needlock) {
3018 ast_mutex_lock(&master->lock);
3019 if (slave) {
3020 while (ast_mutex_trylock(&slave->lock)) {
3021 ast_mutex_unlock(&master->lock);
3022 usleep(1);
3023 ast_mutex_lock(&master->lock);
3027 hasslaves = 0;
3028 for (x = 0; x < MAX_SLAVES; x++) {
3029 if (master->slaves[x]) {
3030 if (!slave || (master->slaves[x] == slave)) {
3031 /* Take slave out of the conference */
3032 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
3033 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
3034 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
3035 master->slaves[x]->master = NULL;
3036 master->slaves[x] = NULL;
3037 } else
3038 hasslaves = 1;
3040 if (!hasslaves)
3041 master->inconference = 0;
3043 if (!slave) {
3044 if (master->master) {
3045 /* Take master out of the conference */
3046 conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
3047 conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
3048 hasslaves = 0;
3049 for (x = 0; x < MAX_SLAVES; x++) {
3050 if (master->master->slaves[x] == master)
3051 master->master->slaves[x] = NULL;
3052 else if (master->master->slaves[x])
3053 hasslaves = 1;
3055 if (!hasslaves)
3056 master->master->inconference = 0;
3058 master->master = NULL;
3060 update_conf(master);
3061 if (needlock) {
3062 if (slave)
3063 ast_mutex_unlock(&slave->lock);
3064 ast_mutex_unlock(&master->lock);
3068 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
3069 int x;
3070 if (!slave || !master) {
3071 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
3072 return;
3074 for (x = 0; x < MAX_SLAVES; x++) {
3075 if (!master->slaves[x]) {
3076 master->slaves[x] = slave;
3077 break;
3080 if (x >= MAX_SLAVES) {
3081 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
3082 master->slaves[MAX_SLAVES - 1] = slave;
3084 if (slave->master)
3085 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
3086 slave->master = master;
3088 ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
3091 static void disable_dtmf_detect(struct zt_pvt *p)
3093 #ifdef ZT_TONEDETECT
3094 int val;
3095 #endif
3097 p->ignoredtmf = 1;
3099 #ifdef ZT_TONEDETECT
3100 val = 0;
3101 ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3102 #endif
3103 if (!p->hardwaredtmf && p->dsp) {
3104 p->dsp_features &= ~DSP_FEATURE_DTMF_DETECT;
3105 ast_dsp_set_features(p->dsp, p->dsp_features);
3109 static void enable_dtmf_detect(struct zt_pvt *p)
3111 #ifdef ZT_TONEDETECT
3112 int val;
3113 #endif
3115 if (p->channel == CHAN_PSEUDO)
3116 return;
3118 p->ignoredtmf = 0;
3120 #ifdef ZT_TONEDETECT
3121 val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
3122 ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3123 #endif
3124 if (!p->hardwaredtmf && p->dsp) {
3125 p->dsp_features |= DSP_FEATURE_DTMF_DETECT;
3126 ast_dsp_set_features(p->dsp, p->dsp_features);
3130 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)
3132 struct ast_channel *who;
3133 struct zt_pvt *p0, *p1, *op0, *op1;
3134 struct zt_pvt *master = NULL, *slave = NULL;
3135 struct ast_frame *f;
3136 int inconf = 0;
3137 int nothingok = 1;
3138 int ofd0, ofd1;
3139 int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
3140 int os0 = -1, os1 = -1;
3141 int priority = 0;
3142 struct ast_channel *oc0, *oc1;
3143 enum ast_bridge_result res;
3145 #ifdef PRI_2BCT
3146 int triedtopribridge = 0;
3147 q931_call *q931c0 = NULL, *q931c1 = NULL;
3148 #endif
3150 /* For now, don't attempt to native bridge if either channel needs DTMF detection.
3151 There is code below to handle it properly until DTMF is actually seen,
3152 but due to currently unresolved issues it's ignored...
3155 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
3156 return AST_BRIDGE_FAILED_NOWARN;
3158 ast_mutex_lock(&c0->lock);
3159 ast_mutex_lock(&c1->lock);
3161 p0 = c0->tech_pvt;
3162 p1 = c1->tech_pvt;
3163 /* cant do pseudo-channels here */
3164 if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
3165 ast_mutex_unlock(&c0->lock);
3166 ast_mutex_unlock(&c1->lock);
3167 return AST_BRIDGE_FAILED_NOWARN;
3170 oi0 = zt_get_index(c0, p0, 0);
3171 oi1 = zt_get_index(c1, p1, 0);
3172 if ((oi0 < 0) || (oi1 < 0)) {
3173 ast_mutex_unlock(&c0->lock);
3174 ast_mutex_unlock(&c1->lock);
3175 return AST_BRIDGE_FAILED;
3178 op0 = p0 = c0->tech_pvt;
3179 op1 = p1 = c1->tech_pvt;
3180 ofd0 = c0->fds[0];
3181 ofd1 = c1->fds[0];
3182 oc0 = p0->owner;
3183 oc1 = p1->owner;
3185 if (ast_mutex_trylock(&p0->lock)) {
3186 /* Don't block, due to potential for deadlock */
3187 ast_mutex_unlock(&c0->lock);
3188 ast_mutex_unlock(&c1->lock);
3189 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
3190 return AST_BRIDGE_RETRY;
3192 if (ast_mutex_trylock(&p1->lock)) {
3193 /* Don't block, due to potential for deadlock */
3194 ast_mutex_unlock(&p0->lock);
3195 ast_mutex_unlock(&c0->lock);
3196 ast_mutex_unlock(&c1->lock);
3197 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
3198 return AST_BRIDGE_RETRY;
3201 if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3202 if (p0->owner && p1->owner) {
3203 /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
3204 if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
3205 master = p0;
3206 slave = p1;
3207 inconf = 1;
3208 } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
3209 master = p1;
3210 slave = p0;
3211 inconf = 1;
3212 } else {
3213 ast_log(LOG_WARNING, "Huh? Both calls are callwaits or 3-ways? That's clever...?\n");
3214 ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
3215 p0->channel,
3216 oi0, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3217 p0->subs[SUB_REAL].inthreeway, p0->channel,
3218 oi0, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3219 p1->subs[SUB_REAL].inthreeway);
3221 nothingok = 0;
3223 } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
3224 if (p1->subs[SUB_THREEWAY].inthreeway) {
3225 master = p1;
3226 slave = p0;
3227 nothingok = 0;
3229 } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
3230 if (p0->subs[SUB_THREEWAY].inthreeway) {
3231 master = p0;
3232 slave = p1;
3233 nothingok = 0;
3235 } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
3236 /* We have a real and a call wait. If we're in a three way call, put us in it, otherwise,
3237 don't put us in anything */
3238 if (p1->subs[SUB_CALLWAIT].inthreeway) {
3239 master = p1;
3240 slave = p0;
3241 nothingok = 0;
3243 } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
3244 /* Same as previous */
3245 if (p0->subs[SUB_CALLWAIT].inthreeway) {
3246 master = p0;
3247 slave = p1;
3248 nothingok = 0;
3251 ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
3252 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
3253 if (master && slave) {
3254 /* Stop any tones, or play ringtone as appropriate. If they're bridged
3255 in an active threeway call with a channel that is ringing, we should
3256 indicate ringing. */
3257 if ((oi1 == SUB_THREEWAY) &&
3258 p1->subs[SUB_THREEWAY].inthreeway &&
3259 p1->subs[SUB_REAL].owner &&
3260 p1->subs[SUB_REAL].inthreeway &&
3261 (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
3262 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
3263 tone_zone_play_tone(p0->subs[oi0].zfd, ZT_TONE_RINGTONE);
3264 os1 = p1->subs[SUB_REAL].owner->_state;
3265 } else {
3266 ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p0->channel, oi0, p1->channel, oi1);
3267 tone_zone_play_tone(p0->subs[oi0].zfd, -1);
3269 if ((oi0 == SUB_THREEWAY) &&
3270 p0->subs[SUB_THREEWAY].inthreeway &&
3271 p0->subs[SUB_REAL].owner &&
3272 p0->subs[SUB_REAL].inthreeway &&
3273 (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
3274 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
3275 tone_zone_play_tone(p1->subs[oi1].zfd, ZT_TONE_RINGTONE);
3276 os0 = p0->subs[SUB_REAL].owner->_state;
3277 } else {
3278 ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p1->channel, oi1, p0->channel, oi0);
3279 tone_zone_play_tone(p1->subs[oi0].zfd, -1);
3281 if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3282 if (!p0->echocanbridged || !p1->echocanbridged) {
3283 /* Disable echo cancellation if appropriate */
3284 zt_disable_ec(p0);
3285 zt_disable_ec(p1);
3288 zt_link(slave, master);
3289 master->inconference = inconf;
3290 } else if (!nothingok)
3291 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
3293 update_conf(p0);
3294 update_conf(p1);
3295 t0 = p0->subs[SUB_REAL].inthreeway;
3296 t1 = p1->subs[SUB_REAL].inthreeway;
3298 ast_mutex_unlock(&p0->lock);
3299 ast_mutex_unlock(&p1->lock);
3301 ast_mutex_unlock(&c0->lock);
3302 ast_mutex_unlock(&c1->lock);
3304 /* Native bridge failed */
3305 if ((!master || !slave) && !nothingok) {
3306 zt_enable_ec(p0);
3307 zt_enable_ec(p1);
3308 return AST_BRIDGE_FAILED;
3311 if (option_verbose > 2)
3312 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
3314 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
3315 disable_dtmf_detect(op0);
3317 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
3318 disable_dtmf_detect(op1);
3320 for (;;) {
3321 struct ast_channel *c0_priority[2] = {c0, c1};
3322 struct ast_channel *c1_priority[2] = {c1, c0};
3324 /* Here's our main loop... Start by locking things, looking for private parts,
3325 and then balking if anything is wrong */
3326 ast_mutex_lock(&c0->lock);
3327 ast_mutex_lock(&c1->lock);
3328 p0 = c0->tech_pvt;
3329 p1 = c1->tech_pvt;
3331 if (op0 == p0)
3332 i0 = zt_get_index(c0, p0, 1);
3333 if (op1 == p1)
3334 i1 = zt_get_index(c1, p1, 1);
3335 ast_mutex_unlock(&c0->lock);
3336 ast_mutex_unlock(&c1->lock);
3338 if (!timeoutms ||
3339 (op0 != p0) ||
3340 (op1 != p1) ||
3341 (ofd0 != c0->fds[0]) ||
3342 (ofd1 != c1->fds[0]) ||
3343 (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) ||
3344 (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) ||
3345 (oc0 != p0->owner) ||
3346 (oc1 != p1->owner) ||
3347 (t0 != p0->subs[SUB_REAL].inthreeway) ||
3348 (t1 != p1->subs[SUB_REAL].inthreeway) ||
3349 (oi0 != i0) ||
3350 (oi1 != i1)) {
3351 ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
3352 op0->channel, oi0, op1->channel, oi1);
3353 res = AST_BRIDGE_RETRY;
3354 goto return_from_bridge;
3357 #ifdef PRI_2BCT
3358 q931c0 = p0->call;
3359 q931c1 = p1->call;
3360 if (p0->transfer && p1->transfer
3361 && q931c0 && q931c1
3362 && !triedtopribridge) {
3363 pri_channel_bridge(q931c0, q931c1);
3364 triedtopribridge = 1;
3366 #endif
3368 who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
3369 if (!who) {
3370 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
3371 continue;
3373 f = ast_read(who);
3374 if (!f || (f->frametype == AST_FRAME_CONTROL)) {
3375 *fo = f;
3376 *rc = who;
3377 res = AST_BRIDGE_COMPLETE;
3378 goto return_from_bridge;
3380 if (f->frametype == AST_FRAME_DTMF) {
3381 if ((who == c0) && p0->pulsedial) {
3382 ast_write(c1, f);
3383 } else if ((who == c1) && p1->pulsedial) {
3384 ast_write(c0, f);
3385 } else {
3386 *fo = f;
3387 *rc = who;
3388 res = AST_BRIDGE_COMPLETE;
3389 goto return_from_bridge;
3392 ast_frfree(f);
3394 /* Swap who gets priority */
3395 priority = !priority;
3398 return_from_bridge:
3399 if (op0 == p0)
3400 zt_enable_ec(p0);
3402 if (op1 == p1)
3403 zt_enable_ec(p1);
3405 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
3406 enable_dtmf_detect(op0);
3408 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
3409 enable_dtmf_detect(op1);
3411 zt_unlink(slave, master, 1);
3413 return res;
3416 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3418 struct zt_pvt *p = newchan->tech_pvt;
3419 int x;
3420 ast_mutex_lock(&p->lock);
3421 ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
3422 if (p->owner == oldchan) {
3423 p->owner = newchan;
3425 for (x = 0; x < 3; x++)
3426 if (p->subs[x].owner == oldchan) {
3427 if (!x)
3428 zt_unlink(NULL, p, 0);
3429 p->subs[x].owner = newchan;
3431 if (newchan->_state == AST_STATE_RINGING)
3432 zt_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
3433 update_conf(p);
3434 ast_mutex_unlock(&p->lock);
3435 return 0;
3438 static int zt_ring_phone(struct zt_pvt *p)
3440 int x;
3441 int res;
3442 /* Make sure our transmit state is on hook */
3443 x = 0;
3444 x = ZT_ONHOOK;
3445 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3446 do {
3447 x = ZT_RING;
3448 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3449 if (res) {
3450 switch (errno) {
3451 case EBUSY:
3452 case EINTR:
3453 /* Wait just in case */
3454 usleep(10000);
3455 continue;
3456 case EINPROGRESS:
3457 res = 0;
3458 break;
3459 default:
3460 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
3461 res = 0;
3464 } while (res);
3465 return res;
3468 static void *ss_thread(void *data);
3470 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
3472 static int attempt_transfer(struct zt_pvt *p)
3474 /* In order to transfer, we need at least one of the channels to
3475 actually be in a call bridge. We can't conference two applications
3476 together (but then, why would we want to?) */
3477 if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
3478 /* The three-way person we're about to transfer to could still be in MOH, so
3479 stop if now if appropriate */
3480 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
3481 ast_queue_control(p->subs[SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
3482 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
3483 ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
3485 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RING) {
3486 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, ZT_TONE_RINGTONE);
3488 if (p->subs[SUB_REAL].owner->cdr) {
3489 /* Move CDR from second channel to current one */
3490 p->subs[SUB_THREEWAY].owner->cdr =
3491 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, p->subs[SUB_REAL].owner->cdr);
3492 p->subs[SUB_REAL].owner->cdr = NULL;
3494 if (ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr) {
3495 /* Move CDR from second channel's bridge to current one */
3496 p->subs[SUB_THREEWAY].owner->cdr =
3497 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr);
3498 ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr = NULL;
3500 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
3501 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3502 ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
3503 return -1;
3505 /* Orphan the channel after releasing the lock */
3506 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3507 unalloc_sub(p, SUB_THREEWAY);
3508 } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
3509 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
3510 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
3511 ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
3513 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RING) {
3514 tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
3516 if (p->subs[SUB_THREEWAY].owner->cdr) {
3517 /* Move CDR from second channel to current one */
3518 p->subs[SUB_REAL].owner->cdr =
3519 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, p->subs[SUB_THREEWAY].owner->cdr);
3520 p->subs[SUB_THREEWAY].owner->cdr = NULL;
3522 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr) {
3523 /* Move CDR from second channel's bridge to current one */
3524 p->subs[SUB_REAL].owner->cdr =
3525 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr);
3526 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr = NULL;
3528 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
3529 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3530 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
3531 return -1;
3533 /* Three-way is now the REAL */
3534 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3535 ast_mutex_unlock(&p->subs[SUB_REAL].owner->lock);
3536 unalloc_sub(p, SUB_THREEWAY);
3537 /* Tell the caller not to hangup */
3538 return 1;
3539 } else {
3540 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
3541 p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
3542 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3543 return -1;
3545 return 0;
3548 static int check_for_conference(struct zt_pvt *p)
3550 ZT_CONFINFO ci;
3551 /* Fine if we already have a master, etc */
3552 if (p->master || (p->confno > -1))
3553 return 0;
3554 memset(&ci, 0, sizeof(ci));
3555 if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
3556 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
3557 return 0;
3559 /* If we have no master and don't have a confno, then
3560 if we're in a conference, it's probably a MeetMe room or
3561 some such, so don't let us 3-way out! */
3562 if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
3563 if (option_verbose > 2)
3564 ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
3565 return 1;
3567 return 0;
3570 static int get_alarms(struct zt_pvt *p)
3572 int res;
3573 ZT_SPANINFO zi;
3574 memset(&zi, 0, sizeof(zi));
3575 zi.spanno = p->span;
3576 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
3577 if (res < 0) {
3578 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
3579 return 0;
3581 return zi.alarms;
3584 static void zt_handle_dtmfup(struct ast_channel *ast, int index, struct ast_frame **dest)
3586 struct zt_pvt *p = ast->tech_pvt;
3587 struct ast_frame *f = *dest;
3589 ast_log(LOG_DEBUG, "DTMF digit: %c on %s\n", f->subclass, ast->name);
3590 if (p->confirmanswer) {
3591 ast_log(LOG_DEBUG, "Confirm answer on %s!\n", ast->name);
3592 /* Upon receiving a DTMF digit, consider this an answer confirmation instead
3593 of a DTMF digit */
3594 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3595 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3596 *dest = &p->subs[index].f;
3597 /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
3598 p->confirmanswer = 0;
3599 } else if (p->callwaitcas) {
3600 if ((f->subclass == 'A') || (f->subclass == 'D')) {
3601 ast_log(LOG_DEBUG, "Got some DTMF, but it's for the CAS\n");
3602 if (p->cidspill)
3603 free(p->cidspill);
3604 send_cwcidspill(p);
3606 if ((f->subclass != 'm') && (f->subclass != 'u'))
3607 p->callwaitcas = 0;
3608 p->subs[index].f.frametype = AST_FRAME_NULL;
3609 p->subs[index].f.subclass = 0;
3610 *dest = &p->subs[index].f;
3611 } else if (f->subclass == 'f') {
3612 /* Fax tone -- Handle and return NULL */
3613 if ((p->callprogress & 0x6) && !p->faxhandled) {
3614 p->faxhandled++;
3615 if (strcmp(ast->exten, "fax")) {
3616 const char *target_context = S_OR(ast->macrocontext, ast->context);
3618 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
3619 if (option_verbose > 2)
3620 ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
3621 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
3622 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
3623 if (ast_async_goto(ast, target_context, "fax", 1))
3624 ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
3625 } else
3626 ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
3627 } else
3628 ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
3629 } else
3630 ast_log(LOG_DEBUG, "Fax already handled\n");
3631 zt_confmute(p, 0);
3632 p->subs[index].f.frametype = AST_FRAME_NULL;
3633 p->subs[index].f.subclass = 0;
3634 *dest = &p->subs[index].f;
3635 } else if (f->subclass == 'm') {
3636 /* Confmute request */
3637 zt_confmute(p, 1);
3638 p->subs[index].f.frametype = AST_FRAME_NULL;
3639 p->subs[index].f.subclass = 0;
3640 *dest = &p->subs[index].f;
3641 } else if (f->subclass == 'u') {
3642 /* Unmute */
3643 zt_confmute(p, 0);
3644 p->subs[index].f.frametype = AST_FRAME_NULL;
3645 p->subs[index].f.subclass = 0;
3646 *dest = &p->subs[index].f;
3647 } else
3648 zt_confmute(p, 0);
3651 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
3653 int res, x;
3654 int index, mysig;
3655 char *c;
3656 struct zt_pvt *p = ast->tech_pvt;
3657 pthread_t threadid;
3658 pthread_attr_t attr;
3659 struct ast_channel *chan;
3660 struct ast_frame *f;
3662 index = zt_get_index(ast, p, 0);
3663 mysig = p->sig;
3664 if (p->outsigmod > -1)
3665 mysig = p->outsigmod;
3666 p->subs[index].f.frametype = AST_FRAME_NULL;
3667 p->subs[index].f.subclass = 0;
3668 p->subs[index].f.datalen = 0;
3669 p->subs[index].f.samples = 0;
3670 p->subs[index].f.mallocd = 0;
3671 p->subs[index].f.offset = 0;
3672 p->subs[index].f.src = "zt_handle_event";
3673 p->subs[index].f.data = NULL;
3674 f = &p->subs[index].f;
3676 if (index < 0)
3677 return &p->subs[index].f;
3678 if (p->fake_event) {
3679 res = p->fake_event;
3680 p->fake_event = 0;
3681 } else
3682 res = zt_get_event(p->subs[index].zfd);
3684 ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
3686 if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFUP)) {
3687 p->pulsedial = (res & ZT_EVENT_PULSEDIGIT) ? 1 : 0;
3689 ast_log(LOG_DEBUG, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
3690 #ifdef HAVE_PRI
3691 if (!p->proceeding && p->sig == SIG_PRI && p->pri && p->pri->overlapdial) {
3692 /* absorb event */
3693 } else {
3694 #endif
3695 p->subs[index].f.frametype = AST_FRAME_DTMF_END;
3696 p->subs[index].f.subclass = res & 0xff;
3697 #ifdef HAVE_PRI
3699 #endif
3700 zt_handle_dtmfup(ast, index, &f);
3701 return f;
3704 if (res & ZT_EVENT_DTMFDOWN) {
3705 ast_log(LOG_DEBUG, "DTMF Down '%c'\n", res & 0xff);
3706 /* Mute conference */
3707 zt_confmute(p, 1);
3708 p->subs[index].f.frametype = AST_FRAME_DTMF_BEGIN;
3709 p->subs[index].f.subclass = res & 0xff;
3710 return &p->subs[index].f;
3713 switch (res) {
3714 #ifdef ZT_EVENT_EC_DISABLED
3715 case ZT_EVENT_EC_DISABLED:
3716 if (option_verbose > 2)
3717 ast_verbose(VERBOSE_PREFIX_3 "Channel %d echo canceler disabled due to CED detection\n", p->channel);
3718 p->echocanon = 0;
3719 break;
3720 #endif
3721 case ZT_EVENT_BITSCHANGED:
3722 ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
3723 case ZT_EVENT_PULSE_START:
3724 /* Stop tone if there's a pulse start and the PBX isn't started */
3725 if (!ast->pbx)
3726 tone_zone_play_tone(p->subs[index].zfd, -1);
3727 break;
3728 case ZT_EVENT_DIALCOMPLETE:
3729 if (p->inalarm) break;
3730 if ((p->radio || (p->oprmode < 0))) break;
3731 if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
3732 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
3733 return NULL;
3735 if (!x) { /* if not still dialing in driver */
3736 zt_enable_ec(p);
3737 if (p->echobreak) {
3738 zt_train_ec(p);
3739 ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
3740 p->dop.op = ZT_DIAL_OP_REPLACE;
3741 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
3742 p->echobreak = 0;
3743 } else {
3744 p->dialing = 0;
3745 if ((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) {
3746 /* if thru with dialing after offhook */
3747 if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
3748 ast_setstate(ast, AST_STATE_UP);
3749 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3750 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3751 break;
3752 } else { /* if to state wait for offhook to dial rest */
3753 /* we now wait for off hook */
3754 ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
3757 if (ast->_state == AST_STATE_DIALING) {
3758 if ((p->callprogress & 1) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
3759 ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
3760 } 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)))) {
3761 ast_setstate(ast, AST_STATE_RINGING);
3762 } else if (!p->answeronpolarityswitch) {
3763 ast_setstate(ast, AST_STATE_UP);
3764 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3765 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3770 break;
3771 case ZT_EVENT_ALARM:
3772 #ifdef HAVE_PRI
3773 if (!p->pri || !p->pri->pri || (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0)) {
3774 /* T309 is not enabled : hangup calls when alarm occurs */
3775 if (p->call) {
3776 if (p->pri && p->pri->pri) {
3777 if (!pri_grab(p, p->pri)) {
3778 pri_hangup(p->pri->pri, p->call, -1);
3779 pri_destroycall(p->pri->pri, p->call);
3780 p->call = NULL;
3781 pri_rel(p->pri);
3782 } else
3783 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
3784 } else
3785 ast_log(LOG_WARNING, "The PRI Call has not been destroyed\n");
3787 if (p->owner)
3788 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3790 if (p->bearer)
3791 p->bearer->inalarm = 1;
3792 else
3793 #endif
3794 p->inalarm = 1;
3795 res = get_alarms(p);
3796 ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm2str(res));
3797 manager_event(EVENT_FLAG_SYSTEM, "Alarm",
3798 "Alarm: %s\r\n"
3799 "Channel: %d\r\n",
3800 alarm2str(res), p->channel);
3801 #ifdef HAVE_LIBPRI
3802 if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
3803 /* fall through intentionally */
3804 } else {
3805 break;
3807 #endif
3808 case ZT_EVENT_ONHOOK:
3809 if (p->radio) {
3810 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3811 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
3812 break;
3814 if (p->oprmode < 0)
3816 if (p->oprmode != -1) break;
3817 if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
3819 /* Make sure it starts ringing */
3820 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RINGOFF);
3821 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RING);
3822 save_conference(p->oprpeer);
3823 tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
3825 break;
3827 switch (p->sig) {
3828 case SIG_FXOLS:
3829 case SIG_FXOGS:
3830 case SIG_FXOKS:
3831 p->onhooktime = time(NULL);
3832 p->msgstate = -1;
3833 /* Check for some special conditions regarding call waiting */
3834 if (index == SUB_REAL) {
3835 /* The normal line was hung up */
3836 if (p->subs[SUB_CALLWAIT].owner) {
3837 /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
3838 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
3839 if (option_verbose > 2)
3840 ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
3841 unalloc_sub(p, SUB_CALLWAIT);
3842 #if 0
3843 p->subs[index].needanswer = 0;
3844 p->subs[index].needringing = 0;
3845 #endif
3846 p->callwaitingrepeat = 0;
3847 p->cidcwexpire = 0;
3848 p->owner = NULL;
3849 /* Don't start streaming audio yet if the incoming call isn't up yet */
3850 if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
3851 p->dialing = 1;
3852 zt_ring_phone(p);
3853 } else if (p->subs[SUB_THREEWAY].owner) {
3854 unsigned int mssinceflash;
3855 /* Here we have to retain the lock on both the main channel, the 3-way channel, and
3856 the private structure -- not especially easy or clean */
3857 while (p->subs[SUB_THREEWAY].owner && ast_mutex_trylock(&p->subs[SUB_THREEWAY].owner->lock)) {
3858 /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
3859 ast_mutex_unlock(&p->lock);
3860 ast_mutex_unlock(&ast->lock);
3861 usleep(1);
3862 /* We can grab ast and p in that order, without worry. We should make sure
3863 nothing seriously bad has happened though like some sort of bizarre double
3864 masquerade! */
3865 ast_mutex_lock(&ast->lock);
3866 ast_mutex_lock(&p->lock);
3867 if (p->owner != ast) {
3868 ast_log(LOG_WARNING, "This isn't good...\n");
3869 return NULL;
3872 if (!p->subs[SUB_THREEWAY].owner) {
3873 ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
3874 return NULL;
3876 mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
3877 ast_log(LOG_DEBUG, "Last flash was %d ms ago\n", mssinceflash);
3878 if (mssinceflash < MIN_MS_SINCE_FLASH) {
3879 /* It hasn't been long enough since the last flashook. This is probably a bounce on
3880 hanging up. Hangup both channels now */
3881 if (p->subs[SUB_THREEWAY].owner)
3882 ast_queue_hangup(p->subs[SUB_THREEWAY].owner);
3883 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3884 ast_log(LOG_DEBUG, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
3885 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3886 } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
3887 if (p->transfer) {
3888 /* In any case this isn't a threeway call anymore */
3889 p->subs[SUB_REAL].inthreeway = 0;
3890 p->subs[SUB_THREEWAY].inthreeway = 0;
3891 /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
3892 if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
3893 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3894 /* Swap subs and dis-own channel */
3895 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3896 p->owner = NULL;
3897 /* Ring the phone */
3898 zt_ring_phone(p);
3899 } else {
3900 if ((res = attempt_transfer(p)) < 0) {
3901 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3902 if (p->subs[SUB_THREEWAY].owner)
3903 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3904 } else if (res) {
3905 /* Don't actually hang up at this point */
3906 if (p->subs[SUB_THREEWAY].owner)
3907 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3908 break;
3911 } else {
3912 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3913 if (p->subs[SUB_THREEWAY].owner)
3914 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3916 } else {
3917 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3918 /* Swap subs and dis-own channel */
3919 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3920 p->owner = NULL;
3921 /* Ring the phone */
3922 zt_ring_phone(p);
3925 } else {
3926 ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
3928 /* Fall through */
3929 default:
3930 zt_disable_ec(p);
3931 return NULL;
3933 break;
3934 case ZT_EVENT_RINGOFFHOOK:
3935 if (p->inalarm) break;
3936 if (p->oprmode < 0)
3938 if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
3940 /* Make sure it stops ringing */
3941 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RINGOFF);
3942 tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].zfd, -1);
3943 restore_conference(p->oprpeer);
3945 break;
3947 if (p->radio)
3949 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3950 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
3951 break;
3953 /* for E911, its supposed to wait for offhook then dial
3954 the second half of the dial string */
3955 if (((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
3956 c = strchr(p->dialdest, '/');
3957 if (c)
3958 c++;
3959 else
3960 c = p->dialdest;
3961 if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
3962 else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
3963 if (strlen(p->dop.dialstr) > 4) {
3964 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
3965 strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
3966 p->echorest[sizeof(p->echorest) - 1] = '\0';
3967 p->echobreak = 1;
3968 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
3969 } else
3970 p->echobreak = 0;
3971 if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
3972 x = ZT_ONHOOK;
3973 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3974 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
3975 return NULL;
3977 p->dialing = 1;
3978 return &p->subs[index].f;
3980 switch (p->sig) {
3981 case SIG_FXOLS:
3982 case SIG_FXOGS:
3983 case SIG_FXOKS:
3984 switch (ast->_state) {
3985 case AST_STATE_RINGING:
3986 zt_enable_ec(p);
3987 zt_train_ec(p);
3988 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3989 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3990 /* Make sure it stops ringing */
3991 zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
3992 ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
3993 if (p->cidspill) {
3994 /* Cancel any running CallerID spill */
3995 free(p->cidspill);
3996 p->cidspill = NULL;
3998 p->dialing = 0;
3999 p->callwaitcas = 0;
4000 if (p->confirmanswer) {
4001 /* Ignore answer if "confirm answer" is enabled */
4002 p->subs[index].f.frametype = AST_FRAME_NULL;
4003 p->subs[index].f.subclass = 0;
4004 } else if (!ast_strlen_zero(p->dop.dialstr)) {
4005 /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
4006 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
4007 if (res < 0) {
4008 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
4009 p->dop.dialstr[0] = '\0';
4010 return NULL;
4011 } else {
4012 ast_log(LOG_DEBUG, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
4013 p->subs[index].f.frametype = AST_FRAME_NULL;
4014 p->subs[index].f.subclass = 0;
4015 p->dialing = 1;
4017 p->dop.dialstr[0] = '\0';
4018 ast_setstate(ast, AST_STATE_DIALING);
4019 } else
4020 ast_setstate(ast, AST_STATE_UP);
4021 return &p->subs[index].f;
4022 case AST_STATE_DOWN:
4023 ast_setstate(ast, AST_STATE_RING);
4024 ast->rings = 1;
4025 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4026 p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
4027 ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
4028 return &p->subs[index].f;
4029 case AST_STATE_UP:
4030 /* Make sure it stops ringing */
4031 zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
4032 /* Okay -- probably call waiting*/
4033 if (ast_bridged_channel(p->owner))
4034 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4035 p->subs[index].needunhold = 1;
4036 break;
4037 case AST_STATE_RESERVED:
4038 /* Start up dialtone */
4039 if (has_voicemail(p))
4040 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_STUTTER);
4041 else
4042 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALTONE);
4043 break;
4044 default:
4045 ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
4047 break;
4048 case SIG_FXSLS:
4049 case SIG_FXSGS:
4050 case SIG_FXSKS:
4051 if (ast->_state == AST_STATE_RING) {
4052 p->ringt = p->ringt_base;
4055 /* If we get a ring then we cannot be in
4056 * reversed polarity. So we reset to idle */
4057 ast_log(LOG_DEBUG, "Setting IDLE polarity due "
4058 "to ring. Old polarity was %d\n",
4059 p->polarity);
4060 p->polarity = POLARITY_IDLE;
4062 /* Fall through */
4063 case SIG_EM:
4064 case SIG_EM_E1:
4065 case SIG_EMWINK:
4066 case SIG_FEATD:
4067 case SIG_FEATDMF:
4068 case SIG_FEATDMF_TA:
4069 case SIG_E911:
4070 case SIG_FGC_CAMA:
4071 case SIG_FGC_CAMAMF:
4072 case SIG_FEATB:
4073 case SIG_SF:
4074 case SIG_SFWINK:
4075 case SIG_SF_FEATD:
4076 case SIG_SF_FEATDMF:
4077 case SIG_SF_FEATB:
4078 if (ast->_state == AST_STATE_PRERING)
4079 ast_setstate(ast, AST_STATE_RING);
4080 if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
4081 if (option_debug)
4082 ast_log(LOG_DEBUG, "Ring detected\n");
4083 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4084 p->subs[index].f.subclass = AST_CONTROL_RING;
4085 } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
4086 if (option_debug)
4087 ast_log(LOG_DEBUG, "Line answered\n");
4088 if (p->confirmanswer) {
4089 p->subs[index].f.frametype = AST_FRAME_NULL;
4090 p->subs[index].f.subclass = 0;
4091 } else {
4092 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4093 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
4094 ast_setstate(ast, AST_STATE_UP);
4096 } else if (ast->_state != AST_STATE_RING)
4097 ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
4098 break;
4099 default:
4100 ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
4102 break;
4103 #ifdef ZT_EVENT_RINGBEGIN
4104 case ZT_EVENT_RINGBEGIN:
4105 switch (p->sig) {
4106 case SIG_FXSLS:
4107 case SIG_FXSGS:
4108 case SIG_FXSKS:
4109 if (ast->_state == AST_STATE_RING) {
4110 p->ringt = p->ringt_base;
4112 break;
4114 break;
4115 #endif
4116 case ZT_EVENT_RINGEROFF:
4117 if (p->inalarm) break;
4118 if ((p->radio || (p->oprmode < 0))) break;
4119 ast->rings++;
4120 if ((ast->rings > p->cidrings) && (p->cidspill)) {
4121 ast_log(LOG_WARNING, "Didn't finish Caller-ID spill. Cancelling.\n");
4122 free(p->cidspill);
4123 p->cidspill = NULL;
4124 p->callwaitcas = 0;
4126 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4127 p->subs[index].f.subclass = AST_CONTROL_RINGING;
4128 break;
4129 case ZT_EVENT_RINGERON:
4130 break;
4131 case ZT_EVENT_NOALARM:
4132 p->inalarm = 0;
4133 #ifdef HAVE_PRI
4134 /* Extremely unlikely but just in case */
4135 if (p->bearer)
4136 p->bearer->inalarm = 0;
4137 #endif
4138 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
4139 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
4140 "Channel: %d\r\n", p->channel);
4141 break;
4142 case ZT_EVENT_WINKFLASH:
4143 if (p->inalarm) break;
4144 if (p->radio) break;
4145 if (p->oprmode < 0) break;
4146 if (p->oprmode > 1)
4148 struct zt_params par;
4150 if (ioctl(p->oprpeer->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par) != -1)
4152 if (!par.rxisoffhook)
4154 /* Make sure it stops ringing */
4155 zt_set_hook(p->oprpeer->subs[SUB_REAL].zfd, ZT_RINGOFF);
4156 zt_set_hook(p->oprpeer->subs[SUB_REAL].zfd, ZT_RING);
4157 save_conference(p);
4158 tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
4161 break;
4163 /* Remember last time we got a flash-hook */
4164 gettimeofday(&p->flashtime, NULL);
4165 switch (mysig) {
4166 case SIG_FXOLS:
4167 case SIG_FXOGS:
4168 case SIG_FXOKS:
4169 ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
4170 index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
4171 p->callwaitcas = 0;
4173 if (index != SUB_REAL) {
4174 ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", index, p->channel);
4175 goto winkflashdone;
4178 if (p->subs[SUB_CALLWAIT].owner) {
4179 /* Swap to call-wait */
4180 swap_subs(p, SUB_REAL, SUB_CALLWAIT);
4181 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
4182 p->owner = p->subs[SUB_REAL].owner;
4183 ast_log(LOG_DEBUG, "Making %s the new owner\n", p->owner->name);
4184 if (p->owner->_state == AST_STATE_RINGING) {
4185 ast_setstate(p->owner, AST_STATE_UP);
4186 p->subs[SUB_REAL].needanswer = 1;
4188 p->callwaitingrepeat = 0;
4189 p->cidcwexpire = 0;
4190 /* Start music on hold if appropriate */
4191 if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
4192 ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
4193 S_OR(p->mohsuggest, NULL),
4194 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4196 p->subs[SUB_CALLWAIT].needhold = 1;
4197 if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
4198 ast_queue_control_data(p->subs[SUB_REAL].owner, AST_CONTROL_HOLD,
4199 S_OR(p->mohsuggest, NULL),
4200 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4202 p->subs[SUB_REAL].needunhold = 1;
4203 } else if (!p->subs[SUB_THREEWAY].owner) {
4204 char cid_num[256];
4205 char cid_name[256];
4207 if (!p->threewaycalling) {
4208 /* Just send a flash if no 3-way calling */
4209 p->subs[SUB_REAL].needflash = 1;
4210 goto winkflashdone;
4211 } else if (!check_for_conference(p)) {
4212 if (p->zaptrcallerid && p->owner) {
4213 if (p->owner->cid.cid_num)
4214 ast_copy_string(cid_num, p->owner->cid.cid_num, sizeof(cid_num));
4215 if (p->owner->cid.cid_name)
4216 ast_copy_string(cid_name, p->owner->cid.cid_name, sizeof(cid_name));
4218 /* XXX This section needs much more error checking!!! XXX */
4219 /* Start a 3-way call if feasible */
4220 if (!((ast->pbx) ||
4221 (ast->_state == AST_STATE_UP) ||
4222 (ast->_state == AST_STATE_RING))) {
4223 ast_log(LOG_DEBUG, "Flash when call not up or ringing\n");
4224 goto winkflashdone;
4226 if (alloc_sub(p, SUB_THREEWAY)) {
4227 ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
4228 goto winkflashdone;
4230 /* Make new channel */
4231 chan = zt_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, 0);
4232 if (p->zaptrcallerid) {
4233 if (!p->origcid_num)
4234 p->origcid_num = ast_strdup(p->cid_num);
4235 if (!p->origcid_name)
4236 p->origcid_name = ast_strdup(p->cid_name);
4237 ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
4238 ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
4240 /* Swap things around between the three-way and real call */
4241 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4242 /* Disable echo canceller for better dialing */
4243 zt_disable_ec(p);
4244 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALRECALL);
4245 if (res)
4246 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
4247 p->owner = chan;
4248 pthread_attr_init(&attr);
4249 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
4250 if (!chan) {
4251 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
4252 } else if (ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
4253 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
4254 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
4255 zt_enable_ec(p);
4256 ast_hangup(chan);
4257 } else {
4258 if (option_verbose > 2)
4259 ast_verbose(VERBOSE_PREFIX_3 "Started three way call on channel %d\n", p->channel);
4260 /* Start music on hold if appropriate */
4261 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
4262 ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
4263 S_OR(p->mohsuggest, NULL),
4264 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4266 p->subs[SUB_THREEWAY].needhold = 1;
4268 pthread_attr_destroy(&attr);
4270 } else {
4271 /* Already have a 3 way call */
4272 if (p->subs[SUB_THREEWAY].inthreeway) {
4273 /* Call is already up, drop the last person */
4274 if (option_debug)
4275 ast_log(LOG_DEBUG, "Got flash with three way call up, dropping last call on %d\n", p->channel);
4276 /* If the primary call isn't answered yet, use it */
4277 if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
4278 /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
4279 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4280 p->owner = p->subs[SUB_REAL].owner;
4282 /* Drop the last call and stop the conference */
4283 if (option_verbose > 2)
4284 ast_verbose(VERBOSE_PREFIX_3 "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
4285 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
4286 p->subs[SUB_REAL].inthreeway = 0;
4287 p->subs[SUB_THREEWAY].inthreeway = 0;
4288 } else {
4289 /* Lets see what we're up to */
4290 if (((ast->pbx) || (ast->_state == AST_STATE_UP)) &&
4291 (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
4292 int otherindex = SUB_THREEWAY;
4294 if (option_verbose > 2)
4295 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);
4296 /* Put them in the threeway, and flip */
4297 p->subs[SUB_THREEWAY].inthreeway = 1;
4298 p->subs[SUB_REAL].inthreeway = 1;
4299 if (ast->_state == AST_STATE_UP) {
4300 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4301 otherindex = SUB_REAL;
4303 if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
4304 ast_queue_control(p->subs[otherindex].owner, AST_CONTROL_UNHOLD);
4305 p->subs[otherindex].needunhold = 1;
4306 p->owner = p->subs[SUB_REAL].owner;
4307 if (ast->_state == AST_STATE_RINGING) {
4308 ast_log(LOG_DEBUG, "Enabling ringtone on real and threeway\n");
4309 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
4310 res = tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, ZT_TONE_RINGTONE);
4312 } else {
4313 if (option_verbose > 2)
4314 ast_verbose(VERBOSE_PREFIX_3 "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
4315 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4316 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
4317 p->owner = p->subs[SUB_REAL].owner;
4318 if (p->subs[SUB_REAL].owner && ast_bridged_channel(p->subs[SUB_REAL].owner))
4319 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
4320 p->subs[SUB_REAL].needunhold = 1;
4321 zt_enable_ec(p);
4326 winkflashdone:
4327 update_conf(p);
4328 break;
4329 case SIG_EM:
4330 case SIG_EM_E1:
4331 case SIG_EMWINK:
4332 case SIG_FEATD:
4333 case SIG_SF:
4334 case SIG_SFWINK:
4335 case SIG_SF_FEATD:
4336 case SIG_FXSLS:
4337 case SIG_FXSGS:
4338 if (p->dialing)
4339 ast_log(LOG_DEBUG, "Ignoring wink on channel %d\n", p->channel);
4340 else
4341 ast_log(LOG_DEBUG, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
4342 break;
4343 case SIG_FEATDMF_TA:
4344 switch (p->whichwink) {
4345 case 0:
4346 ast_log(LOG_DEBUG, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
4347 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
4348 break;
4349 case 1:
4350 ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
4351 break;
4352 case 2:
4353 ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
4354 return NULL;
4356 p->whichwink++;
4357 /* Fall through */
4358 case SIG_FEATDMF:
4359 case SIG_E911:
4360 case SIG_FGC_CAMAMF:
4361 case SIG_FGC_CAMA:
4362 case SIG_FEATB:
4363 case SIG_SF_FEATDMF:
4364 case SIG_SF_FEATB:
4365 /* FGD MF *Must* wait for wink */
4366 if (!ast_strlen_zero(p->dop.dialstr))
4367 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
4368 else if (res < 0) {
4369 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
4370 p->dop.dialstr[0] = '\0';
4371 return NULL;
4372 } else
4373 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
4374 p->dop.dialstr[0] = '\0';
4375 break;
4376 default:
4377 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
4379 break;
4380 case ZT_EVENT_HOOKCOMPLETE:
4381 if (p->inalarm) break;
4382 if ((p->radio || (p->oprmode < 0))) break;
4383 switch (mysig) {
4384 case SIG_FXSLS: /* only interesting for FXS */
4385 case SIG_FXSGS:
4386 case SIG_FXSKS:
4387 case SIG_EM:
4388 case SIG_EM_E1:
4389 case SIG_EMWINK:
4390 case SIG_FEATD:
4391 case SIG_SF:
4392 case SIG_SFWINK:
4393 case SIG_SF_FEATD:
4394 if (!ast_strlen_zero(p->dop.dialstr))
4395 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
4396 else if (res < 0) {
4397 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
4398 p->dop.dialstr[0] = '\0';
4399 return NULL;
4400 } else
4401 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
4402 p->dop.dialstr[0] = '\0';
4403 p->dop.op = ZT_DIAL_OP_REPLACE;
4404 break;
4405 case SIG_FEATDMF:
4406 case SIG_FEATDMF_TA:
4407 case SIG_E911:
4408 case SIG_FGC_CAMA:
4409 case SIG_FGC_CAMAMF:
4410 case SIG_FEATB:
4411 case SIG_SF_FEATDMF:
4412 case SIG_SF_FEATB:
4413 ast_log(LOG_DEBUG, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
4414 break;
4415 default:
4416 break;
4418 break;
4419 case ZT_EVENT_POLARITY:
4421 * If we get a Polarity Switch event, check to see
4422 * if we should change the polarity state and
4423 * mark the channel as UP or if this is an indication
4424 * of remote end disconnect.
4426 if (p->polarity == POLARITY_IDLE) {
4427 p->polarity = POLARITY_REV;
4428 if (p->answeronpolarityswitch &&
4429 ((ast->_state == AST_STATE_DIALING) ||
4430 (ast->_state == AST_STATE_RINGING))) {
4431 ast_log(LOG_DEBUG, "Answering on polarity switch!\n");
4432 ast_setstate(p->owner, AST_STATE_UP);
4433 if (p->hanguponpolarityswitch) {
4434 gettimeofday(&p->polaritydelaytv, NULL);
4436 } else
4437 ast_log(LOG_DEBUG, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
4439 /* Removed else statement from here as it was preventing hangups from ever happening*/
4440 /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
4441 if (p->hanguponpolarityswitch &&
4442 (p->polarityonanswerdelay > 0) &&
4443 (p->polarity == POLARITY_REV) &&
4444 ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
4445 /* Added log_debug information below to provide a better indication of what is going on */
4446 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) );
4448 if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
4449 ast_log(LOG_DEBUG, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
4450 ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
4451 p->polarity = POLARITY_IDLE;
4452 } else {
4453 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);
4455 } else {
4456 p->polarity = POLARITY_IDLE;
4457 ast_log(LOG_DEBUG, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
4459 /* Added more log_debug information below to provide a better indication of what is going on */
4460 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) );
4461 break;
4462 default:
4463 ast_log(LOG_DEBUG, "Dunno what to do with event %d on channel %d\n", res, p->channel);
4465 return &p->subs[index].f;
4468 static struct ast_frame *__zt_exception(struct ast_channel *ast)
4470 struct zt_pvt *p = ast->tech_pvt;
4471 int res;
4472 int usedindex=-1;
4473 int index;
4474 struct ast_frame *f;
4477 index = zt_get_index(ast, p, 1);
4479 p->subs[index].f.frametype = AST_FRAME_NULL;
4480 p->subs[index].f.datalen = 0;
4481 p->subs[index].f.samples = 0;
4482 p->subs[index].f.mallocd = 0;
4483 p->subs[index].f.offset = 0;
4484 p->subs[index].f.subclass = 0;
4485 p->subs[index].f.delivery = ast_tv(0,0);
4486 p->subs[index].f.src = "zt_exception";
4487 p->subs[index].f.data = NULL;
4490 if ((!p->owner) && (!(p->radio || (p->oprmode < 0)))) {
4491 /* If nobody owns us, absorb the event appropriately, otherwise
4492 we loop indefinitely. This occurs when, during call waiting, the
4493 other end hangs up our channel so that it no longer exists, but we
4494 have neither FLASH'd nor ONHOOK'd to signify our desire to
4495 change to the other channel. */
4496 if (p->fake_event) {
4497 res = p->fake_event;
4498 p->fake_event = 0;
4499 } else
4500 res = zt_get_event(p->subs[SUB_REAL].zfd);
4501 /* Switch to real if there is one and this isn't something really silly... */
4502 if ((res != ZT_EVENT_RINGEROFF) && (res != ZT_EVENT_RINGERON) &&
4503 (res != ZT_EVENT_HOOKCOMPLETE)) {
4504 ast_log(LOG_DEBUG, "Restoring owner of channel %d on event %d\n", p->channel, res);
4505 p->owner = p->subs[SUB_REAL].owner;
4506 if (p->owner && ast_bridged_channel(p->owner))
4507 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4508 p->subs[SUB_REAL].needunhold = 1;
4510 switch (res) {
4511 case ZT_EVENT_ONHOOK:
4512 zt_disable_ec(p);
4513 if (p->owner) {
4514 if (option_verbose > 2)
4515 ast_verbose(VERBOSE_PREFIX_3 "Channel %s still has call, ringing phone\n", p->owner->name);
4516 zt_ring_phone(p);
4517 p->callwaitingrepeat = 0;
4518 p->cidcwexpire = 0;
4519 } else
4520 ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
4521 update_conf(p);
4522 break;
4523 case ZT_EVENT_RINGOFFHOOK:
4524 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
4525 if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
4526 p->subs[SUB_REAL].needanswer = 1;
4527 p->dialing = 0;
4529 break;
4530 case ZT_EVENT_HOOKCOMPLETE:
4531 case ZT_EVENT_RINGERON:
4532 case ZT_EVENT_RINGEROFF:
4533 /* Do nothing */
4534 break;
4535 case ZT_EVENT_WINKFLASH:
4536 gettimeofday(&p->flashtime, NULL);
4537 if (p->owner) {
4538 if (option_verbose > 2)
4539 ast_verbose(VERBOSE_PREFIX_3 "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
4540 if (p->owner->_state != AST_STATE_UP) {
4541 /* Answer if necessary */
4542 usedindex = zt_get_index(p->owner, p, 0);
4543 if (usedindex > -1) {
4544 p->subs[usedindex].needanswer = 1;
4546 ast_setstate(p->owner, AST_STATE_UP);
4548 p->callwaitingrepeat = 0;
4549 p->cidcwexpire = 0;
4550 if (ast_bridged_channel(p->owner))
4551 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4552 p->subs[SUB_REAL].needunhold = 1;
4553 } else
4554 ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
4555 update_conf(p);
4556 break;
4557 default:
4558 ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
4560 f = &p->subs[index].f;
4561 return f;
4563 if (!(p->radio || (p->oprmode < 0))) ast_log(LOG_DEBUG, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
4564 /* If it's not us, return NULL immediately */
4565 if (ast != p->owner) {
4566 ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
4567 f = &p->subs[index].f;
4568 return f;
4570 f = zt_handle_event(ast);
4571 return f;
4574 static struct ast_frame *zt_exception(struct ast_channel *ast)
4576 struct zt_pvt *p = ast->tech_pvt;
4577 struct ast_frame *f;
4578 ast_mutex_lock(&p->lock);
4579 f = __zt_exception(ast);
4580 ast_mutex_unlock(&p->lock);
4581 return f;
4584 static struct ast_frame *zt_read(struct ast_channel *ast)
4586 struct zt_pvt *p = ast->tech_pvt;
4587 int res;
4588 int index;
4589 void *readbuf;
4590 struct ast_frame *f;
4593 ast_mutex_lock(&p->lock);
4595 index = zt_get_index(ast, p, 0);
4597 /* Hang up if we don't really exist */
4598 if (index < 0) {
4599 ast_log(LOG_WARNING, "We dont exist?\n");
4600 ast_mutex_unlock(&p->lock);
4601 return NULL;
4604 if ((p->radio || (p->oprmode < 0)) && p->inalarm) return NULL;
4606 p->subs[index].f.frametype = AST_FRAME_NULL;
4607 p->subs[index].f.datalen = 0;
4608 p->subs[index].f.samples = 0;
4609 p->subs[index].f.mallocd = 0;
4610 p->subs[index].f.offset = 0;
4611 p->subs[index].f.subclass = 0;
4612 p->subs[index].f.delivery = ast_tv(0,0);
4613 p->subs[index].f.src = "zt_read";
4614 p->subs[index].f.data = NULL;
4616 /* make sure it sends initial key state as first frame */
4617 if ((p->radio || (p->oprmode < 0)) && (!p->firstradio))
4619 ZT_PARAMS ps;
4621 ps.channo = p->channel;
4622 if (ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps) < 0) {
4623 ast_mutex_unlock(&p->lock);
4624 return NULL;
4626 p->firstradio = 1;
4627 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4628 if (ps.rxisoffhook)
4630 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
4632 else
4634 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
4636 ast_mutex_unlock(&p->lock);
4637 return &p->subs[index].f;
4639 if (p->ringt == 1) {
4640 ast_mutex_unlock(&p->lock);
4641 return NULL;
4643 else if (p->ringt > 0)
4644 p->ringt--;
4646 if (p->subs[index].needringing) {
4647 /* Send ringing frame if requested */
4648 p->subs[index].needringing = 0;
4649 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4650 p->subs[index].f.subclass = AST_CONTROL_RINGING;
4651 ast_setstate(ast, AST_STATE_RINGING);
4652 ast_mutex_unlock(&p->lock);
4653 return &p->subs[index].f;
4656 if (p->subs[index].needbusy) {
4657 /* Send busy frame if requested */
4658 p->subs[index].needbusy = 0;
4659 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4660 p->subs[index].f.subclass = AST_CONTROL_BUSY;
4661 ast_mutex_unlock(&p->lock);
4662 return &p->subs[index].f;
4665 if (p->subs[index].needcongestion) {
4666 /* Send congestion frame if requested */
4667 p->subs[index].needcongestion = 0;
4668 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4669 p->subs[index].f.subclass = AST_CONTROL_CONGESTION;
4670 ast_mutex_unlock(&p->lock);
4671 return &p->subs[index].f;
4674 if (p->subs[index].needcallerid) {
4675 ast_set_callerid(ast, S_OR(p->lastcid_num, NULL),
4676 S_OR(p->lastcid_name, NULL),
4677 S_OR(p->lastcid_num, NULL)
4679 p->subs[index].needcallerid = 0;
4682 if (p->subs[index].needanswer) {
4683 /* Send answer frame if requested */
4684 p->subs[index].needanswer = 0;
4685 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4686 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
4687 ast_mutex_unlock(&p->lock);
4688 return &p->subs[index].f;
4691 if (p->subs[index].needflash) {
4692 /* Send answer frame if requested */
4693 p->subs[index].needflash = 0;
4694 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4695 p->subs[index].f.subclass = AST_CONTROL_FLASH;
4696 ast_mutex_unlock(&p->lock);
4697 return &p->subs[index].f;
4700 if (p->subs[index].needhold) {
4701 /* Send answer frame if requested */
4702 p->subs[index].needhold = 0;
4703 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4704 p->subs[index].f.subclass = AST_CONTROL_HOLD;
4705 ast_mutex_unlock(&p->lock);
4706 ast_log(LOG_DEBUG, "Sending hold on '%s'\n", ast->name);
4707 return &p->subs[index].f;
4710 if (p->subs[index].needunhold) {
4711 /* Send answer frame if requested */
4712 p->subs[index].needunhold = 0;
4713 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4714 p->subs[index].f.subclass = AST_CONTROL_UNHOLD;
4715 ast_mutex_unlock(&p->lock);
4716 ast_log(LOG_DEBUG, "Sending unhold on '%s'\n", ast->name);
4717 return &p->subs[index].f;
4720 if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
4721 if (!p->subs[index].linear) {
4722 p->subs[index].linear = 1;
4723 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4724 if (res)
4725 ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, index);
4727 } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
4728 (ast->rawreadformat == AST_FORMAT_ALAW)) {
4729 if (p->subs[index].linear) {
4730 p->subs[index].linear = 0;
4731 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4732 if (res)
4733 ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, index);
4735 } else {
4736 ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
4737 ast_mutex_unlock(&p->lock);
4738 return NULL;
4740 readbuf = ((unsigned char *)p->subs[index].buffer) + AST_FRIENDLY_OFFSET;
4741 CHECK_BLOCKING(ast);
4742 res = read(p->subs[index].zfd, readbuf, p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE);
4743 ast_clear_flag(ast, AST_FLAG_BLOCKING);
4744 /* Check for hangup */
4745 if (res < 0) {
4746 f = NULL;
4747 if (res == -1) {
4748 if (errno == EAGAIN) {
4749 /* Return "NULL" frame if there is nobody there */
4750 ast_mutex_unlock(&p->lock);
4751 return &p->subs[index].f;
4752 } else if (errno == ELAST) {
4753 f = __zt_exception(ast);
4754 } else
4755 ast_log(LOG_WARNING, "zt_rec: %s\n", strerror(errno));
4757 ast_mutex_unlock(&p->lock);
4758 return f;
4760 if (res != (p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE)) {
4761 ast_log(LOG_DEBUG, "Short read (%d/%d), must be an event...\n", res, p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE);
4762 f = __zt_exception(ast);
4763 ast_mutex_unlock(&p->lock);
4764 return f;
4766 if (p->tdd) { /* if in TDD mode, see if we receive that */
4767 int c;
4769 c = tdd_feed(p->tdd,readbuf,READ_SIZE);
4770 if (c < 0) {
4771 ast_log(LOG_DEBUG,"tdd_feed failed\n");
4772 ast_mutex_unlock(&p->lock);
4773 return NULL;
4775 if (c) { /* if a char to return */
4776 p->subs[index].f.subclass = 0;
4777 p->subs[index].f.frametype = AST_FRAME_TEXT;
4778 p->subs[index].f.mallocd = 0;
4779 p->subs[index].f.offset = AST_FRIENDLY_OFFSET;
4780 p->subs[index].f.data = p->subs[index].buffer + AST_FRIENDLY_OFFSET;
4781 p->subs[index].f.datalen = 1;
4782 *((char *) p->subs[index].f.data) = c;
4783 ast_mutex_unlock(&p->lock);
4784 return &p->subs[index].f;
4787 if (p->callwaitingrepeat)
4788 p->callwaitingrepeat--;
4789 if (p->cidcwexpire)
4790 p->cidcwexpire--;
4791 /* Repeat callwaiting */
4792 if (p->callwaitingrepeat == 1) {
4793 p->callwaitrings++;
4794 zt_callwait(ast);
4796 /* Expire CID/CW */
4797 if (p->cidcwexpire == 1) {
4798 if (option_verbose > 2)
4799 ast_verbose(VERBOSE_PREFIX_3 "CPE does not support Call Waiting Caller*ID.\n");
4800 restore_conference(p);
4802 if (p->subs[index].linear) {
4803 p->subs[index].f.datalen = READ_SIZE * 2;
4804 } else
4805 p->subs[index].f.datalen = READ_SIZE;
4807 /* Handle CallerID Transmission */
4808 if ((p->owner == ast) && p->cidspill &&((ast->_state == AST_STATE_UP) || (ast->rings == p->cidrings))) {
4809 send_callerid(p);
4812 p->subs[index].f.frametype = AST_FRAME_VOICE;
4813 p->subs[index].f.subclass = ast->rawreadformat;
4814 p->subs[index].f.samples = READ_SIZE;
4815 p->subs[index].f.mallocd = 0;
4816 p->subs[index].f.offset = AST_FRIENDLY_OFFSET;
4817 p->subs[index].f.data = p->subs[index].buffer + AST_FRIENDLY_OFFSET / sizeof(p->subs[index].buffer[0]);
4818 #if 0
4819 ast_log(LOG_DEBUG, "Read %d of voice on %s\n", p->subs[index].f.datalen, ast->name);
4820 #endif
4821 if (p->dialing || /* Transmitting something */
4822 (index && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
4823 ((index == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
4825 /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
4826 don't send anything */
4827 p->subs[index].f.frametype = AST_FRAME_NULL;
4828 p->subs[index].f.subclass = 0;
4829 p->subs[index].f.samples = 0;
4830 p->subs[index].f.mallocd = 0;
4831 p->subs[index].f.offset = 0;
4832 p->subs[index].f.data = NULL;
4833 p->subs[index].f.datalen= 0;
4835 if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect || p->callprogress) && !index) {
4836 /* Perform busy detection. etc on the zap line */
4837 f = ast_dsp_process(ast, p->dsp, &p->subs[index].f);
4838 if (f) {
4839 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_BUSY)) {
4840 if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
4841 /* Treat this as a "hangup" instead of a "busy" on the assumption that
4842 a busy */
4843 f = NULL;
4845 } else if (f->frametype == AST_FRAME_DTMF) {
4846 #ifdef HAVE_PRI
4847 if (!p->proceeding && p->sig==SIG_PRI && p->pri && p->pri->overlapdial) {
4848 /* Don't accept in-band DTMF when in overlap dial mode */
4849 f->frametype = AST_FRAME_NULL;
4850 f->subclass = 0;
4852 #endif
4853 /* DSP clears us of being pulse */
4854 p->pulsedial = 0;
4857 } else
4858 f = &p->subs[index].f;
4860 if (f && (f->frametype == AST_FRAME_DTMF))
4861 zt_handle_dtmfup(ast, index, &f);
4863 /* If we have a fake_event, trigger exception to handle it */
4864 if (p->fake_event)
4865 ast_set_flag(ast, AST_FLAG_EXCEPTION);
4867 ast_mutex_unlock(&p->lock);
4868 return f;
4871 static int my_zt_write(struct zt_pvt *p, unsigned char *buf, int len, int index, int linear)
4873 int sent=0;
4874 int size;
4875 int res;
4876 int fd;
4877 fd = p->subs[index].zfd;
4878 while (len) {
4879 size = len;
4880 if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
4881 size = (linear ? READ_SIZE * 2 : READ_SIZE);
4882 res = write(fd, buf, size);
4883 if (res != size) {
4884 if (option_debug)
4885 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
4886 return sent;
4888 len -= size;
4889 buf += size;
4891 return sent;
4894 static int zt_write(struct ast_channel *ast, struct ast_frame *frame)
4896 struct zt_pvt *p = ast->tech_pvt;
4897 int res;
4898 unsigned char outbuf[4096];
4899 int index;
4900 index = zt_get_index(ast, p, 0);
4901 if (index < 0) {
4902 ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
4903 return -1;
4906 #if 0
4907 #ifdef HAVE_PRI
4908 ast_mutex_lock(&p->lock);
4909 if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
4910 if (p->pri->pri) {
4911 if (!pri_grab(p, p->pri)) {
4912 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
4913 pri_rel(p->pri);
4914 } else
4915 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
4917 p->proceeding=1;
4919 ast_mutex_unlock(&p->lock);
4920 #endif
4921 #endif
4922 /* Write a frame of (presumably voice) data */
4923 if (frame->frametype != AST_FRAME_VOICE) {
4924 if (frame->frametype != AST_FRAME_IMAGE)
4925 ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
4926 return 0;
4928 if ((frame->subclass != AST_FORMAT_SLINEAR) &&
4929 (frame->subclass != AST_FORMAT_ULAW) &&
4930 (frame->subclass != AST_FORMAT_ALAW)) {
4931 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
4932 return -1;
4934 if (p->dialing) {
4935 if (option_debug)
4936 ast_log(LOG_DEBUG, "Dropping frame since I'm still dialing on %s...\n",ast->name);
4937 return 0;
4939 if (!p->owner) {
4940 if (option_debug)
4941 ast_log(LOG_DEBUG, "Dropping frame since there is no active owner on %s...\n",ast->name);
4942 return 0;
4944 if (p->cidspill) {
4945 if (option_debug)
4946 ast_log(LOG_DEBUG, "Dropping frame since I've still got a callerid spill\n");
4947 return 0;
4949 /* Return if it's not valid data */
4950 if (!frame->data || !frame->datalen)
4951 return 0;
4952 if (frame->datalen > sizeof(outbuf) * 2) {
4953 ast_log(LOG_WARNING, "Frame too large\n");
4954 return 0;
4957 if (frame->subclass == AST_FORMAT_SLINEAR) {
4958 if (!p->subs[index].linear) {
4959 p->subs[index].linear = 1;
4960 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4961 if (res)
4962 ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
4964 res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, index, 1);
4965 } else {
4966 /* x-law already */
4967 if (p->subs[index].linear) {
4968 p->subs[index].linear = 0;
4969 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4970 if (res)
4971 ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
4973 res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, index, 0);
4975 if (res < 0) {
4976 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
4977 return -1;
4979 return 0;
4982 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
4984 struct zt_pvt *p = chan->tech_pvt;
4985 int res=-1;
4986 int index;
4987 int func = ZT_FLASH;
4988 ast_mutex_lock(&p->lock);
4989 index = zt_get_index(chan, p, 0);
4990 ast_log(LOG_DEBUG, "Requested indication %d on channel %s\n", condition, chan->name);
4991 if (index == SUB_REAL) {
4992 switch (condition) {
4993 case AST_CONTROL_BUSY:
4994 #ifdef HAVE_PRI
4995 if (p->priindication_oob && p->sig == SIG_PRI) {
4996 chan->hangupcause = AST_CAUSE_USER_BUSY;
4997 chan->_softhangup |= AST_SOFTHANGUP_DEV;
4998 res = 0;
4999 } else if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5000 if (p->pri->pri) {
5001 if (!pri_grab(p, p->pri)) {
5002 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5003 pri_rel(p->pri);
5005 else
5006 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5008 p->progress = 1;
5009 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_BUSY);
5010 } else
5011 #endif
5012 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_BUSY);
5013 break;
5014 case AST_CONTROL_RINGING:
5015 #ifdef HAVE_PRI
5016 if ((!p->alerting) && p->sig==SIG_PRI && p->pri && !p->outgoing && (chan->_state != AST_STATE_UP)) {
5017 if (p->pri->pri) {
5018 if (!pri_grab(p, p->pri)) {
5019 pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
5020 pri_rel(p->pri);
5022 else
5023 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5025 p->alerting = 1;
5027 #endif
5028 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_RINGTONE);
5029 if (chan->_state != AST_STATE_UP) {
5030 if ((chan->_state != AST_STATE_RING) ||
5031 ((p->sig != SIG_FXSKS) &&
5032 (p->sig != SIG_FXSLS) &&
5033 (p->sig != SIG_FXSGS)))
5034 ast_setstate(chan, AST_STATE_RINGING);
5036 break;
5037 case AST_CONTROL_PROCEEDING:
5038 ast_log(LOG_DEBUG,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
5039 #ifdef HAVE_PRI
5040 if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5041 if (p->pri->pri) {
5042 if (!pri_grab(p, p->pri)) {
5043 pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
5044 pri_rel(p->pri);
5046 else
5047 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5049 p->proceeding = 1;
5051 #endif
5052 /* don't continue in ast_indicate */
5053 res = 0;
5054 break;
5055 case AST_CONTROL_PROGRESS:
5056 ast_log(LOG_DEBUG,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
5057 #ifdef HAVE_PRI
5058 p->digital = 0; /* Digital-only calls isn't allows any inband progress messages */
5059 if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5060 if (p->pri->pri) {
5061 if (!pri_grab(p, p->pri)) {
5062 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5063 pri_rel(p->pri);
5065 else
5066 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5068 p->progress = 1;
5070 #endif
5071 /* don't continue in ast_indicate */
5072 res = 0;
5073 break;
5074 case AST_CONTROL_CONGESTION:
5075 chan->hangupcause = AST_CAUSE_CONGESTION;
5076 #ifdef HAVE_PRI
5077 if (p->priindication_oob && p->sig == SIG_PRI) {
5078 chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
5079 chan->_softhangup |= AST_SOFTHANGUP_DEV;
5080 res = 0;
5081 } else if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5082 if (p->pri) {
5083 if (!pri_grab(p, p->pri)) {
5084 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5085 pri_rel(p->pri);
5086 } else
5087 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5089 p->progress = 1;
5090 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5091 } else
5092 #endif
5093 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5094 break;
5095 case AST_CONTROL_HOLD:
5096 #ifdef HAVE_PRI
5097 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
5098 if (!pri_grab(p, p->pri)) {
5099 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
5100 pri_rel(p->pri);
5101 } else
5102 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5103 } else
5104 #endif
5105 ast_moh_start(chan, data, p->mohinterpret);
5106 break;
5107 case AST_CONTROL_UNHOLD:
5108 #ifdef HAVE_PRI
5109 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
5110 if (!pri_grab(p, p->pri)) {
5111 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
5112 pri_rel(p->pri);
5113 } else
5114 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5115 } else
5116 #endif
5117 ast_moh_stop(chan);
5118 break;
5119 case AST_CONTROL_RADIO_KEY:
5120 if (p->radio)
5121 res = zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
5122 res = 0;
5123 break;
5124 case AST_CONTROL_RADIO_UNKEY:
5125 if (p->radio)
5126 res = zt_set_hook(p->subs[index].zfd, ZT_RINGOFF);
5127 res = 0;
5128 break;
5129 case AST_CONTROL_FLASH:
5130 /* flash hookswitch */
5131 if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
5132 /* Clear out the dial buffer */
5133 p->dop.dialstr[0] = '\0';
5134 if ((ioctl(p->subs[SUB_REAL].zfd,ZT_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
5135 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
5136 chan->name, strerror(errno));
5137 } else
5138 res = 0;
5139 } else
5140 res = 0;
5141 break;
5142 case -1:
5143 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5144 break;
5146 } else
5147 res = 0;
5148 ast_mutex_unlock(&p->lock);
5149 return res;
5152 static struct ast_channel *zt_new(struct zt_pvt *i, int state, int startpbx, int index, int law, int transfercapability)
5154 struct ast_channel *tmp;
5155 int deflaw;
5156 int res;
5157 int x,y;
5158 int features;
5159 char *b2 = 0;
5160 ZT_PARAMS ps;
5161 if (i->subs[index].owner) {
5162 ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[index]);
5163 return NULL;
5165 y = 1;
5166 do {
5167 if (b2)
5168 free(b2);
5169 #ifdef HAVE_PRI
5170 if (i->bearer || (i->pri && (i->sig == SIG_FXSKS)))
5171 asprintf(&b2, "Zap/%d:%d-%d", i->pri->trunkgroup, i->channel, y);
5172 else
5173 #endif
5174 if (i->channel == CHAN_PSEUDO)
5175 asprintf(&b2, "Zap/pseudo-%ld", ast_random());
5176 else
5177 asprintf(&b2, "Zap/%d-%d", i->channel, y);
5178 for (x = 0; x < 3; x++) {
5179 if ((index != x) && i->subs[x].owner && !strcasecmp(b2, i->subs[x].owner->name))
5180 break;
5182 y++;
5183 } while (x < 3);
5184 tmp = ast_channel_alloc(0, state, 0, 0, i->accountcode, i->exten, i->context, i->amaflags, b2);
5185 if (b2) /*!> b2 can be freed now, it's been copied into the channel structure */
5186 free(b2);
5187 if (!tmp)
5188 return NULL;
5189 tmp->tech = &zap_tech;
5190 ps.channo = i->channel;
5191 res = ioctl(i->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps);
5192 if (res) {
5193 ast_log(LOG_WARNING, "Unable to get parameters, assuming MULAW\n");
5194 ps.curlaw = ZT_LAW_MULAW;
5196 if (ps.curlaw == ZT_LAW_ALAW)
5197 deflaw = AST_FORMAT_ALAW;
5198 else
5199 deflaw = AST_FORMAT_ULAW;
5200 if (law) {
5201 if (law == ZT_LAW_ALAW)
5202 deflaw = AST_FORMAT_ALAW;
5203 else
5204 deflaw = AST_FORMAT_ULAW;
5206 tmp->fds[0] = i->subs[index].zfd;
5207 tmp->nativeformats = AST_FORMAT_SLINEAR | deflaw;
5208 /* Start out assuming ulaw since it's smaller :) */
5209 tmp->rawreadformat = deflaw;
5210 tmp->readformat = deflaw;
5211 tmp->rawwriteformat = deflaw;
5212 tmp->writeformat = deflaw;
5213 i->subs[index].linear = 0;
5214 zt_setlinear(i->subs[index].zfd, i->subs[index].linear);
5215 features = 0;
5216 if (i->busydetect && CANBUSYDETECT(i))
5217 features |= DSP_FEATURE_BUSY_DETECT;
5218 if ((i->callprogress & 1) && CANPROGRESSDETECT(i))
5219 features |= DSP_FEATURE_CALL_PROGRESS;
5220 if ((!i->outgoing && (i->callprogress & 4)) ||
5221 (i->outgoing && (i->callprogress & 2))) {
5222 features |= DSP_FEATURE_FAX_DETECT;
5224 #ifdef ZT_TONEDETECT
5225 x = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
5226 if (ioctl(i->subs[index].zfd, ZT_TONEDETECT, &x)) {
5227 #endif
5228 i->hardwaredtmf = 0;
5229 features |= DSP_FEATURE_DTMF_DETECT;
5230 #ifdef ZT_TONEDETECT
5231 } else if (NEED_MFDETECT(i)) {
5232 i->hardwaredtmf = 1;
5233 features |= DSP_FEATURE_DTMF_DETECT;
5235 #endif
5236 if (features) {
5237 if (i->dsp) {
5238 ast_log(LOG_DEBUG, "Already have a dsp on %s?\n", tmp->name);
5239 } else {
5240 if (i->channel != CHAN_PSEUDO)
5241 i->dsp = ast_dsp_new();
5242 else
5243 i->dsp = NULL;
5244 if (i->dsp) {
5245 i->dsp_features = features & ~DSP_PROGRESS_TALK;
5246 #ifdef HAVE_PRI
5247 /* We cannot do progress detection until receives PROGRESS message */
5248 if (i->outgoing && (i->sig == SIG_PRI)) {
5249 /* Remember requested DSP features, don't treat
5250 talking as ANSWER */
5251 features = 0;
5253 #endif
5254 ast_dsp_set_features(i->dsp, features);
5255 ast_dsp_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
5256 if (!ast_strlen_zero(progzone))
5257 ast_dsp_set_call_progress_zone(i->dsp, progzone);
5258 if (i->busydetect && CANBUSYDETECT(i)) {
5259 ast_dsp_set_busy_count(i->dsp, i->busycount);
5260 ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
5266 if (state == AST_STATE_RING)
5267 tmp->rings = 1;
5268 tmp->tech_pvt = i;
5269 if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
5270 /* Only FXO signalled stuff can be picked up */
5271 tmp->callgroup = i->callgroup;
5272 tmp->pickupgroup = i->pickupgroup;
5274 if (!ast_strlen_zero(i->language))
5275 ast_string_field_set(tmp, language, i->language);
5276 if (!i->owner)
5277 i->owner = tmp;
5278 if (!ast_strlen_zero(i->accountcode))
5279 ast_string_field_set(tmp, accountcode, i->accountcode);
5280 if (i->amaflags)
5281 tmp->amaflags = i->amaflags;
5282 i->subs[index].owner = tmp;
5283 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
5284 ast_string_field_set(tmp, call_forward, i->call_forward);
5285 /* If we've been told "no ADSI" then enforce it */
5286 if (!i->adsi)
5287 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
5288 if (!ast_strlen_zero(i->exten))
5289 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
5290 if (!ast_strlen_zero(i->rdnis))
5291 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
5292 if (!ast_strlen_zero(i->dnid))
5293 tmp->cid.cid_dnid = ast_strdup(i->dnid);
5295 /* Don't use ast_set_callerid() here because it will
5296 * generate a needless NewCallerID event */
5297 #ifdef PRI_ANI
5298 tmp->cid.cid_num = ast_strdup(i->cid_num);
5299 tmp->cid.cid_name = ast_strdup(i->cid_name);
5300 if (!ast_strlen_zero(i->cid_ani))
5301 tmp->cid.cid_ani = ast_strdup(i->cid_ani);
5302 else
5303 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5304 #else
5305 tmp->cid.cid_num = ast_strdup(i->cid_num);
5306 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5307 tmp->cid.cid_name = ast_strdup(i->cid_name);
5308 #endif
5309 tmp->cid.cid_pres = i->callingpres;
5310 tmp->cid.cid_ton = i->cid_ton;
5311 #ifdef HAVE_PRI
5312 tmp->transfercapability = transfercapability;
5313 pbx_builtin_setvar_helper(tmp, "TRANSFERCAPABILITY", ast_transfercapability2str(transfercapability));
5314 if (transfercapability & PRI_TRANS_CAP_DIGITAL)
5315 i->digital = 1;
5316 /* Assume calls are not idle calls unless we're told differently */
5317 i->isidlecall = 0;
5318 i->alreadyhungup = 0;
5319 #endif
5320 /* clear the fake event in case we posted one before we had ast_channel */
5321 i->fake_event = 0;
5322 /* Assure there is no confmute on this channel */
5323 zt_confmute(i, 0);
5324 /* Configure the new channel jb */
5325 ast_jb_configure(tmp, &global_jbconf);
5326 if (startpbx) {
5327 if (ast_pbx_start(tmp)) {
5328 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
5329 ast_hangup(tmp);
5330 i->owner = NULL;
5331 return NULL;
5335 ast_module_ref(ast_module_info->self);
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 /* in the bizarre case where the channel has become a zombie before we
5406 even get started here, abort safely
5408 if (!p) {
5409 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
5410 ast_hangup(chan);
5411 return NULL;
5414 if (option_verbose > 2)
5415 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s'\n", chan->name);
5416 index = zt_get_index(chan, p, 1);
5417 if (index < 0) {
5418 ast_log(LOG_WARNING, "Huh?\n");
5419 ast_hangup(chan);
5420 return NULL;
5422 if (p->dsp)
5423 ast_dsp_digitreset(p->dsp);
5424 switch (p->sig) {
5425 #ifdef HAVE_PRI
5426 case SIG_PRI:
5427 /* Now loop looking for an extension */
5428 ast_copy_string(exten, p->exten, sizeof(exten));
5429 len = strlen(exten);
5430 res = 0;
5431 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
5432 if (len && !ast_ignore_pattern(chan->context, exten))
5433 tone_zone_play_tone(p->subs[index].zfd, -1);
5434 else
5435 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5436 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
5437 timeout = matchdigittimeout;
5438 else
5439 timeout = gendigittimeout;
5440 res = ast_waitfordigit(chan, timeout);
5441 if (res < 0) {
5442 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5443 ast_hangup(chan);
5444 return NULL;
5445 } else if (res) {
5446 exten[len++] = res;
5447 exten[len] = '\0';
5448 } else
5449 break;
5451 /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
5452 if (ast_strlen_zero(exten)) {
5453 if (option_verbose > 2)
5454 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of empty extension received on overlap call\n");
5455 exten[0] = 's';
5456 exten[1] = '\0';
5458 tone_zone_play_tone(p->subs[index].zfd, -1);
5459 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
5460 /* Start the real PBX */
5461 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5462 if (p->dsp) ast_dsp_digitreset(p->dsp);
5463 zt_enable_ec(p);
5464 ast_setstate(chan, AST_STATE_RING);
5465 res = ast_pbx_run(chan);
5466 if (res) {
5467 ast_log(LOG_WARNING, "PBX exited non-zero!\n");
5469 } else {
5470 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
5471 chan->hangupcause = AST_CAUSE_UNALLOCATED;
5472 ast_hangup(chan);
5473 p->exten[0] = '\0';
5474 /* Since we send release complete here, we won't get one */
5475 p->call = NULL;
5477 return NULL;
5478 break;
5479 #endif
5480 case SIG_FEATD:
5481 case SIG_FEATDMF:
5482 case SIG_FEATDMF_TA:
5483 case SIG_E911:
5484 case SIG_FGC_CAMAMF:
5485 case SIG_FEATB:
5486 case SIG_EMWINK:
5487 case SIG_SF_FEATD:
5488 case SIG_SF_FEATDMF:
5489 case SIG_SF_FEATB:
5490 case SIG_SFWINK:
5491 if (zt_wink(p, index))
5492 return NULL;
5493 /* Fall through */
5494 case SIG_EM:
5495 case SIG_EM_E1:
5496 case SIG_SF:
5497 case SIG_FGC_CAMA:
5498 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5499 if (p->dsp)
5500 ast_dsp_digitreset(p->dsp);
5501 /* set digit mode appropriately */
5502 if (p->dsp) {
5503 if (NEED_MFDETECT(p))
5504 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MF | p->dtmfrelax);
5505 else
5506 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5508 memset(dtmfbuf, 0, sizeof(dtmfbuf));
5509 /* Wait for the first digit only if immediate=no */
5510 if (!p->immediate)
5511 /* Wait for the first digit (up to 5 seconds). */
5512 res = ast_waitfordigit(chan, 5000);
5513 else
5514 res = 0;
5515 if (res > 0) {
5516 /* save first char */
5517 dtmfbuf[0] = res;
5518 switch (p->sig) {
5519 case SIG_FEATD:
5520 case SIG_SF_FEATD:
5521 res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
5522 if (res > 0)
5523 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
5524 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5525 break;
5526 case SIG_FEATDMF_TA:
5527 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5528 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5529 if (zt_wink(p, index)) return NULL;
5530 dtmfbuf[0] = 0;
5531 /* Wait for the first digit (up to 5 seconds). */
5532 res = ast_waitfordigit(chan, 5000);
5533 if (res <= 0) break;
5534 dtmfbuf[0] = res;
5535 /* fall through intentionally */
5536 case SIG_FEATDMF:
5537 case SIG_E911:
5538 case SIG_FGC_CAMAMF:
5539 case SIG_SF_FEATDMF:
5540 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5541 /* if international caca, do it again to get real ANO */
5542 if ((p->sig == SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
5544 if (zt_wink(p, index)) return NULL;
5545 dtmfbuf[0] = 0;
5546 /* Wait for the first digit (up to 5 seconds). */
5547 res = ast_waitfordigit(chan, 5000);
5548 if (res <= 0) break;
5549 dtmfbuf[0] = res;
5550 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5552 if (res > 0) {
5553 /* if E911, take off hook */
5554 if (p->sig == SIG_E911)
5555 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
5556 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
5558 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5559 break;
5560 case SIG_FEATB:
5561 case SIG_SF_FEATB:
5562 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5563 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5564 break;
5565 case SIG_EMWINK:
5566 /* if we received a '*', we are actually receiving Feature Group D
5567 dial syntax, so use that mode; otherwise, fall through to normal
5568 mode
5570 if (res == '*') {
5571 res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
5572 if (res > 0)
5573 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
5574 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5575 break;
5577 default:
5578 /* If we got the first digit, get the rest */
5579 len = 1;
5580 dtmfbuf[len] = '\0';
5581 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
5582 if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
5583 timeout = matchdigittimeout;
5584 } else {
5585 timeout = gendigittimeout;
5587 res = ast_waitfordigit(chan, timeout);
5588 if (res < 0) {
5589 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5590 ast_hangup(chan);
5591 return NULL;
5592 } else if (res) {
5593 dtmfbuf[len++] = res;
5594 dtmfbuf[len] = '\0';
5595 } else {
5596 break;
5599 break;
5602 if (res == -1) {
5603 ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
5604 ast_hangup(chan);
5605 return NULL;
5606 } else if (res < 0) {
5607 ast_log(LOG_DEBUG, "Got hung up before digits finished\n");
5608 ast_hangup(chan);
5609 return NULL;
5612 if (p->sig == SIG_FGC_CAMA) {
5613 char anibuf[100];
5615 if (ast_safe_sleep(chan,1000) == -1) {
5616 ast_hangup(chan);
5617 return NULL;
5619 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
5620 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MF | p->dtmfrelax);
5621 res = my_getsigstr(chan, anibuf, "#", 10000);
5622 if ((res > 0) && (strlen(anibuf) > 2)) {
5623 if (anibuf[strlen(anibuf) - 1] == '#')
5624 anibuf[strlen(anibuf) - 1] = 0;
5625 ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
5627 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5630 ast_copy_string(exten, dtmfbuf, sizeof(exten));
5631 if (ast_strlen_zero(exten))
5632 ast_copy_string(exten, "s", sizeof(exten));
5633 if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
5634 /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
5635 if (exten[0] == '*') {
5636 char *stringp=NULL;
5637 ast_copy_string(exten2, exten, sizeof(exten2));
5638 /* Parse out extension and callerid */
5639 stringp=exten2 +1;
5640 s1 = strsep(&stringp, "*");
5641 s2 = strsep(&stringp, "*");
5642 if (s2) {
5643 if (!ast_strlen_zero(p->cid_num))
5644 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5645 else
5646 ast_set_callerid(chan, s1, NULL, s1);
5647 ast_copy_string(exten, s2, sizeof(exten));
5648 } else
5649 ast_copy_string(exten, s1, sizeof(exten));
5650 } else if (p->sig == SIG_FEATD)
5651 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d. Assuming E&M Wink instead\n", p->channel);
5653 if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
5654 if (exten[0] == '*') {
5655 char *stringp=NULL;
5656 ast_copy_string(exten2, exten, sizeof(exten2));
5657 /* Parse out extension and callerid */
5658 stringp=exten2 +1;
5659 s1 = strsep(&stringp, "#");
5660 s2 = strsep(&stringp, "#");
5661 if (s2) {
5662 if (!ast_strlen_zero(p->cid_num))
5663 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5664 else
5665 if (*(s1 + 2))
5666 ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
5667 ast_copy_string(exten, s2 + 1, sizeof(exten));
5668 } else
5669 ast_copy_string(exten, s1 + 2, sizeof(exten));
5670 } else
5671 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d. Assuming E&M Wink instead\n", p->channel);
5673 if ((p->sig == SIG_E911) || (p->sig == SIG_FGC_CAMAMF)) {
5674 if (exten[0] == '*') {
5675 char *stringp=NULL;
5676 ast_copy_string(exten2, exten, sizeof(exten2));
5677 /* Parse out extension and callerid */
5678 stringp=exten2 +1;
5679 s1 = strsep(&stringp, "#");
5680 s2 = strsep(&stringp, "#");
5681 if (s2 && (*(s2 + 1) == '0')) {
5682 if (*(s2 + 2))
5683 ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
5685 if (s1) ast_copy_string(exten, s1, sizeof(exten));
5686 else ast_copy_string(exten, "911", sizeof(exten));
5687 } else
5688 ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d. Assuming E&M Wink instead\n", p->channel);
5690 if (p->sig == SIG_FEATB) {
5691 if (exten[0] == '*') {
5692 char *stringp=NULL;
5693 ast_copy_string(exten2, exten, sizeof(exten2));
5694 /* Parse out extension and callerid */
5695 stringp=exten2 +1;
5696 s1 = strsep(&stringp, "#");
5697 ast_copy_string(exten, exten2 + 1, sizeof(exten));
5698 } else
5699 ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d. Assuming E&M Wink instead\n", p->channel);
5701 if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
5702 zt_wink(p, index);
5703 /* some switches require a minimum guard time between
5704 the last FGD wink and something that answers
5705 immediately. This ensures it */
5706 if (ast_safe_sleep(chan,100)) return NULL;
5708 zt_enable_ec(p);
5709 if (NEED_MFDETECT(p)) {
5710 if (p->dsp) {
5711 if (!p->hardwaredtmf)
5712 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5713 else {
5714 ast_dsp_free(p->dsp);
5715 p->dsp = NULL;
5720 if (ast_exists_extension(chan, chan->context, exten, 1, chan->cid.cid_num)) {
5721 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5722 if (p->dsp) ast_dsp_digitreset(p->dsp);
5723 res = ast_pbx_run(chan);
5724 if (res) {
5725 ast_log(LOG_WARNING, "PBX exited non-zero\n");
5726 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5728 return NULL;
5729 } else {
5730 if (option_verbose > 2)
5731 ast_verbose(VERBOSE_PREFIX_2 "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
5732 sleep(2);
5733 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_INFO);
5734 if (res < 0)
5735 ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
5736 else
5737 sleep(1);
5738 res = ast_streamfile(chan, "ss-noservice", chan->language);
5739 if (res >= 0)
5740 ast_waitstream(chan, "");
5741 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5742 ast_hangup(chan);
5743 return NULL;
5745 break;
5746 case SIG_FXOLS:
5747 case SIG_FXOGS:
5748 case SIG_FXOKS:
5749 /* Read the first digit */
5750 timeout = firstdigittimeout;
5751 /* If starting a threeway call, never timeout on the first digit so someone
5752 can use flash-hook as a "hold" feature */
5753 if (p->subs[SUB_THREEWAY].owner)
5754 timeout = 999999;
5755 while (len < AST_MAX_EXTENSION-1) {
5756 /* Read digit unless it's supposed to be immediate, in which case the
5757 only answer is 's' */
5758 if (p->immediate)
5759 res = 's';
5760 else
5761 res = ast_waitfordigit(chan, timeout);
5762 timeout = 0;
5763 if (res < 0) {
5764 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5765 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5766 ast_hangup(chan);
5767 return NULL;
5768 } else if (res) {
5769 exten[len++]=res;
5770 exten[len] = '\0';
5772 if (!ast_ignore_pattern(chan->context, exten))
5773 tone_zone_play_tone(p->subs[index].zfd, -1);
5774 else
5775 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5776 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && strcmp(exten, ast_parking_ext())) {
5777 if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
5778 if (getforward) {
5779 /* Record this as the forwarding extension */
5780 ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
5781 if (option_verbose > 2)
5782 ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
5783 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5784 if (res)
5785 break;
5786 usleep(500000);
5787 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5788 sleep(1);
5789 memset(exten, 0, sizeof(exten));
5790 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5791 len = 0;
5792 getforward = 0;
5793 } else {
5794 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5795 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5796 if (!ast_strlen_zero(p->cid_num)) {
5797 if (!p->hidecallerid)
5798 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5799 else
5800 ast_set_callerid(chan, NULL, NULL, p->cid_num);
5802 if (!ast_strlen_zero(p->cid_name)) {
5803 if (!p->hidecallerid)
5804 ast_set_callerid(chan, NULL, p->cid_name, NULL);
5806 ast_setstate(chan, AST_STATE_RING);
5807 zt_enable_ec(p);
5808 res = ast_pbx_run(chan);
5809 if (res) {
5810 ast_log(LOG_WARNING, "PBX exited non-zero\n");
5811 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5813 return NULL;
5815 } else {
5816 /* It's a match, but they just typed a digit, and there is an ambiguous match,
5817 so just set the timeout to matchdigittimeout and wait some more */
5818 timeout = matchdigittimeout;
5820 } else if (res == 0) {
5821 ast_log(LOG_DEBUG, "not enough digits (and no ambiguous match)...\n");
5822 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5823 zt_wait_event(p->subs[index].zfd);
5824 ast_hangup(chan);
5825 return NULL;
5826 } else if (p->callwaiting && !strcmp(exten, "*70")) {
5827 if (option_verbose > 2)
5828 ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
5829 /* Disable call waiting if enabled */
5830 p->callwaiting = 0;
5831 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5832 if (res) {
5833 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
5834 chan->name, strerror(errno));
5836 len = 0;
5837 ioctl(p->subs[index].zfd,ZT_CONFDIAG,&len);
5838 memset(exten, 0, sizeof(exten));
5839 timeout = firstdigittimeout;
5841 } else if (!strcmp(exten,ast_pickup_ext())) {
5842 /* Scan all channels and see if any there
5843 * ringing channqels with that have call groups
5844 * that equal this channels pickup group
5846 if (index == SUB_REAL) {
5847 /* Switch us from Third call to Call Wait */
5848 if (p->subs[SUB_THREEWAY].owner) {
5849 /* If you make a threeway call and the *8# a call, it should actually
5850 look like a callwait */
5851 alloc_sub(p, SUB_CALLWAIT);
5852 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
5853 unalloc_sub(p, SUB_THREEWAY);
5855 zt_enable_ec(p);
5856 if (ast_pickup_call(chan)) {
5857 ast_log(LOG_DEBUG, "No call pickup possible...\n");
5858 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5859 zt_wait_event(p->subs[index].zfd);
5861 ast_hangup(chan);
5862 return NULL;
5863 } else {
5864 ast_log(LOG_WARNING, "Huh? Got *8# on call not on real\n");
5865 ast_hangup(chan);
5866 return NULL;
5869 } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
5870 if (option_verbose > 2)
5871 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
5872 /* Disable Caller*ID if enabled */
5873 p->hidecallerid = 1;
5874 if (chan->cid.cid_num)
5875 free(chan->cid.cid_num);
5876 chan->cid.cid_num = NULL;
5877 if (chan->cid.cid_name)
5878 free(chan->cid.cid_name);
5879 chan->cid.cid_name = NULL;
5880 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5881 if (res) {
5882 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
5883 chan->name, strerror(errno));
5885 len = 0;
5886 memset(exten, 0, sizeof(exten));
5887 timeout = firstdigittimeout;
5888 } else if (p->callreturn && !strcmp(exten, "*69")) {
5889 res = 0;
5890 if (!ast_strlen_zero(p->lastcid_num)) {
5891 res = ast_say_digit_str(chan, p->lastcid_num, "", chan->language);
5893 if (!res)
5894 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5895 break;
5896 } else if (!strcmp(exten, "*78")) {
5897 /* Do not disturb */
5898 if (option_verbose > 2)
5899 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %d\n", p->channel);
5900 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
5901 "Channel: Zap/%d\r\n"
5902 "Status: enabled\r\n", p->channel);
5903 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5904 p->dnd = 1;
5905 getforward = 0;
5906 memset(exten, 0, sizeof(exten));
5907 len = 0;
5908 } else if (!strcmp(exten, "*79")) {
5909 /* Do not disturb */
5910 if (option_verbose > 2)
5911 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %d\n", p->channel);
5912 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
5913 "Channel: Zap/%d\r\n"
5914 "Status: disabled\r\n", p->channel);
5915 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5916 p->dnd = 0;
5917 getforward = 0;
5918 memset(exten, 0, sizeof(exten));
5919 len = 0;
5920 } else if (p->cancallforward && !strcmp(exten, "*72")) {
5921 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5922 getforward = 1;
5923 memset(exten, 0, sizeof(exten));
5924 len = 0;
5925 } else if (p->cancallforward && !strcmp(exten, "*73")) {
5926 if (option_verbose > 2)
5927 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %d\n", p->channel);
5928 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5929 memset(p->call_forward, 0, sizeof(p->call_forward));
5930 getforward = 0;
5931 memset(exten, 0, sizeof(exten));
5932 len = 0;
5933 } else if ((p->transfer || p->canpark) && !strcmp(exten, ast_parking_ext()) &&
5934 p->subs[SUB_THREEWAY].owner &&
5935 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
5936 /* This is a three way call, the main call being a real channel,
5937 and we're parking the first call. */
5938 ast_masq_park_call(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), chan, 0, NULL);
5939 if (option_verbose > 2)
5940 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
5941 break;
5942 } else if (!ast_strlen_zero(p->lastcid_num) && !strcmp(exten, "*60")) {
5943 if (option_verbose > 2)
5944 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", p->lastcid_num);
5945 res = ast_db_put("blacklist", p->lastcid_num, "1");
5946 if (!res) {
5947 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5948 memset(exten, 0, sizeof(exten));
5949 len = 0;
5951 } else if (p->hidecallerid && !strcmp(exten, "*82")) {
5952 if (option_verbose > 2)
5953 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
5954 /* Enable Caller*ID if enabled */
5955 p->hidecallerid = 0;
5956 if (chan->cid.cid_num)
5957 free(chan->cid.cid_num);
5958 chan->cid.cid_num = NULL;
5959 if (chan->cid.cid_name)
5960 free(chan->cid.cid_name);
5961 chan->cid.cid_name = NULL;
5962 ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
5963 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5964 if (res) {
5965 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
5966 chan->name, strerror(errno));
5968 len = 0;
5969 memset(exten, 0, sizeof(exten));
5970 timeout = firstdigittimeout;
5971 } else if (!strcmp(exten, "*0")) {
5972 struct ast_channel *nbridge =
5973 p->subs[SUB_THREEWAY].owner;
5974 struct zt_pvt *pbridge = NULL;
5975 /* set up the private struct of the bridged one, if any */
5976 if (nbridge && ast_bridged_channel(nbridge))
5977 pbridge = ast_bridged_channel(nbridge)->tech_pvt;
5978 if (nbridge && pbridge &&
5979 (nbridge->tech == &zap_tech) &&
5980 (ast_bridged_channel(nbridge)->tech == &zap_tech) &&
5981 ISTRUNK(pbridge)) {
5982 int func = ZT_FLASH;
5983 /* Clear out the dial buffer */
5984 p->dop.dialstr[0] = '\0';
5985 /* flash hookswitch */
5986 if ((ioctl(pbridge->subs[SUB_REAL].zfd,ZT_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
5987 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
5988 nbridge->name, strerror(errno));
5990 swap_subs(p, SUB_REAL, SUB_THREEWAY);
5991 unalloc_sub(p, SUB_THREEWAY);
5992 p->owner = p->subs[SUB_REAL].owner;
5993 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
5994 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
5995 ast_hangup(chan);
5996 return NULL;
5997 } else {
5998 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5999 zt_wait_event(p->subs[index].zfd);
6000 tone_zone_play_tone(p->subs[index].zfd, -1);
6001 swap_subs(p, SUB_REAL, SUB_THREEWAY);
6002 unalloc_sub(p, SUB_THREEWAY);
6003 p->owner = p->subs[SUB_REAL].owner;
6004 ast_hangup(chan);
6005 return NULL;
6007 } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
6008 ((exten[0] != '*') || (strlen(exten) > 2))) {
6009 if (option_debug)
6010 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);
6011 break;
6013 if (!timeout)
6014 timeout = gendigittimeout;
6015 if (len && !ast_ignore_pattern(chan->context, exten))
6016 tone_zone_play_tone(p->subs[index].zfd, -1);
6018 break;
6019 case SIG_FXSLS:
6020 case SIG_FXSGS:
6021 case SIG_FXSKS:
6022 #ifdef HAVE_PRI
6023 if (p->pri) {
6024 /* This is a GR-303 trunk actually. Wait for the first ring... */
6025 struct ast_frame *f;
6026 int res;
6027 time_t start;
6029 time(&start);
6030 ast_setstate(chan, AST_STATE_RING);
6031 while (time(NULL) < start + 3) {
6032 res = ast_waitfor(chan, 1000);
6033 if (res) {
6034 f = ast_read(chan);
6035 if (!f) {
6036 ast_log(LOG_WARNING, "Whoa, hangup while waiting for first ring!\n");
6037 ast_hangup(chan);
6038 return NULL;
6039 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_RING)) {
6040 res = 1;
6041 } else
6042 res = 0;
6043 ast_frfree(f);
6044 if (res) {
6045 ast_log(LOG_DEBUG, "Got ring!\n");
6046 res = 0;
6047 break;
6052 #endif
6053 /* check for SMDI messages */
6054 if (p->use_smdi && p->smdi_iface) {
6055 smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, SMDI_MD_WAIT_TIMEOUT);
6057 if (smdi_msg != NULL) {
6058 ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
6060 if (smdi_msg->type == 'B')
6061 pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
6062 else if (smdi_msg->type == 'N')
6063 pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
6065 ast_log(LOG_DEBUG, "Recieved SMDI message on %s\n", chan->name);
6066 } else {
6067 ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
6071 if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
6072 number = smdi_msg->calling_st;
6074 /* If we want caller id, we're in a prering state due to a polarity reversal
6075 * and we're set to use a polarity reversal to trigger the start of caller id,
6076 * grab the caller id and wait for ringing to start... */
6077 } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING && p->cid_start == CID_START_POLARITY)) {
6078 /* If set to use DTMF CID signalling, listen for DTMF */
6079 if (p->cid_signalling == CID_SIG_DTMF) {
6080 int i = 0;
6081 cs = NULL;
6082 ast_log(LOG_DEBUG, "Receiving DTMF cid on "
6083 "channel %s\n", chan->name);
6084 zt_setlinear(p->subs[index].zfd, 0);
6085 res = 2000;
6086 for (;;) {
6087 struct ast_frame *f;
6088 res = ast_waitfor(chan, res);
6089 if (res <= 0) {
6090 ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
6091 "Exiting simple switch\n");
6092 ast_hangup(chan);
6093 return NULL;
6095 f = ast_read(chan);
6096 if (f->frametype == AST_FRAME_DTMF) {
6097 dtmfbuf[i++] = f->subclass;
6098 ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass);
6099 res = 2000;
6101 ast_frfree(f);
6102 if (chan->_state == AST_STATE_RING ||
6103 chan->_state == AST_STATE_RINGING)
6104 break; /* Got ring */
6106 dtmfbuf[i] = '\0';
6107 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6108 /* Got cid and ring. */
6109 ast_log(LOG_DEBUG, "CID got string '%s'\n", dtmfbuf);
6110 callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
6111 ast_log(LOG_DEBUG, "CID is '%s', flags %d\n",
6112 dtmfcid, flags);
6113 /* If first byte is NULL, we have no cid */
6114 if (!ast_strlen_zero(dtmfcid))
6115 number = dtmfcid;
6116 else
6117 number = NULL;
6118 /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
6119 } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
6120 cs = callerid_new(p->cid_signalling);
6121 if (cs) {
6122 samples = 0;
6123 #if 1
6124 bump_gains(p);
6125 #endif
6126 /* Take out of linear mode for Caller*ID processing */
6127 zt_setlinear(p->subs[index].zfd, 0);
6129 /* First we wait and listen for the Caller*ID */
6130 for (;;) {
6131 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6132 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6133 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6134 callerid_free(cs);
6135 ast_hangup(chan);
6136 return NULL;
6138 if (i & ZT_IOMUX_SIGEVENT) {
6139 res = zt_get_event(p->subs[index].zfd);
6140 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6142 if (p->cid_signalling == CID_SIG_V23_JP) {
6143 #ifdef ZT_EVENT_RINGBEGIN
6144 if (res == ZT_EVENT_RINGBEGIN) {
6145 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6146 usleep(1);
6148 #endif
6149 } else {
6150 res = 0;
6151 break;
6153 } else if (i & ZT_IOMUX_READ) {
6154 res = read(p->subs[index].zfd, buf, sizeof(buf));
6155 if (res < 0) {
6156 if (errno != ELAST) {
6157 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6158 callerid_free(cs);
6159 ast_hangup(chan);
6160 return NULL;
6162 break;
6164 samples += res;
6166 if (p->cid_signalling == CID_SIG_V23_JP) {
6167 res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
6168 } else {
6169 res = callerid_feed(cs, buf, res, AST_LAW(p));
6172 if (res < 0) {
6173 ast_log(LOG_WARNING, "CallerID feed failed: %s\n", strerror(errno));
6174 break;
6175 } else if (res)
6176 break;
6177 else if (samples > (8000 * 10))
6178 break;
6181 if (res == 1) {
6182 callerid_get(cs, &name, &number, &flags);
6183 ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
6185 if (res < 0) {
6186 ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
6189 if (p->cid_signalling == CID_SIG_V23_JP) {
6190 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
6191 usleep(1);
6192 res = 4000;
6193 } else {
6195 /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
6196 res = 2000;
6199 for (;;) {
6200 struct ast_frame *f;
6201 res = ast_waitfor(chan, res);
6202 if (res <= 0) {
6203 ast_log(LOG_WARNING, "CID timed out waiting for ring. "
6204 "Exiting simple switch\n");
6205 ast_hangup(chan);
6206 return NULL;
6208 f = ast_read(chan);
6209 ast_frfree(f);
6210 if (chan->_state == AST_STATE_RING ||
6211 chan->_state == AST_STATE_RINGING)
6212 break; /* Got ring */
6215 /* We must have a ring by now, so, if configured, lets try to listen for
6216 * distinctive ringing */
6217 if (p->usedistinctiveringdetection == 1) {
6218 len = 0;
6219 distMatches = 0;
6220 /* Clear the current ring data array so we dont have old data in it. */
6221 for (receivedRingT = 0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
6222 curRingData[receivedRingT] = 0;
6223 receivedRingT = 0;
6224 counter = 0;
6225 counter1 = 0;
6226 /* Check to see if context is what it should be, if not set to be. */
6227 if (strcmp(p->context,p->defcontext) != 0) {
6228 ast_copy_string(p->context, p->defcontext, sizeof(p->context));
6229 ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
6232 for (;;) {
6233 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6234 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6235 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6236 callerid_free(cs);
6237 ast_hangup(chan);
6238 return NULL;
6240 if (i & ZT_IOMUX_SIGEVENT) {
6241 res = zt_get_event(p->subs[index].zfd);
6242 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6243 res = 0;
6244 /* Let us detect distinctive ring */
6246 curRingData[receivedRingT] = p->ringt;
6248 if (p->ringt < p->ringt_base/2)
6249 break;
6250 /* Increment the ringT counter so we can match it against
6251 values in zapata.conf for distinctive ring */
6252 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6253 break;
6254 } else if (i & ZT_IOMUX_READ) {
6255 res = read(p->subs[index].zfd, buf, sizeof(buf));
6256 if (res < 0) {
6257 if (errno != ELAST) {
6258 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6259 callerid_free(cs);
6260 ast_hangup(chan);
6261 return NULL;
6263 break;
6265 if (p->ringt)
6266 p->ringt--;
6267 if (p->ringt == 1) {
6268 res = -1;
6269 break;
6273 if (option_verbose > 2)
6274 /* this only shows up if you have n of the dring patterns filled in */
6275 ast_verbose( VERBOSE_PREFIX_3 "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
6277 for (counter = 0; counter < 3; counter++) {
6278 /* Check to see if the rings we received match any of the ones in zapata.conf for this
6279 channel */
6280 distMatches = 0;
6281 for (counter1 = 0; counter1 < 3; counter1++) {
6282 if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1]+10) && curRingData[counter1] >=
6283 (p->drings.ringnum[counter].ring[counter1]-10)) {
6284 distMatches++;
6287 if (distMatches == 3) {
6288 /* The ring matches, set the context to whatever is for distinctive ring.. */
6289 ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
6290 ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
6291 if (option_verbose > 2)
6292 ast_verbose( VERBOSE_PREFIX_3 "Distinctive Ring matched context %s\n",p->context);
6293 break;
6297 /* Restore linear mode (if appropriate) for Caller*ID processing */
6298 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6299 #if 1
6300 restore_gains(p);
6301 #endif
6302 } else
6303 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
6304 } else {
6305 ast_log(LOG_WARNING, "Channel %s in prering "
6306 "state, but I have nothing to do. "
6307 "Terminating simple switch, should be "
6308 "restarted by the actual ring.\n",
6309 chan->name);
6310 ast_hangup(chan);
6311 return NULL;
6313 } else if (p->use_callerid && p->cid_start == CID_START_RING) {
6314 /* FSK Bell202 callerID */
6315 cs = callerid_new(p->cid_signalling);
6316 if (cs) {
6317 #if 1
6318 bump_gains(p);
6319 #endif
6320 samples = 0;
6321 len = 0;
6322 distMatches = 0;
6323 /* Clear the current ring data array so we dont have old data in it. */
6324 for (receivedRingT = 0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
6325 curRingData[receivedRingT] = 0;
6326 receivedRingT = 0;
6327 counter = 0;
6328 counter1 = 0;
6329 /* Check to see if context is what it should be, if not set to be. */
6330 if (strcmp(p->context,p->defcontext) != 0) {
6331 ast_copy_string(p->context, p->defcontext, sizeof(p->context));
6332 ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
6335 /* Take out of linear mode for Caller*ID processing */
6336 zt_setlinear(p->subs[index].zfd, 0);
6337 for (;;) {
6338 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6339 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6340 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6341 callerid_free(cs);
6342 ast_hangup(chan);
6343 return NULL;
6345 if (i & ZT_IOMUX_SIGEVENT) {
6346 res = zt_get_event(p->subs[index].zfd);
6347 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6348 res = 0;
6349 /* Let us detect callerid when the telco uses distinctive ring */
6351 curRingData[receivedRingT] = p->ringt;
6353 if (p->ringt < p->ringt_base/2)
6354 break;
6355 /* Increment the ringT counter so we can match it against
6356 values in zapata.conf for distinctive ring */
6357 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6358 break;
6359 } else if (i & ZT_IOMUX_READ) {
6360 res = read(p->subs[index].zfd, buf, sizeof(buf));
6361 if (res < 0) {
6362 if (errno != ELAST) {
6363 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6364 callerid_free(cs);
6365 ast_hangup(chan);
6366 return NULL;
6368 break;
6370 if (p->ringt)
6371 p->ringt--;
6372 if (p->ringt == 1) {
6373 res = -1;
6374 break;
6376 samples += res;
6377 res = callerid_feed(cs, buf, res, AST_LAW(p));
6378 if (res < 0) {
6379 ast_log(LOG_WARNING, "CallerID feed failed: %s\n", strerror(errno));
6380 break;
6381 } else if (res)
6382 break;
6383 else if (samples > (8000 * 10))
6384 break;
6387 if (res == 1) {
6388 callerid_get(cs, &name, &number, &flags);
6389 if (option_debug)
6390 ast_log(LOG_DEBUG, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
6392 if (distinctiveringaftercid == 1) {
6393 /* Clear the current ring data array so we dont have old data in it. */
6394 for (receivedRingT = 0; receivedRingT < 3; receivedRingT++) {
6395 curRingData[receivedRingT] = 0;
6397 receivedRingT = 0;
6398 if (option_verbose > 2)
6399 ast_verbose( VERBOSE_PREFIX_3 "Detecting post-CID distinctive ring\n");
6400 for (;;) {
6401 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6402 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6403 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6404 callerid_free(cs);
6405 ast_hangup(chan);
6406 return NULL;
6408 if (i & ZT_IOMUX_SIGEVENT) {
6409 res = zt_get_event(p->subs[index].zfd);
6410 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6411 res = 0;
6412 /* Let us detect callerid when the telco uses distinctive ring */
6414 curRingData[receivedRingT] = p->ringt;
6416 if (p->ringt < p->ringt_base/2)
6417 break;
6418 /* Increment the ringT counter so we can match it against
6419 values in zapata.conf for distinctive ring */
6420 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6421 break;
6422 } else if (i & ZT_IOMUX_READ) {
6423 res = read(p->subs[index].zfd, buf, sizeof(buf));
6424 if (res < 0) {
6425 if (errno != ELAST) {
6426 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6427 callerid_free(cs);
6428 ast_hangup(chan);
6429 return NULL;
6431 break;
6433 if (p->ringt)
6434 p->ringt--;
6435 if (p->ringt == 1) {
6436 res = -1;
6437 break;
6442 if (p->usedistinctiveringdetection == 1) {
6443 if (option_verbose > 2)
6444 /* this only shows up if you have n of the dring patterns filled in */
6445 ast_verbose( VERBOSE_PREFIX_3 "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
6447 for (counter = 0; counter < 3; counter++) {
6448 /* Check to see if the rings we received match any of the ones in zapata.conf for this
6449 channel */
6450 if (option_verbose > 2)
6451 /* this only shows up if you have n of the dring patterns filled in */
6452 ast_verbose( VERBOSE_PREFIX_3 "Checking %d,%d,%d\n",
6453 p->drings.ringnum[counter].ring[0],
6454 p->drings.ringnum[counter].ring[1],
6455 p->drings.ringnum[counter].ring[2]);
6456 distMatches = 0;
6457 for (counter1 = 0; counter1 < 3; counter1++) {
6458 if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1]+10) && curRingData[counter1] >=
6459 (p->drings.ringnum[counter].ring[counter1]-10)) {
6460 distMatches++;
6463 if (distMatches == 3) {
6464 /* The ring matches, set the context to whatever is for distinctive ring.. */
6465 ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
6466 ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
6467 if (option_verbose > 2)
6468 ast_verbose( VERBOSE_PREFIX_3 "Distinctive Ring matched context %s\n",p->context);
6469 break;
6473 /* Restore linear mode (if appropriate) for Caller*ID processing */
6474 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6475 #if 1
6476 restore_gains(p);
6477 #endif
6478 if (res < 0) {
6479 ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
6481 } else
6482 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
6484 else
6485 cs = NULL;
6487 if (number)
6488 ast_shrink_phone_number(number);
6489 ast_set_callerid(chan, number, name, number);
6491 if (smdi_msg)
6492 ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
6494 if (cs)
6495 callerid_free(cs);
6497 ast_setstate(chan, AST_STATE_RING);
6498 chan->rings = 1;
6499 p->ringt = p->ringt_base;
6500 res = ast_pbx_run(chan);
6501 if (res) {
6502 ast_hangup(chan);
6503 ast_log(LOG_WARNING, "PBX exited non-zero\n");
6505 return NULL;
6506 default:
6507 ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", sig2str(p->sig), p->channel);
6508 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
6509 if (res < 0)
6510 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
6512 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
6513 if (res < 0)
6514 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
6515 ast_hangup(chan);
6516 return NULL;
6519 /* destroy a zaptel channel, identified by its number */
6520 static int zap_destroy_channel_bynum(int channel)
6522 struct zt_pvt *tmp = NULL;
6523 struct zt_pvt *prev = NULL;
6525 tmp = iflist;
6526 while (tmp) {
6527 if (tmp->channel == channel) {
6528 destroy_channel(prev, tmp, 1);
6529 return RESULT_SUCCESS;
6531 prev = tmp;
6532 tmp = tmp->next;
6534 return RESULT_FAILURE;
6537 static int handle_init_event(struct zt_pvt *i, int event)
6539 int res;
6540 pthread_t threadid;
6541 pthread_attr_t attr;
6542 struct ast_channel *chan;
6543 pthread_attr_init(&attr);
6544 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6545 /* Handle an event on a given channel for the monitor thread. */
6546 switch (event) {
6547 case ZT_EVENT_NONE:
6548 case ZT_EVENT_BITSCHANGED:
6549 break;
6550 case ZT_EVENT_WINKFLASH:
6551 case ZT_EVENT_RINGOFFHOOK:
6552 if (i->inalarm) break;
6553 if (i->radio) break;
6554 /* Got a ring/answer. What kind of channel are we? */
6555 switch (i->sig) {
6556 case SIG_FXOLS:
6557 case SIG_FXOGS:
6558 case SIG_FXOKS:
6559 res = zt_set_hook(i->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6560 if (res && (errno == EBUSY))
6561 break;
6562 if (i->cidspill) {
6563 /* Cancel VMWI spill */
6564 free(i->cidspill);
6565 i->cidspill = NULL;
6567 if (i->immediate) {
6568 zt_enable_ec(i);
6569 /* The channel is immediately up. Start right away */
6570 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
6571 chan = zt_new(i, AST_STATE_RING, 1, SUB_REAL, 0, 0);
6572 if (!chan) {
6573 ast_log(LOG_WARNING, "Unable to start PBX on channel %d\n", i->channel);
6574 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6575 if (res < 0)
6576 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6578 } else {
6579 /* Check for callerid, digits, etc */
6580 chan = zt_new(i, AST_STATE_RESERVED, 0, SUB_REAL, 0, 0);
6581 if (chan) {
6582 if (has_voicemail(i))
6583 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_STUTTER);
6584 else
6585 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_DIALTONE);
6586 if (res < 0)
6587 ast_log(LOG_WARNING, "Unable to play dialtone on channel %d\n", i->channel);
6588 if (ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6589 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6590 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6591 if (res < 0)
6592 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6593 ast_hangup(chan);
6595 } else
6596 ast_log(LOG_WARNING, "Unable to create channel\n");
6598 break;
6599 case SIG_FXSLS:
6600 case SIG_FXSGS:
6601 case SIG_FXSKS:
6602 i->ringt = i->ringt_base;
6603 /* Fall through */
6604 case SIG_EMWINK:
6605 case SIG_FEATD:
6606 case SIG_FEATDMF:
6607 case SIG_FEATDMF_TA:
6608 case SIG_E911:
6609 case SIG_FGC_CAMA:
6610 case SIG_FGC_CAMAMF:
6611 case SIG_FEATB:
6612 case SIG_EM:
6613 case SIG_EM_E1:
6614 case SIG_SFWINK:
6615 case SIG_SF_FEATD:
6616 case SIG_SF_FEATDMF:
6617 case SIG_SF_FEATB:
6618 case SIG_SF:
6619 /* Check for callerid, digits, etc */
6620 chan = zt_new(i, AST_STATE_RING, 0, SUB_REAL, 0, 0);
6621 if (chan && ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6622 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6623 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6624 if (res < 0)
6625 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6626 ast_hangup(chan);
6627 } else if (!chan) {
6628 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
6630 break;
6631 default:
6632 ast_log(LOG_WARNING, "Don't know how to handle ring/answer with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
6633 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6634 if (res < 0)
6635 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6636 return -1;
6638 break;
6639 case ZT_EVENT_NOALARM:
6640 i->inalarm = 0;
6641 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", i->channel);
6642 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
6643 "Channel: %d\r\n", i->channel);
6644 break;
6645 case ZT_EVENT_ALARM:
6646 i->inalarm = 1;
6647 res = get_alarms(i);
6648 ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", i->channel, alarm2str(res));
6649 manager_event(EVENT_FLAG_SYSTEM, "Alarm",
6650 "Alarm: %s\r\n"
6651 "Channel: %d\r\n",
6652 alarm2str(res), i->channel);
6653 /* fall thru intentionally */
6654 case ZT_EVENT_ONHOOK:
6655 if (i->radio)
6656 break;
6657 /* Back on hook. Hang up. */
6658 switch (i->sig) {
6659 case SIG_FXOLS:
6660 case SIG_FXOGS:
6661 case SIG_FEATD:
6662 case SIG_FEATDMF:
6663 case SIG_FEATDMF_TA:
6664 case SIG_E911:
6665 case SIG_FGC_CAMA:
6666 case SIG_FGC_CAMAMF:
6667 case SIG_FEATB:
6668 case SIG_EM:
6669 case SIG_EM_E1:
6670 case SIG_EMWINK:
6671 case SIG_SF_FEATD:
6672 case SIG_SF_FEATDMF:
6673 case SIG_SF_FEATB:
6674 case SIG_SF:
6675 case SIG_SFWINK:
6676 case SIG_FXSLS:
6677 case SIG_FXSGS:
6678 case SIG_FXSKS:
6679 case SIG_GR303FXSKS:
6680 zt_disable_ec(i);
6681 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6682 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_ONHOOK);
6683 break;
6684 case SIG_GR303FXOKS:
6685 case SIG_FXOKS:
6686 zt_disable_ec(i);
6687 /* Diddle the battery for the zhone */
6688 #ifdef ZHONE_HACK
6689 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6690 usleep(1);
6691 #endif
6692 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6693 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_ONHOOK);
6694 break;
6695 case SIG_PRI:
6696 zt_disable_ec(i);
6697 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6698 break;
6699 default:
6700 ast_log(LOG_WARNING, "Don't know how to handle on hook with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
6701 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6702 return -1;
6704 break;
6705 case ZT_EVENT_POLARITY:
6706 switch (i->sig) {
6707 case SIG_FXSLS:
6708 case SIG_FXSKS:
6709 case SIG_FXSGS:
6710 if (i->cid_start == CID_START_POLARITY) {
6711 i->polarity = POLARITY_REV;
6712 ast_verbose(VERBOSE_PREFIX_2 "Starting post polarity "
6713 "CID detection on channel %d\n",
6714 i->channel);
6715 chan = zt_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, 0);
6716 if (chan && ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6717 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6720 break;
6721 default:
6722 ast_log(LOG_WARNING, "handle_init_event detected "
6723 "polarity reversal on non-FXO (SIG_FXS) "
6724 "interface %d\n", i->channel);
6726 break;
6727 case ZT_EVENT_REMOVED: /* destroy channel */
6728 ast_log(LOG_NOTICE,
6729 "Got ZT_EVENT_REMOVED. Destroying channel %d\n",
6730 i->channel);
6731 zap_destroy_channel_bynum(i->channel);
6732 break;
6734 pthread_attr_destroy(&attr);
6735 return 0;
6738 static void *do_monitor(void *data)
6740 int count, res, res2, spoint, pollres=0;
6741 struct zt_pvt *i;
6742 struct zt_pvt *last = NULL;
6743 time_t thispass = 0, lastpass = 0;
6744 int found;
6745 char buf[1024];
6746 struct pollfd *pfds=NULL;
6747 int lastalloc = -1;
6748 /* This thread monitors all the frame relay interfaces which are not yet in use
6749 (and thus do not have a separate thread) indefinitely */
6750 /* From here on out, we die whenever asked */
6751 #if 0
6752 if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
6753 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
6754 return NULL;
6756 ast_log(LOG_DEBUG, "Monitor starting...\n");
6757 #endif
6758 for (;;) {
6759 /* Lock the interface list */
6760 ast_mutex_lock(&iflock);
6761 if (!pfds || (lastalloc != ifcount)) {
6762 if (pfds)
6763 free(pfds);
6764 if (ifcount) {
6765 if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
6766 ast_mutex_unlock(&iflock);
6767 return NULL;
6770 lastalloc = ifcount;
6772 /* Build the stuff we're going to poll on, that is the socket of every
6773 zt_pvt that does not have an associated owner channel */
6774 count = 0;
6775 i = iflist;
6776 while (i) {
6777 if ((i->subs[SUB_REAL].zfd > -1) && i->sig && (!i->radio)) {
6778 if (!i->owner && !i->subs[SUB_REAL].owner) {
6779 /* This needs to be watched, as it lacks an owner */
6780 pfds[count].fd = i->subs[SUB_REAL].zfd;
6781 pfds[count].events = POLLPRI;
6782 pfds[count].revents = 0;
6783 /* Message waiting or r2 channels also get watched for reading */
6784 if (i->cidspill)
6785 pfds[count].events |= POLLIN;
6786 count++;
6789 i = i->next;
6791 /* Okay, now that we know what to do, release the interface lock */
6792 ast_mutex_unlock(&iflock);
6794 pthread_testcancel();
6795 /* Wait at least a second for something to happen */
6796 res = poll(pfds, count, 1000);
6797 pthread_testcancel();
6798 /* Okay, poll has finished. Let's see what happened. */
6799 if (res < 0) {
6800 if ((errno != EAGAIN) && (errno != EINTR))
6801 ast_log(LOG_WARNING, "poll return %d: %s\n", res, strerror(errno));
6802 continue;
6804 /* Alright, lock the interface list again, and let's look and see what has
6805 happened */
6806 ast_mutex_lock(&iflock);
6807 found = 0;
6808 spoint = 0;
6809 lastpass = thispass;
6810 thispass = time(NULL);
6811 i = iflist;
6812 while (i) {
6813 if (thispass != lastpass) {
6814 if (!found && ((i == last) || ((i == iflist) && !last))) {
6815 last = i;
6816 if (last) {
6817 if (!last->cidspill && !last->owner && !ast_strlen_zero(last->mailbox) && (thispass - last->onhooktime > 3) &&
6818 (last->sig & __ZT_SIG_FXO)) {
6819 res = ast_app_has_voicemail(last->mailbox, NULL);
6820 if (last->msgstate != res) {
6821 int x;
6822 ast_log(LOG_DEBUG, "Message status for %s changed from %d to %d on %d\n", last->mailbox, last->msgstate, res, last->channel);
6823 x = ZT_FLUSH_BOTH;
6824 res2 = ioctl(last->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
6825 if (res2)
6826 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", last->channel);
6827 if ((last->cidspill = ast_calloc(1, MAX_CALLERID_SIZE))) {
6828 /* Turn on on hook transfer for 4 seconds */
6829 x = 4000;
6830 ioctl(last->subs[SUB_REAL].zfd, ZT_ONHOOKTRANSFER, &x);
6831 last->cidlen = vmwi_generate(last->cidspill, res, 1, AST_LAW(last));
6832 last->cidpos = 0;
6833 last->msgstate = res;
6834 last->onhooktime = thispass;
6836 found ++;
6839 last = last->next;
6843 if ((i->subs[SUB_REAL].zfd > -1) && i->sig) {
6844 if (i->radio && !i->owner)
6846 res = zt_get_event(i->subs[SUB_REAL].zfd);
6847 if (res)
6849 if (option_debug)
6850 ast_log(LOG_DEBUG, "Monitor doohicky got event %s on radio channel %d\n", event2str(res), i->channel);
6851 /* Don't hold iflock while handling init events */
6852 ast_mutex_unlock(&iflock);
6853 handle_init_event(i, res);
6854 ast_mutex_lock(&iflock);
6856 i = i->next;
6857 continue;
6859 pollres = ast_fdisset(pfds, i->subs[SUB_REAL].zfd, count, &spoint);
6860 if (pollres & POLLIN) {
6861 if (i->owner || i->subs[SUB_REAL].owner) {
6862 #ifdef HAVE_PRI
6863 if (!i->pri)
6864 #endif
6865 ast_log(LOG_WARNING, "Whoa.... I'm owned but found (%d) in read...\n", i->subs[SUB_REAL].zfd);
6866 i = i->next;
6867 continue;
6869 if (!i->cidspill) {
6870 ast_log(LOG_WARNING, "Whoa.... I'm reading but have no cidspill (%d)...\n", i->subs[SUB_REAL].zfd);
6871 i = i->next;
6872 continue;
6874 res = read(i->subs[SUB_REAL].zfd, buf, sizeof(buf));
6875 if (res > 0) {
6876 /* We read some number of bytes. Write an equal amount of data */
6877 if (res > i->cidlen - i->cidpos)
6878 res = i->cidlen - i->cidpos;
6879 res2 = write(i->subs[SUB_REAL].zfd, i->cidspill + i->cidpos, res);
6880 if (res2 > 0) {
6881 i->cidpos += res2;
6882 if (i->cidpos >= i->cidlen) {
6883 free(i->cidspill);
6884 i->cidspill = 0;
6885 i->cidpos = 0;
6886 i->cidlen = 0;
6888 } else {
6889 ast_log(LOG_WARNING, "Write failed: %s\n", strerror(errno));
6890 i->msgstate = -1;
6892 } else {
6893 ast_log(LOG_WARNING, "Read failed with %d: %s\n", res, strerror(errno));
6895 if (option_debug)
6896 ast_log(LOG_DEBUG, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
6897 /* Don't hold iflock while handling init events -- race with chlock */
6898 ast_mutex_unlock(&iflock);
6899 handle_init_event(i, res);
6900 ast_mutex_lock(&iflock);
6902 if (pollres & POLLPRI) {
6903 if (i->owner || i->subs[SUB_REAL].owner) {
6904 #ifdef HAVE_PRI
6905 if (!i->pri)
6906 #endif
6907 ast_log(LOG_WARNING, "Whoa.... I'm owned but found (%d)...\n", i->subs[SUB_REAL].zfd);
6908 i = i->next;
6909 continue;
6911 res = zt_get_event(i->subs[SUB_REAL].zfd);
6912 if (option_debug)
6913 ast_log(LOG_DEBUG, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
6914 /* Don't hold iflock while handling init events */
6915 ast_mutex_unlock(&iflock);
6916 handle_init_event(i, res);
6917 ast_mutex_lock(&iflock);
6920 i=i->next;
6922 ast_mutex_unlock(&iflock);
6924 /* Never reached */
6925 return NULL;
6929 static int restart_monitor(void)
6931 pthread_attr_t attr;
6932 pthread_attr_init(&attr);
6933 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6934 /* If we're supposed to be stopped -- stay stopped */
6935 if (monitor_thread == AST_PTHREADT_STOP)
6936 return 0;
6937 ast_mutex_lock(&monlock);
6938 if (monitor_thread == pthread_self()) {
6939 ast_mutex_unlock(&monlock);
6940 ast_log(LOG_WARNING, "Cannot kill myself\n");
6941 return -1;
6943 if (monitor_thread != AST_PTHREADT_NULL) {
6944 /* Wake up the thread */
6945 pthread_kill(monitor_thread, SIGURG);
6946 } else {
6947 /* Start a new monitor */
6948 if (ast_pthread_create_background(&monitor_thread, &attr, do_monitor, NULL) < 0) {
6949 ast_mutex_unlock(&monlock);
6950 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
6951 pthread_attr_destroy(&attr);
6952 return -1;
6955 ast_mutex_unlock(&monlock);
6956 pthread_attr_destroy(&attr);
6957 return 0;
6960 #ifdef HAVE_PRI
6961 static int pri_resolve_span(int *span, int channel, int offset, struct zt_spaninfo *si)
6963 int x;
6964 int trunkgroup;
6965 /* Get appropriate trunk group if there is one */
6966 trunkgroup = pris[*span].mastertrunkgroup;
6967 if (trunkgroup) {
6968 /* Select a specific trunk group */
6969 for (x = 0; x < NUM_SPANS; x++) {
6970 if (pris[x].trunkgroup == trunkgroup) {
6971 *span = x;
6972 return 0;
6975 ast_log(LOG_WARNING, "Channel %d on span %d configured to use nonexistent trunk group %d\n", channel, *span, trunkgroup);
6976 *span = -1;
6977 } else {
6978 if (pris[*span].trunkgroup) {
6979 ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is trunk group %d (please use spanmap)\n", *span, pris[*span].trunkgroup);
6980 *span = -1;
6981 } else if (pris[*span].mastertrunkgroup) {
6982 ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is already part of trunk group %d\n", *span, pris[*span].mastertrunkgroup);
6983 *span = -1;
6984 } else {
6985 if (si->totalchans == 31) { /* if it's an E1 */
6986 pris[*span].dchannels[0] = 16 + offset;
6987 } else {
6988 pris[*span].dchannels[0] = 24 + offset;
6990 pris[*span].dchanavail[0] |= DCHAN_PROVISIONED;
6991 pris[*span].offset = offset;
6992 pris[*span].span = *span + 1;
6995 return 0;
6998 static int pri_create_trunkgroup(int trunkgroup, int *channels)
7000 struct zt_spaninfo si;
7001 ZT_PARAMS p;
7002 int fd;
7003 int span;
7004 int ospan=0;
7005 int x,y;
7006 for (x = 0; x < NUM_SPANS; x++) {
7007 if (pris[x].trunkgroup == trunkgroup) {
7008 ast_log(LOG_WARNING, "Trunk group %d already exists on span %d, Primary d-channel %d\n", trunkgroup, x + 1, pris[x].dchannels[0]);
7009 return -1;
7012 for (y = 0; y < NUM_DCHANS; y++) {
7013 if (!channels[y])
7014 break;
7015 memset(&si, 0, sizeof(si));
7016 memset(&p, 0, sizeof(p));
7017 fd = open("/dev/zap/channel", O_RDWR);
7018 if (fd < 0) {
7019 ast_log(LOG_WARNING, "Failed to open channel: %s\n", strerror(errno));
7020 return -1;
7022 x = channels[y];
7023 if (ioctl(fd, ZT_SPECIFY, &x)) {
7024 ast_log(LOG_WARNING, "Failed to specify channel %d: %s\n", channels[y], strerror(errno));
7025 zt_close(fd);
7026 return -1;
7028 if (ioctl(fd, ZT_GET_PARAMS, &p)) {
7029 ast_log(LOG_WARNING, "Failed to get channel parameters for channel %d: %s\n", channels[y], strerror(errno));
7030 return -1;
7032 if (ioctl(fd, ZT_SPANSTAT, &si)) {
7033 ast_log(LOG_WARNING, "Failed go get span information on channel %d (span %d)\n", channels[y], p.spanno);
7034 zt_close(fd);
7035 return -1;
7037 span = p.spanno - 1;
7038 if (pris[span].trunkgroup) {
7039 ast_log(LOG_WARNING, "Span %d is already provisioned for trunk group %d\n", span + 1, pris[span].trunkgroup);
7040 zt_close(fd);
7041 return -1;
7043 if (pris[span].pvts[0]) {
7044 ast_log(LOG_WARNING, "Span %d is already provisioned with channels (implicit PRI maybe?)\n", span + 1);
7045 zt_close(fd);
7046 return -1;
7048 if (!y) {
7049 pris[span].trunkgroup = trunkgroup;
7050 pris[span].offset = channels[y] - p.chanpos;
7051 ospan = span;
7053 pris[ospan].dchannels[y] = channels[y];
7054 pris[ospan].dchanavail[y] |= DCHAN_PROVISIONED;
7055 pris[span].span = span + 1;
7056 zt_close(fd);
7058 return 0;
7061 static int pri_create_spanmap(int span, int trunkgroup, int logicalspan)
7063 if (pris[span].mastertrunkgroup) {
7064 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);
7065 return -1;
7067 pris[span].mastertrunkgroup = trunkgroup;
7068 pris[span].prilogicalspan = logicalspan;
7069 return 0;
7072 #endif
7074 static struct zt_pvt *mkintf(int channel, struct zt_chan_conf conf, struct zt_pri *pri, int reloading)
7076 /* Make a zt_pvt structure for this interface (or CRV if "pri" is specified) */
7077 struct zt_pvt *tmp = NULL, *tmp2, *prev = NULL;
7078 char fn[80];
7079 #if 1
7080 struct zt_bufferinfo bi;
7081 #endif
7082 struct zt_spaninfo si;
7083 int res;
7084 int span=0;
7085 int here = 0;
7086 int x;
7087 struct zt_pvt **wlist;
7088 struct zt_pvt **wend;
7089 ZT_PARAMS p;
7091 wlist = &iflist;
7092 wend = &ifend;
7094 #ifdef HAVE_PRI
7095 if (pri) {
7096 wlist = &pri->crvs;
7097 wend = &pri->crvend;
7099 #endif
7101 tmp2 = *wlist;
7102 prev = NULL;
7104 while (tmp2) {
7105 if (!tmp2->destroy) {
7106 if (tmp2->channel == channel) {
7107 tmp = tmp2;
7108 here = 1;
7109 break;
7111 if (tmp2->channel > channel) {
7112 break;
7115 prev = tmp2;
7116 tmp2 = tmp2->next;
7119 if (!here && !reloading) {
7120 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
7121 destroy_zt_pvt(&tmp);
7122 return NULL;
7124 ast_mutex_init(&tmp->lock);
7125 ifcount++;
7126 for (x = 0; x < 3; x++)
7127 tmp->subs[x].zfd = -1;
7128 tmp->channel = channel;
7131 if (tmp) {
7132 if (!here) {
7133 if ((channel != CHAN_PSEUDO) && !pri) {
7134 snprintf(fn, sizeof(fn), "%d", channel);
7135 /* Open non-blocking */
7136 if (!here)
7137 tmp->subs[SUB_REAL].zfd = zt_open(fn);
7138 /* Allocate a zapata structure */
7139 if (tmp->subs[SUB_REAL].zfd < 0) {
7140 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);
7141 destroy_zt_pvt(&tmp);
7142 return NULL;
7144 memset(&p, 0, sizeof(p));
7145 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &p);
7146 if (res < 0) {
7147 ast_log(LOG_ERROR, "Unable to get parameters\n");
7148 destroy_zt_pvt(&tmp);
7149 return NULL;
7151 if (p.sigtype != (conf.chan.sig & 0x3ffff)) {
7152 ast_log(LOG_ERROR, "Signalling requested on channel %d is %s but line is in %s signalling\n", channel, sig2str(conf.chan.sig), sig2str(p.sigtype));
7153 destroy_zt_pvt(&tmp);
7154 return NULL;
7156 tmp->law = p.curlaw;
7157 tmp->span = p.spanno;
7158 span = p.spanno - 1;
7159 } else {
7160 if (channel == CHAN_PSEUDO)
7161 conf.chan.sig = 0;
7162 else if ((conf.chan.sig != SIG_FXOKS) && (conf.chan.sig != SIG_FXSKS)) {
7163 ast_log(LOG_ERROR, "CRV's must use FXO/FXS Kewl Start (fxo_ks/fxs_ks) signalling only.\n");
7164 return NULL;
7167 #ifdef HAVE_PRI
7168 if ((conf.chan.sig == SIG_PRI) || (conf.chan.sig == SIG_GR303FXOKS) || (conf.chan.sig == SIG_GR303FXSKS)) {
7169 int offset;
7170 int myswitchtype;
7171 int matchesdchan;
7172 int x,y;
7173 offset = 0;
7174 if ((conf.chan.sig == SIG_PRI) && ioctl(tmp->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &offset)) {
7175 ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
7176 destroy_zt_pvt(&tmp);
7177 return NULL;
7179 if (span >= NUM_SPANS) {
7180 ast_log(LOG_ERROR, "Channel %d does not lie on a span I know of (%d)\n", channel, span);
7181 destroy_zt_pvt(&tmp);
7182 return NULL;
7183 } else {
7184 si.spanno = 0;
7185 if (ioctl(tmp->subs[SUB_REAL].zfd,ZT_SPANSTAT,&si) == -1) {
7186 ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
7187 destroy_zt_pvt(&tmp);
7188 return NULL;
7190 /* Store the logical span first based upon the real span */
7191 tmp->logicalspan = pris[span].prilogicalspan;
7192 pri_resolve_span(&span, channel, (channel - p.chanpos), &si);
7193 if (span < 0) {
7194 ast_log(LOG_WARNING, "Channel %d: Unable to find locate channel/trunk group!\n", channel);
7195 destroy_zt_pvt(&tmp);
7196 return NULL;
7198 if (conf.chan.sig == SIG_PRI)
7199 myswitchtype = conf.pri.switchtype;
7200 else
7201 myswitchtype = PRI_SWITCH_GR303_TMC;
7202 /* Make sure this isn't a d-channel */
7203 matchesdchan=0;
7204 for (x = 0; x < NUM_SPANS; x++) {
7205 for (y = 0; y < NUM_DCHANS; y++) {
7206 if (pris[x].dchannels[y] == tmp->channel) {
7207 matchesdchan = 1;
7208 break;
7212 offset = p.chanpos;
7213 if (!matchesdchan) {
7214 if (pris[span].nodetype && (pris[span].nodetype != conf.pri.nodetype)) {
7215 ast_log(LOG_ERROR, "Span %d is already a %s node\n", span + 1, pri_node2str(pris[span].nodetype));
7216 destroy_zt_pvt(&tmp);
7217 return NULL;
7219 if (pris[span].switchtype && (pris[span].switchtype != myswitchtype)) {
7220 ast_log(LOG_ERROR, "Span %d is already a %s switch\n", span + 1, pri_switch2str(pris[span].switchtype));
7221 destroy_zt_pvt(&tmp);
7222 return NULL;
7224 if ((pris[span].dialplan) && (pris[span].dialplan != conf.pri.dialplan)) {
7225 ast_log(LOG_ERROR, "Span %d is already a %s dialing plan\n", span + 1, dialplan2str(pris[span].dialplan));
7226 destroy_zt_pvt(&tmp);
7227 return NULL;
7229 if (!ast_strlen_zero(pris[span].idledial) && strcmp(pris[span].idledial, conf.pri.idledial)) {
7230 ast_log(LOG_ERROR, "Span %d already has idledial '%s'.\n", span + 1, conf.pri.idledial);
7231 destroy_zt_pvt(&tmp);
7232 return NULL;
7234 if (!ast_strlen_zero(pris[span].idleext) && strcmp(pris[span].idleext, conf.pri.idleext)) {
7235 ast_log(LOG_ERROR, "Span %d already has idleext '%s'.\n", span + 1, conf.pri.idleext);
7236 destroy_zt_pvt(&tmp);
7237 return NULL;
7239 if (pris[span].minunused && (pris[span].minunused != conf.pri.minunused)) {
7240 ast_log(LOG_ERROR, "Span %d already has minunused of %d.\n", span + 1, conf.pri.minunused);
7241 destroy_zt_pvt(&tmp);
7242 return NULL;
7244 if (pris[span].minidle && (pris[span].minidle != conf.pri.minidle)) {
7245 ast_log(LOG_ERROR, "Span %d already has minidle of %d.\n", span + 1, conf.pri.minidle);
7246 destroy_zt_pvt(&tmp);
7247 return NULL;
7249 if (pris[span].numchans >= MAX_CHANNELS) {
7250 ast_log(LOG_ERROR, "Unable to add channel %d: Too many channels in trunk group %d!\n", channel,
7251 pris[span].trunkgroup);
7252 destroy_zt_pvt(&tmp);
7253 return NULL;
7255 pris[span].nodetype = conf.pri.nodetype;
7256 pris[span].switchtype = myswitchtype;
7257 pris[span].nsf = conf.pri.nsf;
7258 pris[span].dialplan = conf.pri.dialplan;
7259 pris[span].localdialplan = conf.pri.localdialplan;
7260 pris[span].pvts[pris[span].numchans++] = tmp;
7261 pris[span].minunused = conf.pri.minunused;
7262 pris[span].minidle = conf.pri.minidle;
7263 pris[span].overlapdial = conf.pri.overlapdial;
7264 pris[span].facilityenable = conf.pri.facilityenable;
7265 ast_copy_string(pris[span].idledial, conf.pri.idledial, sizeof(pris[span].idledial));
7266 ast_copy_string(pris[span].idleext, conf.pri.idleext, sizeof(pris[span].idleext));
7267 ast_copy_string(pris[span].internationalprefix, conf.pri.internationalprefix, sizeof(pris[span].internationalprefix));
7268 ast_copy_string(pris[span].nationalprefix, conf.pri.nationalprefix, sizeof(pris[span].nationalprefix));
7269 ast_copy_string(pris[span].localprefix, conf.pri.localprefix, sizeof(pris[span].localprefix));
7270 ast_copy_string(pris[span].privateprefix, conf.pri.privateprefix, sizeof(pris[span].privateprefix));
7271 ast_copy_string(pris[span].unknownprefix, conf.pri.unknownprefix, sizeof(pris[span].unknownprefix));
7272 pris[span].resetinterval = conf.pri.resetinterval;
7274 tmp->pri = &pris[span];
7275 tmp->prioffset = offset;
7276 tmp->call = NULL;
7277 } else {
7278 ast_log(LOG_ERROR, "Channel %d is reserved for D-channel.\n", offset);
7279 destroy_zt_pvt(&tmp);
7280 return NULL;
7283 } else {
7284 tmp->prioffset = 0;
7286 #endif
7287 } else {
7288 conf.chan.sig = tmp->sig;
7289 conf.chan.radio = tmp->radio;
7290 memset(&p, 0, sizeof(p));
7291 if (tmp->subs[SUB_REAL].zfd > -1)
7292 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &p);
7294 /* Adjust starttime on loopstart and kewlstart trunks to reasonable values */
7295 if ((conf.chan.sig == SIG_FXSKS) || (conf.chan.sig == SIG_FXSLS) ||
7296 (conf.chan.sig == SIG_EM) || (conf.chan.sig == SIG_EM_E1) || (conf.chan.sig == SIG_EMWINK) ||
7297 (conf.chan.sig == SIG_FEATD) || (conf.chan.sig == SIG_FEATDMF) || (conf.chan.sig == SIG_FEATDMF_TA) ||
7298 (conf.chan.sig == SIG_FEATB) || (conf.chan.sig == SIG_E911) ||
7299 (conf.chan.sig == SIG_SF) || (conf.chan.sig == SIG_SFWINK) || (conf.chan.sig == SIG_FGC_CAMA) || (conf.chan.sig == SIG_FGC_CAMAMF) ||
7300 (conf.chan.sig == SIG_SF_FEATD) || (conf.chan.sig == SIG_SF_FEATDMF) ||
7301 (conf.chan.sig == SIG_SF_FEATB)) {
7302 p.starttime = 250;
7304 if (conf.chan.radio) {
7305 /* XXX Waiting to hear back from Jim if these should be adjustable XXX */
7306 p.channo = channel;
7307 p.rxwinktime = 1;
7308 p.rxflashtime = 1;
7309 p.starttime = 1;
7310 p.debouncetime = 5;
7312 if (!conf.chan.radio) {
7313 p.channo = channel;
7314 /* Override timing settings based on config file */
7315 if (conf.timing.prewinktime >= 0)
7316 p.prewinktime = conf.timing.prewinktime;
7317 if (conf.timing.preflashtime >= 0)
7318 p.preflashtime = conf.timing.preflashtime;
7319 if (conf.timing.winktime >= 0)
7320 p.winktime = conf.timing.winktime;
7321 if (conf.timing.flashtime >= 0)
7322 p.flashtime = conf.timing.flashtime;
7323 if (conf.timing.starttime >= 0)
7324 p.starttime = conf.timing.starttime;
7325 if (conf.timing.rxwinktime >= 0)
7326 p.rxwinktime = conf.timing.rxwinktime;
7327 if (conf.timing.rxflashtime >= 0)
7328 p.rxflashtime = conf.timing.rxflashtime;
7329 if (conf.timing.debouncetime >= 0)
7330 p.debouncetime = conf.timing.debouncetime;
7333 /* dont set parms on a pseudo-channel (or CRV) */
7334 if (tmp->subs[SUB_REAL].zfd >= 0)
7336 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_SET_PARAMS, &p);
7337 if (res < 0) {
7338 ast_log(LOG_ERROR, "Unable to set parameters\n");
7339 destroy_zt_pvt(&tmp);
7340 return NULL;
7343 #if 1
7344 if (!here && (tmp->subs[SUB_REAL].zfd > -1)) {
7345 memset(&bi, 0, sizeof(bi));
7346 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_BUFINFO, &bi);
7347 if (!res) {
7348 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
7349 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
7350 bi.numbufs = numbufs;
7351 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_SET_BUFINFO, &bi);
7352 if (res < 0) {
7353 ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", channel);
7355 } else
7356 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", channel);
7358 #endif
7359 tmp->immediate = conf.chan.immediate;
7360 tmp->transfertobusy = conf.chan.transfertobusy;
7361 tmp->sig = conf.chan.sig;
7362 tmp->outsigmod = conf.chan.outsigmod;
7363 tmp->radio = conf.chan.radio;
7364 tmp->ringt_base = ringt_base;
7365 tmp->firstradio = 0;
7366 if ((conf.chan.sig == SIG_FXOKS) || (conf.chan.sig == SIG_FXOLS) || (conf.chan.sig == SIG_FXOGS))
7367 tmp->permcallwaiting = conf.chan.callwaiting;
7368 else
7369 tmp->permcallwaiting = 0;
7370 /* Flag to destroy the channel must be cleared on new mkif. Part of changes for reload to work */
7371 tmp->destroy = 0;
7372 tmp->drings = drings;
7373 tmp->usedistinctiveringdetection = usedistinctiveringdetection;
7374 tmp->callwaitingcallerid = conf.chan.callwaitingcallerid;
7375 tmp->threewaycalling = conf.chan.threewaycalling;
7376 tmp->adsi = conf.chan.adsi;
7377 tmp->use_smdi = conf.chan.use_smdi;
7378 tmp->permhidecallerid = conf.chan.hidecallerid;
7379 tmp->callreturn = conf.chan.callreturn;
7380 tmp->echocancel = conf.chan.echocancel;
7381 tmp->echotraining = conf.chan.echotraining;
7382 tmp->pulse = conf.chan.pulse;
7383 tmp->echocanbridged = conf.chan.echocanbridged;
7384 tmp->busydetect = conf.chan.busydetect;
7385 tmp->busycount = conf.chan.busycount;
7386 tmp->busy_tonelength = conf.chan.busy_tonelength;
7387 tmp->busy_quietlength = conf.chan.busy_quietlength;
7388 tmp->callprogress = conf.chan.callprogress;
7389 tmp->cancallforward = conf.chan.cancallforward;
7390 tmp->dtmfrelax = conf.chan.dtmfrelax;
7391 tmp->callwaiting = tmp->permcallwaiting;
7392 tmp->hidecallerid = tmp->permhidecallerid;
7393 tmp->channel = channel;
7394 tmp->stripmsd = conf.chan.stripmsd;
7395 tmp->use_callerid = conf.chan.use_callerid;
7396 tmp->cid_signalling = conf.chan.cid_signalling;
7397 tmp->cid_start = conf.chan.cid_start;
7398 tmp->zaptrcallerid = conf.chan.zaptrcallerid;
7399 tmp->restrictcid = conf.chan.restrictcid;
7400 tmp->use_callingpres = conf.chan.use_callingpres;
7401 tmp->priindication_oob = conf.chan.priindication_oob;
7402 tmp->priexclusive = conf.chan.priexclusive;
7403 if (tmp->usedistinctiveringdetection) {
7404 if (!tmp->use_callerid) {
7405 ast_log(LOG_NOTICE, "Distinctive Ring detect requires 'usecallerid' be on\n");
7406 tmp->use_callerid = 1;
7410 if (tmp->cid_signalling == CID_SIG_SMDI) {
7411 if (!tmp->use_smdi) {
7412 ast_log(LOG_WARNING, "SMDI callerid requires SMDI to be enabled, enabling...\n");
7413 tmp->use_smdi = 1;
7416 if (tmp->use_smdi) {
7417 tmp->smdi_iface = ast_smdi_interface_find(conf.smdi_port);
7418 if (!(tmp->smdi_iface)) {
7419 ast_log(LOG_ERROR, "Invalid SMDI port specfied, disabling SMDI support\n");
7420 tmp->use_smdi = 0;
7424 ast_copy_string(tmp->accountcode, conf.chan.accountcode, sizeof(tmp->accountcode));
7425 tmp->amaflags = conf.chan.amaflags;
7426 if (!here) {
7427 tmp->confno = -1;
7428 tmp->propconfno = -1;
7430 tmp->canpark = conf.chan.canpark;
7431 tmp->transfer = conf.chan.transfer;
7432 ast_copy_string(tmp->defcontext,conf.chan.context,sizeof(tmp->defcontext));
7433 ast_copy_string(tmp->language, language, sizeof(tmp->language));
7434 ast_copy_string(tmp->mohinterpret, conf.chan.mohinterpret, sizeof(tmp->mohinterpret));
7435 ast_copy_string(tmp->mohsuggest, conf.chan.mohsuggest, sizeof(tmp->mohsuggest));
7436 ast_copy_string(tmp->context, conf.chan.context, sizeof(tmp->context));
7437 ast_copy_string(tmp->cid_num, conf.chan.cid_num, sizeof(tmp->cid_num));
7438 tmp->cid_ton = 0;
7439 ast_copy_string(tmp->cid_name, conf.chan.cid_name, sizeof(tmp->cid_name));
7440 ast_copy_string(tmp->mailbox, conf.chan.mailbox, sizeof(tmp->mailbox));
7441 tmp->msgstate = -1;
7442 tmp->group = conf.chan.group;
7443 tmp->callgroup = conf.chan.callgroup;
7444 tmp->pickupgroup= conf.chan.pickupgroup;
7445 tmp->rxgain = conf.chan.rxgain;
7446 tmp->txgain = conf.chan.txgain;
7447 tmp->tonezone = conf.chan.tonezone;
7448 tmp->onhooktime = time(NULL);
7449 if (tmp->subs[SUB_REAL].zfd > -1) {
7450 set_actual_gain(tmp->subs[SUB_REAL].zfd, 0, tmp->rxgain, tmp->txgain, tmp->law);
7451 if (tmp->dsp)
7452 ast_dsp_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
7453 update_conf(tmp);
7454 if (!here) {
7455 if (conf.chan.sig != SIG_PRI)
7456 /* Hang it up to be sure it's good */
7457 zt_set_hook(tmp->subs[SUB_REAL].zfd, ZT_ONHOOK);
7459 ioctl(tmp->subs[SUB_REAL].zfd,ZT_SETTONEZONE,&tmp->tonezone);
7460 #ifdef HAVE_PRI
7461 /* the dchannel is down so put the channel in alarm */
7462 if (tmp->pri && !pri_is_up(tmp->pri))
7463 tmp->inalarm = 1;
7464 else
7465 tmp->inalarm = 0;
7466 #endif
7467 memset(&si, 0, sizeof(si));
7468 if (ioctl(tmp->subs[SUB_REAL].zfd,ZT_SPANSTAT,&si) == -1) {
7469 ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
7470 destroy_zt_pvt(&tmp);
7471 return NULL;
7473 if (si.alarms) tmp->inalarm = 1;
7476 tmp->polarityonanswerdelay = conf.chan.polarityonanswerdelay;
7477 tmp->answeronpolarityswitch = conf.chan.answeronpolarityswitch;
7478 tmp->hanguponpolarityswitch = conf.chan.hanguponpolarityswitch;
7479 tmp->sendcalleridafter = conf.chan.sendcalleridafter;
7482 if (tmp && !here) {
7483 /* nothing on the iflist */
7484 if (!*wlist) {
7485 *wlist = tmp;
7486 tmp->prev = NULL;
7487 tmp->next = NULL;
7488 *wend = tmp;
7489 } else {
7490 /* at least one member on the iflist */
7491 struct zt_pvt *working = *wlist;
7493 /* check if we maybe have to put it on the begining */
7494 if (working->channel > tmp->channel) {
7495 tmp->next = *wlist;
7496 tmp->prev = NULL;
7497 (*wlist)->prev = tmp;
7498 *wlist = tmp;
7499 } else {
7500 /* go through all the members and put the member in the right place */
7501 while (working) {
7502 /* in the middle */
7503 if (working->next) {
7504 if (working->channel < tmp->channel && working->next->channel > tmp->channel) {
7505 tmp->next = working->next;
7506 tmp->prev = working;
7507 working->next->prev = tmp;
7508 working->next = tmp;
7509 break;
7511 } else {
7512 /* the last */
7513 if (working->channel < tmp->channel) {
7514 working->next = tmp;
7515 tmp->next = NULL;
7516 tmp->prev = working;
7517 *wend = tmp;
7518 break;
7521 working = working->next;
7526 return tmp;
7529 static inline int available(struct zt_pvt *p, int channelmatch, int groupmatch, int *busy, int *channelmatched, int *groupmatched)
7531 int res;
7532 ZT_PARAMS par;
7534 /* First, check group matching */
7535 if (groupmatch) {
7536 if ((p->group & groupmatch) != groupmatch)
7537 return 0;
7538 *groupmatched = 1;
7540 /* Check to see if we have a channel match */
7541 if (channelmatch != -1) {
7542 if (p->channel != channelmatch)
7543 return 0;
7544 *channelmatched = 1;
7546 /* We're at least busy at this point */
7547 if (busy) {
7548 if ((p->sig == SIG_FXOKS) || (p->sig == SIG_FXOLS) || (p->sig == SIG_FXOGS))
7549 *busy = 1;
7551 /* If do not disturb, definitely not */
7552 if (p->dnd)
7553 return 0;
7554 /* If guard time, definitely not */
7555 if (p->guardtime && (time(NULL) < p->guardtime))
7556 return 0;
7558 /* If no owner definitely available */
7559 if (!p->owner) {
7560 #ifdef HAVE_PRI
7561 /* Trust PRI */
7562 if (p->pri) {
7563 if (p->resetting || p->call)
7564 return 0;
7565 else
7566 return 1;
7568 #endif
7569 if (!(p->radio || (p->oprmode < 0)))
7571 if (!p->sig || (p->sig == SIG_FXSLS))
7572 return 1;
7573 /* Check hook state */
7574 if (p->subs[SUB_REAL].zfd > -1)
7575 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
7576 else {
7577 /* Assume not off hook on CVRS */
7578 res = 0;
7579 par.rxisoffhook = 0;
7581 if (res) {
7582 ast_log(LOG_WARNING, "Unable to check hook state on channel %d\n", p->channel);
7583 } else if ((p->sig == SIG_FXSKS) || (p->sig == SIG_FXSGS)) {
7584 /* When "onhook" that means no battery on the line, and thus
7585 it is out of service..., if it's on a TDM card... If it's a channel
7586 bank, there is no telling... */
7587 if (par.rxbits > -1)
7588 return 1;
7589 if (par.rxisoffhook)
7590 return 1;
7591 else
7592 #ifdef ZAP_CHECK_HOOKSTATE
7593 return 0;
7594 #else
7595 return 1;
7596 #endif
7597 } else if (par.rxisoffhook) {
7598 ast_log(LOG_DEBUG, "Channel %d off hook, can't use\n", p->channel);
7599 /* Not available when the other end is off hook */
7600 return 0;
7603 return 1;
7606 /* If it's not an FXO, forget about call wait */
7607 if ((p->sig != SIG_FXOKS) && (p->sig != SIG_FXOLS) && (p->sig != SIG_FXOGS))
7608 return 0;
7610 if (!p->callwaiting) {
7611 /* If they don't have call waiting enabled, then for sure they're unavailable at this point */
7612 return 0;
7615 if (p->subs[SUB_CALLWAIT].zfd > -1) {
7616 /* If there is already a call waiting call, then we can't take a second one */
7617 return 0;
7620 if ((p->owner->_state != AST_STATE_UP) &&
7621 ((p->owner->_state != AST_STATE_RINGING) || p->outgoing)) {
7622 /* If the current call is not up, then don't allow the call */
7623 return 0;
7625 if ((p->subs[SUB_THREEWAY].owner) && (!p->subs[SUB_THREEWAY].inthreeway)) {
7626 /* Can't take a call wait when the three way calling hasn't been merged yet. */
7627 return 0;
7629 /* We're cool */
7630 return 1;
7633 static struct zt_pvt *chandup(struct zt_pvt *src)
7635 struct zt_pvt *p;
7636 ZT_BUFFERINFO bi;
7637 int res;
7639 if ((p = ast_malloc(sizeof(*p)))) {
7640 memcpy(p, src, sizeof(struct zt_pvt));
7641 ast_mutex_init(&p->lock);
7642 p->subs[SUB_REAL].zfd = zt_open("/dev/zap/pseudo");
7643 /* Allocate a zapata structure */
7644 if (p->subs[SUB_REAL].zfd < 0) {
7645 ast_log(LOG_ERROR, "Unable to dup channel: %s\n", strerror(errno));
7646 destroy_zt_pvt(&p);
7647 return NULL;
7649 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_BUFINFO, &bi);
7650 if (!res) {
7651 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
7652 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
7653 bi.numbufs = numbufs;
7654 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SET_BUFINFO, &bi);
7655 if (res < 0) {
7656 ast_log(LOG_WARNING, "Unable to set buffer policy on dup channel\n");
7658 } else
7659 ast_log(LOG_WARNING, "Unable to check buffer policy on dup channel\n");
7661 p->destroy = 1;
7662 p->next = iflist;
7663 iflist = p;
7664 return p;
7668 #ifdef HAVE_PRI
7669 static int pri_find_empty_chan(struct zt_pri *pri, int backwards)
7671 int x;
7672 if (backwards)
7673 x = pri->numchans;
7674 else
7675 x = 0;
7676 for (;;) {
7677 if (backwards && (x < 0))
7678 break;
7679 if (!backwards && (x >= pri->numchans))
7680 break;
7681 if (pri->pvts[x] && !pri->pvts[x]->inalarm && !pri->pvts[x]->owner) {
7682 ast_log(LOG_DEBUG, "Found empty available channel %d/%d\n",
7683 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
7684 return x;
7686 if (backwards)
7687 x--;
7688 else
7689 x++;
7691 return -1;
7693 #endif
7695 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause)
7697 int groupmatch = 0;
7698 int channelmatch = -1;
7699 int roundrobin = 0;
7700 int callwait = 0;
7701 int busy = 0;
7702 struct zt_pvt *p;
7703 struct ast_channel *tmp = NULL;
7704 char *dest=NULL;
7705 int x;
7706 char *s;
7707 char opt=0;
7708 int res=0, y=0;
7709 int backwards = 0;
7710 #ifdef HAVE_PRI
7711 int crv;
7712 int bearer = -1;
7713 int trunkgroup;
7714 struct zt_pri *pri=NULL;
7715 #endif
7716 struct zt_pvt *exit, *start, *end;
7717 ast_mutex_t *lock;
7718 int channelmatched = 0;
7719 int groupmatched = 0;
7721 /* Assume we're locking the iflock */
7722 lock = &iflock;
7723 start = iflist;
7724 end = ifend;
7725 if (data) {
7726 dest = ast_strdupa((char *)data);
7727 } else {
7728 ast_log(LOG_WARNING, "Channel requested with no data\n");
7729 return NULL;
7731 if (toupper(dest[0]) == 'G' || toupper(dest[0])=='R') {
7732 /* Retrieve the group number */
7733 char *stringp=NULL;
7734 stringp=dest + 1;
7735 s = strsep(&stringp, "/");
7736 if ((res = sscanf(s, "%d%c%d", &x, &opt, &y)) < 1) {
7737 ast_log(LOG_WARNING, "Unable to determine group for data %s\n", (char *)data);
7738 return NULL;
7740 groupmatch = 1 << x;
7741 if (toupper(dest[0]) == 'G') {
7742 if (dest[0] == 'G') {
7743 backwards = 1;
7744 p = ifend;
7745 } else
7746 p = iflist;
7747 } else {
7748 if (dest[0] == 'R') {
7749 backwards = 1;
7750 p = round_robin[x]?round_robin[x]->prev:ifend;
7751 if (!p)
7752 p = ifend;
7753 } else {
7754 p = round_robin[x]?round_robin[x]->next:iflist;
7755 if (!p)
7756 p = iflist;
7758 roundrobin = 1;
7760 } else {
7761 char *stringp=NULL;
7762 stringp=dest;
7763 s = strsep(&stringp, "/");
7764 p = iflist;
7765 if (!strcasecmp(s, "pseudo")) {
7766 /* Special case for pseudo */
7767 x = CHAN_PSEUDO;
7768 channelmatch = x;
7770 #ifdef HAVE_PRI
7771 else if ((res = sscanf(s, "%d:%d%c%d", &trunkgroup, &crv, &opt, &y)) > 1) {
7772 if ((trunkgroup < 1) || (crv < 1)) {
7773 ast_log(LOG_WARNING, "Unable to determine trunk group and CRV for data %s\n", (char *)data);
7774 return NULL;
7776 res--;
7777 for (x = 0; x < NUM_SPANS; x++) {
7778 if (pris[x].trunkgroup == trunkgroup) {
7779 pri = pris + x;
7780 lock = &pri->lock;
7781 start = pri->crvs;
7782 end = pri->crvend;
7783 break;
7786 if (!pri) {
7787 ast_log(LOG_WARNING, "Unable to find trunk group %d\n", trunkgroup);
7788 return NULL;
7790 channelmatch = crv;
7791 p = pris[x].crvs;
7793 #endif
7794 else if ((res = sscanf(s, "%d%c%d", &x, &opt, &y)) < 1) {
7795 ast_log(LOG_WARNING, "Unable to determine channel for data %s\n", (char *)data);
7796 return NULL;
7797 } else {
7798 channelmatch = x;
7801 /* Search for an unowned channel */
7802 ast_mutex_lock(lock);
7803 exit = p;
7804 while (p && !tmp) {
7805 if (roundrobin)
7806 round_robin[x] = p;
7807 #if 0
7808 ast_verbose("name = %s, %d, %d, %d\n",p->owner ? p->owner->name : "<none>", p->channel, channelmatch, groupmatch);
7809 #endif
7811 if (p && available(p, channelmatch, groupmatch, &busy, &channelmatched, &groupmatched)) {
7812 if (option_debug)
7813 ast_log(LOG_DEBUG, "Using channel %d\n", p->channel);
7814 if (p->inalarm)
7815 goto next;
7817 callwait = (p->owner != NULL);
7818 #ifdef HAVE_PRI
7819 if (pri && (p->subs[SUB_REAL].zfd < 0)) {
7820 if (p->sig != SIG_FXSKS) {
7821 /* Gotta find an actual channel to use for this
7822 CRV if this isn't a callwait */
7823 bearer = pri_find_empty_chan(pri, 0);
7824 if (bearer < 0) {
7825 ast_log(LOG_NOTICE, "Out of bearer channels on span %d for call to CRV %d:%d\n", pri->span, trunkgroup, crv);
7826 p = NULL;
7827 break;
7829 pri_assign_bearer(p, pri, pri->pvts[bearer]);
7830 } else {
7831 if (alloc_sub(p, 0)) {
7832 ast_log(LOG_NOTICE, "Failed to allocate place holder pseudo channel!\n");
7833 p = NULL;
7834 break;
7835 } else
7836 ast_log(LOG_DEBUG, "Allocated placeholder pseudo channel\n");
7837 p->pri = pri;
7840 #endif
7841 if (p->channel == CHAN_PSEUDO) {
7842 p = chandup(p);
7843 if (!p) {
7844 break;
7847 if (p->owner) {
7848 if (alloc_sub(p, SUB_CALLWAIT)) {
7849 p = NULL;
7850 break;
7853 p->outgoing = 1;
7854 tmp = zt_new(p, AST_STATE_RESERVED, 0, p->owner ? SUB_CALLWAIT : SUB_REAL, 0, 0);
7855 #ifdef HAVE_PRI
7856 if (p->bearer) {
7857 /* Log owner to bearer channel, too */
7858 p->bearer->owner = tmp;
7860 #endif
7861 /* Make special notes */
7862 if (res > 1) {
7863 if (opt == 'c') {
7864 /* Confirm answer */
7865 p->confirmanswer = 1;
7866 } else if (opt == 'r') {
7867 /* Distinctive ring */
7868 if (res < 3)
7869 ast_log(LOG_WARNING, "Distinctive ring missing identifier in '%s'\n", (char *)data);
7870 else
7871 p->distinctivering = y;
7872 } else if (opt == 'd') {
7873 /* If this is an ISDN call, make it digital */
7874 p->digital = 1;
7875 if (tmp)
7876 tmp->transfercapability = AST_TRANS_CAP_DIGITAL;
7877 } else {
7878 ast_log(LOG_WARNING, "Unknown option '%c' in '%s'\n", opt, (char *)data);
7881 /* Note if the call is a call waiting call */
7882 if (tmp && callwait)
7883 tmp->cdrflags |= AST_CDR_CALLWAIT;
7884 break;
7886 next:
7887 if (backwards) {
7888 p = p->prev;
7889 if (!p)
7890 p = end;
7891 } else {
7892 p = p->next;
7893 if (!p)
7894 p = start;
7896 /* stop when you roll to the one that we started from */
7897 if (p == exit)
7898 break;
7900 ast_mutex_unlock(lock);
7901 restart_monitor();
7902 if (callwait)
7903 *cause = AST_CAUSE_BUSY;
7904 else if (!tmp) {
7905 if (channelmatched) {
7906 if (busy)
7907 *cause = AST_CAUSE_BUSY;
7908 } else if (groupmatched) {
7909 *cause = AST_CAUSE_CONGESTION;
7913 return tmp;
7917 #ifdef HAVE_PRI
7918 static struct zt_pvt *pri_find_crv(struct zt_pri *pri, int crv)
7920 struct zt_pvt *p;
7921 p = pri->crvs;
7922 while (p) {
7923 if (p->channel == crv)
7924 return p;
7925 p = p->next;
7927 return NULL;
7931 static int pri_find_principle(struct zt_pri *pri, int channel)
7933 int x;
7934 int span = PRI_SPAN(channel);
7935 int spanfd;
7936 ZT_PARAMS param;
7937 int principle = -1;
7938 int explicit = PRI_EXPLICIT(channel);
7939 channel = PRI_CHANNEL(channel);
7941 if (!explicit) {
7942 spanfd = pri_active_dchan_fd(pri);
7943 if (ioctl(spanfd, ZT_GET_PARAMS, &param))
7944 return -1;
7945 span = pris[param.spanno - 1].prilogicalspan;
7948 for (x = 0; x < pri->numchans; x++) {
7949 if (pri->pvts[x] && (pri->pvts[x]->prioffset == channel) && (pri->pvts[x]->logicalspan == span)) {
7950 principle = x;
7951 break;
7955 return principle;
7958 static int pri_fixup_principle(struct zt_pri *pri, int principle, q931_call *c)
7960 int x;
7961 struct zt_pvt *crv;
7962 if (!c) {
7963 if (principle < 0)
7964 return -1;
7965 return principle;
7967 if ((principle > -1) &&
7968 (principle < pri->numchans) &&
7969 (pri->pvts[principle]) &&
7970 (pri->pvts[principle]->call == c))
7971 return principle;
7972 /* First, check for other bearers */
7973 for (x = 0; x < pri->numchans; x++) {
7974 if (!pri->pvts[x])
7975 continue;
7976 if (pri->pvts[x]->call == c) {
7977 /* Found our call */
7978 if (principle != x) {
7979 if (option_verbose > 2)
7980 ast_verbose(VERBOSE_PREFIX_3 "Moving call from channel %d to channel %d\n",
7981 pri->pvts[x]->channel, pri->pvts[principle]->channel);
7982 if (pri->pvts[principle]->owner) {
7983 ast_log(LOG_WARNING, "Can't fix up channel from %d to %d because %d is already in use\n",
7984 pri->pvts[x]->channel, pri->pvts[principle]->channel, pri->pvts[principle]->channel);
7985 return -1;
7987 /* Fix it all up now */
7988 pri->pvts[principle]->owner = pri->pvts[x]->owner;
7989 if (pri->pvts[principle]->owner) {
7990 ast_string_field_build(pri->pvts[principle]->owner, name,
7991 "Zap/%d:%d-%d", pri->trunkgroup,
7992 pri->pvts[principle]->channel, 1);
7993 pri->pvts[principle]->owner->tech_pvt = pri->pvts[principle];
7994 pri->pvts[principle]->owner->fds[0] = pri->pvts[principle]->subs[SUB_REAL].zfd;
7995 pri->pvts[principle]->subs[SUB_REAL].owner = pri->pvts[x]->subs[SUB_REAL].owner;
7996 } else
7997 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);
7998 pri->pvts[principle]->call = pri->pvts[x]->call;
7999 /* Free up the old channel, now not in use */
8000 pri->pvts[x]->subs[SUB_REAL].owner = NULL;
8001 pri->pvts[x]->owner = NULL;
8002 pri->pvts[x]->call = NULL;
8004 return principle;
8007 /* Now check for a CRV with no bearer */
8008 crv = pri->crvs;
8009 while (crv) {
8010 if (crv->call == c) {
8011 /* This is our match... Perform some basic checks */
8012 if (crv->bearer)
8013 ast_log(LOG_WARNING, "Trying to fix up call which already has a bearer which isn't the one we think it is\n");
8014 else if (pri->pvts[principle]->owner)
8015 ast_log(LOG_WARNING, "Tring to fix up a call to a bearer which already has an owner!\n");
8016 else {
8017 /* Looks good. Drop the pseudo channel now, clear up the assignment, and
8018 wakeup the potential sleeper */
8019 zt_close(crv->subs[SUB_REAL].zfd);
8020 pri->pvts[principle]->call = crv->call;
8021 pri_assign_bearer(crv, pri, pri->pvts[principle]);
8022 ast_log(LOG_DEBUG, "Assigning bearer %d/%d to CRV %d:%d\n",
8023 pri->pvts[principle]->logicalspan, pri->pvts[principle]->prioffset,
8024 pri->trunkgroup, crv->channel);
8025 wakeup_sub(crv, SUB_REAL, pri);
8027 return principle;
8029 crv = crv->next;
8031 ast_log(LOG_WARNING, "Call specified, but not found?\n");
8032 return -1;
8035 static void *do_idle_thread(void *vchan)
8037 struct ast_channel *chan = vchan;
8038 struct zt_pvt *pvt = chan->tech_pvt;
8039 struct ast_frame *f;
8040 char ex[80];
8041 /* Wait up to 30 seconds for an answer */
8042 int newms, ms = 30000;
8043 if (option_verbose > 2)
8044 ast_verbose(VERBOSE_PREFIX_3 "Initiating idle call on channel %s\n", chan->name);
8045 snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
8046 if (ast_call(chan, ex, 0)) {
8047 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
8048 ast_hangup(chan);
8049 return NULL;
8051 while ((newms = ast_waitfor(chan, ms)) > 0) {
8052 f = ast_read(chan);
8053 if (!f) {
8054 /* Got hangup */
8055 break;
8057 if (f->frametype == AST_FRAME_CONTROL) {
8058 switch (f->subclass) {
8059 case AST_CONTROL_ANSWER:
8060 /* Launch the PBX */
8061 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
8062 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
8063 chan->priority = 1;
8064 if (option_verbose > 3)
8065 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
8066 ast_pbx_run(chan);
8067 /* It's already hungup, return immediately */
8068 return NULL;
8069 case AST_CONTROL_BUSY:
8070 if (option_verbose > 3)
8071 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' busy, waiting...\n", chan->name);
8072 break;
8073 case AST_CONTROL_CONGESTION:
8074 if (option_verbose > 3)
8075 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' congested, waiting...\n", chan->name);
8076 break;
8079 ast_frfree(f);
8080 ms = newms;
8082 /* Hangup the channel since nothing happend */
8083 ast_hangup(chan);
8084 return NULL;
8087 #ifndef PRI_RESTART
8088 #error "Upgrade your libpri"
8089 #endif
8090 static void zt_pri_message(struct pri *pri, char *s)
8092 int x, y;
8093 int dchan = -1, span = -1;
8094 int dchancount = 0;
8096 if (pri) {
8097 for (x = 0; x < NUM_SPANS; x++) {
8098 for (y = 0; y < NUM_DCHANS; y++) {
8099 if (pris[x].dchans[y])
8100 dchancount++;
8102 if (pris[x].dchans[y] == pri)
8103 dchan = y;
8105 if (dchan >= 0) {
8106 span = x;
8107 break;
8109 dchancount = 0;
8111 if ((dchan >= 0) && (span >= 0)) {
8112 if (dchancount > 1)
8113 ast_verbose("[Span %d D-Channel %d]%s", span, dchan, s);
8114 else
8115 ast_verbose("%s", s);
8116 } else
8117 ast_log(LOG_ERROR, "PRI debug error: could not find pri associated it with debug message output\n");
8118 } else
8119 ast_verbose("%s", s);
8121 ast_mutex_lock(&pridebugfdlock);
8123 if (pridebugfd >= 0)
8124 write(pridebugfd, s, strlen(s));
8126 ast_mutex_unlock(&pridebugfdlock);
8129 static void zt_pri_error(struct pri *pri, char *s)
8131 int x, y;
8132 int dchan = -1, span = -1;
8133 int dchancount = 0;
8135 if (pri) {
8136 for (x = 0; x < NUM_SPANS; x++) {
8137 for (y = 0; y < NUM_DCHANS; y++) {
8138 if (pris[x].dchans[y])
8139 dchancount++;
8141 if (pris[x].dchans[y] == pri)
8142 dchan = y;
8144 if (dchan >= 0) {
8145 span = x;
8146 break;
8148 dchancount = 0;
8150 if ((dchan >= 0) && (span >= 0)) {
8151 if (dchancount > 1)
8152 ast_log(LOG_ERROR, "[Span %d D-Channel %d] PRI: %s", span, dchan, s);
8153 else
8154 ast_log(LOG_ERROR, "%s", s);
8155 } else
8156 ast_log(LOG_ERROR, "PRI debug error: could not find pri associated it with debug message output\n");
8157 } else
8158 ast_log(LOG_ERROR, "%s", s);
8160 ast_mutex_lock(&pridebugfdlock);
8162 if (pridebugfd >= 0)
8163 write(pridebugfd, s, strlen(s));
8165 ast_mutex_unlock(&pridebugfdlock);
8168 static int pri_check_restart(struct zt_pri *pri)
8170 do {
8171 pri->resetpos++;
8172 } while ((pri->resetpos < pri->numchans) &&
8173 (!pri->pvts[pri->resetpos] ||
8174 pri->pvts[pri->resetpos]->call ||
8175 pri->pvts[pri->resetpos]->resetting));
8176 if (pri->resetpos < pri->numchans) {
8177 /* Mark the channel as resetting and restart it */
8178 pri->pvts[pri->resetpos]->resetting = 1;
8179 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
8180 } else {
8181 pri->resetting = 0;
8182 time(&pri->lastreset);
8184 return 0;
8187 static int pri_hangup_all(struct zt_pvt *p, struct zt_pri *pri)
8189 int x;
8190 int redo;
8191 ast_mutex_unlock(&pri->lock);
8192 ast_mutex_lock(&p->lock);
8193 do {
8194 redo = 0;
8195 for (x = 0; x < 3; x++) {
8196 while (p->subs[x].owner && ast_mutex_trylock(&p->subs[x].owner->lock)) {
8197 redo++;
8198 ast_mutex_unlock(&p->lock);
8199 usleep(1);
8200 ast_mutex_lock(&p->lock);
8202 if (p->subs[x].owner) {
8203 ast_queue_hangup(p->subs[x].owner);
8204 ast_mutex_unlock(&p->subs[x].owner->lock);
8207 } while (redo);
8208 ast_mutex_unlock(&p->lock);
8209 ast_mutex_lock(&pri->lock);
8210 return 0;
8213 static char * redirectingreason2str(int redirectingreason)
8215 switch (redirectingreason) {
8216 case 0:
8217 return "UNKNOWN";
8218 case 1:
8219 return "BUSY";
8220 case 2:
8221 return "NO_REPLY";
8222 case 0xF:
8223 return "UNCONDITIONAL";
8224 default:
8225 return "NOREDIRECT";
8229 static void apply_plan_to_number(char *buf, size_t size, const struct zt_pri *pri, const char *number, const int plan)
8231 switch (plan) {
8232 case PRI_INTERNATIONAL_ISDN: /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
8233 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
8234 break;
8235 case PRI_NATIONAL_ISDN: /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
8236 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
8237 break;
8238 case PRI_LOCAL_ISDN: /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
8239 snprintf(buf, size, "%s%s", pri->localprefix, number);
8240 break;
8241 case PRI_PRIVATE: /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
8242 snprintf(buf, size, "%s%s", pri->privateprefix, number);
8243 break;
8244 case PRI_UNKNOWN: /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
8245 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
8246 break;
8247 default: /* other Q.931 dialplan => don't twiddle with callingnum */
8248 snprintf(buf, size, "%s", number);
8249 break;
8253 static int zt_setlaw(int zfd, int law)
8255 int res;
8256 res = ioctl(zfd, ZT_SETLAW, &law);
8257 if (res)
8258 return res;
8259 return 0;
8262 static void *pri_dchannel(void *vpri)
8264 struct zt_pri *pri = vpri;
8265 pri_event *e;
8266 struct pollfd fds[NUM_DCHANS];
8267 int res;
8268 int chanpos = 0;
8269 int x;
8270 int haveidles;
8271 int activeidles;
8272 int nextidle = -1;
8273 struct ast_channel *c;
8274 struct timeval tv, lowest, *next;
8275 struct timeval lastidle = { 0, 0 };
8276 int doidling=0;
8277 char *cc;
8278 char idlen[80];
8279 struct ast_channel *idle;
8280 pthread_t p;
8281 time_t t;
8282 int i, which=-1;
8283 int numdchans;
8284 int cause=0;
8285 struct zt_pvt *crv;
8286 pthread_t threadid;
8287 pthread_attr_t attr;
8288 char ani2str[6];
8289 char plancallingnum[256];
8290 char plancallingani[256];
8291 char calledtonstr[10];
8293 gettimeofday(&lastidle, NULL);
8294 if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
8295 /* Need to do idle dialing, check to be sure though */
8296 cc = strchr(pri->idleext, '@');
8297 if (cc) {
8298 *cc = '\0';
8299 cc++;
8300 ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
8301 #if 0
8302 /* Extensions may not be loaded yet */
8303 if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
8304 ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
8305 else
8306 #endif
8307 doidling = 1;
8308 } else
8309 ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
8311 for (;;) {
8312 for (i = 0; i < NUM_DCHANS; i++) {
8313 if (!pri->dchannels[i])
8314 break;
8315 fds[i].fd = pri->fds[i];
8316 fds[i].events = POLLIN | POLLPRI;
8317 fds[i].revents = 0;
8319 numdchans = i;
8320 time(&t);
8321 ast_mutex_lock(&pri->lock);
8322 if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->resetinterval > 0)) {
8323 if (pri->resetting && pri_is_up(pri)) {
8324 if (pri->resetpos < 0)
8325 pri_check_restart(pri);
8326 } else {
8327 if (!pri->resetting && (t - pri->lastreset) >= pri->resetinterval) {
8328 pri->resetting = 1;
8329 pri->resetpos = -1;
8333 /* Look for any idle channels if appropriate */
8334 if (doidling && pri_is_up(pri)) {
8335 nextidle = -1;
8336 haveidles = 0;
8337 activeidles = 0;
8338 for (x = pri->numchans; x >= 0; x--) {
8339 if (pri->pvts[x] && !pri->pvts[x]->owner &&
8340 !pri->pvts[x]->call) {
8341 if (haveidles < pri->minunused) {
8342 haveidles++;
8343 } else if (!pri->pvts[x]->resetting) {
8344 nextidle = x;
8345 break;
8347 } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
8348 activeidles++;
8350 if (nextidle > -1) {
8351 if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
8352 /* Don't create a new idle call more than once per second */
8353 snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
8354 idle = zt_request("Zap", AST_FORMAT_ULAW, idlen, &cause);
8355 if (idle) {
8356 pri->pvts[nextidle]->isidlecall = 1;
8357 if (ast_pthread_create_background(&p, NULL, do_idle_thread, idle)) {
8358 ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
8359 zt_hangup(idle);
8361 } else
8362 ast_log(LOG_WARNING, "Unable to request channel 'Zap/%s' for idle call\n", idlen);
8363 gettimeofday(&lastidle, NULL);
8365 } else if ((haveidles < pri->minunused) &&
8366 (activeidles > pri->minidle)) {
8367 /* Mark something for hangup if there is something
8368 that can be hungup */
8369 for (x = pri->numchans; x >= 0; x--) {
8370 /* find a candidate channel */
8371 if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
8372 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8373 haveidles++;
8374 /* Stop if we have enough idle channels or
8375 can't spare any more active idle ones */
8376 if ((haveidles >= pri->minunused) ||
8377 (activeidles <= pri->minidle))
8378 break;
8383 /* Start with reasonable max */
8384 lowest = ast_tv(60, 0);
8385 for (i = 0; i < NUM_DCHANS; i++) {
8386 /* Find lowest available d-channel */
8387 if (!pri->dchannels[i])
8388 break;
8389 if ((next = pri_schedule_next(pri->dchans[i]))) {
8390 /* We need relative time here */
8391 tv = ast_tvsub(*next, ast_tvnow());
8392 if (tv.tv_sec < 0) {
8393 tv = ast_tv(0,0);
8395 if (doidling || pri->resetting) {
8396 if (tv.tv_sec > 1) {
8397 tv = ast_tv(1, 0);
8399 } else {
8400 if (tv.tv_sec > 60) {
8401 tv = ast_tv(60, 0);
8404 } else if (doidling || pri->resetting) {
8405 /* Make sure we stop at least once per second if we're
8406 monitoring idle channels */
8407 tv = ast_tv(1,0);
8408 } else {
8409 /* Don't poll for more than 60 seconds */
8410 tv = ast_tv(60, 0);
8412 if (!i || ast_tvcmp(tv, lowest) < 0) {
8413 lowest = tv;
8416 ast_mutex_unlock(&pri->lock);
8418 e = NULL;
8419 res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
8421 ast_mutex_lock(&pri->lock);
8422 if (!res) {
8423 for (which = 0; which < NUM_DCHANS; which++) {
8424 if (!pri->dchans[which])
8425 break;
8426 /* Just a timeout, run the scheduler */
8427 e = pri_schedule_run(pri->dchans[which]);
8428 if (e)
8429 break;
8431 } else if (res > -1) {
8432 for (which = 0; which < NUM_DCHANS; which++) {
8433 if (!pri->dchans[which])
8434 break;
8435 if (fds[which].revents & POLLPRI) {
8436 /* Check for an event */
8437 x = 0;
8438 res = ioctl(pri->fds[which], ZT_GETEVENT, &x);
8439 if (x)
8440 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);
8441 /* Keep track of alarm state */
8442 if (x == ZT_EVENT_ALARM) {
8443 pri->dchanavail[which] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
8444 pri_find_dchan(pri);
8445 } else if (x == ZT_EVENT_NOALARM) {
8446 pri->dchanavail[which] |= DCHAN_NOTINALARM;
8447 pri_restart(pri->dchans[which]);
8450 if (option_debug)
8451 ast_log(LOG_DEBUG, "Got event %s (%d) on D-channel for span %d\n", event2str(x), x, pri->span);
8452 } else if (fds[which].revents & POLLIN) {
8453 e = pri_check_event(pri->dchans[which]);
8455 if (e)
8456 break;
8458 } else if (errno != EINTR)
8459 ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
8461 if (e) {
8462 if (pri->debug)
8463 pri_dump_event(pri->dchans[which], e);
8464 if (e->e != PRI_EVENT_DCHAN_DOWN)
8465 pri->dchanavail[which] |= DCHAN_UP;
8467 if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
8468 /* Must be an NFAS group that has the secondary dchan active */
8469 pri->pri = pri->dchans[which];
8471 switch (e->e) {
8472 case PRI_EVENT_DCHAN_UP:
8473 if (option_verbose > 1)
8474 ast_verbose(VERBOSE_PREFIX_2 "%s D-Channel on span %d up\n", pri_order(which), pri->span);
8475 pri->dchanavail[which] |= DCHAN_UP;
8476 if (!pri->pri) pri_find_dchan(pri);
8478 /* Note presense of D-channel */
8479 time(&pri->lastreset);
8481 /* Restart in 5 seconds */
8482 if (pri->resetinterval > -1) {
8483 pri->lastreset -= pri->resetinterval;
8484 pri->lastreset += 5;
8486 pri->resetting = 0;
8487 /* Take the channels from inalarm condition */
8488 for (i = 0; i < pri->numchans; i++)
8489 if (pri->pvts[i]) {
8490 pri->pvts[i]->inalarm = 0;
8492 break;
8493 case PRI_EVENT_DCHAN_DOWN:
8494 if (option_verbose > 1)
8495 ast_verbose(VERBOSE_PREFIX_2 "%s D-Channel on span %d down\n", pri_order(which), pri->span);
8496 pri->dchanavail[which] &= ~DCHAN_UP;
8497 pri_find_dchan(pri);
8498 if (!pri_is_up(pri)) {
8499 pri->resetting = 0;
8500 /* Hangup active channels and put them in alarm mode */
8501 for (i = 0; i < pri->numchans; i++) {
8502 struct zt_pvt *p = pri->pvts[i];
8503 if (p) {
8504 if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
8505 /* T309 is not enabled : hangup calls when alarm occurs */
8506 if (p->call) {
8507 if (p->pri && p->pri->pri) {
8508 pri_hangup(p->pri->pri, p->call, -1);
8509 pri_destroycall(p->pri->pri, p->call);
8510 p->call = NULL;
8511 } else
8512 ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
8514 if (p->realcall) {
8515 pri_hangup_all(p->realcall, pri);
8516 } else if (p->owner)
8517 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8519 p->inalarm = 1;
8523 break;
8524 case PRI_EVENT_RESTART:
8525 if (e->restart.channel > -1) {
8526 chanpos = pri_find_principle(pri, e->restart.channel);
8527 if (chanpos < 0)
8528 ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
8529 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
8530 else {
8531 if (option_verbose > 2)
8532 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d restarted on span %d\n",
8533 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
8534 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8535 if (pri->pvts[chanpos]->call) {
8536 pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
8537 pri->pvts[chanpos]->call = NULL;
8539 /* Force soft hangup if appropriate */
8540 if (pri->pvts[chanpos]->realcall)
8541 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
8542 else if (pri->pvts[chanpos]->owner)
8543 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8544 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8546 } else {
8547 if (option_verbose > 2)
8548 ast_verbose(VERBOSE_PREFIX_2 "Restart on requested on entire span %d\n", pri->span);
8549 for (x = 0; x < pri->numchans; x++)
8550 if (pri->pvts[x]) {
8551 ast_mutex_lock(&pri->pvts[x]->lock);
8552 if (pri->pvts[x]->call) {
8553 pri_destroycall(pri->pri, pri->pvts[x]->call);
8554 pri->pvts[x]->call = NULL;
8556 if (pri->pvts[chanpos]->realcall)
8557 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
8558 else if (pri->pvts[x]->owner)
8559 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8560 ast_mutex_unlock(&pri->pvts[x]->lock);
8563 break;
8564 case PRI_EVENT_KEYPAD_DIGIT:
8565 chanpos = pri_find_principle(pri, e->digit.channel);
8566 if (chanpos < 0) {
8567 ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
8568 PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
8569 } else {
8570 chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
8571 if (chanpos > -1) {
8572 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8573 /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
8574 if (pri->overlapdial && pri->pvts[chanpos]->call==e->digit.call && pri->pvts[chanpos]->owner) {
8575 /* how to do that */
8576 int digitlen = strlen(e->digit.digits);
8577 char digit;
8578 int i;
8579 for (i = 0; i < digitlen; i++) {
8580 digit = e->digit.digits[i];
8582 struct ast_frame f = { AST_FRAME_DTMF, digit, };
8583 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8587 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8590 break;
8592 case PRI_EVENT_INFO_RECEIVED:
8593 chanpos = pri_find_principle(pri, e->ring.channel);
8594 if (chanpos < 0) {
8595 ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
8596 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8597 } else {
8598 chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
8599 if (chanpos > -1) {
8600 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8601 /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
8602 if (pri->overlapdial && pri->pvts[chanpos]->call==e->ring.call && pri->pvts[chanpos]->owner) {
8603 /* how to do that */
8604 int digitlen = strlen(e->ring.callednum);
8605 char digit;
8606 int i;
8607 for (i = 0; i < digitlen; i++) {
8608 digit = e->ring.callednum[i];
8610 struct ast_frame f = { AST_FRAME_DTMF, digit, };
8611 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8615 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8618 break;
8619 case PRI_EVENT_RING:
8620 crv = NULL;
8621 if (e->ring.channel == -1)
8622 chanpos = pri_find_empty_chan(pri, 1);
8623 else
8624 chanpos = pri_find_principle(pri, e->ring.channel);
8625 /* if no channel specified find one empty */
8626 if (chanpos < 0) {
8627 ast_log(LOG_WARNING, "Ring requested on unconfigured channel %d/%d span %d\n",
8628 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8629 } else {
8630 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8631 if (pri->pvts[chanpos]->owner) {
8632 if (pri->pvts[chanpos]->call == e->ring.call) {
8633 ast_log(LOG_WARNING, "Duplicate setup requested on channel %d/%d already in use on span %d\n",
8634 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8635 break;
8636 } else {
8637 /* This is where we handle initial glare */
8638 ast_log(LOG_DEBUG, "Ring requested on channel %d/%d already in use or previously requested on span %d. Attempting to renegotiating channel.\n",
8639 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8640 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8641 chanpos = -1;
8644 if (chanpos > -1)
8645 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8647 if ((chanpos < 0) && (e->ring.flexible))
8648 chanpos = pri_find_empty_chan(pri, 1);
8649 if (chanpos > -1) {
8650 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8651 if (pri->switchtype == PRI_SWITCH_GR303_TMC) {
8652 /* Should be safe to lock CRV AFAIK while bearer is still locked */
8653 crv = pri_find_crv(pri, pri_get_crv(pri->pri, e->ring.call, NULL));
8654 if (crv)
8655 ast_mutex_lock(&crv->lock);
8656 if (!crv || crv->owner) {
8657 pri->pvts[chanpos]->call = NULL;
8658 if (crv) {
8659 if (crv->owner)
8660 crv->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8661 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);
8662 } else
8663 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);
8664 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_INVALID_CALL_REFERENCE);
8665 if (crv)
8666 ast_mutex_unlock(&crv->lock);
8667 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8668 break;
8671 pri->pvts[chanpos]->call = e->ring.call;
8672 apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri, e->ring.callingnum, e->ring.callingplan);
8673 if (pri->pvts[chanpos]->use_callerid) {
8674 ast_shrink_phone_number(plancallingnum);
8675 ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
8676 #ifdef PRI_ANI
8677 if (!ast_strlen_zero(e->ring.callingani)) {
8678 apply_plan_to_number(plancallingani, sizeof(plancallingani), pri, e->ring.callingani, e->ring.callingplanani);
8679 ast_shrink_phone_number(plancallingani);
8680 ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani, sizeof(pri->pvts[chanpos]->cid_ani));
8681 } else {
8682 pri->pvts[chanpos]->cid_ani[0] = '\0';
8684 #endif
8685 ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
8686 pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
8687 } else {
8688 pri->pvts[chanpos]->cid_num[0] = '\0';
8689 pri->pvts[chanpos]->cid_ani[0] = '\0';
8690 pri->pvts[chanpos]->cid_name[0] = '\0';
8691 pri->pvts[chanpos]->cid_ton = 0;
8693 apply_plan_to_number(pri->pvts[chanpos]->rdnis, sizeof(pri->pvts[chanpos]->rdnis), pri,
8694 e->ring.redirectingnum, e->ring.callingplanrdnis);
8695 /* If immediate=yes go to s|1 */
8696 if (pri->pvts[chanpos]->immediate) {
8697 if (option_verbose > 2)
8698 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of immediate=yes\n");
8699 pri->pvts[chanpos]->exten[0] = 's';
8700 pri->pvts[chanpos]->exten[1] = '\0';
8702 /* Get called number */
8703 else if (!ast_strlen_zero(e->ring.callednum)) {
8704 ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
8705 ast_copy_string(pri->pvts[chanpos]->dnid, e->ring.callednum, sizeof(pri->pvts[chanpos]->dnid));
8706 } else
8707 pri->pvts[chanpos]->exten[0] = '\0';
8708 /* Set DNID on all incoming calls -- even immediate */
8709 if (!ast_strlen_zero(e->ring.callednum))
8710 ast_copy_string(pri->pvts[chanpos]->dnid, e->ring.callednum, sizeof(pri->pvts[chanpos]->dnid));
8711 /* No number yet, but received "sending complete"? */
8712 if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
8713 if (option_verbose > 2)
8714 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of Complete received\n");
8715 pri->pvts[chanpos]->exten[0] = 's';
8716 pri->pvts[chanpos]->exten[1] = '\0';
8718 /* Make sure extension exists (or in overlap dial mode, can exist) */
8719 if ((pri->overlapdial && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
8720 ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
8721 /* Setup law */
8722 int law;
8723 if (pri->switchtype != PRI_SWITCH_GR303_TMC) {
8724 /* Set to audio mode at this point */
8725 law = 1;
8726 if (ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &law) == -1)
8727 ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", pri->pvts[chanpos]->channel, law);
8729 if (e->ring.layer1 == PRI_LAYER_1_ALAW)
8730 law = ZT_LAW_ALAW;
8731 else
8732 law = ZT_LAW_MULAW;
8733 res = zt_setlaw(pri->pvts[chanpos]->subs[SUB_REAL].zfd, law);
8734 if (res < 0)
8735 ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pri->pvts[chanpos]->channel);
8736 res = set_actual_gain(pri->pvts[chanpos]->subs[SUB_REAL].zfd, 0, pri->pvts[chanpos]->rxgain, pri->pvts[chanpos]->txgain, law);
8737 if (res < 0)
8738 ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pri->pvts[chanpos]->channel);
8739 if (e->ring.complete || !pri->overlapdial) {
8740 /* Just announce proceeding */
8741 pri->pvts[chanpos]->proceeding = 1;
8742 pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
8743 } else {
8744 if (pri->switchtype != PRI_SWITCH_GR303_TMC)
8745 pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
8746 else
8747 pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
8749 /* Get the use_callingpres state */
8750 pri->pvts[chanpos]->callingpres = e->ring.callingpres;
8752 /* Start PBX */
8753 if (pri->overlapdial && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
8754 /* Release the PRI lock while we create the channel */
8755 ast_mutex_unlock(&pri->lock);
8756 if (crv) {
8757 /* Set bearer and such */
8758 pri_assign_bearer(crv, pri, pri->pvts[chanpos]);
8759 c = zt_new(crv, AST_STATE_RESERVED, 0, SUB_REAL, law, e->ring.ctype);
8760 pri->pvts[chanpos]->owner = &inuse;
8761 ast_log(LOG_DEBUG, "Started up crv %d:%d on bearer channel %d\n", pri->trunkgroup, crv->channel, crv->bearer->channel);
8762 } else {
8763 c = zt_new(pri->pvts[chanpos], AST_STATE_RESERVED, 0, SUB_REAL, law, e->ring.ctype);
8765 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
8766 pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
8768 if (e->ring.ani2 >= 0) {
8769 snprintf(ani2str, 5, "%.2d", e->ring.ani2);
8770 pbx_builtin_setvar_helper(c, "ANI2", ani2str);
8773 #ifdef SUPPORT_USERUSER
8774 if (!ast_strlen_zero(e->ring.useruserinfo)) {
8775 pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
8777 #endif
8779 snprintf(calledtonstr, sizeof(calledtonstr)-1, "%d", e->ring.calledplan);
8780 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
8781 if (e->ring.redirectingreason >= 0)
8782 pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
8784 ast_mutex_lock(&pri->lock);
8785 pthread_attr_init(&attr);
8786 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
8787 if (c && !ast_pthread_create(&threadid, &attr, ss_thread, c)) {
8788 if (option_verbose > 2)
8789 ast_verbose(VERBOSE_PREFIX_3 "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
8790 plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
8791 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8792 } else {
8793 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
8794 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8795 if (c)
8796 ast_hangup(c);
8797 else {
8798 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
8799 pri->pvts[chanpos]->call = NULL;
8802 pthread_attr_destroy(&attr);
8803 } else {
8804 ast_mutex_unlock(&pri->lock);
8805 /* Release PRI lock while we create the channel */
8806 c = zt_new(pri->pvts[chanpos], AST_STATE_RING, 1, SUB_REAL, law, e->ring.ctype);
8807 ast_mutex_lock(&pri->lock);
8808 if (c) {
8809 char calledtonstr[10];
8810 if (e->ring.ani2 >= 0) {
8811 snprintf(ani2str, 5, "%d", e->ring.ani2);
8812 pbx_builtin_setvar_helper(c, "ANI2", ani2str);
8815 #ifdef SUPPORT_USERUSER
8816 if (!ast_strlen_zero(e->ring.useruserinfo)) {
8817 pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
8819 #endif
8821 if (e->ring.redirectingreason >= 0)
8822 pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
8824 snprintf(calledtonstr, sizeof(calledtonstr)-1, "%d", e->ring.calledplan);
8825 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
8826 if (option_verbose > 2)
8827 ast_verbose(VERBOSE_PREFIX_3 "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
8828 plancallingnum, pri->pvts[chanpos]->exten,
8829 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8830 zt_enable_ec(pri->pvts[chanpos]);
8831 } else {
8832 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
8833 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8834 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
8835 pri->pvts[chanpos]->call = NULL;
8838 } else {
8839 if (option_verbose > 2)
8840 ast_verbose(VERBOSE_PREFIX_3 "Extension '%s' in context '%s' from '%s' does not exist. Rejecting call on channel %d/%d, span %d\n",
8841 pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context, pri->pvts[chanpos]->cid_num, pri->pvts[chanpos]->logicalspan,
8842 pri->pvts[chanpos]->prioffset, pri->span);
8843 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
8844 pri->pvts[chanpos]->call = NULL;
8845 pri->pvts[chanpos]->exten[0] = '\0';
8847 if (crv)
8848 ast_mutex_unlock(&crv->lock);
8849 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8850 } else {
8851 if (e->ring.flexible)
8852 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
8853 else
8854 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
8856 break;
8857 case PRI_EVENT_RINGING:
8858 chanpos = pri_find_principle(pri, e->ringing.channel);
8859 if (chanpos < 0) {
8860 ast_log(LOG_WARNING, "Ringing requested on unconfigured channel %d/%d span %d\n",
8861 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
8862 } else {
8863 chanpos = pri_fixup_principle(pri, chanpos, e->ringing.call);
8864 if (chanpos < 0) {
8865 ast_log(LOG_WARNING, "Ringing requested on channel %d/%d not in use on span %d\n",
8866 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
8867 } else {
8868 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8869 if (ast_strlen_zero(pri->pvts[chanpos]->dop.dialstr)) {
8870 zt_enable_ec(pri->pvts[chanpos]);
8871 pri->pvts[chanpos]->subs[SUB_REAL].needringing = 1;
8872 pri->pvts[chanpos]->alerting = 1;
8873 } else
8874 ast_log(LOG_DEBUG, "Deferring ringing notification because of extra digits to dial...\n");
8875 #ifdef PRI_PROGRESS_MASK
8876 if (e->ringing.progressmask & PRI_PROG_INBAND_AVAILABLE) {
8877 #else
8878 if (e->ringing.progress == 8) {
8879 #endif
8880 /* Now we can do call progress detection */
8881 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
8882 /* RINGING detection isn't required because we got ALERTING signal */
8883 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features & ~DSP_PROGRESS_RINGING);
8884 pri->pvts[chanpos]->dsp_features = 0;
8888 #ifdef SUPPORT_USERUSER
8889 if (!ast_strlen_zero(e->ringing.useruserinfo)) {
8890 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->ringing.useruserinfo);
8892 #endif
8894 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8897 break;
8898 case PRI_EVENT_PROGRESS:
8899 /* Get chan value if e->e is not PRI_EVNT_RINGING */
8900 chanpos = pri_find_principle(pri, e->proceeding.channel);
8901 if (chanpos > -1) {
8902 #ifdef PRI_PROGRESS_MASK
8903 if ((!pri->pvts[chanpos]->progress) || (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE)) {
8904 #else
8905 if ((!pri->pvts[chanpos]->progress) || (e->proceeding.progress == 8)) {
8906 #endif
8907 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, };
8909 if (e->proceeding.cause > -1) {
8910 if (option_verbose > 2)
8911 ast_verbose(VERBOSE_PREFIX_3 "PROGRESS with cause code %d received\n", e->proceeding.cause);
8913 /* Work around broken, out of spec USER_BUSY cause in a progress message */
8914 if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
8915 if (pri->pvts[chanpos]->owner) {
8916 if (option_verbose > 2)
8917 ast_verbose(VERBOSE_PREFIX_3 "PROGRESS with 'user busy' received, signaling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
8919 pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
8920 f.subclass = AST_CONTROL_BUSY;
8925 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8926 ast_log(LOG_DEBUG, "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
8927 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
8928 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8929 #ifdef PRI_PROGRESS_MASK
8930 if (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE) {
8931 #else
8932 if (e->proceeding.progress == 8) {
8933 #endif
8934 /* Now we can do call progress detection */
8935 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
8936 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
8937 pri->pvts[chanpos]->dsp_features = 0;
8940 pri->pvts[chanpos]->progress = 1;
8941 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8944 break;
8945 case PRI_EVENT_PROCEEDING:
8946 chanpos = pri_find_principle(pri, e->proceeding.channel);
8947 if (chanpos > -1) {
8948 if (!pri->pvts[chanpos]->proceeding) {
8949 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROCEEDING, };
8951 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8952 ast_log(LOG_DEBUG, "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
8953 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
8954 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8955 #ifdef PRI_PROGRESS_MASK
8956 if (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE) {
8957 #else
8958 if (e->proceeding.progress == 8) {
8959 #endif
8960 /* Now we can do call progress detection */
8961 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
8962 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
8963 pri->pvts[chanpos]->dsp_features = 0;
8965 /* Bring voice path up */
8966 f.subclass = AST_CONTROL_PROGRESS;
8967 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8969 pri->pvts[chanpos]->proceeding = 1;
8970 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8973 break;
8974 case PRI_EVENT_FACNAME:
8975 chanpos = pri_find_principle(pri, e->facname.channel);
8976 if (chanpos < 0) {
8977 ast_log(LOG_WARNING, "Facility Name requested on unconfigured channel %d/%d span %d\n",
8978 PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
8979 } else {
8980 chanpos = pri_fixup_principle(pri, chanpos, e->facname.call);
8981 if (chanpos < 0) {
8982 ast_log(LOG_WARNING, "Facility Name requested on channel %d/%d not in use on span %d\n",
8983 PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
8984 } else {
8985 /* Re-use *69 field for PRI */
8986 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8987 ast_copy_string(pri->pvts[chanpos]->lastcid_num, e->facname.callingnum, sizeof(pri->pvts[chanpos]->lastcid_num));
8988 ast_copy_string(pri->pvts[chanpos]->lastcid_name, e->facname.callingname, sizeof(pri->pvts[chanpos]->lastcid_name));
8989 pri->pvts[chanpos]->subs[SUB_REAL].needcallerid =1;
8990 zt_enable_ec(pri->pvts[chanpos]);
8991 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8994 break;
8995 case PRI_EVENT_ANSWER:
8996 chanpos = pri_find_principle(pri, e->answer.channel);
8997 if (chanpos < 0) {
8998 ast_log(LOG_WARNING, "Answer on unconfigured channel %d/%d span %d\n",
8999 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
9000 } else {
9001 chanpos = pri_fixup_principle(pri, chanpos, e->answer.call);
9002 if (chanpos < 0) {
9003 ast_log(LOG_WARNING, "Answer requested on channel %d/%d not in use on span %d\n",
9004 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
9005 } else {
9006 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9007 /* Now we can do call progress detection */
9009 /* We changed this so it turns on the DSP no matter what... progress or no progress.
9010 * By this time, we need DTMF detection and other features that were previously disabled
9011 * -- Matt F */
9012 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
9013 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
9014 pri->pvts[chanpos]->dsp_features = 0;
9016 if (pri->pvts[chanpos]->realcall && (pri->pvts[chanpos]->realcall->sig == SIG_FXSKS)) {
9017 ast_log(LOG_DEBUG, "Starting up GR-303 trunk now that we got CONNECT...\n");
9018 x = ZT_START;
9019 res = ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_HOOK, &x);
9020 if (res < 0) {
9021 if (errno != EINPROGRESS) {
9022 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
9025 } else if (!ast_strlen_zero(pri->pvts[chanpos]->dop.dialstr)) {
9026 pri->pvts[chanpos]->dialing = 1;
9027 /* Send any "w" waited stuff */
9028 res = ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_DIAL, &pri->pvts[chanpos]->dop);
9029 if (res < 0) {
9030 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", pri->pvts[chanpos]->channel);
9031 pri->pvts[chanpos]->dop.dialstr[0] = '\0';
9032 } else
9033 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", pri->pvts[chanpos]->dop.dialstr);
9034 pri->pvts[chanpos]->dop.dialstr[0] = '\0';
9035 } else if (pri->pvts[chanpos]->confirmanswer) {
9036 ast_log(LOG_DEBUG, "Waiting on answer confirmation on channel %d!\n", pri->pvts[chanpos]->channel);
9037 } else {
9038 pri->pvts[chanpos]->subs[SUB_REAL].needanswer =1;
9039 /* Enable echo cancellation if it's not on already */
9040 zt_enable_ec(pri->pvts[chanpos]);
9043 #ifdef SUPPORT_USERUSER
9044 if (!ast_strlen_zero(e->answer.useruserinfo)) {
9045 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->answer.useruserinfo);
9047 #endif
9049 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9052 break;
9053 case PRI_EVENT_HANGUP:
9054 chanpos = pri_find_principle(pri, e->hangup.channel);
9055 if (chanpos < 0) {
9056 ast_log(LOG_WARNING, "Hangup requested on unconfigured channel %d/%d span %d\n",
9057 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9058 } else {
9059 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9060 if (chanpos > -1) {
9061 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9062 if (!pri->pvts[chanpos]->alreadyhungup) {
9063 /* we're calling here zt_hangup so once we get there we need to clear p->call after calling pri_hangup */
9064 pri->pvts[chanpos]->alreadyhungup = 1;
9065 if (pri->pvts[chanpos]->realcall)
9066 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9067 else if (pri->pvts[chanpos]->owner) {
9068 /* Queue a BUSY instead of a hangup if our cause is appropriate */
9069 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
9070 switch (e->hangup.cause) {
9071 case PRI_CAUSE_USER_BUSY:
9072 pri->pvts[chanpos]->subs[SUB_REAL].needbusy =1;
9073 break;
9074 case PRI_CAUSE_CALL_REJECTED:
9075 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
9076 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
9077 case PRI_CAUSE_SWITCH_CONGESTION:
9078 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
9079 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
9080 pri->pvts[chanpos]->subs[SUB_REAL].needcongestion =1;
9081 break;
9082 default:
9083 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9086 if (option_verbose > 2)
9087 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d got hangup\n",
9088 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
9089 } else {
9090 pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
9091 pri->pvts[chanpos]->call = NULL;
9093 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
9094 if (option_verbose > 2)
9095 ast_verbose(VERBOSE_PREFIX_3 "Forcing restart of channel %d/%d on span %d since channel reported in use\n",
9096 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9097 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
9098 pri->pvts[chanpos]->resetting = 1;
9100 if (e->hangup.aoc_units > -1)
9101 if (option_verbose > 2)
9102 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
9103 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
9105 #ifdef SUPPORT_USERUSER
9106 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
9107 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->hangup.useruserinfo);
9109 #endif
9111 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9112 } else {
9113 ast_log(LOG_WARNING, "Hangup on bad channel %d/%d on span %d\n",
9114 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9117 break;
9118 #ifndef PRI_EVENT_HANGUP_REQ
9119 #error please update libpri
9120 #endif
9121 case PRI_EVENT_HANGUP_REQ:
9122 chanpos = pri_find_principle(pri, e->hangup.channel);
9123 if (chanpos < 0) {
9124 ast_log(LOG_WARNING, "Hangup REQ requested on unconfigured channel %d/%d span %d\n",
9125 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9126 } else {
9127 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9128 if (chanpos > -1) {
9129 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9130 if (pri->pvts[chanpos]->realcall)
9131 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9132 else if (pri->pvts[chanpos]->owner) {
9133 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
9134 switch (e->hangup.cause) {
9135 case PRI_CAUSE_USER_BUSY:
9136 pri->pvts[chanpos]->subs[SUB_REAL].needbusy =1;
9137 break;
9138 case PRI_CAUSE_CALL_REJECTED:
9139 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
9140 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
9141 case PRI_CAUSE_SWITCH_CONGESTION:
9142 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
9143 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
9144 pri->pvts[chanpos]->subs[SUB_REAL].needcongestion =1;
9145 break;
9146 default:
9147 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9149 if (option_verbose > 2)
9150 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);
9151 if (e->hangup.aoc_units > -1)
9152 if (option_verbose > 2)
9153 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
9154 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
9155 } else {
9156 pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
9157 pri->pvts[chanpos]->call = NULL;
9159 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
9160 if (option_verbose > 2)
9161 ast_verbose(VERBOSE_PREFIX_3 "Forcing restart of channel %d/%d span %d since channel reported in use\n",
9162 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9163 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
9164 pri->pvts[chanpos]->resetting = 1;
9167 #ifdef SUPPORT_USERUSER
9168 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
9169 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->hangup.useruserinfo);
9171 #endif
9173 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9174 } else {
9175 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);
9178 break;
9179 case PRI_EVENT_HANGUP_ACK:
9180 chanpos = pri_find_principle(pri, e->hangup.channel);
9181 if (chanpos < 0) {
9182 ast_log(LOG_WARNING, "Hangup ACK requested on unconfigured channel number %d/%d span %d\n",
9183 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9184 } else {
9185 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9186 if (chanpos > -1) {
9187 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9188 pri->pvts[chanpos]->call = NULL;
9189 pri->pvts[chanpos]->resetting = 0;
9190 if (pri->pvts[chanpos]->owner) {
9191 if (option_verbose > 2)
9192 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);
9195 #ifdef SUPPORT_USERUSER
9196 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
9197 pbx_builtin_setvar_helper(pri->pvts[chanpos]->owner, "USERUSERINFO", e->hangup.useruserinfo);
9199 #endif
9201 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9204 break;
9205 case PRI_EVENT_CONFIG_ERR:
9206 ast_log(LOG_WARNING, "PRI Error on span %d: %s\n", pri->trunkgroup, e->err.err);
9207 break;
9208 case PRI_EVENT_RESTART_ACK:
9209 chanpos = pri_find_principle(pri, e->restartack.channel);
9210 if (chanpos < 0) {
9211 /* Sometime switches (e.g. I421 / British Telecom) don't give us the
9212 channel number, so we have to figure it out... This must be why
9213 everybody resets exactly a channel at a time. */
9214 for (x = 0; x < pri->numchans; x++) {
9215 if (pri->pvts[x] && pri->pvts[x]->resetting) {
9216 chanpos = x;
9217 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9218 ast_log(LOG_DEBUG, "Assuming restart ack is really for channel %d/%d span %d\n", pri->pvts[chanpos]->logicalspan,
9219 pri->pvts[chanpos]->prioffset, pri->span);
9220 if (pri->pvts[chanpos]->realcall)
9221 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9222 else if (pri->pvts[chanpos]->owner) {
9223 ast_log(LOG_WARNING, "Got restart ack on channel %d/%d with owner on span %d\n", pri->pvts[chanpos]->logicalspan,
9224 pri->pvts[chanpos]->prioffset, pri->span);
9225 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9227 pri->pvts[chanpos]->resetting = 0;
9228 if (option_verbose > 2)
9229 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
9230 pri->pvts[chanpos]->prioffset, pri->span);
9231 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9232 if (pri->resetting)
9233 pri_check_restart(pri);
9234 break;
9237 if (chanpos < 0) {
9238 ast_log(LOG_WARNING, "Restart ACK requested on strange channel %d/%d span %d\n",
9239 PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
9241 } else {
9242 if (pri->pvts[chanpos]) {
9243 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9244 if (pri->pvts[chanpos]->realcall)
9245 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9246 else if (pri->pvts[chanpos]->owner) {
9247 ast_log(LOG_WARNING, "Got restart ack on channel %d/%d span %d with owner\n",
9248 PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
9249 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9251 pri->pvts[chanpos]->resetting = 0;
9252 if (option_verbose > 2)
9253 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
9254 pri->pvts[chanpos]->prioffset, pri->span);
9255 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9256 if (pri->resetting)
9257 pri_check_restart(pri);
9260 break;
9261 case PRI_EVENT_SETUP_ACK:
9262 chanpos = pri_find_principle(pri, e->setup_ack.channel);
9263 if (chanpos < 0) {
9264 ast_log(LOG_WARNING, "Received SETUP_ACKNOWLEDGE on unconfigured channel %d/%d span %d\n",
9265 PRI_SPAN(e->setup_ack.channel), PRI_CHANNEL(e->setup_ack.channel), pri->span);
9266 } else {
9267 chanpos = pri_fixup_principle(pri, chanpos, e->setup_ack.call);
9268 if (chanpos > -1) {
9269 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9270 pri->pvts[chanpos]->setup_ack = 1;
9271 /* Send any queued digits */
9272 for (x = 0;x < strlen(pri->pvts[chanpos]->dialdest); x++) {
9273 ast_log(LOG_DEBUG, "Sending pending digit '%c'\n", pri->pvts[chanpos]->dialdest[x]);
9274 pri_information(pri->pri, pri->pvts[chanpos]->call,
9275 pri->pvts[chanpos]->dialdest[x]);
9277 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9278 } else
9279 ast_log(LOG_WARNING, "Unable to move channel %d!\n", e->setup_ack.channel);
9281 break;
9282 case PRI_EVENT_NOTIFY:
9283 chanpos = pri_find_principle(pri, e->notify.channel);
9284 if (chanpos < 0) {
9285 ast_log(LOG_WARNING, "Received NOTIFY on unconfigured channel %d/%d span %d\n",
9286 PRI_SPAN(e->notify.channel), PRI_CHANNEL(e->notify.channel), pri->span);
9287 } else {
9288 struct ast_frame f = { AST_FRAME_CONTROL, };
9289 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9290 switch (e->notify.info) {
9291 case PRI_NOTIFY_REMOTE_HOLD:
9292 f.subclass = AST_CONTROL_HOLD;
9293 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9294 break;
9295 case PRI_NOTIFY_REMOTE_RETRIEVAL:
9296 f.subclass = AST_CONTROL_UNHOLD;
9297 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9298 break;
9300 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9302 break;
9303 default:
9304 ast_log(LOG_DEBUG, "Event: %d\n", e->e);
9307 ast_mutex_unlock(&pri->lock);
9309 /* Never reached */
9310 return NULL;
9313 static int start_pri(struct zt_pri *pri)
9315 int res, x;
9316 ZT_PARAMS p;
9317 ZT_BUFFERINFO bi;
9318 struct zt_spaninfo si;
9319 int i;
9321 for (i = 0; i < NUM_DCHANS; i++) {
9322 if (!pri->dchannels[i])
9323 break;
9324 pri->fds[i] = open("/dev/zap/channel", O_RDWR, 0600);
9325 x = pri->dchannels[i];
9326 if ((pri->fds[i] < 0) || (ioctl(pri->fds[i],ZT_SPECIFY,&x) == -1)) {
9327 ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
9328 return -1;
9330 res = ioctl(pri->fds[i], ZT_GET_PARAMS, &p);
9331 if (res) {
9332 zt_close(pri->fds[i]);
9333 pri->fds[i] = -1;
9334 ast_log(LOG_ERROR, "Unable to get parameters for D-channel %d (%s)\n", x, strerror(errno));
9335 return -1;
9337 if ((p.sigtype != ZT_SIG_HDLCFCS) && (p.sigtype != ZT_SIG_HARDHDLC)) {
9338 zt_close(pri->fds[i]);
9339 pri->fds[i] = -1;
9340 ast_log(LOG_ERROR, "D-channel %d is not in HDLC/FCS mode. See /etc/zaptel.conf\n", x);
9341 return -1;
9343 memset(&si, 0, sizeof(si));
9344 res = ioctl(pri->fds[i], ZT_SPANSTAT, &si);
9345 if (res) {
9346 zt_close(pri->fds[i]);
9347 pri->fds[i] = -1;
9348 ast_log(LOG_ERROR, "Unable to get span state for D-channel %d (%s)\n", x, strerror(errno));
9350 if (!si.alarms)
9351 pri->dchanavail[i] |= DCHAN_NOTINALARM;
9352 else
9353 pri->dchanavail[i] &= ~DCHAN_NOTINALARM;
9354 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
9355 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
9356 bi.numbufs = 32;
9357 bi.bufsize = 1024;
9358 if (ioctl(pri->fds[i], ZT_SET_BUFINFO, &bi)) {
9359 ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d\n", x);
9360 zt_close(pri->fds[i]);
9361 pri->fds[i] = -1;
9362 return -1;
9364 pri->dchans[i] = pri_new(pri->fds[i], pri->nodetype, pri->switchtype);
9365 /* Force overlap dial if we're doing GR-303! */
9366 if (pri->switchtype == PRI_SWITCH_GR303_TMC)
9367 pri->overlapdial = 1;
9368 pri_set_overlapdial(pri->dchans[i],pri->overlapdial);
9369 /* Enslave to master if appropriate */
9370 if (i)
9371 pri_enslave(pri->dchans[0], pri->dchans[i]);
9372 if (!pri->dchans[i]) {
9373 zt_close(pri->fds[i]);
9374 pri->fds[i] = -1;
9375 ast_log(LOG_ERROR, "Unable to create PRI structure\n");
9376 return -1;
9378 pri_set_debug(pri->dchans[i], DEFAULT_PRI_DEBUG);
9379 pri_set_nsf(pri->dchans[i], pri->nsf);
9380 #ifdef PRI_GETSET_TIMERS
9381 for (x = 0; x < PRI_MAX_TIMERS; x++) {
9382 if (pritimers[x] != 0)
9383 pri_set_timer(pri->dchans[i], x, pritimers[x]);
9385 #endif
9387 /* Assume primary is the one we use */
9388 pri->pri = pri->dchans[0];
9389 pri->resetpos = -1;
9390 if (ast_pthread_create_background(&pri->master, NULL, pri_dchannel, pri)) {
9391 for (i = 0; i < NUM_DCHANS; i++) {
9392 if (!pri->dchannels[i])
9393 break;
9394 zt_close(pri->fds[i]);
9395 pri->fds[i] = -1;
9397 ast_log(LOG_ERROR, "Unable to spawn D-channel: %s\n", strerror(errno));
9398 return -1;
9400 return 0;
9403 static char *complete_span_helper(const char *line, const char *word, int pos, int state, int rpos)
9405 int which, span;
9406 char *ret = NULL;
9408 if (pos != rpos)
9409 return ret;
9411 for (which = span = 0; span < NUM_SPANS; span++) {
9412 if (pris[span].pri && ++which > state) {
9413 asprintf(&ret, "%d", span + 1); /* user indexes start from 1 */
9414 break;
9417 return ret;
9420 static char *complete_span_4(const char *line, const char *word, int pos, int state)
9422 return complete_span_helper(line,word,pos,state,3);
9425 static char *complete_span_5(const char *line, const char *word, int pos, int state)
9427 return complete_span_helper(line,word,pos,state,4);
9430 static int handle_pri_set_debug_file(int fd, int argc, char **argv)
9432 int myfd;
9434 if (!strncasecmp(argv[1], "set", 3)) {
9435 if (argc < 5)
9436 return RESULT_SHOWUSAGE;
9438 if (ast_strlen_zero(argv[4]))
9439 return RESULT_SHOWUSAGE;
9441 myfd = open(argv[4], O_CREAT|O_WRONLY);
9442 if (myfd < 0) {
9443 ast_cli(fd, "Unable to open '%s' for writing\n", argv[4]);
9444 return RESULT_SUCCESS;
9447 ast_mutex_lock(&pridebugfdlock);
9449 if (pridebugfd >= 0)
9450 close(pridebugfd);
9452 pridebugfd = myfd;
9453 ast_copy_string(pridebugfilename,argv[4],sizeof(pridebugfilename));
9455 ast_mutex_unlock(&pridebugfdlock);
9457 ast_cli(fd, "PRI debug output will be sent to '%s'\n", argv[4]);
9458 } else {
9459 /* Assume it is unset */
9460 ast_mutex_lock(&pridebugfdlock);
9461 close(pridebugfd);
9462 pridebugfd = -1;
9463 ast_cli(fd, "PRI debug output to file disabled\n");
9464 ast_mutex_unlock(&pridebugfdlock);
9467 return RESULT_SUCCESS;
9470 static int handle_pri_debug(int fd, int argc, char *argv[])
9472 int span;
9473 int x;
9474 if (argc < 4) {
9475 return RESULT_SHOWUSAGE;
9477 span = atoi(argv[3]);
9478 if ((span < 1) || (span > NUM_SPANS)) {
9479 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[3], 1, NUM_SPANS);
9480 return RESULT_SUCCESS;
9482 if (!pris[span-1].pri) {
9483 ast_cli(fd, "No PRI running on span %d\n", span);
9484 return RESULT_SUCCESS;
9486 for (x = 0; x < NUM_DCHANS; x++) {
9487 if (pris[span-1].dchans[x])
9488 pri_set_debug(pris[span-1].dchans[x], PRI_DEBUG_APDU |
9489 PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q931_STATE |
9490 PRI_DEBUG_Q921_STATE);
9492 ast_cli(fd, "Enabled debugging on span %d\n", span);
9493 return RESULT_SUCCESS;
9498 static int handle_pri_no_debug(int fd, int argc, char *argv[])
9500 int span;
9501 int x;
9502 if (argc < 5)
9503 return RESULT_SHOWUSAGE;
9504 span = atoi(argv[4]);
9505 if ((span < 1) || (span > NUM_SPANS)) {
9506 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[4], 1, NUM_SPANS);
9507 return RESULT_SUCCESS;
9509 if (!pris[span-1].pri) {
9510 ast_cli(fd, "No PRI running on span %d\n", span);
9511 return RESULT_SUCCESS;
9513 for (x = 0; x < NUM_DCHANS; x++) {
9514 if (pris[span-1].dchans[x])
9515 pri_set_debug(pris[span-1].dchans[x], 0);
9517 ast_cli(fd, "Disabled debugging on span %d\n", span);
9518 return RESULT_SUCCESS;
9521 static int handle_pri_really_debug(int fd, int argc, char *argv[])
9523 int span;
9524 int x;
9525 if (argc < 5)
9526 return RESULT_SHOWUSAGE;
9527 span = atoi(argv[4]);
9528 if ((span < 1) || (span > NUM_SPANS)) {
9529 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[4], 1, NUM_SPANS);
9530 return RESULT_SUCCESS;
9532 if (!pris[span-1].pri) {
9533 ast_cli(fd, "No PRI running on span %d\n", span);
9534 return RESULT_SUCCESS;
9536 for (x = 0; x < NUM_DCHANS; x++) {
9537 if (pris[span-1].dchans[x])
9538 pri_set_debug(pris[span-1].dchans[x], PRI_DEBUG_APDU |
9539 PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q931_STATE |
9540 PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_STATE);
9542 ast_cli(fd, "Enabled EXTENSIVE debugging on span %d\n", span);
9543 return RESULT_SUCCESS;
9546 static void build_status(char *s, size_t len, int status, int active)
9548 if (!s || len < 1) {
9549 return;
9551 s[0] = '\0';
9552 if (status & DCHAN_PROVISIONED)
9553 strncat(s, "Provisioned, ", len - strlen(s) - 1);
9554 if (!(status & DCHAN_NOTINALARM))
9555 strncat(s, "In Alarm, ", len - strlen(s) - 1);
9556 if (status & DCHAN_UP)
9557 strncat(s, "Up", len - strlen(s) - 1);
9558 else
9559 strncat(s, "Down", len - strlen(s) - 1);
9560 if (active)
9561 strncat(s, ", Active", len - strlen(s) - 1);
9562 else
9563 strncat(s, ", Standby", len - strlen(s) - 1);
9564 s[len - 1] = '\0';
9567 static int handle_pri_show_spans(int fd, int argc, char *argv[])
9569 int span;
9570 int x;
9571 char status[256];
9572 if (argc != 3)
9573 return RESULT_SHOWUSAGE;
9575 for (span = 0; span < NUM_SPANS; span++) {
9576 if (pris[span].pri) {
9577 for (x = 0; x < NUM_DCHANS; x++) {
9578 if (pris[span].dchannels[x]) {
9579 build_status(status, sizeof(status), pris[span].dchanavail[x], pris[span].dchans[x] == pris[span].pri);
9580 ast_cli(fd, "PRI span %d/%d: %s\n", span + 1, x, status);
9585 return RESULT_SUCCESS;
9588 static int handle_pri_show_span(int fd, int argc, char *argv[])
9590 int span;
9591 int x;
9592 char status[256];
9593 if (argc < 4)
9594 return RESULT_SHOWUSAGE;
9595 span = atoi(argv[3]);
9596 if ((span < 1) || (span > NUM_SPANS)) {
9597 ast_cli(fd, "Invalid span '%s'. Should be a number from %d to %d\n", argv[3], 1, NUM_SPANS);
9598 return RESULT_SUCCESS;
9600 if (!pris[span-1].pri) {
9601 ast_cli(fd, "No PRI running on span %d\n", span);
9602 return RESULT_SUCCESS;
9604 for (x = 0; x < NUM_DCHANS; x++) {
9605 if (pris[span-1].dchannels[x]) {
9606 #ifdef PRI_DUMP_INFO_STR
9607 char *info_str = NULL;
9608 #endif
9609 ast_cli(fd, "%s D-channel: %d\n", pri_order(x), pris[span-1].dchannels[x]);
9610 build_status(status, sizeof(status), pris[span-1].dchanavail[x], pris[span-1].dchans[x] == pris[span-1].pri);
9611 ast_cli(fd, "Status: %s\n", status);
9612 #ifdef PRI_DUMP_INFO_STR
9613 info_str = pri_dump_info_str(pris[span-1].pri);
9614 if (info_str) {
9615 ast_cli(fd, "%s", info_str);
9616 free(info_str);
9618 #else
9619 pri_dump_info(pris[span-1].pri);
9620 #endif
9621 ast_cli(fd, "\n");
9624 return RESULT_SUCCESS;
9627 static int handle_pri_show_debug(int fd, int argc, char *argv[])
9629 int x;
9630 int span;
9631 int count=0;
9632 int debug=0;
9634 for (span = 0; span < NUM_SPANS; span++) {
9635 if (pris[span].pri) {
9636 for (x = 0; x < NUM_DCHANS; x++) {
9637 debug = 0;
9638 if (pris[span].dchans[x]) {
9639 debug = pri_get_debug(pris[span].dchans[x]);
9640 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" );
9641 count++;
9647 ast_mutex_lock(&pridebugfdlock);
9648 if (pridebugfd >= 0)
9649 ast_cli(fd, "Logging PRI debug to file %s\n", pridebugfilename);
9650 ast_mutex_unlock(&pridebugfdlock);
9652 if (!count)
9653 ast_cli(fd, "No debug set or no PRI running\n");
9654 return RESULT_SUCCESS;
9657 static const char pri_debug_help[] =
9658 "Usage: pri debug span <span>\n"
9659 " Enables debugging on a given PRI span\n";
9661 static const char pri_no_debug_help[] =
9662 "Usage: pri no debug span <span>\n"
9663 " Disables debugging on a given PRI span\n";
9665 static const char pri_really_debug_help[] =
9666 "Usage: pri intensive debug span <span>\n"
9667 " Enables debugging down to the Q.921 level\n";
9669 static const char pri_show_span_help[] =
9670 "Usage: pri show span <span>\n"
9671 " Displays PRI Information on a given PRI span\n";
9673 static const char pri_show_spans_help[] =
9674 "Usage: pri show spans\n"
9675 " Displays PRI Information\n";
9677 static struct ast_cli_entry zap_pri_cli[] = {
9678 { { "pri", "debug", "span", NULL },
9679 handle_pri_debug, "Enables PRI debugging on a span",
9680 pri_debug_help, complete_span_4 },
9682 { { "pri", "no", "debug", "span", NULL },
9683 handle_pri_no_debug, "Disables PRI debugging on a span",
9684 pri_no_debug_help, complete_span_5 },
9686 { { "pri", "intense", "debug", "span", NULL },
9687 handle_pri_really_debug, "Enables REALLY INTENSE PRI debugging",
9688 pri_really_debug_help, complete_span_5 },
9690 { { "pri", "show", "spans", NULL },
9691 handle_pri_show_spans, "Displays PRI Information",
9692 pri_show_spans_help },
9694 { { "pri", "show", "span", NULL },
9695 handle_pri_show_span, "Displays PRI Information",
9696 pri_show_span_help, complete_span_4 },
9698 { { "pri", "show", "debug", NULL },
9699 handle_pri_show_debug, "Displays current PRI debug settings" },
9701 { { "pri", "set", "debug", "file", NULL },
9702 handle_pri_set_debug_file, "Sends PRI debug output to the specified file" },
9704 { { "pri", "unset", "debug", "file", NULL },
9705 handle_pri_set_debug_file, "Ends PRI debug output to file" },
9708 #endif /* HAVE_PRI */
9710 static int zap_destroy_channel(int fd, int argc, char **argv)
9712 int channel;
9714 if (argc != 4)
9715 return RESULT_SHOWUSAGE;
9717 channel = atoi(argv[3]);
9719 return zap_destroy_channel_bynum(channel);
9722 static int setup_zap(int reload);
9723 static int zap_restart(void)
9725 if (option_verbose > 0)
9726 ast_verbose(VERBOSE_PREFIX_1 "Destroying channels and reloading zaptel configuration.\n");
9727 while (iflist) {
9728 if (option_debug)
9729 ast_log(LOG_DEBUG, "Destroying zaptel channel no. %d\n", iflist->channel);
9730 /* Also updates iflist: */
9731 destroy_channel(NULL, iflist, 1);
9733 if (option_debug)
9734 ast_log(LOG_DEBUG, "Channels destroyed. Now re-reading config.\n");
9735 if (setup_zap(0) != 0) {
9736 ast_log(LOG_WARNING, "Reload channels from zap config failed!\n");
9737 return 1;
9739 return 0;
9742 static int zap_restart_cmd(int fd, int argc, char **argv)
9744 if (argc != 2) {
9745 return RESULT_SHOWUSAGE;
9748 if (zap_restart() != 0)
9749 return RESULT_FAILURE;
9750 return RESULT_SUCCESS;
9753 static int action_zaprestart(struct mansession *s, const struct message *m)
9755 if (zap_restart() != 0) {
9756 astman_send_error(s, m, "Failed rereading zaptel configuration");
9757 return 1;
9759 astman_send_ack(s, m, "ZapRestart: Success");
9760 return 0;
9763 static int zap_show_channels(int fd, int argc, char **argv)
9765 #define FORMAT "%7s %-10.10s %-15.15s %-10.10s %-20.20s\n"
9766 #define FORMAT2 "%7s %-10.10s %-15.15s %-10.10s %-20.20s\n"
9767 struct zt_pvt *tmp = NULL;
9768 char tmps[20] = "";
9769 ast_mutex_t *lock;
9770 struct zt_pvt *start;
9771 #ifdef HAVE_PRI
9772 int trunkgroup;
9773 struct zt_pri *pri = NULL;
9774 int x;
9775 #endif
9777 lock = &iflock;
9778 start = iflist;
9780 #ifdef HAVE_PRI
9781 if (argc == 4) {
9782 if ((trunkgroup = atoi(argv[3])) < 1)
9783 return RESULT_SHOWUSAGE;
9784 for (x = 0; x < NUM_SPANS; x++) {
9785 if (pris[x].trunkgroup == trunkgroup) {
9786 pri = pris + x;
9787 break;
9790 if (pri) {
9791 start = pri->crvs;
9792 lock = &pri->lock;
9793 } else {
9794 ast_cli(fd, "No such trunk group %d\n", trunkgroup);
9795 return RESULT_FAILURE;
9797 } else
9798 #endif
9799 if (argc != 3)
9800 return RESULT_SHOWUSAGE;
9802 ast_mutex_lock(lock);
9803 #ifdef HAVE_PRI
9804 ast_cli(fd, FORMAT2, pri ? "CRV" : "Chan", "Extension", "Context", "Language", "MOH Interpret");
9805 #else
9806 ast_cli(fd, FORMAT2, "Chan", "Extension", "Context", "Language", "MOH Interpret");
9807 #endif
9809 tmp = start;
9810 while (tmp) {
9811 if (tmp->channel > 0) {
9812 snprintf(tmps, sizeof(tmps), "%d", tmp->channel);
9813 } else
9814 ast_copy_string(tmps, "pseudo", sizeof(tmps));
9815 ast_cli(fd, FORMAT, tmps, tmp->exten, tmp->context, tmp->language, tmp->mohinterpret);
9816 tmp = tmp->next;
9818 ast_mutex_unlock(lock);
9819 return RESULT_SUCCESS;
9820 #undef FORMAT
9821 #undef FORMAT2
9824 static int zap_show_channel(int fd, int argc, char **argv)
9826 int channel;
9827 struct zt_pvt *tmp = NULL;
9828 ZT_CONFINFO ci;
9829 ZT_PARAMS ps;
9830 int x;
9831 ast_mutex_t *lock;
9832 struct zt_pvt *start;
9833 #ifdef HAVE_PRI
9834 char *c;
9835 int trunkgroup;
9836 struct zt_pri *pri=NULL;
9837 #endif
9839 lock = &iflock;
9840 start = iflist;
9842 if (argc != 4)
9843 return RESULT_SHOWUSAGE;
9844 #ifdef HAVE_PRI
9845 if ((c = strchr(argv[3], ':'))) {
9846 if (sscanf(argv[3], "%d:%d", &trunkgroup, &channel) != 2)
9847 return RESULT_SHOWUSAGE;
9848 if ((trunkgroup < 1) || (channel < 1))
9849 return RESULT_SHOWUSAGE;
9850 for (x = 0; x < NUM_SPANS; x++) {
9851 if (pris[x].trunkgroup == trunkgroup) {
9852 pri = pris + x;
9853 break;
9856 if (pri) {
9857 start = pri->crvs;
9858 lock = &pri->lock;
9859 } else {
9860 ast_cli(fd, "No such trunk group %d\n", trunkgroup);
9861 return RESULT_FAILURE;
9863 } else
9864 #endif
9865 channel = atoi(argv[3]);
9867 ast_mutex_lock(lock);
9868 tmp = start;
9869 while (tmp) {
9870 if (tmp->channel == channel) {
9871 #ifdef HAVE_PRI
9872 if (pri)
9873 ast_cli(fd, "Trunk/CRV: %d/%d\n", trunkgroup, tmp->channel);
9874 else
9875 #endif
9876 ast_cli(fd, "Channel: %d\n", tmp->channel);
9877 ast_cli(fd, "File Descriptor: %d\n", tmp->subs[SUB_REAL].zfd);
9878 ast_cli(fd, "Span: %d\n", tmp->span);
9879 ast_cli(fd, "Extension: %s\n", tmp->exten);
9880 ast_cli(fd, "Dialing: %s\n", tmp->dialing ? "yes" : "no");
9881 ast_cli(fd, "Context: %s\n", tmp->context);
9882 ast_cli(fd, "Caller ID: %s\n", tmp->cid_num);
9883 ast_cli(fd, "Calling TON: %d\n", tmp->cid_ton);
9884 ast_cli(fd, "Caller ID name: %s\n", tmp->cid_name);
9885 ast_cli(fd, "Destroy: %d\n", tmp->destroy);
9886 ast_cli(fd, "InAlarm: %d\n", tmp->inalarm);
9887 ast_cli(fd, "Signalling Type: %s\n", sig2str(tmp->sig));
9888 ast_cli(fd, "Radio: %d\n", tmp->radio);
9889 ast_cli(fd, "Owner: %s\n", tmp->owner ? tmp->owner->name : "<None>");
9890 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)" : "");
9891 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)" : "");
9892 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)" : "");
9893 ast_cli(fd, "Confno: %d\n", tmp->confno);
9894 ast_cli(fd, "Propagated Conference: %d\n", tmp->propconfno);
9895 ast_cli(fd, "Real in conference: %d\n", tmp->inconference);
9896 ast_cli(fd, "DSP: %s\n", tmp->dsp ? "yes" : "no");
9897 ast_cli(fd, "Relax DTMF: %s\n", tmp->dtmfrelax ? "yes" : "no");
9898 ast_cli(fd, "Dialing/CallwaitCAS: %d/%d\n", tmp->dialing, tmp->callwaitcas);
9899 ast_cli(fd, "Default law: %s\n", tmp->law == ZT_LAW_MULAW ? "ulaw" : tmp->law == ZT_LAW_ALAW ? "alaw" : "unknown");
9900 ast_cli(fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
9901 ast_cli(fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
9902 ast_cli(fd, "Echo Cancellation: %d taps%s, currently %s\n", tmp->echocancel, tmp->echocanbridged ? "" : " unless TDM bridged", tmp->echocanon ? "ON" : "OFF");
9903 if (tmp->master)
9904 ast_cli(fd, "Master Channel: %d\n", tmp->master->channel);
9905 for (x = 0; x < MAX_SLAVES; x++) {
9906 if (tmp->slaves[x])
9907 ast_cli(fd, "Slave Channel: %d\n", tmp->slaves[x]->channel);
9909 #ifdef HAVE_PRI
9910 if (tmp->pri) {
9911 ast_cli(fd, "PRI Flags: ");
9912 if (tmp->resetting)
9913 ast_cli(fd, "Resetting ");
9914 if (tmp->call)
9915 ast_cli(fd, "Call ");
9916 if (tmp->bearer)
9917 ast_cli(fd, "Bearer ");
9918 ast_cli(fd, "\n");
9919 if (tmp->logicalspan)
9920 ast_cli(fd, "PRI Logical Span: %d\n", tmp->logicalspan);
9921 else
9922 ast_cli(fd, "PRI Logical Span: Implicit\n");
9925 #endif
9926 memset(&ci, 0, sizeof(ci));
9927 ps.channo = tmp->channel;
9928 if (tmp->subs[SUB_REAL].zfd > -1) {
9929 if (!ioctl(tmp->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
9930 ast_cli(fd, "Actual Confinfo: Num/%d, Mode/0x%04x\n", ci.confno, ci.confmode);
9932 #ifdef ZT_GETCONFMUTE
9933 if (!ioctl(tmp->subs[SUB_REAL].zfd, ZT_GETCONFMUTE, &x)) {
9934 ast_cli(fd, "Actual Confmute: %s\n", x ? "Yes" : "No");
9936 #endif
9937 if (ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps) < 0) {
9938 ast_log(LOG_WARNING, "Failed to get parameters on channel %d\n", tmp->channel);
9939 } else {
9940 ast_cli(fd, "Hookstate (FXS only): %s\n", ps.rxisoffhook ? "Offhook" : "Onhook");
9943 ast_mutex_unlock(lock);
9944 return RESULT_SUCCESS;
9946 tmp = tmp->next;
9949 ast_cli(fd, "Unable to find given channel %d\n", channel);
9950 ast_mutex_unlock(lock);
9951 return RESULT_FAILURE;
9954 static char zap_show_cadences_help[] =
9955 "Usage: zap show cadences\n"
9956 " Shows all cadences currently defined\n";
9958 static int handle_zap_show_cadences(int fd, int argc, char *argv[])
9960 int i, j;
9961 for (i = 0; i < num_cadence; i++) {
9962 char output[1024];
9963 char tmp[16], tmp2[64];
9964 snprintf(tmp, sizeof(tmp), "r%d: ", i + 1);
9965 term_color(output, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(output));
9967 for (j = 0; j < 16; j++) {
9968 if (cadences[i].ringcadence[j] == 0)
9969 break;
9970 snprintf(tmp, sizeof(tmp), "%d", cadences[i].ringcadence[j]);
9971 if (cidrings[i] * 2 - 1 == j)
9972 term_color(tmp2, tmp, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp2) - 1);
9973 else
9974 term_color(tmp2, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(tmp2) - 1);
9975 if (j != 0)
9976 strncat(output, ",", sizeof(output) - strlen(output) - 1);
9977 strncat(output, tmp2, sizeof(output) - strlen(output) - 1);
9979 ast_cli(fd,"%s\n",output);
9981 return 0;
9984 /* Based on irqmiss.c */
9985 static int zap_show_status(int fd, int argc, char *argv[]) {
9986 #define FORMAT "%-40.40s %-10.10s %-10d %-10d %-10d\n"
9987 #define FORMAT2 "%-40.40s %-10.10s %-10.10s %-10.10s %-10.10s\n"
9989 int span;
9990 int res;
9991 char alarms[50];
9993 int ctl;
9994 ZT_SPANINFO s;
9996 ctl = open("/dev/zap/ctl", O_RDWR);
9997 if (ctl < 0) {
9998 ast_log(LOG_WARNING, "Unable to open /dev/zap/ctl: %s\n", strerror(errno));
9999 ast_cli(fd, "No Zaptel interface found.\n");
10000 return RESULT_FAILURE;
10002 ast_cli(fd, FORMAT2, "Description", "Alarms", "IRQ", "bpviol", "CRC4");
10004 for (span = 1; span < ZT_MAX_SPANS; ++span) {
10005 s.spanno = span;
10006 res = ioctl(ctl, ZT_SPANSTAT, &s);
10007 if (res) {
10008 continue;
10010 alarms[0] = '\0';
10011 if (s.alarms > 0) {
10012 if (s.alarms & ZT_ALARM_BLUE)
10013 strcat(alarms, "BLU/");
10014 if (s.alarms & ZT_ALARM_YELLOW)
10015 strcat(alarms, "YEL/");
10016 if (s.alarms & ZT_ALARM_RED)
10017 strcat(alarms, "RED/");
10018 if (s.alarms & ZT_ALARM_LOOPBACK)
10019 strcat(alarms, "LB/");
10020 if (s.alarms & ZT_ALARM_RECOVER)
10021 strcat(alarms, "REC/");
10022 if (s.alarms & ZT_ALARM_NOTOPEN)
10023 strcat(alarms, "NOP/");
10024 if (!strlen(alarms))
10025 strcat(alarms, "UUU/");
10026 if (strlen(alarms)) {
10027 /* Strip trailing / */
10028 alarms[strlen(alarms) - 1] = '\0';
10030 } else {
10031 if (s.numchans)
10032 strcpy(alarms, "OK");
10033 else
10034 strcpy(alarms, "UNCONFIGURED");
10037 ast_cli(fd, FORMAT, s.desc, alarms, s.irqmisses, s.bpvcount, s.crc4count);
10039 close(ctl);
10041 return RESULT_SUCCESS;
10042 #undef FORMAT
10043 #undef FORMAT2
10046 static char show_channels_usage[] =
10047 "Usage: zap show channels\n"
10048 " Shows a list of available channels\n";
10050 static char show_channel_usage[] =
10051 "Usage: zap show channel <chan num>\n"
10052 " Detailed information about a given channel\n";
10054 static char zap_show_status_usage[] =
10055 "Usage: zap show status\n"
10056 " Shows a list of Zaptel cards with status\n";
10058 static char destroy_channel_usage[] =
10059 "Usage: zap destroy channel <chan num>\n"
10060 " DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING. Immediately removes a given channel, whether it is in use or not\n";
10062 static char zap_restart_usage[] =
10063 "Usage: zap restart\n"
10064 " Restarts the zaptel channels: destroys them all and then\n"
10065 " re-reads them from zapata.conf.\n"
10066 " Note that this will STOP any running CALL on zaptel channels.\n"
10069 static struct ast_cli_entry zap_cli[] = {
10070 { { "zap", "show", "cadences", NULL },
10071 handle_zap_show_cadences, "List cadences",
10072 zap_show_cadences_help },
10074 { { "zap", "show", "channels", NULL},
10075 zap_show_channels, "Show active zapata channels",
10076 show_channels_usage },
10078 { { "zap", "show", "channel", NULL},
10079 zap_show_channel, "Show information on a channel",
10080 show_channel_usage },
10082 { { "zap", "destroy", "channel", NULL},
10083 zap_destroy_channel, "Destroy a channel",
10084 destroy_channel_usage },
10086 { { "zap", "restart", NULL},
10087 zap_restart_cmd, "Fully restart zaptel channels",
10088 zap_restart_usage },
10090 { { "zap", "show", "status", NULL},
10091 zap_show_status, "Show all Zaptel cards status",
10092 zap_show_status_usage },
10095 #define TRANSFER 0
10096 #define HANGUP 1
10098 static int zap_fake_event(struct zt_pvt *p, int mode)
10100 if (p) {
10101 switch (mode) {
10102 case TRANSFER:
10103 p->fake_event = ZT_EVENT_WINKFLASH;
10104 break;
10105 case HANGUP:
10106 p->fake_event = ZT_EVENT_ONHOOK;
10107 break;
10108 default:
10109 ast_log(LOG_WARNING, "I don't know how to handle transfer event with this: %d on channel %s\n",mode, p->owner->name);
10112 return 0;
10114 static struct zt_pvt *find_channel(int channel)
10116 struct zt_pvt *p = iflist;
10117 while (p) {
10118 if (p->channel == channel) {
10119 break;
10121 p = p->next;
10123 return p;
10126 static int action_zapdndon(struct mansession *s, const struct message *m)
10128 struct zt_pvt *p = NULL;
10129 const char *channel = astman_get_header(m, "ZapChannel");
10131 if (ast_strlen_zero(channel)) {
10132 astman_send_error(s, m, "No channel specified");
10133 return 0;
10135 p = find_channel(atoi(channel));
10136 if (!p) {
10137 astman_send_error(s, m, "No such channel");
10138 return 0;
10140 p->dnd = 1;
10141 astman_send_ack(s, m, "DND Enabled");
10142 return 0;
10145 static int action_zapdndoff(struct mansession *s, const struct message *m)
10147 struct zt_pvt *p = NULL;
10148 const char *channel = astman_get_header(m, "ZapChannel");
10150 if (ast_strlen_zero(channel)) {
10151 astman_send_error(s, m, "No channel specified");
10152 return 0;
10154 p = find_channel(atoi(channel));
10155 if (!p) {
10156 astman_send_error(s, m, "No such channel");
10157 return 0;
10159 p->dnd = 0;
10160 astman_send_ack(s, m, "DND Disabled");
10161 return 0;
10164 static int action_transfer(struct mansession *s, const struct message *m)
10166 struct zt_pvt *p = NULL;
10167 const char *channel = astman_get_header(m, "ZapChannel");
10169 if (ast_strlen_zero(channel)) {
10170 astman_send_error(s, m, "No channel specified");
10171 return 0;
10173 p = find_channel(atoi(channel));
10174 if (!p) {
10175 astman_send_error(s, m, "No such channel");
10176 return 0;
10178 zap_fake_event(p,TRANSFER);
10179 astman_send_ack(s, m, "ZapTransfer");
10180 return 0;
10183 static int action_transferhangup(struct mansession *s, const struct message *m)
10185 struct zt_pvt *p = NULL;
10186 const char *channel = astman_get_header(m, "ZapChannel");
10188 if (ast_strlen_zero(channel)) {
10189 astman_send_error(s, m, "No channel specified");
10190 return 0;
10192 p = find_channel(atoi(channel));
10193 if (!p) {
10194 astman_send_error(s, m, "No such channel");
10195 return 0;
10197 zap_fake_event(p,HANGUP);
10198 astman_send_ack(s, m, "ZapHangup");
10199 return 0;
10202 static int action_zapdialoffhook(struct mansession *s, const struct message *m)
10204 struct zt_pvt *p = NULL;
10205 const char *channel = astman_get_header(m, "ZapChannel");
10206 const char *number = astman_get_header(m, "Number");
10207 int i;
10209 if (ast_strlen_zero(channel)) {
10210 astman_send_error(s, m, "No channel specified");
10211 return 0;
10213 if (ast_strlen_zero(number)) {
10214 astman_send_error(s, m, "No number specified");
10215 return 0;
10217 p = find_channel(atoi(channel));
10218 if (!p) {
10219 astman_send_error(s, m, "No such channel");
10220 return 0;
10222 if (!p->owner) {
10223 astman_send_error(s, m, "Channel does not have it's owner");
10224 return 0;
10226 for (i = 0; i < strlen(number); i++) {
10227 struct ast_frame f = { AST_FRAME_DTMF, number[i] };
10228 zap_queue_frame(p, &f, NULL);
10230 astman_send_ack(s, m, "ZapDialOffhook");
10231 return 0;
10234 static int action_zapshowchannels(struct mansession *s, const struct message *m)
10236 struct zt_pvt *tmp = NULL;
10237 const char *id = astman_get_header(m, "ActionID");
10238 char idText[256] = "";
10240 astman_send_ack(s, m, "Zapata channel status will follow");
10241 if (!ast_strlen_zero(id))
10242 snprintf(idText, sizeof(idText) - 1, "ActionID: %s\r\n", id);
10244 ast_mutex_lock(&iflock);
10246 tmp = iflist;
10247 while (tmp) {
10248 if (tmp->channel > 0) {
10249 int alarm = get_alarms(tmp);
10250 astman_append(s,
10251 "Event: ZapShowChannels\r\n"
10252 "Channel: %d\r\n"
10253 "Signalling: %s\r\n"
10254 "Context: %s\r\n"
10255 "DND: %s\r\n"
10256 "Alarm: %s\r\n"
10257 "%s"
10258 "\r\n",
10259 tmp->channel, sig2str(tmp->sig), tmp->context,
10260 tmp->dnd ? "Enabled" : "Disabled",
10261 alarm2str(alarm), idText);
10264 tmp = tmp->next;
10267 ast_mutex_unlock(&iflock);
10269 astman_append(s,
10270 "Event: ZapShowChannelsComplete\r\n"
10271 "%s"
10272 "\r\n",
10273 idText);
10274 return 0;
10277 static int __unload_module(void)
10279 int x = 0;
10280 struct zt_pvt *p, *pl;
10281 #ifdef HAVE_PRI
10282 int i;
10283 for (i = 0; i < NUM_SPANS; i++) {
10284 if (pris[i].master != AST_PTHREADT_NULL)
10285 pthread_cancel(pris[i].master);
10287 ast_cli_unregister_multiple(zap_pri_cli, sizeof(zap_pri_cli) / sizeof(struct ast_cli_entry));
10288 ast_unregister_application(zap_send_keypad_facility_app);
10289 #endif
10290 ast_cli_unregister_multiple(zap_cli, sizeof(zap_cli) / sizeof(struct ast_cli_entry));
10291 ast_manager_unregister( "ZapDialOffhook" );
10292 ast_manager_unregister( "ZapHangup" );
10293 ast_manager_unregister( "ZapTransfer" );
10294 ast_manager_unregister( "ZapDNDoff" );
10295 ast_manager_unregister( "ZapDNDon" );
10296 ast_manager_unregister("ZapShowChannels");
10297 ast_manager_unregister("ZapRestart");
10298 ast_channel_unregister(&zap_tech);
10299 ast_mutex_lock(&iflock);
10300 /* Hangup all interfaces if they have an owner */
10301 p = iflist;
10302 while (p) {
10303 if (p->owner)
10304 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
10305 p = p->next;
10307 ast_mutex_unlock(&iflock);
10308 ast_mutex_lock(&monlock);
10309 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
10310 pthread_cancel(monitor_thread);
10311 pthread_kill(monitor_thread, SIGURG);
10312 pthread_join(monitor_thread, NULL);
10314 monitor_thread = AST_PTHREADT_STOP;
10315 ast_mutex_unlock(&monlock);
10317 ast_mutex_lock(&iflock);
10318 /* Destroy all the interfaces and free their memory */
10319 p = iflist;
10320 while (p) {
10321 /* Free any callerid */
10322 if (p->cidspill)
10323 free(p->cidspill);
10324 /* Close the zapata thingy */
10325 if (p->subs[SUB_REAL].zfd > -1)
10326 zt_close(p->subs[SUB_REAL].zfd);
10327 pl = p;
10328 p = p->next;
10329 x++;
10330 /* Free associated memory */
10331 if (pl)
10332 destroy_zt_pvt(&pl);
10333 ast_verbose(VERBOSE_PREFIX_3 "Unregistered channel %d\n", x);
10335 iflist = NULL;
10336 ifcount = 0;
10337 ast_mutex_unlock(&iflock);
10338 #ifdef HAVE_PRI
10339 for (i = 0; i < NUM_SPANS; i++) {
10340 if (pris[i].master && (pris[i].master != AST_PTHREADT_NULL))
10341 pthread_join(pris[i].master, NULL);
10342 zt_close(pris[i].fds[i]);
10344 #endif
10345 return 0;
10348 static int unload_module(void)
10350 #ifdef HAVE_PRI
10351 int y;
10352 for (y = 0; y < NUM_SPANS; y++)
10353 ast_mutex_destroy(&pris[y].lock);
10354 #endif
10355 return __unload_module();
10358 static int build_channels(struct zt_chan_conf conf, int iscrv, const char *value, int reload, int lineno, int *found_pseudo)
10360 char *c, *chan;
10361 int x, start, finish;
10362 struct zt_pvt *tmp;
10363 #ifdef HAVE_PRI
10364 struct zt_pri *pri;
10365 int trunkgroup, y;
10366 #endif
10368 if ((reload == 0) && (conf.chan.sig < 0)) {
10369 ast_log(LOG_ERROR, "Signalling must be specified before any channels are.\n");
10370 return -1;
10373 c = ast_strdupa(value);
10375 #ifdef HAVE_PRI
10376 pri = NULL;
10377 if (iscrv) {
10378 if (sscanf(c, "%d:%n", &trunkgroup, &y) != 1) {
10379 ast_log(LOG_WARNING, "CRV must begin with trunkgroup followed by a colon at line %d\n", lineno);
10380 return -1;
10382 if (trunkgroup < 1) {
10383 ast_log(LOG_WARNING, "CRV trunk group must be a positive number at line %d\n", lineno);
10384 return -1;
10386 c += y;
10387 for (y = 0; y < NUM_SPANS; y++) {
10388 if (pris[y].trunkgroup == trunkgroup) {
10389 pri = pris + y;
10390 break;
10393 if (!pri) {
10394 ast_log(LOG_WARNING, "No such trunk group %d at CRV declaration at line %d\n", trunkgroup, lineno);
10395 return -1;
10398 #endif
10400 while ((chan = strsep(&c, ","))) {
10401 if (sscanf(chan, "%d-%d", &start, &finish) == 2) {
10402 /* Range */
10403 } else if (sscanf(chan, "%d", &start)) {
10404 /* Just one */
10405 finish = start;
10406 } else if (!strcasecmp(chan, "pseudo")) {
10407 finish = start = CHAN_PSEUDO;
10408 if (found_pseudo)
10409 *found_pseudo = 1;
10410 } else {
10411 ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
10412 return -1;
10414 if (finish < start) {
10415 ast_log(LOG_WARNING, "Sillyness: %d < %d\n", start, finish);
10416 x = finish;
10417 finish = start;
10418 start = x;
10421 for (x = start; x <= finish; x++) {
10422 #ifdef HAVE_PRI
10423 tmp = mkintf(x, conf, pri, reload);
10424 #else
10425 tmp = mkintf(x, conf, NULL, reload);
10426 #endif
10428 if (tmp) {
10429 if (option_verbose > 2) {
10430 #ifdef HAVE_PRI
10431 if (pri)
10432 ast_verbose(VERBOSE_PREFIX_3 "%s CRV %d:%d, %s signalling\n", reload ? "Reconfigured" : "Registered", trunkgroup, x, sig2str(tmp->sig));
10433 else
10434 #endif
10435 ast_verbose(VERBOSE_PREFIX_3 "%s channel %d, %s signalling\n", reload ? "Reconfigured" : "Registered", x, sig2str(tmp->sig));
10437 } else {
10438 ast_log(LOG_ERROR, "Unable to %s channel '%s'\n",
10439 (reload == 1) ? "reconfigure" : "register", value);
10440 return -1;
10445 return 0;
10448 /** The length of the parameters list of 'zapchan'.
10449 * \todo Move definition of MAX_CHANLIST_LEN to a proper place. */
10450 #define MAX_CHANLIST_LEN 80
10451 static int process_zap(struct zt_chan_conf *confp, struct ast_variable *v, int reload, int skipchannels)
10453 struct zt_pvt *tmp;
10454 char *ringc; /* temporary string for parsing the dring number. */
10455 int y;
10456 int found_pseudo = 0;
10457 char zapchan[MAX_CHANLIST_LEN] = {};
10459 for (; v; v = v->next) {
10460 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
10461 continue;
10463 /* Create the interface list */
10464 if (!strcasecmp(v->name, "channel")
10465 #ifdef HAVE_PRI
10466 || !strcasecmp(v->name, "crv")
10467 #endif
10469 if (skipchannels)
10470 continue;
10471 int iscrv = !strcasecmp(v->name, "crv");
10472 if (build_channels(*confp, iscrv, v->value, reload, v->lineno, &found_pseudo))
10473 return -1;
10474 } else if (!strcasecmp(v->name, "zapchan")) {
10475 ast_copy_string(zapchan, v->value, sizeof(zapchan));
10476 } else if (!strcasecmp(v->name, "usedistinctiveringdetection")) {
10477 if (ast_true(v->value))
10478 confp->chan.usedistinctiveringdetection = 1;
10479 } else if (!strcasecmp(v->name, "distinctiveringaftercid")) {
10480 if (ast_true(v->value))
10481 distinctiveringaftercid = 1;
10482 } else if (!strcasecmp(v->name, "dring1context")) {
10483 ast_copy_string(confp->chan.drings.ringContext[0].contextData,v->value,sizeof(confp->chan.drings.ringContext[0].contextData));
10484 } else if (!strcasecmp(v->name, "dring2context")) {
10485 ast_copy_string(confp->chan.drings.ringContext[1].contextData,v->value,sizeof(confp->chan.drings.ringContext[1].contextData));
10486 } else if (!strcasecmp(v->name, "dring3context")) {
10487 ast_copy_string(confp->chan.drings.ringContext[2].contextData,v->value,sizeof(confp->chan.drings.ringContext[2].contextData));
10488 } else if (!strcasecmp(v->name, "dring1")) {
10489 ringc = v->value;
10490 sscanf(ringc, "%d,%d,%d", &confp->chan.drings.ringnum[0].ring[0], &confp->chan.drings.ringnum[0].ring[1], &drings.ringnum[0].ring[2]);
10491 } else if (!strcasecmp(v->name, "dring2")) {
10492 ringc = v->value;
10493 sscanf(ringc,"%d,%d,%d", &drings.ringnum[1].ring[0], &drings.ringnum[1].ring[1], &drings.ringnum[1].ring[2]);
10494 } else if (!strcasecmp(v->name, "dring3")) {
10495 ringc = v->value;
10496 sscanf(ringc, "%d,%d,%d", &drings.ringnum[2].ring[0], &drings.ringnum[2].ring[1], &drings.ringnum[2].ring[2]);
10497 } else if (!strcasecmp(v->name, "usecallerid")) {
10498 confp->chan.use_callerid = ast_true(v->value);
10499 } else if (!strcasecmp(v->name, "cidsignalling")) {
10500 if (!strcasecmp(v->value, "bell"))
10501 confp->chan.cid_signalling = CID_SIG_BELL;
10502 else if (!strcasecmp(v->value, "v23"))
10503 confp->chan.cid_signalling = CID_SIG_V23;
10504 else if (!strcasecmp(v->value, "dtmf"))
10505 confp->chan.cid_signalling = CID_SIG_DTMF;
10506 else if (!strcasecmp(v->value, "smdi"))
10507 confp->chan.cid_signalling = CID_SIG_SMDI;
10508 else if (!strcasecmp(v->value, "v23_jp"))
10509 confp->chan.cid_signalling = CID_SIG_V23_JP;
10510 else if (ast_true(v->value))
10511 confp->chan.cid_signalling = CID_SIG_BELL;
10512 } else if (!strcasecmp(v->name, "cidstart")) {
10513 if (!strcasecmp(v->value, "ring"))
10514 confp->chan.cid_start = CID_START_RING;
10515 else if (!strcasecmp(v->value, "polarity"))
10516 confp->chan.cid_start = CID_START_POLARITY;
10517 else if (ast_true(v->value))
10518 confp->chan.cid_start = CID_START_RING;
10519 } else if (!strcasecmp(v->name, "threewaycalling")) {
10520 confp->chan.threewaycalling = ast_true(v->value);
10521 } else if (!strcasecmp(v->name, "cancallforward")) {
10522 confp->chan.cancallforward = ast_true(v->value);
10523 } else if (!strcasecmp(v->name, "relaxdtmf")) {
10524 if (ast_true(v->value))
10525 confp->chan.dtmfrelax = DSP_DIGITMODE_RELAXDTMF;
10526 else
10527 confp->chan.dtmfrelax = 0;
10528 } else if (!strcasecmp(v->name, "mailbox")) {
10529 ast_copy_string(confp->chan.mailbox, v->value, sizeof(confp->chan.mailbox));
10530 } else if (!strcasecmp(v->name, "adsi")) {
10531 confp->chan.adsi = ast_true(v->value);
10532 } else if (!strcasecmp(v->name, "usesmdi")) {
10533 confp->chan.use_smdi = ast_true(v->value);
10534 } else if (!strcasecmp(v->name, "smdiport")) {
10535 ast_copy_string(confp->smdi_port, v->value, sizeof(confp->smdi_port));
10536 } else if (!strcasecmp(v->name, "transfer")) {
10537 confp->chan.transfer = ast_true(v->value);
10538 } else if (!strcasecmp(v->name, "canpark")) {
10539 confp->chan.canpark = ast_true(v->value);
10540 } else if (!strcasecmp(v->name, "echocancelwhenbridged")) {
10541 confp->chan.echocanbridged = ast_true(v->value);
10542 } else if (!strcasecmp(v->name, "busydetect")) {
10543 confp->chan.busydetect = ast_true(v->value);
10544 } else if (!strcasecmp(v->name, "busycount")) {
10545 confp->chan.busycount = atoi(v->value);
10546 } else if (!strcasecmp(v->name, "busypattern")) {
10547 if (sscanf(v->value, "%d,%d", &confp->chan.busy_tonelength, &confp->chan.busy_quietlength) != 2) {
10548 ast_log(LOG_ERROR, "busypattern= expects busypattern=tonelength,quietlength\n");
10550 } else if (!strcasecmp(v->name, "callprogress")) {
10551 if (ast_true(v->value))
10552 confp->chan.callprogress |= 1;
10553 else
10554 confp->chan.callprogress &= ~1;
10555 } else if (!strcasecmp(v->name, "faxdetect")) {
10556 if (!strcasecmp(v->value, "incoming")) {
10557 confp->chan.callprogress |= 4;
10558 confp->chan.callprogress &= ~2;
10559 } else if (!strcasecmp(v->value, "outgoing")) {
10560 confp->chan.callprogress &= ~4;
10561 confp->chan.callprogress |= 2;
10562 } else if (!strcasecmp(v->value, "both") || ast_true(v->value))
10563 confp->chan.callprogress |= 6;
10564 else
10565 confp->chan.callprogress &= ~6;
10566 } else if (!strcasecmp(v->name, "echocancel")) {
10567 if (!ast_strlen_zero(v->value)) {
10568 y = atoi(v->value);
10569 } else
10570 y = 0;
10571 if ((y == 32) || (y == 64) || (y == 128) || (y == 256) || (y == 512) || (y == 1024))
10572 confp->chan.echocancel = y;
10573 else {
10574 confp->chan.echocancel = ast_true(v->value);
10575 if (confp->chan.echocancel)
10576 confp->chan.echocancel=128;
10578 } else if (!strcasecmp(v->name, "echotraining")) {
10579 if (sscanf(v->value, "%d", &y) == 1) {
10580 if ((y < 10) || (y > 4000)) {
10581 ast_log(LOG_WARNING, "Echo training time must be within the range of 10 to 4000 ms at line %d\n", v->lineno);
10582 } else {
10583 confp->chan.echotraining = y;
10585 } else if (ast_true(v->value)) {
10586 confp->chan.echotraining = 400;
10587 } else
10588 confp->chan.echotraining = 0;
10589 } else if (!strcasecmp(v->name, "hidecallerid")) {
10590 confp->chan.hidecallerid = ast_true(v->value);
10591 } else if (!strcasecmp(v->name, "hidecalleridname")) {
10592 confp->chan.hidecalleridname = ast_true(v->value);
10593 } else if (!strcasecmp(v->name, "pulsedial")) {
10594 confp->chan.pulse = ast_true(v->value);
10595 } else if (!strcasecmp(v->name, "callreturn")) {
10596 confp->chan.callreturn = ast_true(v->value);
10597 } else if (!strcasecmp(v->name, "callwaiting")) {
10598 confp->chan.callwaiting = ast_true(v->value);
10599 } else if (!strcasecmp(v->name, "callwaitingcallerid")) {
10600 confp->chan.callwaitingcallerid = ast_true(v->value);
10601 } else if (!strcasecmp(v->name, "context")) {
10602 ast_copy_string(confp->chan.context, v->value, sizeof(confp->chan.context));
10603 } else if (!strcasecmp(v->name, "language")) {
10604 ast_copy_string(confp->chan.language, v->value, sizeof(confp->chan.language));
10605 } else if (!strcasecmp(v->name, "progzone")) {
10606 ast_copy_string(progzone, v->value, sizeof(progzone));
10607 } else if (!strcasecmp(v->name, "mohinterpret")
10608 ||!strcasecmp(v->name, "musiconhold") || !strcasecmp(v->name, "musicclass")) {
10609 ast_copy_string(confp->chan.mohinterpret, v->value, sizeof(confp->chan.mohinterpret));
10610 } else if (!strcasecmp(v->name, "mohsuggest")) {
10611 ast_copy_string(confp->chan.mohsuggest, v->value, sizeof(confp->chan.mohsuggest));
10612 } else if (!strcasecmp(v->name, "stripmsd")) {
10613 confp->chan.stripmsd = atoi(v->value);
10614 } else if (!strcasecmp(v->name, "jitterbuffers")) {
10615 numbufs = atoi(v->value);
10616 } else if (!strcasecmp(v->name, "group")) {
10617 confp->chan.group = ast_get_group(v->value);
10618 } else if (!strcasecmp(v->name, "callgroup")) {
10619 confp->chan.callgroup = ast_get_group(v->value);
10620 } else if (!strcasecmp(v->name, "pickupgroup")) {
10621 confp->chan.pickupgroup = ast_get_group(v->value);
10622 } else if (!strcasecmp(v->name, "immediate")) {
10623 confp->chan.immediate = ast_true(v->value);
10624 } else if (!strcasecmp(v->name, "transfertobusy")) {
10625 confp->chan.transfertobusy = ast_true(v->value);
10626 } else if (!strcasecmp(v->name, "rxgain")) {
10627 if (sscanf(v->value, "%f", &confp->chan.rxgain) != 1) {
10628 ast_log(LOG_WARNING, "Invalid rxgain: %s\n", v->value);
10630 } else if (!strcasecmp(v->name, "txgain")) {
10631 if (sscanf(v->value, "%f", &confp->chan.txgain) != 1) {
10632 ast_log(LOG_WARNING, "Invalid txgain: %s\n", v->value);
10634 } else if (!strcasecmp(v->name, "tonezone")) {
10635 if (sscanf(v->value, "%d", &confp->chan.tonezone) != 1) {
10636 ast_log(LOG_WARNING, "Invalid tonezone: %s\n", v->value);
10638 } else if (!strcasecmp(v->name, "callerid")) {
10639 if (!strcasecmp(v->value, "asreceived")) {
10640 confp->chan.cid_num[0] = '\0';
10641 confp->chan.cid_name[0] = '\0';
10642 } else {
10643 ast_callerid_split(v->value, confp->chan.cid_name, sizeof(confp->chan.cid_name), confp->chan.cid_num, sizeof(confp->chan.cid_num));
10645 } else if (!strcasecmp(v->name, "fullname")) {
10646 ast_copy_string(confp->chan.cid_name, v->value, sizeof(confp->chan.cid_name));
10647 } else if (!strcasecmp(v->name, "cid_number")) {
10648 ast_copy_string(confp->chan.cid_num, v->value, sizeof(confp->chan.cid_num));
10649 } else if (!strcasecmp(v->name, "useincomingcalleridonzaptransfer")) {
10650 confp->chan.zaptrcallerid = ast_true(v->value);
10651 } else if (!strcasecmp(v->name, "restrictcid")) {
10652 confp->chan.restrictcid = ast_true(v->value);
10653 } else if (!strcasecmp(v->name, "usecallingpres")) {
10654 confp->chan.use_callingpres = ast_true(v->value);
10655 } else if (!strcasecmp(v->name, "accountcode")) {
10656 ast_copy_string(confp->chan.accountcode, v->value, sizeof(confp->chan.accountcode));
10657 } else if (!strcasecmp(v->name, "amaflags")) {
10658 y = ast_cdr_amaflags2int(v->value);
10659 if (y < 0)
10660 ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
10661 else
10662 confp->chan.amaflags = y;
10663 } else if (!reload){
10664 if (!strcasecmp(v->name, "signalling")) {
10665 confp->chan.outsigmod = -1;
10666 if (!strcasecmp(v->value, "em")) {
10667 confp->chan.sig = SIG_EM;
10668 } else if (!strcasecmp(v->value, "em_e1")) {
10669 confp->chan.sig = SIG_EM_E1;
10670 } else if (!strcasecmp(v->value, "em_w")) {
10671 confp->chan.sig = SIG_EMWINK;
10672 confp->chan.radio = 0;
10673 } else if (!strcasecmp(v->value, "fxs_ls")) {
10674 confp->chan.sig = SIG_FXSLS;
10675 confp->chan.radio = 0;
10676 } else if (!strcasecmp(v->value, "fxs_gs")) {
10677 confp->chan.sig = SIG_FXSGS;
10678 confp->chan.radio = 0;
10679 } else if (!strcasecmp(v->value, "fxs_ks")) {
10680 confp->chan.sig = SIG_FXSKS;
10681 confp->chan.radio = 0;
10682 } else if (!strcasecmp(v->value, "fxo_ls")) {
10683 confp->chan.sig = SIG_FXOLS;
10684 confp->chan.radio = 0;
10685 } else if (!strcasecmp(v->value, "fxo_gs")) {
10686 confp->chan.sig = SIG_FXOGS;
10687 confp->chan.radio = 0;
10688 } else if (!strcasecmp(v->value, "fxo_ks")) {
10689 confp->chan.sig = SIG_FXOKS;
10690 confp->chan.radio = 0;
10691 } else if (!strcasecmp(v->value, "fxs_rx")) {
10692 confp->chan.sig = SIG_FXSKS;
10693 confp->chan.radio = 1;
10694 } else if (!strcasecmp(v->value, "fxo_rx")) {
10695 confp->chan.sig = SIG_FXOLS;
10696 confp->chan.radio = 1;
10697 } else if (!strcasecmp(v->value, "fxs_tx")) {
10698 confp->chan.sig = SIG_FXSLS;
10699 confp->chan.radio = 1;
10700 } else if (!strcasecmp(v->value, "fxo_tx")) {
10701 confp->chan.sig = SIG_FXOGS;
10702 confp->chan.radio = 1;
10703 } else if (!strcasecmp(v->value, "em_rx")) {
10704 confp->chan.sig = SIG_EM;
10705 confp->chan.radio = 1;
10706 } else if (!strcasecmp(v->value, "em_tx")) {
10707 confp->chan.sig = SIG_EM;
10708 confp->chan.radio = 1;
10709 } else if (!strcasecmp(v->value, "em_rxtx")) {
10710 confp->chan.sig = SIG_EM;
10711 confp->chan.radio = 2;
10712 } else if (!strcasecmp(v->value, "em_txrx")) {
10713 confp->chan.sig = SIG_EM;
10714 confp->chan.radio = 2;
10715 } else if (!strcasecmp(v->value, "sf")) {
10716 confp->chan.sig = SIG_SF;
10717 confp->chan.radio = 0;
10718 } else if (!strcasecmp(v->value, "sf_w")) {
10719 confp->chan.sig = SIG_SFWINK;
10720 confp->chan.radio = 0;
10721 } else if (!strcasecmp(v->value, "sf_featd")) {
10722 confp->chan.sig = SIG_FEATD;
10723 confp->chan.radio = 0;
10724 } else if (!strcasecmp(v->value, "sf_featdmf")) {
10725 confp->chan.sig = SIG_FEATDMF;
10726 confp->chan.radio = 0;
10727 } else if (!strcasecmp(v->value, "sf_featb")) {
10728 confp->chan.sig = SIG_SF_FEATB;
10729 confp->chan.radio = 0;
10730 } else if (!strcasecmp(v->value, "sf")) {
10731 confp->chan.sig = SIG_SF;
10732 confp->chan.radio = 0;
10733 } else if (!strcasecmp(v->value, "sf_rx")) {
10734 confp->chan.sig = SIG_SF;
10735 confp->chan.radio = 1;
10736 } else if (!strcasecmp(v->value, "sf_tx")) {
10737 confp->chan.sig = SIG_SF;
10738 confp->chan.radio = 1;
10739 } else if (!strcasecmp(v->value, "sf_rxtx")) {
10740 confp->chan.sig = SIG_SF;
10741 confp->chan.radio = 2;
10742 } else if (!strcasecmp(v->value, "sf_txrx")) {
10743 confp->chan.sig = SIG_SF;
10744 confp->chan.radio = 2;
10745 } else if (!strcasecmp(v->value, "featd")) {
10746 confp->chan.sig = SIG_FEATD;
10747 confp->chan.radio = 0;
10748 } else if (!strcasecmp(v->value, "featdmf")) {
10749 confp->chan.sig = SIG_FEATDMF;
10750 confp->chan.radio = 0;
10751 } else if (!strcasecmp(v->value, "featdmf_ta")) {
10752 confp->chan.sig = SIG_FEATDMF_TA;
10753 confp->chan.radio = 0;
10754 } else if (!strcasecmp(v->value, "e911")) {
10755 confp->chan.sig = SIG_E911;
10756 confp->chan.radio = 0;
10757 } else if (!strcasecmp(v->value, "fgccama")) {
10758 confp->chan.sig = SIG_FGC_CAMA;
10759 confp->chan.radio = 0;
10760 } else if (!strcasecmp(v->value, "fgccamamf")) {
10761 confp->chan.sig = SIG_FGC_CAMAMF;
10762 confp->chan.radio = 0;
10763 } else if (!strcasecmp(v->value, "featb")) {
10764 confp->chan.sig = SIG_FEATB;
10765 confp->chan.radio = 0;
10766 #ifdef HAVE_PRI
10767 } else if (!strcasecmp(v->value, "pri_net")) {
10768 confp->chan.radio = 0;
10769 confp->chan.sig = SIG_PRI;
10770 confp->pri.nodetype = PRI_NETWORK;
10771 } else if (!strcasecmp(v->value, "pri_cpe")) {
10772 confp->chan.sig = SIG_PRI;
10773 confp->chan.radio = 0;
10774 confp->pri.nodetype = PRI_CPE;
10775 } else if (!strcasecmp(v->value, "gr303fxoks_net")) {
10776 confp->chan.sig = SIG_GR303FXOKS;
10777 confp->chan.radio = 0;
10778 confp->pri.nodetype = PRI_NETWORK;
10779 } else if (!strcasecmp(v->value, "gr303fxsks_cpe")) {
10780 confp->chan.sig = SIG_GR303FXSKS;
10781 confp->chan.radio = 0;
10782 confp->pri.nodetype = PRI_CPE;
10783 #endif
10784 } else {
10785 ast_log(LOG_ERROR, "Unknown signalling method '%s'\n", v->value);
10787 } else if (!strcasecmp(v->name, "outsignalling")) {
10788 if (!strcasecmp(v->value, "em")) {
10789 confp->chan.outsigmod = SIG_EM;
10790 } else if (!strcasecmp(v->value, "em_e1")) {
10791 confp->chan.outsigmod = SIG_EM_E1;
10792 } else if (!strcasecmp(v->value, "em_w")) {
10793 confp->chan.outsigmod = SIG_EMWINK;
10794 } else if (!strcasecmp(v->value, "sf")) {
10795 confp->chan.outsigmod = SIG_SF;
10796 } else if (!strcasecmp(v->value, "sf_w")) {
10797 confp->chan.outsigmod = SIG_SFWINK;
10798 } else if (!strcasecmp(v->value, "sf_featd")) {
10799 confp->chan.outsigmod = SIG_FEATD;
10800 } else if (!strcasecmp(v->value, "sf_featdmf")) {
10801 confp->chan.outsigmod = SIG_FEATDMF;
10802 } else if (!strcasecmp(v->value, "sf_featb")) {
10803 confp->chan.outsigmod = SIG_SF_FEATB;
10804 } else if (!strcasecmp(v->value, "sf")) {
10805 confp->chan.outsigmod = SIG_SF;
10806 } else if (!strcasecmp(v->value, "featd")) {
10807 confp->chan.outsigmod = SIG_FEATD;
10808 } else if (!strcasecmp(v->value, "featdmf")) {
10809 confp->chan.outsigmod = SIG_FEATDMF;
10810 } else if (!strcasecmp(v->value, "featdmf_ta")) {
10811 confp->chan.outsigmod = SIG_FEATDMF_TA;
10812 } else if (!strcasecmp(v->value, "e911")) {
10813 confp->chan.outsigmod = SIG_E911;
10814 } else if (!strcasecmp(v->value, "fgccama")) {
10815 confp->chan.outsigmod = SIG_FGC_CAMA;
10816 } else if (!strcasecmp(v->value, "fgccamamf")) {
10817 confp->chan.outsigmod = SIG_FGC_CAMAMF;
10818 } else if (!strcasecmp(v->value, "featb")) {
10819 confp->chan.outsigmod = SIG_FEATB;
10820 } else {
10821 ast_log(LOG_ERROR, "Unknown signalling method '%s'\n", v->value);
10823 #ifdef HAVE_PRI
10824 } else if (!strcasecmp(v->name, "pridialplan")) {
10825 if (!strcasecmp(v->value, "national")) {
10826 confp->pri.dialplan = PRI_NATIONAL_ISDN + 1;
10827 } else if (!strcasecmp(v->value, "unknown")) {
10828 confp->pri.dialplan = PRI_UNKNOWN + 1;
10829 } else if (!strcasecmp(v->value, "private")) {
10830 confp->pri.dialplan = PRI_PRIVATE + 1;
10831 } else if (!strcasecmp(v->value, "international")) {
10832 confp->pri.dialplan = PRI_INTERNATIONAL_ISDN + 1;
10833 } else if (!strcasecmp(v->value, "local")) {
10834 confp->pri.dialplan = PRI_LOCAL_ISDN + 1;
10835 } else if (!strcasecmp(v->value, "dynamic")) {
10836 confp->pri.dialplan = -1;
10837 } else {
10838 ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
10840 } else if (!strcasecmp(v->name, "prilocaldialplan")) {
10841 if (!strcasecmp(v->value, "national")) {
10842 confp->pri.localdialplan = PRI_NATIONAL_ISDN + 1;
10843 } else if (!strcasecmp(v->value, "unknown")) {
10844 confp->pri.localdialplan = PRI_UNKNOWN + 1;
10845 } else if (!strcasecmp(v->value, "private")) {
10846 confp->pri.localdialplan = PRI_PRIVATE + 1;
10847 } else if (!strcasecmp(v->value, "international")) {
10848 confp->pri.localdialplan = PRI_INTERNATIONAL_ISDN + 1;
10849 } else if (!strcasecmp(v->value, "local")) {
10850 confp->pri.localdialplan = PRI_LOCAL_ISDN + 1;
10851 } else if (!strcasecmp(v->value, "dynamic")) {
10852 confp->pri.localdialplan = -1;
10853 } else {
10854 ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
10856 } else if (!strcasecmp(v->name, "switchtype")) {
10857 if (!strcasecmp(v->value, "national"))
10858 confp->pri.switchtype = PRI_SWITCH_NI2;
10859 else if (!strcasecmp(v->value, "ni1"))
10860 confp->pri.switchtype = PRI_SWITCH_NI1;
10861 else if (!strcasecmp(v->value, "dms100"))
10862 confp->pri.switchtype = PRI_SWITCH_DMS100;
10863 else if (!strcasecmp(v->value, "4ess"))
10864 confp->pri.switchtype = PRI_SWITCH_ATT4ESS;
10865 else if (!strcasecmp(v->value, "5ess"))
10866 confp->pri.switchtype = PRI_SWITCH_LUCENT5E;
10867 else if (!strcasecmp(v->value, "euroisdn"))
10868 confp->pri.switchtype = PRI_SWITCH_EUROISDN_E1;
10869 else if (!strcasecmp(v->value, "qsig"))
10870 confp->pri.switchtype = PRI_SWITCH_QSIG;
10871 else {
10872 ast_log(LOG_ERROR, "Unknown switchtype '%s'\n", v->value);
10873 return -1;
10875 } else if (!strcasecmp(v->name, "nsf")) {
10876 if (!strcasecmp(v->value, "sdn"))
10877 confp->pri.nsf = PRI_NSF_SDN;
10878 else if (!strcasecmp(v->value, "megacom"))
10879 confp->pri.nsf = PRI_NSF_MEGACOM;
10880 else if (!strcasecmp(v->value, "tollfreemegacom"))
10881 confp->pri.nsf = PRI_NSF_TOLL_FREE_MEGACOM;
10882 else if (!strcasecmp(v->value, "accunet"))
10883 confp->pri.nsf = PRI_NSF_ACCUNET;
10884 else if (!strcasecmp(v->value, "none"))
10885 confp->pri.nsf = PRI_NSF_NONE;
10886 else {
10887 ast_log(LOG_WARNING, "Unknown network-specific facility '%s'\n", v->value);
10888 confp->pri.nsf = PRI_NSF_NONE;
10890 } else if (!strcasecmp(v->name, "priindication")) {
10891 if (!strcasecmp(v->value, "outofband"))
10892 confp->chan.priindication_oob = 1;
10893 else if (!strcasecmp(v->value, "inband"))
10894 confp->chan.priindication_oob = 0;
10895 else
10896 ast_log(LOG_WARNING, "'%s' is not a valid pri indication value, should be 'inband' or 'outofband' at line %d\n",
10897 v->value, v->lineno);
10898 } else if (!strcasecmp(v->name, "priexclusive")) {
10899 confp->chan.priexclusive = ast_true(v->value);
10900 } else if (!strcasecmp(v->name, "internationalprefix")) {
10901 ast_copy_string(confp->pri.internationalprefix, v->value, sizeof(confp->pri.internationalprefix));
10902 } else if (!strcasecmp(v->name, "nationalprefix")) {
10903 ast_copy_string(confp->pri.nationalprefix, v->value, sizeof(confp->pri.nationalprefix));
10904 } else if (!strcasecmp(v->name, "localprefix")) {
10905 ast_copy_string(confp->pri.localprefix, v->value, sizeof(confp->pri.localprefix));
10906 } else if (!strcasecmp(v->name, "privateprefix")) {
10907 ast_copy_string(confp->pri.privateprefix, v->value, sizeof(confp->pri.privateprefix));
10908 } else if (!strcasecmp(v->name, "unknownprefix")) {
10909 ast_copy_string(confp->pri.unknownprefix, v->value, sizeof(confp->pri.unknownprefix));
10910 } else if (!strcasecmp(v->name, "resetinterval")) {
10911 if (!strcasecmp(v->value, "never"))
10912 confp->pri.resetinterval = -1;
10913 else if (atoi(v->value) >= 60)
10914 confp->pri.resetinterval = atoi(v->value);
10915 else
10916 ast_log(LOG_WARNING, "'%s' is not a valid reset interval, should be >= 60 seconds or 'never' at line %d\n",
10917 v->value, v->lineno);
10918 } else if (!strcasecmp(v->name, "minunused")) {
10919 confp->pri.minunused = atoi(v->value);
10920 } else if (!strcasecmp(v->name, "minidle")) {
10921 confp->pri.minidle = atoi(v->value);
10922 } else if (!strcasecmp(v->name, "idleext")) {
10923 ast_copy_string(confp->pri.idleext, v->value, sizeof(confp->pri.idleext));
10924 } else if (!strcasecmp(v->name, "idledial")) {
10925 ast_copy_string(confp->pri.idledial, v->value, sizeof(confp->pri.idledial));
10926 } else if (!strcasecmp(v->name, "overlapdial")) {
10927 confp->pri.overlapdial = ast_true(v->value);
10928 } else if (!strcasecmp(v->name, "pritimer")) {
10929 #ifdef PRI_GETSET_TIMERS
10930 char *timerc, *c;
10931 int timer, timeridx;
10932 c = v->value;
10933 timerc = strsep(&c, ",");
10934 if (timerc) {
10935 timer = atoi(c);
10936 if (!timer)
10937 ast_log(LOG_WARNING, "'%s' is not a valid value for an ISDN timer\n", timerc);
10938 else {
10939 if ((timeridx = pri_timer2idx(timerc)) >= 0)
10940 pritimers[timeridx] = timer;
10941 else
10942 ast_log(LOG_WARNING, "'%s' is not a valid ISDN timer\n", timerc);
10944 } else
10945 ast_log(LOG_WARNING, "'%s' is not a valid ISDN timer configuration string\n", v->value);
10947 } else if (!strcasecmp(v->name, "facilityenable")) {
10948 confp->pri.facilityenable = ast_true(v->value);
10949 #endif /* PRI_GETSET_TIMERS */
10950 #endif /* HAVE_PRI */
10951 } else if (!strcasecmp(v->name, "cadence")) {
10952 /* setup to scan our argument */
10953 int element_count, c[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
10954 int i;
10955 struct zt_ring_cadence new_cadence;
10956 int cid_location = -1;
10957 int firstcadencepos = 0;
10958 char original_args[80];
10959 int cadence_is_ok = 1;
10961 ast_copy_string(original_args, v->value, sizeof(original_args));
10962 /* 16 cadences allowed (8 pairs) */
10963 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]);
10965 /* Cadence must be even (on/off) */
10966 if (element_count % 2 == 1) {
10967 ast_log(LOG_ERROR, "Must be a silence duration for each ring duration: %s\n",original_args);
10968 cadence_is_ok = 0;
10971 /* Ring cadences cannot be negative */
10972 for (i = 0; i < element_count; i++) {
10973 if (c[i] == 0) {
10974 ast_log(LOG_ERROR, "Ring or silence duration cannot be zero: %s\n", original_args);
10975 cadence_is_ok = 0;
10976 break;
10977 } else if (c[i] < 0) {
10978 if (i % 2 == 1) {
10979 /* Silence duration, negative possibly okay */
10980 if (cid_location == -1) {
10981 cid_location = i;
10982 c[i] *= -1;
10983 } else {
10984 ast_log(LOG_ERROR, "CID location specified twice: %s\n",original_args);
10985 cadence_is_ok = 0;
10986 break;
10988 } else {
10989 if (firstcadencepos == 0) {
10990 firstcadencepos = i; /* only recorded to avoid duplicate specification */
10991 /* duration will be passed negative to the zaptel driver */
10992 } else {
10993 ast_log(LOG_ERROR, "First cadence position specified twice: %s\n",original_args);
10994 cadence_is_ok = 0;
10995 break;
11001 /* Substitute our scanned cadence */
11002 for (i = 0; i < 16; i++) {
11003 new_cadence.ringcadence[i] = c[i];
11006 if (cadence_is_ok) {
11007 /* ---we scanned it without getting annoyed; now some sanity checks--- */
11008 if (element_count < 2) {
11009 ast_log(LOG_ERROR, "Minimum cadence is ring,pause: %s\n", original_args);
11010 } else {
11011 if (cid_location == -1) {
11012 /* user didn't say; default to first pause */
11013 cid_location = 1;
11014 } else {
11015 /* convert element_index to cidrings value */
11016 cid_location = (cid_location + 1) / 2;
11018 /* ---we like their cadence; try to install it--- */
11019 if (!user_has_defined_cadences++)
11020 /* this is the first user-defined cadence; clear the default user cadences */
11021 num_cadence = 0;
11022 if ((num_cadence+1) >= NUM_CADENCE_MAX)
11023 ast_log(LOG_ERROR, "Already %d cadences; can't add another: %s\n", NUM_CADENCE_MAX, original_args);
11024 else {
11025 cadences[num_cadence] = new_cadence;
11026 cidrings[num_cadence++] = cid_location;
11027 if (option_verbose > 2)
11028 ast_verbose(VERBOSE_PREFIX_3 "cadence 'r%d' added: %s\n",num_cadence,original_args);
11032 } else if (!strcasecmp(v->name, "ringtimeout")) {
11033 ringt_base = (atoi(v->value) * 8) / READ_SIZE;
11034 } else if (!strcasecmp(v->name, "prewink")) {
11035 confp->timing.prewinktime = atoi(v->value);
11036 } else if (!strcasecmp(v->name, "preflash")) {
11037 confp->timing.preflashtime = atoi(v->value);
11038 } else if (!strcasecmp(v->name, "wink")) {
11039 confp->timing.winktime = atoi(v->value);
11040 } else if (!strcasecmp(v->name, "flash")) {
11041 confp->timing.flashtime = atoi(v->value);
11042 } else if (!strcasecmp(v->name, "start")) {
11043 confp->timing.starttime = atoi(v->value);
11044 } else if (!strcasecmp(v->name, "rxwink")) {
11045 confp->timing.rxwinktime = atoi(v->value);
11046 } else if (!strcasecmp(v->name, "rxflash")) {
11047 confp->timing.rxflashtime = atoi(v->value);
11048 } else if (!strcasecmp(v->name, "debounce")) {
11049 confp->timing.debouncetime = atoi(v->value);
11050 } else if (!strcasecmp(v->name, "toneduration")) {
11051 int toneduration;
11052 int ctlfd;
11053 int res;
11054 struct zt_dialparams dps;
11056 ctlfd = open("/dev/zap/ctl", O_RDWR);
11057 if (ctlfd == -1) {
11058 ast_log(LOG_ERROR, "Unable to open /dev/zap/ctl to set toneduration\n");
11059 return -1;
11062 toneduration = atoi(v->value);
11063 if (toneduration > -1) {
11064 dps.dtmf_tonelen = dps.mfv1_tonelen = toneduration;
11065 res = ioctl(ctlfd, ZT_SET_DIALPARAMS, &dps);
11066 if (res < 0) {
11067 ast_log(LOG_ERROR, "Invalid tone duration: %d ms\n", toneduration);
11068 return -1;
11071 close(ctlfd);
11072 } else if (!strcasecmp(v->name, "polarityonanswerdelay")) {
11073 confp->chan.polarityonanswerdelay = atoi(v->value);
11074 } else if (!strcasecmp(v->name, "answeronpolarityswitch")) {
11075 confp->chan.answeronpolarityswitch = ast_true(v->value);
11076 } else if (!strcasecmp(v->name, "hanguponpolarityswitch")) {
11077 confp->chan.hanguponpolarityswitch = ast_true(v->value);
11078 } else if (!strcasecmp(v->name, "sendcalleridafter")) {
11079 confp->chan.sendcalleridafter = atoi(v->value);
11080 } else if (!strcasecmp(v->name, "defaultcic")) {
11081 ast_copy_string(defaultcic, v->value, sizeof(defaultcic));
11082 } else if (!strcasecmp(v->name, "defaultozz")) {
11083 ast_copy_string(defaultozz, v->value, sizeof(defaultozz));
11085 } else if (!skipchannels)
11086 ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
11088 if (zapchan[0]) {
11089 /* The user has set 'zapchan' */
11090 /*< \todo pass proper line number instead of 0 */
11091 if (build_channels(*confp, 0, zapchan, reload, 0, &found_pseudo)) {
11092 return -1;
11095 /*< \todo why check for the pseudo in the per-channel section.
11096 * Any actual use for manual setup of the pseudo channel? */
11097 if (!found_pseudo && reload == 0) {
11098 /* Make sure pseudo isn't a member of any groups if
11099 we're automatically making it. */
11101 confp->chan.group = 0;
11102 confp->chan.callgroup = 0;
11103 confp->chan.pickupgroup = 0;
11105 tmp = mkintf(CHAN_PSEUDO, *confp, NULL, reload);
11107 if (tmp) {
11108 if (option_verbose > 2)
11109 ast_verbose(VERBOSE_PREFIX_3 "Automatically generated pseudo channel\n");
11110 } else {
11111 ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
11114 return 0;
11117 static int setup_zap(int reload)
11119 struct ast_config *cfg;
11120 struct ast_variable *v;
11121 struct zt_chan_conf conf = zt_chan_conf_default();
11122 int res;
11124 #ifdef HAVE_PRI
11125 char *c;
11126 int spanno;
11127 int i, x;
11128 int logicalspan;
11129 int trunkgroup;
11130 int dchannels[NUM_DCHANS];
11131 #endif
11133 cfg = ast_config_load(config);
11135 /* Error if we have no config file */
11136 if (!cfg) {
11137 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
11138 return 0;
11141 /* It's a little silly to lock it, but we mind as well just to be sure */
11142 ast_mutex_lock(&iflock);
11143 #ifdef HAVE_PRI
11144 if (!reload) {
11145 /* Process trunkgroups first */
11146 v = ast_variable_browse(cfg, "trunkgroups");
11147 while (v) {
11148 if (!strcasecmp(v->name, "trunkgroup")) {
11149 trunkgroup = atoi(v->value);
11150 if (trunkgroup > 0) {
11151 if ((c = strchr(v->value, ','))) {
11152 i = 0;
11153 memset(dchannels, 0, sizeof(dchannels));
11154 while (c && (i < NUM_DCHANS)) {
11155 dchannels[i] = atoi(c + 1);
11156 if (dchannels[i] < 0) {
11157 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);
11158 } else
11159 i++;
11160 c = strchr(c + 1, ',');
11162 if (i) {
11163 if (pri_create_trunkgroup(trunkgroup, dchannels)) {
11164 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);
11165 } else if (option_verbose > 1)
11166 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");
11167 } else
11168 ast_log(LOG_WARNING, "Trunk group %d lacks any valid D-channels at line %d of zapata.conf\n", trunkgroup, v->lineno);
11169 } else
11170 ast_log(LOG_WARNING, "Trunk group %d lacks a primary D-channel at line %d of zapata.conf\n", trunkgroup, v->lineno);
11171 } else
11172 ast_log(LOG_WARNING, "Trunk group identifier must be a positive integer at line %d of zapata.conf\n", v->lineno);
11173 } else if (!strcasecmp(v->name, "spanmap")) {
11174 spanno = atoi(v->value);
11175 if (spanno > 0) {
11176 if ((c = strchr(v->value, ','))) {
11177 trunkgroup = atoi(c + 1);
11178 if (trunkgroup > 0) {
11179 if ((c = strchr(c + 1, ',')))
11180 logicalspan = atoi(c + 1);
11181 else
11182 logicalspan = 0;
11183 if (logicalspan >= 0) {
11184 if (pri_create_spanmap(spanno - 1, trunkgroup, logicalspan)) {
11185 ast_log(LOG_WARNING, "Failed to map span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
11186 } else if (option_verbose > 1)
11187 ast_verbose(VERBOSE_PREFIX_2 "Mapped span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
11188 } else
11189 ast_log(LOG_WARNING, "Logical span must be a postive number, or '0' (for unspecified) at line %d of zapata.conf\n", v->lineno);
11190 } else
11191 ast_log(LOG_WARNING, "Trunk group must be a postive number at line %d of zapata.conf\n", v->lineno);
11192 } else
11193 ast_log(LOG_WARNING, "Missing trunk group for span map at line %d of zapata.conf\n", v->lineno);
11194 } else
11195 ast_log(LOG_WARNING, "Span number must be a postive integer at line %d of zapata.conf\n", v->lineno);
11196 } else {
11197 ast_log(LOG_NOTICE, "Ignoring unknown keyword '%s' in trunkgroups\n", v->name);
11199 v = v->next;
11202 #endif
11204 /* Copy the default jb config over global_jbconf */
11205 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
11207 v = ast_variable_browse(cfg, "channels");
11208 res = process_zap(&conf, v, reload, 0);
11209 ast_mutex_unlock(&iflock);
11210 ast_config_destroy(cfg);
11211 if (res)
11212 return res;
11213 cfg = ast_config_load("users.conf");
11214 if (cfg) {
11215 char *cat;
11216 const char *chans;
11217 process_zap(&conf, ast_variable_browse(cfg, "general"), 1, 1);
11218 for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
11219 if (!strcasecmp(cat, "general"))
11220 continue;
11221 chans = ast_variable_retrieve(cfg, cat, "zapchan");
11222 if (!ast_strlen_zero(chans)) {
11223 /** \todo At this point we should probably
11224 * duplicate conf, and pass a copy, to prevent
11225 * one section from affecting another
11227 process_zap(&conf, ast_variable_browse(cfg, cat), reload, 0);
11230 ast_config_destroy(cfg);
11232 #ifdef HAVE_PRI
11233 if (!reload) {
11234 for (x = 0; x < NUM_SPANS; x++) {
11235 if (pris[x].pvts[0]) {
11236 if (start_pri(pris + x)) {
11237 ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
11238 return -1;
11239 } else if (option_verbose > 1)
11240 ast_verbose(VERBOSE_PREFIX_2 "Starting D-Channel on span %d\n", x + 1);
11244 #endif
11245 /* And start the monitor for the first time */
11246 restart_monitor();
11247 return 0;
11250 static int load_module(void)
11252 int res;
11254 #ifdef HAVE_PRI
11255 int y,i;
11256 memset(pris, 0, sizeof(pris));
11257 for (y = 0; y < NUM_SPANS; y++) {
11258 ast_mutex_init(&pris[y].lock);
11259 pris[y].offset = -1;
11260 pris[y].master = AST_PTHREADT_NULL;
11261 for (i = 0; i < NUM_DCHANS; i++)
11262 pris[y].fds[i] = -1;
11264 pri_set_error(zt_pri_error);
11265 pri_set_message(zt_pri_message);
11266 ast_register_application(zap_send_keypad_facility_app, zap_send_keypad_facility_exec,
11267 zap_send_keypad_facility_synopsis, zap_send_keypad_facility_descrip);
11268 #endif
11269 res = setup_zap(0);
11270 /* Make sure we can register our Zap channel type */
11271 if (res)
11272 return AST_MODULE_LOAD_DECLINE;
11273 if (ast_channel_register(&zap_tech)) {
11274 ast_log(LOG_ERROR, "Unable to register channel class 'Zap'\n");
11275 __unload_module();
11276 return -1;
11278 #ifdef HAVE_PRI
11279 ast_string_field_init(&inuse, 16);
11280 ast_string_field_set(&inuse, name, "GR-303InUse");
11281 ast_cli_register_multiple(zap_pri_cli, sizeof(zap_pri_cli) / sizeof(struct ast_cli_entry));
11282 #endif
11283 ast_cli_register_multiple(zap_cli, sizeof(zap_cli) / sizeof(struct ast_cli_entry));
11285 memset(round_robin, 0, sizeof(round_robin));
11286 ast_manager_register( "ZapTransfer", 0, action_transfer, "Transfer Zap Channel" );
11287 ast_manager_register( "ZapHangup", 0, action_transferhangup, "Hangup Zap Channel" );
11288 ast_manager_register( "ZapDialOffhook", 0, action_zapdialoffhook, "Dial over Zap channel while offhook" );
11289 ast_manager_register( "ZapDNDon", 0, action_zapdndon, "Toggle Zap channel Do Not Disturb status ON" );
11290 ast_manager_register( "ZapDNDoff", 0, action_zapdndoff, "Toggle Zap channel Do Not Disturb status OFF" );
11291 ast_manager_register("ZapShowChannels", 0, action_zapshowchannels, "Show status zapata channels");
11292 ast_manager_register("ZapRestart", 0, action_zaprestart, "Fully Restart zaptel channels (terminates calls)");
11294 return res;
11297 static int zt_sendtext(struct ast_channel *c, const char *text)
11299 #define END_SILENCE_LEN 400
11300 #define HEADER_MS 50
11301 #define TRAILER_MS 5
11302 #define HEADER_LEN ((HEADER_MS + TRAILER_MS) * 8)
11303 #define ASCII_BYTES_PER_CHAR 80
11305 unsigned char *buf,*mybuf;
11306 struct zt_pvt *p = c->tech_pvt;
11307 struct pollfd fds[1];
11308 int size,res,fd,len,x;
11309 int bytes=0;
11310 /* Initial carrier (imaginary) */
11311 float cr = 1.0;
11312 float ci = 0.0;
11313 float scont = 0.0;
11314 int index;
11316 index = zt_get_index(c, p, 0);
11317 if (index < 0) {
11318 ast_log(LOG_WARNING, "Huh? I don't exist?\n");
11319 return -1;
11321 if (!text[0]) return(0); /* if nothing to send, dont */
11322 if ((!p->tdd) && (!p->mate)) return(0); /* if not in TDD mode, just return */
11323 if (p->mate)
11324 buf = ast_malloc(((strlen(text) + 1) * ASCII_BYTES_PER_CHAR) + END_SILENCE_LEN + HEADER_LEN);
11325 else
11326 buf = ast_malloc(((strlen(text) + 1) * TDD_BYTES_PER_CHAR) + END_SILENCE_LEN);
11327 if (!buf)
11328 return -1;
11329 mybuf = buf;
11330 if (p->mate) {
11331 int codec = AST_LAW(p);
11332 for (x = 0; x < HEADER_MS; x++) { /* 50 ms of Mark */
11333 PUT_CLID_MARKMS;
11335 /* Put actual message */
11336 for (x = 0; text[x]; x++) {
11337 PUT_CLID(text[x]);
11339 for (x = 0; x < TRAILER_MS; x++) { /* 5 ms of Mark */
11340 PUT_CLID_MARKMS;
11342 len = bytes;
11343 buf = mybuf;
11344 } else {
11345 len = tdd_generate(p->tdd, buf, text);
11346 if (len < 1) {
11347 ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
11348 free(mybuf);
11349 return -1;
11352 memset(buf + len, 0x7f, END_SILENCE_LEN);
11353 len += END_SILENCE_LEN;
11354 fd = p->subs[index].zfd;
11355 while (len) {
11356 if (ast_check_hangup(c)) {
11357 free(mybuf);
11358 return -1;
11360 size = len;
11361 if (size > READ_SIZE)
11362 size = READ_SIZE;
11363 fds[0].fd = fd;
11364 fds[0].events = POLLOUT | POLLPRI;
11365 fds[0].revents = 0;
11366 res = poll(fds, 1, -1);
11367 if (!res) {
11368 ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
11369 continue;
11371 /* if got exception */
11372 if (fds[0].revents & POLLPRI)
11373 return -1;
11374 if (!(fds[0].revents & POLLOUT)) {
11375 ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
11376 continue;
11378 res = write(fd, buf, size);
11379 if (res != size) {
11380 if (res == -1) {
11381 free(mybuf);
11382 return -1;
11384 if (option_debug)
11385 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
11386 break;
11388 len -= size;
11389 buf += size;
11391 free(mybuf);
11392 return(0);
11396 static int reload(void)
11398 int res = 0;
11400 res = setup_zap(1);
11401 if (res) {
11402 ast_log(LOG_WARNING, "Reload of chan_zap.so is unsuccessful!\n");
11403 return -1;
11405 return 0;
11408 /* This is a workaround so that menuselect displays a proper description
11409 * AST_MODULE_INFO(, , "Zapata Telephony"
11412 #ifdef ZAPATA_PRI
11413 #define tdesc "Zapata Telephony w/PRI"
11414 #else
11415 #define tdesc "Zapata Telephony"
11416 #endif
11418 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, tdesc,
11419 .load = load_module,
11420 .unload = unload_module,
11421 .reload = reload,