Don't declare a function that takes variable arguments as inline, because it's
[asterisk-bristuff.git] / channels / chan_zap.c
blob024fb138fa19f068e3132591101f4a443e2d34bf
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>res_smdi</depend>
42 <depend>zaptel_vldtmf</depend>
43 <depend>zaptel</depend>
44 <depend>tonezone</depend>
45 <depend>res_features</depend>
46 <use>pri</use>
47 ***/
49 #include "asterisk.h"
51 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
53 #include <stdio.h>
54 #include <string.h>
55 #ifdef __NetBSD__
56 #include <pthread.h>
57 #include <signal.h>
58 #else
59 #include <sys/signal.h>
60 #endif
61 #include <errno.h>
62 #include <stdlib.h>
63 #if !defined(SOLARIS) && !defined(__FreeBSD__)
64 #include <stdint.h>
65 #endif
66 #include <unistd.h>
67 #include <sys/ioctl.h>
68 #include <math.h>
69 #include <ctype.h>
70 #include <zaptel/zaptel.h>
71 #include <zaptel/tonezone.h>
73 #ifdef HAVE_PRI
74 #include <libpri.h>
75 #endif
77 #include "asterisk/lock.h"
78 #include "asterisk/channel.h"
79 #include "asterisk/config.h"
80 #include "asterisk/logger.h"
81 #include "asterisk/module.h"
82 #include "asterisk/pbx.h"
83 #include "asterisk/options.h"
84 #include "asterisk/file.h"
85 #include "asterisk/ulaw.h"
86 #include "asterisk/alaw.h"
87 #include "asterisk/callerid.h"
88 #include "asterisk/adsi.h"
89 #include "asterisk/cli.h"
90 #include "asterisk/cdr.h"
91 #include "asterisk/features.h"
92 #include "asterisk/musiconhold.h"
93 #include "asterisk/say.h"
94 #include "asterisk/tdd.h"
95 #include "asterisk/app.h"
96 #include "asterisk/dsp.h"
97 #include "asterisk/astdb.h"
98 #include "asterisk/manager.h"
99 #include "asterisk/causes.h"
100 #include "asterisk/term.h"
101 #include "asterisk/utils.h"
102 #include "asterisk/transcap.h"
103 #include "asterisk/stringfields.h"
104 #include "asterisk/abstract_jb.h"
105 #include "asterisk/smdi.h"
106 #include "asterisk/astobj.h"
107 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
109 /*! Global jitterbuffer configuration - by default, jb is disabled */
110 static struct ast_jb_conf default_jbconf =
112 .flags = 0,
113 .max_size = -1,
114 .resync_threshold = -1,
115 .impl = ""
117 static struct ast_jb_conf global_jbconf;
119 #if !defined(ZT_SIG_EM_E1) || (defined(HAVE_PRI) && !defined(ZT_SIG_HARDHDLC))
120 #error "Your zaptel is too old. Please update"
121 #endif
123 #ifndef ZT_TONEDETECT
124 /* Work around older code with no tone detect */
125 #define ZT_EVENT_DTMFDOWN 0
126 #define ZT_EVENT_DTMFUP 0
127 #endif
129 /* define this to send PRI user-user information elements */
130 #undef SUPPORT_USERUSER
132 /*!
133 * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
134 * the user hangs up to reset the state machine so ring works properly.
135 * This is used to be able to support kewlstart by putting the zhone in
136 * groundstart mode since their forward disconnect supervision is entirely
137 * broken even though their documentation says it isn't and their support
138 * is entirely unwilling to provide any assistance with their channel banks
139 * even though their web site says they support their products for life.
141 /* #define ZHONE_HACK */
143 /*! \note
144 * Define if you want to check the hook state for an FXO (FXS signalled) interface
145 * before dialing on it. Certain FXO interfaces always think they're out of
146 * service with this method however.
148 /* #define ZAP_CHECK_HOOKSTATE */
150 /*! \brief Typically, how many rings before we should send Caller*ID */
151 #define DEFAULT_CIDRINGS 1
153 #define CHANNEL_PSEUDO -12
155 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
157 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
158 #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))
160 static const char tdesc[] = "Zapata Telephony Driver"
161 #ifdef HAVE_PRI
162 " w/PRI"
163 #endif
166 static const char config[] = "zapata.conf";
168 #define SIG_EM ZT_SIG_EM
169 #define SIG_EMWINK (0x0100000 | ZT_SIG_EM)
170 #define SIG_FEATD (0x0200000 | ZT_SIG_EM)
171 #define SIG_FEATDMF (0x0400000 | ZT_SIG_EM)
172 #define SIG_FEATB (0x0800000 | ZT_SIG_EM)
173 #define SIG_E911 (0x1000000 | ZT_SIG_EM)
174 #define SIG_FEATDMF_TA (0x2000000 | ZT_SIG_EM)
175 #define SIG_FGC_CAMA (0x4000000 | ZT_SIG_EM)
176 #define SIG_FGC_CAMAMF (0x8000000 | ZT_SIG_EM)
177 #define SIG_FXSLS ZT_SIG_FXSLS
178 #define SIG_FXSGS ZT_SIG_FXSGS
179 #define SIG_FXSKS ZT_SIG_FXSKS
180 #define SIG_FXOLS ZT_SIG_FXOLS
181 #define SIG_FXOGS ZT_SIG_FXOGS
182 #define SIG_FXOKS ZT_SIG_FXOKS
183 #define SIG_PRI ZT_SIG_CLEAR
184 #define SIG_SF ZT_SIG_SF
185 #define SIG_SFWINK (0x0100000 | ZT_SIG_SF)
186 #define SIG_SF_FEATD (0x0200000 | ZT_SIG_SF)
187 #define SIG_SF_FEATDMF (0x0400000 | ZT_SIG_SF)
188 #define SIG_SF_FEATB (0x0800000 | ZT_SIG_SF)
189 #define SIG_EM_E1 ZT_SIG_EM_E1
190 #define SIG_GR303FXOKS (0x0100000 | ZT_SIG_FXOKS)
191 #define SIG_GR303FXSKS (0x0100000 | ZT_SIG_FXSKS)
193 #define NUM_SPANS 32
194 #define NUM_DCHANS 4 /*!< No more than 4 d-channels */
195 #define MAX_CHANNELS 672 /*!< No more than a DS3 per trunk group */
197 #define CHAN_PSEUDO -2
199 #define DCHAN_PROVISIONED (1 << 0)
200 #define DCHAN_NOTINALARM (1 << 1)
201 #define DCHAN_UP (1 << 2)
203 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
205 static char defaultcic[64] = "";
206 static char defaultozz[64] = "";
208 static char progzone[10] = "";
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 unknown_alarm:1;
465 unsigned int mate:1; /*!< flag to say its in MATE mode */
466 unsigned int outgoing:1;
467 unsigned int overlapdial:1;
468 unsigned int permcallwaiting:1;
469 unsigned int permhidecallerid:1; /*!< Whether to hide our outgoing caller ID or not */
470 unsigned int priindication_oob:1;
471 unsigned int priexclusive:1;
472 unsigned int pulse:1;
473 unsigned int pulsedial:1; /*!< whether a pulse dial phone is detected */
474 unsigned int restrictcid:1; /*!< Whether restrict the callerid -> only send ANI */
475 unsigned int threewaycalling:1;
476 unsigned int transfer:1;
477 unsigned int use_callerid:1; /*!< Whether or not to use caller id on this channel */
478 unsigned int use_callingpres:1; /*!< Whether to use the callingpres the calling switch sends */
479 unsigned int usedistinctiveringdetection:1;
480 unsigned int zaptrcallerid:1; /*!< should we use the callerid from incoming call on zap transfer or not */
481 unsigned int transfertobusy:1; /*!< allow flash-transfers to busy channels */
482 #if defined(HAVE_PRI)
483 unsigned int alerting:1;
484 unsigned int alreadyhungup:1;
485 unsigned int isidlecall:1;
486 unsigned int proceeding:1;
487 unsigned int progress:1;
488 unsigned int resetting:1;
489 unsigned int setup_ack:1;
490 #endif
491 unsigned int use_smdi:1; /* Whether to use SMDI on this channel */
492 struct ast_smdi_interface *smdi_iface; /* The serial port to listen for SMDI data on */
494 struct zt_distRings drings;
496 char context[AST_MAX_CONTEXT];
497 char defcontext[AST_MAX_CONTEXT];
498 char exten[AST_MAX_EXTENSION];
499 char language[MAX_LANGUAGE];
500 char mohinterpret[MAX_MUSICCLASS];
501 char mohsuggest[MAX_MUSICCLASS];
502 #ifdef PRI_ANI
503 char cid_ani[AST_MAX_EXTENSION];
504 #endif
505 char cid_num[AST_MAX_EXTENSION];
506 int cid_ton; /*!< Type Of Number (TON) */
507 char cid_name[AST_MAX_EXTENSION];
508 char lastcid_num[AST_MAX_EXTENSION];
509 char lastcid_name[AST_MAX_EXTENSION];
510 char *origcid_num; /*!< malloced original callerid */
511 char *origcid_name; /*!< malloced original callerid */
512 char callwait_num[AST_MAX_EXTENSION];
513 char callwait_name[AST_MAX_EXTENSION];
514 char rdnis[AST_MAX_EXTENSION];
515 char dnid[AST_MAX_EXTENSION];
516 ast_group_t group;
517 int law;
518 int confno; /*!< Our conference */
519 int confusers; /*!< Who is using our conference */
520 int propconfno; /*!< Propagated conference number */
521 ast_group_t callgroup;
522 ast_group_t pickupgroup;
523 int channel; /*!< Channel Number or CRV */
524 int span; /*!< Span number */
525 time_t guardtime; /*!< Must wait this much time before using for new call */
526 int cid_signalling; /*!< CID signalling type bell202 or v23 */
527 int cid_start; /*!< CID start indicator, polarity or ring */
528 int callingpres; /*!< The value of callling presentation that we're going to use when placing a PRI call */
529 int callwaitingrepeat; /*!< How many samples to wait before repeating call waiting */
530 int cidcwexpire; /*!< When to expire our muting for CID/CW */
531 unsigned char *cidspill;
532 int cidpos;
533 int cidlen;
534 int ringt;
535 int ringt_base;
536 int stripmsd;
537 int callwaitcas;
538 int callwaitrings;
539 int echocancel;
540 int echotraining;
541 char echorest[20];
542 int busycount;
543 int busy_tonelength;
544 int busy_quietlength;
545 int callprogress;
546 struct timeval flashtime; /*!< Last flash-hook time */
547 struct ast_dsp *dsp;
548 int cref; /*!< Call reference number */
549 ZT_DIAL_OPERATION dop;
550 int whichwink; /*!< SIG_FEATDMF_TA Which wink are we on? */
551 char finaldial[64];
552 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
553 int amaflags; /*!< AMA Flags */
554 struct tdd_state *tdd; /*!< TDD flag */
555 char call_forward[AST_MAX_EXTENSION];
556 char mailbox[AST_MAX_EXTENSION];
557 char dialdest[256];
558 int onhooktime;
559 int msgstate;
560 int distinctivering; /*!< Which distinctivering to use */
561 int cidrings; /*!< Which ring to deliver CID on */
562 int dtmfrelax; /*!< whether to run in relaxed DTMF mode */
563 int fake_event;
564 int polarityonanswerdelay;
565 struct timeval polaritydelaytv;
566 int sendcalleridafter;
567 #ifdef HAVE_PRI
568 struct zt_pri *pri;
569 struct zt_pvt *bearer;
570 struct zt_pvt *realcall;
571 q931_call *call;
572 int prioffset;
573 int logicalspan;
574 #endif
575 int polarity;
576 int dsp_features;
577 char begindigit;
578 } *iflist = NULL, *ifend = NULL;
580 /*! \brief Channel configuration from zapata.conf .
581 * This struct is used for parsing the [channels] section of zapata.conf.
582 * Generally there is a field here for every possible configuration item.
584 * The state of fields is saved along the parsing and whenever a 'channel'
585 * statement is reached, the current zt_chan_conf is used to configure the
586 * channel (struct zt_pvt)
588 * @seealso zt_chan_init for the default values.
590 struct zt_chan_conf {
591 struct zt_pvt chan;
592 #ifdef HAVE_PRI
593 struct zt_pri pri;
594 #endif
595 ZT_PARAMS timing;
597 char smdi_port[SMDI_MAX_FILENAME_LEN];
600 /** returns a new zt_chan_conf with default values (by-value) */
601 static struct zt_chan_conf zt_chan_conf_default(void) {
602 /* recall that if a field is not included here it is initialized
603 * to 0 or equivalent
605 struct zt_chan_conf conf = {
606 #ifdef HAVE_PRI
607 .pri = {
608 .nsf = PRI_NSF_NONE,
609 .switchtype = PRI_SWITCH_NI2,
610 .dialplan = PRI_NATIONAL_ISDN + 1,
611 .localdialplan = PRI_NATIONAL_ISDN + 1,
612 .nodetype = PRI_CPE,
614 .minunused = 2,
615 .idleext = "",
616 .idledial = "",
617 .internationalprefix = "",
618 .nationalprefix = "",
619 .localprefix = "",
620 .privateprefix = "",
621 .unknownprefix = "",
623 .resetinterval = 3600
625 #endif
626 .chan = {
627 .context = "default",
628 .cid_num = "",
629 .cid_name = "",
630 .mohinterpret = "default",
631 .mohsuggest = "",
632 .transfertobusy = 1,
634 .cid_signalling = CID_SIG_BELL,
635 .cid_start = CID_START_RING,
636 .zaptrcallerid = 0,
637 .use_callerid = 1,
638 .sig = -1,
639 .outsigmod = -1,
641 .tonezone = -1,
643 .echocancel = 1,
645 .busycount = 3,
647 .accountcode = "",
649 .mailbox = "",
652 .polarityonanswerdelay = 600,
654 .sendcalleridafter = DEFAULT_CIDRINGS
656 .timing = {
657 .prewinktime = -1,
658 .preflashtime = -1,
659 .winktime = -1,
660 .flashtime = -1,
661 .starttime = -1,
662 .rxwinktime = -1,
663 .rxflashtime = -1,
664 .debouncetime = -1
666 .smdi_port = "/dev/ttyS0",
669 return conf;
673 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
674 static int zt_digit_begin(struct ast_channel *ast, char digit);
675 static int zt_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
676 static int zt_sendtext(struct ast_channel *c, const char *text);
677 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
678 static int zt_hangup(struct ast_channel *ast);
679 static int zt_answer(struct ast_channel *ast);
680 static struct ast_frame *zt_read(struct ast_channel *ast);
681 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
682 static struct ast_frame *zt_exception(struct ast_channel *ast);
683 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
684 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
685 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
686 static int zt_func_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
688 static const struct ast_channel_tech zap_tech = {
689 .type = "Zap",
690 .description = tdesc,
691 .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
692 .requester = zt_request,
693 .send_digit_begin = zt_digit_begin,
694 .send_digit_end = zt_digit_end,
695 .send_text = zt_sendtext,
696 .call = zt_call,
697 .hangup = zt_hangup,
698 .answer = zt_answer,
699 .read = zt_read,
700 .write = zt_write,
701 .bridge = zt_bridge,
702 .exception = zt_exception,
703 .indicate = zt_indicate,
704 .fixup = zt_fixup,
705 .setoption = zt_setoption,
706 .func_channel_read = zt_func_read,
709 #ifdef HAVE_PRI
710 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
711 #else
712 #define GET_CHANNEL(p) ((p)->channel)
713 #endif
715 struct zt_pvt *round_robin[32];
717 #ifdef HAVE_PRI
718 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
720 int res;
721 /* Grab the lock first */
722 do {
723 res = ast_mutex_trylock(&pri->lock);
724 if (res) {
725 ast_mutex_unlock(&pvt->lock);
726 /* Release the lock and try again */
727 usleep(1);
728 ast_mutex_lock(&pvt->lock);
730 } while (res);
731 /* Then break the poll */
732 pthread_kill(pri->master, SIGURG);
733 return 0;
735 #endif
737 #define NUM_CADENCE_MAX 25
738 static int num_cadence = 4;
739 static int user_has_defined_cadences = 0;
741 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
742 { { 125, 125, 2000, 4000 } }, /*!< Quick chirp followed by normal ring */
743 { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
744 { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
745 { { 1000, 500, 2500, 5000 } }, /*!< Long ring */
748 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
749 * is 1, the second pause is 2 and so on.
752 static int cidrings[NUM_CADENCE_MAX] = {
753 2, /*!< Right after first long ring */
754 4, /*!< Right after long part */
755 3, /*!< After third chirp */
756 2, /*!< Second spell */
759 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
760 (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
762 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
763 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
765 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
767 int res;
768 if (p->subs[0].owner == ast)
769 res = 0;
770 else if (p->subs[1].owner == ast)
771 res = 1;
772 else if (p->subs[2].owner == ast)
773 res = 2;
774 else {
775 res = -1;
776 if (!nullok)
777 ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
779 return res;
782 #ifdef HAVE_PRI
783 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
784 #else
785 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
786 #endif
788 #ifdef HAVE_PRI
789 if (pri)
790 ast_mutex_unlock(&pri->lock);
791 #endif
792 for (;;) {
793 if (p->subs[a].owner) {
794 if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
795 ast_mutex_unlock(&p->lock);
796 usleep(1);
797 ast_mutex_lock(&p->lock);
798 } else {
799 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
800 ast_mutex_unlock(&p->subs[a].owner->lock);
801 break;
803 } else
804 break;
806 #ifdef HAVE_PRI
807 if (pri)
808 ast_mutex_lock(&pri->lock);
809 #endif
812 #ifdef HAVE_PRI
813 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, struct zt_pri *pri)
814 #else
815 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *pri)
816 #endif
818 /* We must unlock the PRI to avoid the possibility of a deadlock */
819 #ifdef HAVE_PRI
820 if (pri)
821 ast_mutex_unlock(&pri->lock);
822 #endif
823 for (;;) {
824 if (p->owner) {
825 if (ast_mutex_trylock(&p->owner->lock)) {
826 ast_mutex_unlock(&p->lock);
827 usleep(1);
828 ast_mutex_lock(&p->lock);
829 } else {
830 ast_queue_frame(p->owner, f);
831 ast_mutex_unlock(&p->owner->lock);
832 break;
834 } else
835 break;
837 #ifdef HAVE_PRI
838 if (pri)
839 ast_mutex_lock(&pri->lock);
840 #endif
843 static int restore_gains(struct zt_pvt *p);
845 static void swap_subs(struct zt_pvt *p, int a, int b)
847 int tchan;
848 int tinthreeway;
849 struct ast_channel *towner;
851 ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
853 tchan = p->subs[a].chan;
854 towner = p->subs[a].owner;
855 tinthreeway = p->subs[a].inthreeway;
857 p->subs[a].chan = p->subs[b].chan;
858 p->subs[a].owner = p->subs[b].owner;
859 p->subs[a].inthreeway = p->subs[b].inthreeway;
861 p->subs[b].chan = tchan;
862 p->subs[b].owner = towner;
863 p->subs[b].inthreeway = tinthreeway;
865 if (p->subs[a].owner)
866 p->subs[a].owner->fds[0] = p->subs[a].zfd;
867 if (p->subs[b].owner)
868 p->subs[b].owner->fds[0] = p->subs[b].zfd;
869 wakeup_sub(p, a, NULL);
870 wakeup_sub(p, b, NULL);
873 static int zt_open(char *fn)
875 int fd;
876 int isnum;
877 int chan = 0;
878 int bs;
879 int x;
880 isnum = 1;
881 for (x = 0; x < strlen(fn); x++) {
882 if (!isdigit(fn[x])) {
883 isnum = 0;
884 break;
887 if (isnum) {
888 chan = atoi(fn);
889 if (chan < 1) {
890 ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
891 return -1;
893 fn = "/dev/zap/channel";
895 fd = open(fn, O_RDWR | O_NONBLOCK);
896 if (fd < 0) {
897 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
898 return -1;
900 if (chan) {
901 if (ioctl(fd, ZT_SPECIFY, &chan)) {
902 x = errno;
903 close(fd);
904 errno = x;
905 ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
906 return -1;
909 bs = READ_SIZE;
910 if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) {
911 ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs, strerror(errno));
912 x = errno;
913 close(fd);
914 errno = x;
915 return -1;
917 return fd;
920 static void zt_close(int fd)
922 if (fd > 0)
923 close(fd);
926 static int zt_setlinear(int zfd, int linear)
928 int res;
929 res = ioctl(zfd, ZT_SETLINEAR, &linear);
930 if (res)
931 return res;
932 return 0;
936 static int alloc_sub(struct zt_pvt *p, int x)
938 ZT_BUFFERINFO bi;
939 int res;
940 if (p->subs[x].zfd < 0) {
941 p->subs[x].zfd = zt_open("/dev/zap/pseudo");
942 if (p->subs[x].zfd > -1) {
943 res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
944 if (!res) {
945 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
946 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
947 bi.numbufs = numbufs;
948 res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
949 if (res < 0) {
950 ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
952 } else
953 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
954 if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
955 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d\n", p->subs[x].zfd);
956 zt_close(p->subs[x].zfd);
957 p->subs[x].zfd = -1;
958 return -1;
960 if (option_debug)
961 ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
962 return 0;
963 } else
964 ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
965 return -1;
967 ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
968 return -1;
971 static int unalloc_sub(struct zt_pvt *p, int x)
973 if (!x) {
974 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
975 return -1;
977 ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
978 if (p->subs[x].zfd > -1) {
979 zt_close(p->subs[x].zfd);
981 p->subs[x].zfd = -1;
982 p->subs[x].linear = 0;
983 p->subs[x].chan = 0;
984 p->subs[x].owner = NULL;
985 p->subs[x].inthreeway = 0;
986 p->polarity = POLARITY_IDLE;
987 memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
988 return 0;
991 static int digit_to_dtmfindex(char digit)
993 if (isdigit(digit))
994 return ZT_TONE_DTMF_BASE + (digit - '0');
995 else if (digit >= 'A' && digit <= 'D')
996 return ZT_TONE_DTMF_A + (digit - 'A');
997 else if (digit >= 'a' && digit <= 'd')
998 return ZT_TONE_DTMF_A + (digit - 'a');
999 else if (digit == '*')
1000 return ZT_TONE_DTMF_s;
1001 else if (digit == '#')
1002 return ZT_TONE_DTMF_p;
1003 else
1004 return -1;
1007 static int zt_digit_begin(struct ast_channel *chan, char digit)
1009 struct zt_pvt *pvt;
1010 int index;
1011 int dtmf = -1;
1013 pvt = chan->tech_pvt;
1015 ast_mutex_lock(&pvt->lock);
1017 index = zt_get_index(chan, pvt, 0);
1019 if ((index != SUB_REAL) || !pvt->owner)
1020 goto out;
1022 #ifdef HAVE_PRI
1023 if ((pvt->sig == SIG_PRI) && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
1024 if (pvt->setup_ack) {
1025 if (!pri_grab(pvt, pvt->pri)) {
1026 pri_information(pvt->pri->pri, pvt->call, digit);
1027 pri_rel(pvt->pri);
1028 } else
1029 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
1030 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
1031 int res;
1032 ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
1033 res = strlen(pvt->dialdest);
1034 pvt->dialdest[res++] = digit;
1035 pvt->dialdest[res] = '\0';
1037 goto out;
1039 #endif
1040 if ((dtmf = digit_to_dtmfindex(digit)) == -1)
1041 goto out;
1043 if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &dtmf)) {
1044 int res;
1045 ZT_DIAL_OPERATION zo = {
1046 .op = ZT_DIAL_OP_APPEND,
1047 .dialstr[0] = 'T',
1048 .dialstr[1] = digit,
1049 .dialstr[2] = 0,
1051 if ((res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
1052 ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
1053 else
1054 pvt->dialing = 1;
1055 } else {
1056 ast_log(LOG_DEBUG, "Started VLDTMF digit '%c'\n", digit);
1057 pvt->dialing = 1;
1058 pvt->begindigit = digit;
1061 out:
1062 ast_mutex_unlock(&pvt->lock);
1064 return 0;
1067 static int zt_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1069 struct zt_pvt *pvt;
1070 int res = 0;
1071 int index;
1072 int x;
1074 pvt = chan->tech_pvt;
1076 ast_mutex_lock(&pvt->lock);
1078 index = zt_get_index(chan, pvt, 0);
1080 if ((index != SUB_REAL) || !pvt->owner || pvt->pulse)
1081 goto out;
1083 #ifdef HAVE_PRI
1084 /* This means that the digit was already sent via PRI signalling */
1085 if (pvt->sig == SIG_PRI && !pvt->begindigit)
1086 goto out;
1087 #endif
1089 if (pvt->begindigit) {
1090 x = -1;
1091 ast_log(LOG_DEBUG, "Ending VLDTMF digit '%c'\n", digit);
1092 res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &x);
1093 pvt->dialing = 0;
1094 pvt->begindigit = 0;
1097 out:
1098 ast_mutex_unlock(&pvt->lock);
1100 return res;
1103 static char *events[] = {
1104 "No event",
1105 "On hook",
1106 "Ring/Answered",
1107 "Wink/Flash",
1108 "Alarm",
1109 "No more alarm",
1110 "HDLC Abort",
1111 "HDLC Overrun",
1112 "HDLC Bad FCS",
1113 "Dial Complete",
1114 "Ringer On",
1115 "Ringer Off",
1116 "Hook Transition Complete",
1117 "Bits Changed",
1118 "Pulse Start",
1119 "Timer Expired",
1120 "Timer Ping",
1121 "Polarity Reversal",
1122 "Ring Begin",
1125 static struct {
1126 int alarm;
1127 char *name;
1128 } alarms[] = {
1129 { ZT_ALARM_RED, "Red Alarm" },
1130 { ZT_ALARM_YELLOW, "Yellow Alarm" },
1131 { ZT_ALARM_BLUE, "Blue Alarm" },
1132 { ZT_ALARM_RECOVER, "Recovering" },
1133 { ZT_ALARM_LOOPBACK, "Loopback" },
1134 { ZT_ALARM_NOTOPEN, "Not Open" },
1135 { ZT_ALARM_NONE, "None" },
1138 static char *alarm2str(int alarm)
1140 int x;
1141 for (x = 0; x < sizeof(alarms) / sizeof(alarms[0]); x++) {
1142 if (alarms[x].alarm & alarm)
1143 return alarms[x].name;
1145 return alarm ? "Unknown Alarm" : "No Alarm";
1148 static char *event2str(int event)
1150 static char buf[256];
1151 if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
1152 return events[event];
1153 sprintf(buf, "Event %d", event); /* safe */
1154 return buf;
1157 #ifdef HAVE_PRI
1158 static char *dialplan2str(int dialplan)
1160 if (dialplan == -1) {
1161 return("Dynamically set dialplan in ISDN");
1163 return (pri_plan2str(dialplan));
1165 #endif
1167 static char *zap_sig2str(int sig)
1169 static char buf[256];
1170 switch (sig) {
1171 case SIG_EM:
1172 return "E & M Immediate";
1173 case SIG_EMWINK:
1174 return "E & M Wink";
1175 case SIG_EM_E1:
1176 return "E & M E1";
1177 case SIG_FEATD:
1178 return "Feature Group D (DTMF)";
1179 case SIG_FEATDMF:
1180 return "Feature Group D (MF)";
1181 case SIG_FEATDMF_TA:
1182 return "Feature Groud D (MF) Tandem Access";
1183 case SIG_FEATB:
1184 return "Feature Group B (MF)";
1185 case SIG_E911:
1186 return "E911 (MF)";
1187 case SIG_FGC_CAMA:
1188 return "FGC/CAMA (Dialpulse)";
1189 case SIG_FGC_CAMAMF:
1190 return "FGC/CAMA (MF)";
1191 case SIG_FXSLS:
1192 return "FXS Loopstart";
1193 case SIG_FXSGS:
1194 return "FXS Groundstart";
1195 case SIG_FXSKS:
1196 return "FXS Kewlstart";
1197 case SIG_FXOLS:
1198 return "FXO Loopstart";
1199 case SIG_FXOGS:
1200 return "FXO Groundstart";
1201 case SIG_FXOKS:
1202 return "FXO Kewlstart";
1203 case SIG_PRI:
1204 return "ISDN PRI";
1205 case SIG_SF:
1206 return "SF (Tone) Immediate";
1207 case SIG_SFWINK:
1208 return "SF (Tone) Wink";
1209 case SIG_SF_FEATD:
1210 return "SF (Tone) with Feature Group D (DTMF)";
1211 case SIG_SF_FEATDMF:
1212 return "SF (Tone) with Feature Group D (MF)";
1213 case SIG_SF_FEATB:
1214 return "SF (Tone) with Feature Group B (MF)";
1215 case SIG_GR303FXOKS:
1216 return "GR-303 with FXOKS";
1217 case SIG_GR303FXSKS:
1218 return "GR-303 with FXSKS";
1219 case 0:
1220 return "Pseudo";
1221 default:
1222 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1223 return buf;
1227 #define sig2str zap_sig2str
1229 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1231 /* If the conference already exists, and we're already in it
1232 don't bother doing anything */
1233 ZT_CONFINFO zi;
1235 memset(&zi, 0, sizeof(zi));
1236 zi.chan = 0;
1238 if (slavechannel > 0) {
1239 /* If we have only one slave, do a digital mon */
1240 zi.confmode = ZT_CONF_DIGITALMON;
1241 zi.confno = slavechannel;
1242 } else {
1243 if (!index) {
1244 /* Real-side and pseudo-side both participate in conference */
1245 zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1246 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1247 } else
1248 zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1249 zi.confno = p->confno;
1251 if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1252 return 0;
1253 if (c->zfd < 0)
1254 return 0;
1255 if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1256 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1257 return -1;
1259 if (slavechannel < 1) {
1260 p->confno = zi.confno;
1262 memcpy(&c->curconf, &zi, sizeof(c->curconf));
1263 ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1264 return 0;
1267 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1269 /* If they're listening to our channel, they're ours */
1270 if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1271 return 1;
1272 /* If they're a talker on our (allocated) conference, they're ours */
1273 if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1274 return 1;
1275 return 0;
1278 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1280 ZT_CONFINFO zi;
1281 if (/* Can't delete if there's no zfd */
1282 (c->zfd < 0) ||
1283 /* Don't delete from the conference if it's not our conference */
1284 !isourconf(p, c)
1285 /* Don't delete if we don't think it's conferenced at all (implied) */
1286 ) return 0;
1287 memset(&zi, 0, sizeof(zi));
1288 zi.chan = 0;
1289 zi.confno = 0;
1290 zi.confmode = 0;
1291 if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1292 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1293 return -1;
1295 ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1296 memcpy(&c->curconf, &zi, sizeof(c->curconf));
1297 return 0;
1300 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1302 int x;
1303 int useslavenative;
1304 struct zt_pvt *slave = NULL;
1305 /* Start out optimistic */
1306 useslavenative = 1;
1307 /* Update conference state in a stateless fashion */
1308 for (x = 0; x < 3; x++) {
1309 /* Any three-way calling makes slave native mode *definitely* out
1310 of the question */
1311 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1312 useslavenative = 0;
1314 /* If we don't have any 3-way calls, check to see if we have
1315 precisely one slave */
1316 if (useslavenative) {
1317 for (x = 0; x < MAX_SLAVES; x++) {
1318 if (p->slaves[x]) {
1319 if (slave) {
1320 /* Whoops already have a slave! No
1321 slave native and stop right away */
1322 slave = NULL;
1323 useslavenative = 0;
1324 break;
1325 } else {
1326 /* We have one slave so far */
1327 slave = p->slaves[x];
1332 /* If no slave, slave native definitely out */
1333 if (!slave)
1334 useslavenative = 0;
1335 else if (slave->law != p->law) {
1336 useslavenative = 0;
1337 slave = NULL;
1339 if (out)
1340 *out = slave;
1341 return useslavenative;
1344 static int reset_conf(struct zt_pvt *p)
1346 ZT_CONFINFO zi;
1347 memset(&zi, 0, sizeof(zi));
1348 p->confno = -1;
1349 memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1350 if (p->subs[SUB_REAL].zfd > -1) {
1351 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1352 ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1354 return 0;
1357 static int update_conf(struct zt_pvt *p)
1359 int needconf = 0;
1360 int x;
1361 int useslavenative;
1362 struct zt_pvt *slave = NULL;
1364 useslavenative = isslavenative(p, &slave);
1365 /* Start with the obvious, general stuff */
1366 for (x = 0; x < 3; x++) {
1367 /* Look for three way calls */
1368 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1369 conf_add(p, &p->subs[x], x, 0);
1370 needconf++;
1371 } else {
1372 conf_del(p, &p->subs[x], x);
1375 /* If we have a slave, add him to our conference now. or DAX
1376 if this is slave native */
1377 for (x = 0; x < MAX_SLAVES; x++) {
1378 if (p->slaves[x]) {
1379 if (useslavenative)
1380 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1381 else {
1382 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1383 needconf++;
1387 /* If we're supposed to be in there, do so now */
1388 if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1389 if (useslavenative)
1390 conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1391 else {
1392 conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1393 needconf++;
1396 /* If we have a master, add ourselves to his conference */
1397 if (p->master) {
1398 if (isslavenative(p->master, NULL)) {
1399 conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1400 } else {
1401 conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1404 if (!needconf) {
1405 /* Nobody is left (or should be left) in our conference.
1406 Kill it. */
1407 p->confno = -1;
1409 if (option_debug)
1410 ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1411 return 0;
1414 static void zt_enable_ec(struct zt_pvt *p)
1416 int x;
1417 int res;
1418 if (!p)
1419 return;
1420 if (p->echocanon) {
1421 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1422 return;
1424 if (p->digital) {
1425 ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
1426 return;
1428 if (p->echocancel) {
1429 if (p->sig == SIG_PRI) {
1430 x = 1;
1431 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1432 if (res)
1433 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n", p->channel, strerror(errno));
1435 x = p->echocancel;
1436 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1437 if (res)
1438 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
1439 else {
1440 p->echocanon = 1;
1441 if (option_debug)
1442 ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1444 } else if (option_debug)
1445 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1448 static void zt_train_ec(struct zt_pvt *p)
1450 int x;
1451 int res;
1452 if (p && p->echocancel && p->echotraining) {
1453 x = p->echotraining;
1454 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1455 if (res)
1456 ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1457 else {
1458 ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1460 } else
1461 ast_log(LOG_DEBUG, "No echo training requested\n");
1464 static void zt_disable_ec(struct zt_pvt *p)
1466 int x;
1467 int res;
1468 if (p->echocancel) {
1469 x = 0;
1470 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1471 if (res)
1472 ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1473 else if (option_debug)
1474 ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1476 p->echocanon = 0;
1479 static void fill_txgain(struct zt_gains *g, float gain, int law)
1481 int j;
1482 int k;
1483 float linear_gain = pow(10.0, gain / 20.0);
1485 switch (law) {
1486 case ZT_LAW_ALAW:
1487 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1488 if (gain) {
1489 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1490 if (k > 32767) k = 32767;
1491 if (k < -32767) k = -32767;
1492 g->txgain[j] = AST_LIN2A(k);
1493 } else {
1494 g->txgain[j] = j;
1497 break;
1498 case ZT_LAW_MULAW:
1499 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1500 if (gain) {
1501 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1502 if (k > 32767) k = 32767;
1503 if (k < -32767) k = -32767;
1504 g->txgain[j] = AST_LIN2MU(k);
1505 } else {
1506 g->txgain[j] = j;
1509 break;
1513 static void fill_rxgain(struct zt_gains *g, float gain, int law)
1515 int j;
1516 int k;
1517 float linear_gain = pow(10.0, gain / 20.0);
1519 switch (law) {
1520 case ZT_LAW_ALAW:
1521 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1522 if (gain) {
1523 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1524 if (k > 32767) k = 32767;
1525 if (k < -32767) k = -32767;
1526 g->rxgain[j] = AST_LIN2A(k);
1527 } else {
1528 g->rxgain[j] = j;
1531 break;
1532 case ZT_LAW_MULAW:
1533 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1534 if (gain) {
1535 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1536 if (k > 32767) k = 32767;
1537 if (k < -32767) k = -32767;
1538 g->rxgain[j] = AST_LIN2MU(k);
1539 } else {
1540 g->rxgain[j] = j;
1543 break;
1547 static int set_actual_txgain(int fd, int chan, float gain, int law)
1549 struct zt_gains g;
1550 int res;
1552 memset(&g, 0, sizeof(g));
1553 g.chan = chan;
1554 res = ioctl(fd, ZT_GETGAINS, &g);
1555 if (res) {
1556 if (option_debug)
1557 ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1558 return res;
1561 fill_txgain(&g, gain, law);
1563 return ioctl(fd, ZT_SETGAINS, &g);
1566 static int set_actual_rxgain(int fd, int chan, float gain, int law)
1568 struct zt_gains g;
1569 int res;
1571 memset(&g, 0, sizeof(g));
1572 g.chan = chan;
1573 res = ioctl(fd, ZT_GETGAINS, &g);
1574 if (res) {
1575 ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1576 return res;
1579 fill_rxgain(&g, gain, law);
1581 return ioctl(fd, ZT_SETGAINS, &g);
1584 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1586 return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
1589 static int bump_gains(struct zt_pvt *p)
1591 int res;
1593 /* Bump receive gain by 5.0db */
1594 res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + 5.0, p->txgain, p->law);
1595 if (res) {
1596 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
1597 return -1;
1600 return 0;
1603 static int restore_gains(struct zt_pvt *p)
1605 int res;
1607 res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1608 if (res) {
1609 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
1610 return -1;
1613 return 0;
1616 static inline int zt_set_hook(int fd, int hs)
1618 int x, res;
1620 x = hs;
1621 res = ioctl(fd, ZT_HOOK, &x);
1623 if (res < 0) {
1624 if (errno == EINPROGRESS)
1625 return 0;
1626 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1629 return res;
1632 static inline int zt_confmute(struct zt_pvt *p, int muted)
1634 int x, y, res;
1635 x = muted;
1636 if (p->sig == SIG_PRI) {
1637 y = 1;
1638 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1639 if (res)
1640 ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1642 res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1643 if (res < 0)
1644 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1645 return res;
1648 static int save_conference(struct zt_pvt *p)
1650 struct zt_confinfo c;
1651 int res;
1652 if (p->saveconf.confmode) {
1653 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1654 return -1;
1656 p->saveconf.chan = 0;
1657 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1658 if (res) {
1659 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1660 p->saveconf.confmode = 0;
1661 return -1;
1663 c.chan = 0;
1664 c.confno = 0;
1665 c.confmode = ZT_CONF_NORMAL;
1666 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1667 if (res) {
1668 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1669 return -1;
1671 if (option_debug)
1672 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1673 return 0;
1676 static int restore_conference(struct zt_pvt *p)
1678 int res;
1679 if (p->saveconf.confmode) {
1680 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1681 p->saveconf.confmode = 0;
1682 if (res) {
1683 ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1684 return -1;
1687 if (option_debug)
1688 ast_log(LOG_DEBUG, "Restored conferencing\n");
1689 return 0;
1692 static int send_callerid(struct zt_pvt *p);
1694 static int send_cwcidspill(struct zt_pvt *p)
1696 p->callwaitcas = 0;
1697 p->cidcwexpire = 0;
1698 if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
1699 return -1;
1700 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1701 /* Make sure we account for the end */
1702 p->cidlen += READ_SIZE * 4;
1703 p->cidpos = 0;
1704 send_callerid(p);
1705 if (option_verbose > 2)
1706 ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID. Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1707 return 0;
1710 static int has_voicemail(struct zt_pvt *p)
1713 return ast_app_has_voicemail(p->mailbox, NULL);
1716 static int send_callerid(struct zt_pvt *p)
1718 /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1719 int res;
1720 /* Take out of linear mode if necessary */
1721 if (p->subs[SUB_REAL].linear) {
1722 p->subs[SUB_REAL].linear = 0;
1723 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1725 while (p->cidpos < p->cidlen) {
1726 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1727 if (res < 0) {
1728 if (errno == EAGAIN)
1729 return 0;
1730 else {
1731 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1732 return -1;
1735 if (!res)
1736 return 0;
1737 p->cidpos += res;
1739 free(p->cidspill);
1740 p->cidspill = NULL;
1741 if (p->callwaitcas) {
1742 /* Wait for CID/CW to expire */
1743 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1744 } else
1745 restore_conference(p);
1746 return 0;
1749 static int zt_callwait(struct ast_channel *ast)
1751 struct zt_pvt *p = ast->tech_pvt;
1752 p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1753 if (p->cidspill) {
1754 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1755 free(p->cidspill);
1757 if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
1758 return -1;
1759 save_conference(p);
1760 /* Silence */
1761 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1762 if (!p->callwaitrings && p->callwaitingcallerid) {
1763 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1764 p->callwaitcas = 1;
1765 p->cidlen = 2400 + 680 + READ_SIZE * 4;
1766 } else {
1767 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1768 p->callwaitcas = 0;
1769 p->cidlen = 2400 + READ_SIZE * 4;
1771 p->cidpos = 0;
1772 send_callerid(p);
1774 return 0;
1777 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1779 struct zt_pvt *p = ast->tech_pvt;
1780 int x, res, index,mysig;
1781 char *c, *n, *l;
1782 #ifdef HAVE_PRI
1783 char *s = NULL;
1784 #endif
1785 char dest[256]; /* must be same length as p->dialdest */
1786 ast_mutex_lock(&p->lock);
1787 ast_copy_string(dest, rdest, sizeof(dest));
1788 ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
1789 if ((ast->_state == AST_STATE_BUSY)) {
1790 p->subs[SUB_REAL].needbusy = 1;
1791 ast_mutex_unlock(&p->lock);
1792 return 0;
1794 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1795 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1796 ast_mutex_unlock(&p->lock);
1797 return -1;
1799 p->dialednone = 0;
1800 if ((p->radio || (p->oprmode < 0))) /* if a radio channel, up immediately */
1802 /* Special pseudo -- automatically up */
1803 ast_setstate(ast, AST_STATE_UP);
1804 ast_mutex_unlock(&p->lock);
1805 return 0;
1807 x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1808 res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1809 if (res)
1810 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1811 p->outgoing = 1;
1813 set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1815 mysig = p->sig;
1816 if (p->outsigmod > -1)
1817 mysig = p->outsigmod;
1819 switch (mysig) {
1820 case SIG_FXOLS:
1821 case SIG_FXOGS:
1822 case SIG_FXOKS:
1823 if (p->owner == ast) {
1824 /* Normal ring, on hook */
1826 /* Don't send audio while on hook, until the call is answered */
1827 p->dialing = 1;
1828 if (p->use_callerid) {
1829 /* Generate the Caller-ID spill if desired */
1830 if (p->cidspill) {
1831 ast_log(LOG_WARNING, "cidspill already exists??\n");
1832 free(p->cidspill);
1834 p->callwaitcas = 0;
1835 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
1836 p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1837 p->cidpos = 0;
1838 send_callerid(p);
1841 /* Choose proper cadence */
1842 if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1843 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering - 1]))
1844 ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1845 p->cidrings = cidrings[p->distinctivering - 1];
1846 } else {
1847 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1848 ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1849 p->cidrings = p->sendcalleridafter;
1852 /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1853 c = strchr(dest, '/');
1854 if (c)
1855 c++;
1856 if (c && (strlen(c) < p->stripmsd)) {
1857 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1858 c = NULL;
1860 if (c) {
1861 p->dop.op = ZT_DIAL_OP_REPLACE;
1862 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1863 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1864 } else {
1865 p->dop.dialstr[0] = '\0';
1867 x = ZT_RING;
1868 if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1869 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1870 ast_mutex_unlock(&p->lock);
1871 return -1;
1873 p->dialing = 1;
1874 } else {
1875 /* Call waiting call */
1876 p->callwaitrings = 0;
1877 if (ast->cid.cid_num)
1878 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
1879 else
1880 p->callwait_num[0] = '\0';
1881 if (ast->cid.cid_name)
1882 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
1883 else
1884 p->callwait_name[0] = '\0';
1885 /* Call waiting tone instead */
1886 if (zt_callwait(ast)) {
1887 ast_mutex_unlock(&p->lock);
1888 return -1;
1890 /* Make ring-back */
1891 if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1892 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1895 n = ast->cid.cid_name;
1896 l = ast->cid.cid_num;
1897 if (l)
1898 ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
1899 else
1900 p->lastcid_num[0] = '\0';
1901 if (n)
1902 ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
1903 else
1904 p->lastcid_name[0] = '\0';
1905 ast_setstate(ast, AST_STATE_RINGING);
1906 index = zt_get_index(ast, p, 0);
1907 if (index > -1) {
1908 p->subs[index].needringing = 1;
1910 break;
1911 case SIG_FXSLS:
1912 case SIG_FXSGS:
1913 case SIG_FXSKS:
1914 case SIG_EMWINK:
1915 case SIG_EM:
1916 case SIG_EM_E1:
1917 case SIG_FEATD:
1918 case SIG_FEATDMF:
1919 case SIG_E911:
1920 case SIG_FGC_CAMA:
1921 case SIG_FGC_CAMAMF:
1922 case SIG_FEATB:
1923 case SIG_SFWINK:
1924 case SIG_SF:
1925 case SIG_SF_FEATD:
1926 case SIG_SF_FEATDMF:
1927 case SIG_FEATDMF_TA:
1928 case SIG_SF_FEATB:
1929 c = strchr(dest, '/');
1930 if (c)
1931 c++;
1932 else
1933 c = "";
1934 if (strlen(c) < p->stripmsd) {
1935 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1936 ast_mutex_unlock(&p->lock);
1937 return -1;
1939 #ifdef HAVE_PRI
1940 /* Start the trunk, if not GR-303 */
1941 if (!p->pri) {
1942 #endif
1943 x = ZT_START;
1944 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1945 if (res < 0) {
1946 if (errno != EINPROGRESS) {
1947 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1948 ast_mutex_unlock(&p->lock);
1949 return -1;
1952 #ifdef HAVE_PRI
1954 #endif
1955 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1956 p->dop.op = ZT_DIAL_OP_REPLACE;
1958 c += p->stripmsd;
1960 switch (mysig) {
1961 case SIG_FEATD:
1962 l = ast->cid.cid_num;
1963 if (l)
1964 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
1965 else
1966 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
1967 break;
1968 case SIG_FEATDMF:
1969 l = ast->cid.cid_num;
1970 if (l)
1971 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
1972 else
1973 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
1974 break;
1975 case SIG_FEATDMF_TA:
1977 const char *cic, *ozz;
1979 /* If you have to go through a Tandem Access point you need to use this */
1980 ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
1981 if (!ozz)
1982 ozz = defaultozz;
1983 cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
1984 if (!cic)
1985 cic = defaultcic;
1986 if (!ozz || !cic) {
1987 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
1988 ast_mutex_unlock(&p->lock);
1989 return -1;
1991 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
1992 snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
1993 p->whichwink = 0;
1995 break;
1996 case SIG_E911:
1997 ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
1998 break;
1999 case SIG_FGC_CAMA:
2000 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
2001 break;
2002 case SIG_FGC_CAMAMF:
2003 case SIG_FEATB:
2004 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
2005 break;
2006 default:
2007 if (p->pulse)
2008 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
2009 else
2010 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
2011 break;
2014 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
2015 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2016 strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2017 p->echorest[sizeof(p->echorest) - 1] = '\0';
2018 p->echobreak = 1;
2019 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2020 } else
2021 p->echobreak = 0;
2022 if (!res) {
2023 if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
2024 x = ZT_ONHOOK;
2025 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2026 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
2027 ast_mutex_unlock(&p->lock);
2028 return -1;
2030 } else
2031 ast_log(LOG_DEBUG, "Deferring dialing...\n");
2032 p->dialing = 1;
2033 if (ast_strlen_zero(c))
2034 p->dialednone = 1;
2035 ast_setstate(ast, AST_STATE_DIALING);
2036 break;
2037 case 0:
2038 /* Special pseudo -- automatically up*/
2039 ast_setstate(ast, AST_STATE_UP);
2040 break;
2041 case SIG_PRI:
2042 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
2043 p->dialdest[0] = '\0';
2044 break;
2045 default:
2046 ast_log(LOG_DEBUG, "not yet implemented\n");
2047 ast_mutex_unlock(&p->lock);
2048 return -1;
2050 #ifdef HAVE_PRI
2051 if (p->pri) {
2052 struct pri_sr *sr;
2053 #ifdef SUPPORT_USERUSER
2054 const char *useruser;
2055 #endif
2056 int pridialplan;
2057 int dp_strip;
2058 int prilocaldialplan;
2059 int ldp_strip;
2060 int exclusive;
2061 const char *rr_str;
2062 int redirect_reason;
2064 c = strchr(dest, '/');
2065 if (c)
2066 c++;
2067 else
2068 c = dest;
2070 l = NULL;
2071 n = NULL;
2073 if (!p->hidecallerid) {
2074 l = ast->cid.cid_num;
2075 if (!p->hidecalleridname) {
2076 n = ast->cid.cid_name;
2081 if (strlen(c) < p->stripmsd) {
2082 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2083 ast_mutex_unlock(&p->lock);
2084 return -1;
2086 if (mysig != SIG_FXSKS) {
2087 p->dop.op = ZT_DIAL_OP_REPLACE;
2088 s = strchr(c + p->stripmsd, 'w');
2089 if (s) {
2090 if (strlen(s) > 1)
2091 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2092 else
2093 p->dop.dialstr[0] = '\0';
2094 *s = '\0';
2095 } else {
2096 p->dop.dialstr[0] = '\0';
2099 if (pri_grab(p, p->pri)) {
2100 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2101 ast_mutex_unlock(&p->lock);
2102 return -1;
2104 if (!(p->call = pri_new_call(p->pri->pri))) {
2105 ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2106 pri_rel(p->pri);
2107 ast_mutex_unlock(&p->lock);
2108 return -1;
2110 if (!(sr = pri_sr_new())) {
2111 ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2112 pri_rel(p->pri);
2113 ast_mutex_unlock(&p->lock);
2115 if (p->bearer || (mysig == SIG_FXSKS)) {
2116 if (p->bearer) {
2117 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);
2118 p->bearer->call = p->call;
2119 } else
2120 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
2121 pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2123 p->digital = IS_DIGITAL(ast->transfercapability);
2124 /* Add support for exclusive override */
2125 if (p->priexclusive)
2126 exclusive = 1;
2127 else {
2128 /* otherwise, traditional behavior */
2129 if (p->pri->nodetype == PRI_NETWORK)
2130 exclusive = 0;
2131 else
2132 exclusive = 1;
2135 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2136 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability,
2137 (p->digital ? -1 :
2138 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2139 if (p->pri->facilityenable)
2140 pri_facility_enable(p->pri->pri);
2142 if (option_verbose > 2)
2143 ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2144 dp_strip = 0;
2145 pridialplan = p->pri->dialplan - 1;
2146 if (pridialplan == -2) { /* compute dynamically */
2147 if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2148 dp_strip = strlen(p->pri->internationalprefix);
2149 pridialplan = PRI_INTERNATIONAL_ISDN;
2150 } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2151 dp_strip = strlen(p->pri->nationalprefix);
2152 pridialplan = PRI_NATIONAL_ISDN;
2153 } else {
2154 pridialplan = PRI_LOCAL_ISDN;
2157 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2159 ldp_strip = 0;
2160 prilocaldialplan = p->pri->localdialplan - 1;
2161 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
2162 if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2163 ldp_strip = strlen(p->pri->internationalprefix);
2164 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2165 } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2166 ldp_strip = strlen(p->pri->nationalprefix);
2167 prilocaldialplan = PRI_NATIONAL_ISDN;
2168 } else {
2169 prilocaldialplan = PRI_LOCAL_ISDN;
2172 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2173 p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2174 if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
2175 if (!strcasecmp(rr_str, "UNKNOWN"))
2176 redirect_reason = 0;
2177 else if (!strcasecmp(rr_str, "BUSY"))
2178 redirect_reason = 1;
2179 else if (!strcasecmp(rr_str, "NO_REPLY"))
2180 redirect_reason = 2;
2181 else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
2182 redirect_reason = 15;
2183 else
2184 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2185 } else
2186 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2187 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
2189 #ifdef SUPPORT_USERUSER
2190 /* User-user info */
2191 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2193 if (useruser)
2194 pri_sr_set_useruser(sr, useruser);
2195 #endif
2197 if (pri_setup(p->pri->pri, p->call, sr)) {
2198 ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n",
2199 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2200 pri_rel(p->pri);
2201 ast_mutex_unlock(&p->lock);
2202 pri_sr_free(sr);
2203 return -1;
2205 pri_sr_free(sr);
2206 ast_setstate(ast, AST_STATE_DIALING);
2207 pri_rel(p->pri);
2209 #endif
2210 ast_mutex_unlock(&p->lock);
2211 return 0;
2214 static void destroy_zt_pvt(struct zt_pvt **pvt)
2216 struct zt_pvt *p = *pvt;
2217 /* Remove channel from the list */
2218 if (p->prev)
2219 p->prev->next = p->next;
2220 if (p->next)
2221 p->next->prev = p->prev;
2222 if (p->use_smdi)
2223 ast_smdi_interface_unref(p->smdi_iface);
2224 ast_mutex_destroy(&p->lock);
2225 free(p);
2226 *pvt = NULL;
2229 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
2231 int owned = 0;
2232 int i = 0;
2234 if (!now) {
2235 if (cur->owner) {
2236 owned = 1;
2239 for (i = 0; i < 3; i++) {
2240 if (cur->subs[i].owner) {
2241 owned = 1;
2244 if (!owned) {
2245 if (prev) {
2246 prev->next = cur->next;
2247 if (prev->next)
2248 prev->next->prev = prev;
2249 else
2250 ifend = prev;
2251 } else {
2252 iflist = cur->next;
2253 if (iflist)
2254 iflist->prev = NULL;
2255 else
2256 ifend = NULL;
2258 if (cur->subs[SUB_REAL].zfd > -1) {
2259 zt_close(cur->subs[SUB_REAL].zfd);
2261 destroy_zt_pvt(&cur);
2263 } else {
2264 if (prev) {
2265 prev->next = cur->next;
2266 if (prev->next)
2267 prev->next->prev = prev;
2268 else
2269 ifend = prev;
2270 } else {
2271 iflist = cur->next;
2272 if (iflist)
2273 iflist->prev = NULL;
2274 else
2275 ifend = NULL;
2277 if (cur->subs[SUB_REAL].zfd > -1) {
2278 zt_close(cur->subs[SUB_REAL].zfd);
2280 destroy_zt_pvt(&cur);
2282 return 0;
2285 #ifdef HAVE_PRI
2286 static char *zap_send_keypad_facility_app = "ZapSendKeypadFacility";
2288 static char *zap_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
2290 static char *zap_send_keypad_facility_descrip =
2291 " ZapSendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
2292 " IE over the current channel.\n";
2294 static int zap_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2296 /* Data will be our digit string */
2297 struct zt_pvt *p;
2298 char *digits = (char *) data;
2300 if (ast_strlen_zero(digits)) {
2301 ast_log(LOG_DEBUG, "No digit string sent to application!\n");
2302 return -1;
2305 p = (struct zt_pvt *)chan->tech_pvt;
2307 if (!p) {
2308 ast_log(LOG_DEBUG, "Unable to find technology private\n");
2309 return -1;
2312 ast_mutex_lock(&p->lock);
2314 if (!p->pri || !p->call) {
2315 ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
2316 ast_mutex_unlock(&p->lock);
2317 return -1;
2320 if (!pri_grab(p, p->pri)) {
2321 pri_keypad_facility(p->pri->pri, p->call, digits);
2322 pri_rel(p->pri);
2323 } else {
2324 ast_log(LOG_DEBUG, "Unable to grab pri to send keypad facility!\n");
2325 ast_mutex_unlock(&p->lock);
2326 return -1;
2329 ast_mutex_unlock(&p->lock);
2331 return 0;
2334 static int pri_is_up(struct zt_pri *pri)
2336 int x;
2337 for (x = 0; x < NUM_DCHANS; x++) {
2338 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2339 return 1;
2341 return 0;
2344 static int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2346 bearer->owner = &inuse;
2347 bearer->realcall = crv;
2348 crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2349 if (crv->subs[SUB_REAL].owner)
2350 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2351 crv->bearer = bearer;
2352 crv->call = bearer->call;
2353 crv->pri = pri;
2354 return 0;
2357 static char *pri_order(int level)
2359 switch (level) {
2360 case 0:
2361 return "Primary";
2362 case 1:
2363 return "Secondary";
2364 case 2:
2365 return "Tertiary";
2366 case 3:
2367 return "Quaternary";
2368 default:
2369 return "<Unknown>";
2373 /* Returns fd of the active dchan */
2374 static int pri_active_dchan_fd(struct zt_pri *pri)
2376 int x = -1;
2378 for (x = 0; x < NUM_DCHANS; x++) {
2379 if ((pri->dchans[x] == pri->pri))
2380 break;
2383 return pri->fds[x];
2386 static int pri_find_dchan(struct zt_pri *pri)
2388 int oldslot = -1;
2389 struct pri *old;
2390 int newslot = -1;
2391 int x;
2392 old = pri->pri;
2393 for (x = 0; x < NUM_DCHANS; x++) {
2394 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2395 newslot = x;
2396 if (pri->dchans[x] == old) {
2397 oldslot = x;
2400 if (newslot < 0) {
2401 newslot = 0;
2402 ast_log(LOG_WARNING, "No D-channels available! Using Primary channel %d as D-channel anyway!\n",
2403 pri->dchannels[newslot]);
2405 if (old && (oldslot != newslot))
2406 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2407 pri->dchannels[oldslot], pri->dchannels[newslot]);
2408 pri->pri = pri->dchans[newslot];
2409 return 0;
2411 #endif
2413 static int zt_hangup(struct ast_channel *ast)
2415 int res;
2416 int index,x, law;
2417 /*static int restore_gains(struct zt_pvt *p);*/
2418 struct zt_pvt *p = ast->tech_pvt;
2419 struct zt_pvt *tmp = NULL;
2420 struct zt_pvt *prev = NULL;
2421 ZT_PARAMS par;
2423 if (option_debug)
2424 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2425 if (!ast->tech_pvt) {
2426 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2427 return 0;
2430 ast_mutex_lock(&p->lock);
2432 index = zt_get_index(ast, p, 1);
2434 if (p->sig == SIG_PRI) {
2435 x = 1;
2436 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2439 x = 0;
2440 zt_confmute(p, 0);
2441 restore_gains(p);
2442 if (p->origcid_num) {
2443 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2444 free(p->origcid_num);
2445 p->origcid_num = NULL;
2447 if (p->origcid_name) {
2448 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2449 free(p->origcid_name);
2450 p->origcid_name = NULL;
2452 if (p->dsp)
2453 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2454 if (p->exten)
2455 p->exten[0] = '\0';
2457 if (option_debug)
2458 ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2459 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2460 p->ignoredtmf = 0;
2462 if (index > -1) {
2463 /* Real channel, do some fixup */
2464 p->subs[index].owner = NULL;
2465 p->subs[index].needanswer = 0;
2466 p->subs[index].needflash = 0;
2467 p->subs[index].needringing = 0;
2468 p->subs[index].needbusy = 0;
2469 p->subs[index].needcongestion = 0;
2470 p->subs[index].linear = 0;
2471 p->subs[index].needcallerid = 0;
2472 p->polarity = POLARITY_IDLE;
2473 zt_setlinear(p->subs[index].zfd, 0);
2474 if (index == SUB_REAL) {
2475 if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2476 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2477 if (p->subs[SUB_CALLWAIT].inthreeway) {
2478 /* We had flipped over to answer a callwait and now it's gone */
2479 ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2480 /* Move to the call-wait, but un-own us until they flip back. */
2481 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2482 unalloc_sub(p, SUB_CALLWAIT);
2483 p->owner = NULL;
2484 } else {
2485 /* The three way hung up, but we still have a call wait */
2486 ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still. Ditching the threeway.\n");
2487 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2488 unalloc_sub(p, SUB_THREEWAY);
2489 if (p->subs[SUB_REAL].inthreeway) {
2490 /* This was part of a three way call. Immediately make way for
2491 another call */
2492 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2493 p->owner = p->subs[SUB_REAL].owner;
2494 } else {
2495 /* This call hasn't been completed yet... Set owner to NULL */
2496 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2497 p->owner = NULL;
2499 p->subs[SUB_REAL].inthreeway = 0;
2501 } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2502 /* Move to the call-wait and switch back to them. */
2503 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2504 unalloc_sub(p, SUB_CALLWAIT);
2505 p->owner = p->subs[SUB_REAL].owner;
2506 if (p->owner->_state != AST_STATE_UP)
2507 p->subs[SUB_REAL].needanswer = 1;
2508 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2509 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
2510 } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2511 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2512 unalloc_sub(p, SUB_THREEWAY);
2513 if (p->subs[SUB_REAL].inthreeway) {
2514 /* This was part of a three way call. Immediately make way for
2515 another call */
2516 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2517 p->owner = p->subs[SUB_REAL].owner;
2518 } else {
2519 /* This call hasn't been completed yet... Set owner to NULL */
2520 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2521 p->owner = NULL;
2523 p->subs[SUB_REAL].inthreeway = 0;
2525 } else if (index == SUB_CALLWAIT) {
2526 /* Ditch the holding callwait call, and immediately make it availabe */
2527 if (p->subs[SUB_CALLWAIT].inthreeway) {
2528 /* This is actually part of a three way, placed on hold. Place the third part
2529 on music on hold now */
2530 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
2531 ast_queue_control_data(p->subs[SUB_THREEWAY].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_THREEWAY].inthreeway = 0;
2536 /* Make it the call wait now */
2537 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2538 unalloc_sub(p, SUB_THREEWAY);
2539 } else
2540 unalloc_sub(p, SUB_CALLWAIT);
2541 } else if (index == SUB_THREEWAY) {
2542 if (p->subs[SUB_CALLWAIT].inthreeway) {
2543 /* The other party of the three way call is currently in a call-wait state.
2544 Start music on hold for them, and take the main guy out of the third call */
2545 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
2546 ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
2547 S_OR(p->mohsuggest, NULL),
2548 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2550 p->subs[SUB_CALLWAIT].inthreeway = 0;
2552 p->subs[SUB_REAL].inthreeway = 0;
2553 /* If this was part of a three way call index, let us make
2554 another three way call */
2555 unalloc_sub(p, SUB_THREEWAY);
2556 } else {
2557 /* This wasn't any sort of call, but how are we an index? */
2558 ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2562 if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2563 p->owner = NULL;
2564 p->ringt = 0;
2565 p->distinctivering = 0;
2566 p->confirmanswer = 0;
2567 p->cidrings = 1;
2568 p->outgoing = 0;
2569 p->digital = 0;
2570 p->faxhandled = 0;
2571 p->pulsedial = 0;
2572 p->onhooktime = time(NULL);
2573 #ifdef HAVE_PRI
2574 p->proceeding = 0;
2575 p->progress = 0;
2576 p->alerting = 0;
2577 p->setup_ack = 0;
2578 #endif
2579 if (p->dsp) {
2580 ast_dsp_free(p->dsp);
2581 p->dsp = NULL;
2584 law = ZT_LAW_DEFAULT;
2585 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2586 if (res < 0)
2587 ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2588 /* Perform low level hangup if no owner left */
2589 #ifdef HAVE_PRI
2590 if (p->pri) {
2591 #ifdef SUPPORT_USERUSER
2592 const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
2593 #endif
2595 /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2596 if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2597 if (!pri_grab(p, p->pri)) {
2598 if (p->alreadyhungup) {
2599 ast_log(LOG_DEBUG, "Already hungup... Calling hangup once, and clearing call\n");
2601 #ifdef SUPPORT_USERUSER
2602 pri_call_set_useruser(p->call, useruser);
2603 #endif
2605 pri_hangup(p->pri->pri, p->call, -1);
2606 p->call = NULL;
2607 if (p->bearer)
2608 p->bearer->call = NULL;
2609 } else {
2610 const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2611 int icause = ast->hangupcause ? ast->hangupcause : -1;
2612 ast_log(LOG_DEBUG, "Not yet hungup... Calling hangup once with icause, and clearing call\n");
2614 #ifdef SUPPORT_USERUSER
2615 pri_call_set_useruser(p->call, useruser);
2616 #endif
2618 p->alreadyhungup = 1;
2619 if (p->bearer)
2620 p->bearer->alreadyhungup = 1;
2621 if (cause) {
2622 if (atoi(cause))
2623 icause = atoi(cause);
2625 pri_hangup(p->pri->pri, p->call, icause);
2627 if (res < 0)
2628 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2629 pri_rel(p->pri);
2630 } else {
2631 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2632 res = -1;
2634 } else {
2635 if (p->bearer)
2636 ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2637 p->call = NULL;
2638 res = 0;
2641 #endif
2642 if (p->sig && (p->sig != SIG_PRI))
2643 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2644 if (res < 0) {
2645 ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2647 switch (p->sig) {
2648 case SIG_FXOGS:
2649 case SIG_FXOLS:
2650 case SIG_FXOKS:
2651 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2652 if (!res) {
2653 #if 0
2654 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2655 #endif
2656 /* If they're off hook, try playing congestion */
2657 if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
2658 tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2659 else
2660 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2662 break;
2663 case SIG_FXSGS:
2664 case SIG_FXSLS:
2665 case SIG_FXSKS:
2666 /* Make sure we're not made available for at least two seconds assuming
2667 we were actually used for an inbound or outbound call. */
2668 if (ast->_state != AST_STATE_RESERVED) {
2669 time(&p->guardtime);
2670 p->guardtime += 2;
2672 break;
2673 default:
2674 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2676 if (p->cidspill)
2677 free(p->cidspill);
2678 if (p->sig)
2679 zt_disable_ec(p);
2680 x = 0;
2681 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2682 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2683 p->didtdd = 0;
2684 p->cidspill = NULL;
2685 p->callwaitcas = 0;
2686 p->callwaiting = p->permcallwaiting;
2687 p->hidecallerid = p->permhidecallerid;
2688 p->dialing = 0;
2689 p->rdnis[0] = '\0';
2690 update_conf(p);
2691 reset_conf(p);
2692 /* Restore data mode */
2693 if (p->sig == SIG_PRI) {
2694 x = 0;
2695 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2697 #ifdef HAVE_PRI
2698 if (p->bearer) {
2699 ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2700 /* Free up the bearer channel as well, and
2701 don't use its file descriptor anymore */
2702 update_conf(p->bearer);
2703 reset_conf(p->bearer);
2704 p->bearer->owner = NULL;
2705 p->bearer->realcall = NULL;
2706 p->bearer = NULL;
2707 p->subs[SUB_REAL].zfd = -1;
2708 p->pri = NULL;
2710 #endif
2711 restart_monitor();
2714 p->callwaitingrepeat = 0;
2715 p->cidcwexpire = 0;
2716 p->oprmode = 0;
2717 ast->tech_pvt = NULL;
2718 ast_mutex_unlock(&p->lock);
2719 ast_module_unref(ast_module_info->self);
2720 if (option_verbose > 2)
2721 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2723 ast_mutex_lock(&iflock);
2724 tmp = iflist;
2725 prev = NULL;
2726 if (p->destroy) {
2727 while (tmp) {
2728 if (tmp == p) {
2729 destroy_channel(prev, tmp, 0);
2730 break;
2731 } else {
2732 prev = tmp;
2733 tmp = tmp->next;
2737 ast_mutex_unlock(&iflock);
2738 return 0;
2741 static int zt_answer(struct ast_channel *ast)
2743 struct zt_pvt *p = ast->tech_pvt;
2744 int res = 0;
2745 int index;
2746 int oldstate = ast->_state;
2747 ast_setstate(ast, AST_STATE_UP);
2748 ast_mutex_lock(&p->lock);
2749 index = zt_get_index(ast, p, 0);
2750 if (index < 0)
2751 index = SUB_REAL;
2752 /* nothing to do if a radio channel */
2753 if ((p->radio || (p->oprmode < 0))) {
2754 ast_mutex_unlock(&p->lock);
2755 return 0;
2757 switch (p->sig) {
2758 case SIG_FXSLS:
2759 case SIG_FXSGS:
2760 case SIG_FXSKS:
2761 p->ringt = 0;
2762 /* Fall through */
2763 case SIG_EM:
2764 case SIG_EM_E1:
2765 case SIG_EMWINK:
2766 case SIG_FEATD:
2767 case SIG_FEATDMF:
2768 case SIG_FEATDMF_TA:
2769 case SIG_E911:
2770 case SIG_FGC_CAMA:
2771 case SIG_FGC_CAMAMF:
2772 case SIG_FEATB:
2773 case SIG_SF:
2774 case SIG_SFWINK:
2775 case SIG_SF_FEATD:
2776 case SIG_SF_FEATDMF:
2777 case SIG_SF_FEATB:
2778 case SIG_FXOLS:
2779 case SIG_FXOGS:
2780 case SIG_FXOKS:
2781 /* Pick up the line */
2782 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2783 if (p->hanguponpolarityswitch) {
2784 gettimeofday(&p->polaritydelaytv, NULL);
2786 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2787 tone_zone_play_tone(p->subs[index].zfd, -1);
2788 p->dialing = 0;
2789 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2790 if (oldstate == AST_STATE_RINGING) {
2791 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2792 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2793 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2794 p->owner = p->subs[SUB_REAL].owner;
2797 if (p->sig & __ZT_SIG_FXS) {
2798 zt_enable_ec(p);
2799 zt_train_ec(p);
2801 break;
2802 #ifdef HAVE_PRI
2803 case SIG_PRI:
2804 /* Send a pri acknowledge */
2805 if (!pri_grab(p, p->pri)) {
2806 p->proceeding = 1;
2807 res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2808 pri_rel(p->pri);
2809 } else {
2810 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2811 res = -1;
2813 break;
2814 #endif
2815 case 0:
2816 ast_mutex_unlock(&p->lock);
2817 return 0;
2818 default:
2819 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2820 res = -1;
2822 ast_mutex_unlock(&p->lock);
2823 return res;
2826 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2828 char *cp;
2829 signed char *scp;
2830 int x;
2831 int index;
2832 struct zt_pvt *p = chan->tech_pvt, *pp;
2833 struct oprmode *oprmode;
2836 /* all supported options require data */
2837 if (!data || (datalen < 1)) {
2838 errno = EINVAL;
2839 return -1;
2842 switch (option) {
2843 case AST_OPTION_TXGAIN:
2844 scp = (signed char *) data;
2845 index = zt_get_index(chan, p, 0);
2846 if (index < 0) {
2847 ast_log(LOG_WARNING, "No index in TXGAIN?\n");
2848 return -1;
2850 if (option_debug)
2851 ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
2852 return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
2853 case AST_OPTION_RXGAIN:
2854 scp = (signed char *) data;
2855 index = zt_get_index(chan, p, 0);
2856 if (index < 0) {
2857 ast_log(LOG_WARNING, "No index in RXGAIN?\n");
2858 return -1;
2860 if (option_debug)
2861 ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
2862 return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
2863 case AST_OPTION_TONE_VERIFY:
2864 if (!p->dsp)
2865 break;
2866 cp = (char *) data;
2867 switch (*cp) {
2868 case 1:
2869 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2870 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax); /* set mute mode if desired */
2871 break;
2872 case 2:
2873 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2874 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax); /* set mute mode if desired */
2875 break;
2876 default:
2877 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2878 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax); /* set mute mode if desired */
2879 break;
2881 break;
2882 case AST_OPTION_TDD:
2883 /* turn on or off TDD */
2884 cp = (char *) data;
2885 p->mate = 0;
2886 if (!*cp) { /* turn it off */
2887 if (option_debug)
2888 ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2889 if (p->tdd)
2890 tdd_free(p->tdd);
2891 p->tdd = 0;
2892 break;
2894 ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
2895 (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
2896 zt_disable_ec(p);
2897 /* otherwise, turn it on */
2898 if (!p->didtdd) { /* if havent done it yet */
2899 unsigned char mybuf[41000], *buf;
2900 int size, res, fd, len;
2901 struct pollfd fds[1];
2903 buf = mybuf;
2904 memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
2905 ast_tdd_gen_ecdisa(buf + 16000, 16000); /* put in tone */
2906 len = 40000;
2907 index = zt_get_index(chan, p, 0);
2908 if (index < 0) {
2909 ast_log(LOG_WARNING, "No index in TDD?\n");
2910 return -1;
2912 fd = p->subs[index].zfd;
2913 while (len) {
2914 if (ast_check_hangup(chan))
2915 return -1;
2916 size = len;
2917 if (size > READ_SIZE)
2918 size = READ_SIZE;
2919 fds[0].fd = fd;
2920 fds[0].events = POLLPRI | POLLOUT;
2921 fds[0].revents = 0;
2922 res = poll(fds, 1, -1);
2923 if (!res) {
2924 ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2925 continue;
2927 /* if got exception */
2928 if (fds[0].revents & POLLPRI)
2929 return -1;
2930 if (!(fds[0].revents & POLLOUT)) {
2931 ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2932 continue;
2934 res = write(fd, buf, size);
2935 if (res != size) {
2936 if (res == -1) return -1;
2937 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2938 break;
2940 len -= size;
2941 buf += size;
2943 p->didtdd = 1; /* set to have done it now */
2945 if (*cp == 2) { /* Mate mode */
2946 if (p->tdd)
2947 tdd_free(p->tdd);
2948 p->tdd = 0;
2949 p->mate = 1;
2950 break;
2952 if (!p->tdd) { /* if we dont have one yet */
2953 p->tdd = tdd_new(); /* allocate one */
2955 break;
2956 case AST_OPTION_RELAXDTMF: /* Relax DTMF decoding (or not) */
2957 if (!p->dsp)
2958 break;
2959 cp = (char *) data;
2960 ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
2961 *cp ? "ON" : "OFF", (int) *cp, chan->name);
2962 p->dtmfrelax = 0;
2963 if (*cp) p->dtmfrelax = DSP_DIGITMODE_RELAXDTMF;
2964 ast_dsp_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
2965 break;
2966 case AST_OPTION_AUDIO_MODE: /* Set AUDIO mode (or not) */
2967 cp = (char *) data;
2968 if (!*cp) {
2969 ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
2970 x = 0;
2971 zt_disable_ec(p);
2972 } else {
2973 ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
2974 x = 1;
2976 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2977 ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2978 break;
2979 case AST_OPTION_OPRMODE: /* Operator services mode */
2980 oprmode = (struct oprmode *) data;
2981 pp = oprmode->peer->tech_pvt;
2982 p->oprmode = pp->oprmode = 0;
2983 /* setup peers */
2984 p->oprpeer = pp;
2985 pp->oprpeer = p;
2986 /* setup modes, if any */
2987 if (oprmode->mode)
2989 pp->oprmode = oprmode->mode;
2990 p->oprmode = -oprmode->mode;
2992 ast_log(LOG_DEBUG, "Set Operator Services mode, value: %d on %s/%s\n",
2993 oprmode->mode, chan->name,oprmode->peer->name);;
2994 break;
2995 case AST_OPTION_ECHOCAN:
2996 cp = (char *) data;
2997 if (*cp) {
2998 ast_log(LOG_DEBUG, "Enabling echo cancelation on %s\n", chan->name);
2999 zt_enable_ec(p);
3000 } else {
3001 ast_log(LOG_DEBUG, "Disabling echo cancelation on %s\n", chan->name);
3002 zt_disable_ec(p);
3004 break;
3006 errno = 0;
3008 return 0;
3011 static int zt_func_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
3013 struct zt_pvt *p = chan->tech_pvt;
3015 if (!strcasecmp(data, "rxgain")) {
3016 ast_mutex_lock(&p->lock);
3017 snprintf(buf, len, "%f", p->rxgain);
3018 ast_mutex_unlock(&p->lock);
3019 } else if (!strcasecmp(data, "txgain")) {
3020 ast_mutex_lock(&p->lock);
3021 snprintf(buf, len, "%f", p->txgain);
3022 ast_mutex_unlock(&p->lock);
3023 } else {
3024 ast_copy_string(buf, "", len);
3026 return 0;
3030 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
3032 /* Unlink a specific slave or all slaves/masters from a given master */
3033 int x;
3034 int hasslaves;
3035 if (!master)
3036 return;
3037 if (needlock) {
3038 ast_mutex_lock(&master->lock);
3039 if (slave) {
3040 while (ast_mutex_trylock(&slave->lock)) {
3041 ast_mutex_unlock(&master->lock);
3042 usleep(1);
3043 ast_mutex_lock(&master->lock);
3047 hasslaves = 0;
3048 for (x = 0; x < MAX_SLAVES; x++) {
3049 if (master->slaves[x]) {
3050 if (!slave || (master->slaves[x] == slave)) {
3051 /* Take slave out of the conference */
3052 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
3053 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
3054 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
3055 master->slaves[x]->master = NULL;
3056 master->slaves[x] = NULL;
3057 } else
3058 hasslaves = 1;
3060 if (!hasslaves)
3061 master->inconference = 0;
3063 if (!slave) {
3064 if (master->master) {
3065 /* Take master out of the conference */
3066 conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
3067 conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
3068 hasslaves = 0;
3069 for (x = 0; x < MAX_SLAVES; x++) {
3070 if (master->master->slaves[x] == master)
3071 master->master->slaves[x] = NULL;
3072 else if (master->master->slaves[x])
3073 hasslaves = 1;
3075 if (!hasslaves)
3076 master->master->inconference = 0;
3078 master->master = NULL;
3080 update_conf(master);
3081 if (needlock) {
3082 if (slave)
3083 ast_mutex_unlock(&slave->lock);
3084 ast_mutex_unlock(&master->lock);
3088 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
3089 int x;
3090 if (!slave || !master) {
3091 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
3092 return;
3094 for (x = 0; x < MAX_SLAVES; x++) {
3095 if (!master->slaves[x]) {
3096 master->slaves[x] = slave;
3097 break;
3100 if (x >= MAX_SLAVES) {
3101 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
3102 master->slaves[MAX_SLAVES - 1] = slave;
3104 if (slave->master)
3105 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
3106 slave->master = master;
3108 ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
3111 static void disable_dtmf_detect(struct zt_pvt *p)
3113 #ifdef ZT_TONEDETECT
3114 int val;
3115 #endif
3117 p->ignoredtmf = 1;
3119 #ifdef ZT_TONEDETECT
3120 val = 0;
3121 ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3122 #endif
3123 if (!p->hardwaredtmf && p->dsp) {
3124 p->dsp_features &= ~DSP_FEATURE_DTMF_DETECT;
3125 ast_dsp_set_features(p->dsp, p->dsp_features);
3129 static void enable_dtmf_detect(struct zt_pvt *p)
3131 #ifdef ZT_TONEDETECT
3132 int val;
3133 #endif
3135 if (p->channel == CHAN_PSEUDO)
3136 return;
3138 p->ignoredtmf = 0;
3140 #ifdef ZT_TONEDETECT
3141 val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
3142 ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3143 #endif
3144 if (!p->hardwaredtmf && p->dsp) {
3145 p->dsp_features |= DSP_FEATURE_DTMF_DETECT;
3146 ast_dsp_set_features(p->dsp, p->dsp_features);
3150 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)
3152 struct ast_channel *who;
3153 struct zt_pvt *p0, *p1, *op0, *op1;
3154 struct zt_pvt *master = NULL, *slave = NULL;
3155 struct ast_frame *f;
3156 int inconf = 0;
3157 int nothingok = 1;
3158 int ofd0, ofd1;
3159 int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
3160 int os0 = -1, os1 = -1;
3161 int priority = 0;
3162 struct ast_channel *oc0, *oc1;
3163 enum ast_bridge_result res;
3165 #ifdef PRI_2BCT
3166 int triedtopribridge = 0;
3167 q931_call *q931c0 = NULL, *q931c1 = NULL;
3168 #endif
3170 /* For now, don't attempt to native bridge if either channel needs DTMF detection.
3171 There is code below to handle it properly until DTMF is actually seen,
3172 but due to currently unresolved issues it's ignored...
3175 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
3176 return AST_BRIDGE_FAILED_NOWARN;
3178 ast_mutex_lock(&c0->lock);
3179 while (ast_mutex_trylock(&c1->lock)) {
3180 ast_mutex_unlock(&c0->lock);
3181 usleep(1);
3182 ast_mutex_lock(&c0->lock);
3185 p0 = c0->tech_pvt;
3186 p1 = c1->tech_pvt;
3187 /* cant do pseudo-channels here */
3188 if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
3189 ast_mutex_unlock(&c0->lock);
3190 ast_mutex_unlock(&c1->lock);
3191 return AST_BRIDGE_FAILED_NOWARN;
3194 oi0 = zt_get_index(c0, p0, 0);
3195 oi1 = zt_get_index(c1, p1, 0);
3196 if ((oi0 < 0) || (oi1 < 0)) {
3197 ast_mutex_unlock(&c0->lock);
3198 ast_mutex_unlock(&c1->lock);
3199 return AST_BRIDGE_FAILED;
3202 op0 = p0 = c0->tech_pvt;
3203 op1 = p1 = c1->tech_pvt;
3204 ofd0 = c0->fds[0];
3205 ofd1 = c1->fds[0];
3206 oc0 = p0->owner;
3207 oc1 = p1->owner;
3209 if (ast_mutex_trylock(&p0->lock)) {
3210 /* Don't block, due to potential for deadlock */
3211 ast_mutex_unlock(&c0->lock);
3212 ast_mutex_unlock(&c1->lock);
3213 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
3214 return AST_BRIDGE_RETRY;
3216 if (ast_mutex_trylock(&p1->lock)) {
3217 /* Don't block, due to potential for deadlock */
3218 ast_mutex_unlock(&p0->lock);
3219 ast_mutex_unlock(&c0->lock);
3220 ast_mutex_unlock(&c1->lock);
3221 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
3222 return AST_BRIDGE_RETRY;
3225 if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3226 if (p0->owner && p1->owner) {
3227 /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
3228 if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
3229 master = p0;
3230 slave = p1;
3231 inconf = 1;
3232 } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
3233 master = p1;
3234 slave = p0;
3235 inconf = 1;
3236 } else {
3237 ast_log(LOG_WARNING, "Huh? Both calls are callwaits or 3-ways? That's clever...?\n");
3238 ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
3239 p0->channel,
3240 oi0, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3241 p0->subs[SUB_REAL].inthreeway, p0->channel,
3242 oi0, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3243 p1->subs[SUB_REAL].inthreeway);
3245 nothingok = 0;
3247 } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
3248 if (p1->subs[SUB_THREEWAY].inthreeway) {
3249 master = p1;
3250 slave = p0;
3251 nothingok = 0;
3253 } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
3254 if (p0->subs[SUB_THREEWAY].inthreeway) {
3255 master = p0;
3256 slave = p1;
3257 nothingok = 0;
3259 } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
3260 /* We have a real and a call wait. If we're in a three way call, put us in it, otherwise,
3261 don't put us in anything */
3262 if (p1->subs[SUB_CALLWAIT].inthreeway) {
3263 master = p1;
3264 slave = p0;
3265 nothingok = 0;
3267 } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
3268 /* Same as previous */
3269 if (p0->subs[SUB_CALLWAIT].inthreeway) {
3270 master = p0;
3271 slave = p1;
3272 nothingok = 0;
3275 ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
3276 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
3277 if (master && slave) {
3278 /* Stop any tones, or play ringtone as appropriate. If they're bridged
3279 in an active threeway call with a channel that is ringing, we should
3280 indicate ringing. */
3281 if ((oi1 == SUB_THREEWAY) &&
3282 p1->subs[SUB_THREEWAY].inthreeway &&
3283 p1->subs[SUB_REAL].owner &&
3284 p1->subs[SUB_REAL].inthreeway &&
3285 (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
3286 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
3287 tone_zone_play_tone(p0->subs[oi0].zfd, ZT_TONE_RINGTONE);
3288 os1 = p1->subs[SUB_REAL].owner->_state;
3289 } else {
3290 ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p0->channel, oi0, p1->channel, oi1);
3291 tone_zone_play_tone(p0->subs[oi0].zfd, -1);
3293 if ((oi0 == SUB_THREEWAY) &&
3294 p0->subs[SUB_THREEWAY].inthreeway &&
3295 p0->subs[SUB_REAL].owner &&
3296 p0->subs[SUB_REAL].inthreeway &&
3297 (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
3298 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
3299 tone_zone_play_tone(p1->subs[oi1].zfd, ZT_TONE_RINGTONE);
3300 os0 = p0->subs[SUB_REAL].owner->_state;
3301 } else {
3302 ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p1->channel, oi1, p0->channel, oi0);
3303 tone_zone_play_tone(p1->subs[oi0].zfd, -1);
3305 if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3306 if (!p0->echocanbridged || !p1->echocanbridged) {
3307 /* Disable echo cancellation if appropriate */
3308 zt_disable_ec(p0);
3309 zt_disable_ec(p1);
3312 zt_link(slave, master);
3313 master->inconference = inconf;
3314 } else if (!nothingok)
3315 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
3317 update_conf(p0);
3318 update_conf(p1);
3319 t0 = p0->subs[SUB_REAL].inthreeway;
3320 t1 = p1->subs[SUB_REAL].inthreeway;
3322 ast_mutex_unlock(&p0->lock);
3323 ast_mutex_unlock(&p1->lock);
3325 ast_mutex_unlock(&c0->lock);
3326 ast_mutex_unlock(&c1->lock);
3328 /* Native bridge failed */
3329 if ((!master || !slave) && !nothingok) {
3330 zt_enable_ec(p0);
3331 zt_enable_ec(p1);
3332 return AST_BRIDGE_FAILED;
3335 if (option_verbose > 2)
3336 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
3338 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
3339 disable_dtmf_detect(op0);
3341 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
3342 disable_dtmf_detect(op1);
3344 for (;;) {
3345 struct ast_channel *c0_priority[2] = {c0, c1};
3346 struct ast_channel *c1_priority[2] = {c1, c0};
3348 /* Here's our main loop... Start by locking things, looking for private parts,
3349 and then balking if anything is wrong */
3350 ast_mutex_lock(&c0->lock);
3351 while (ast_mutex_trylock(&c1->lock)) {
3352 ast_mutex_unlock(&c0->lock);
3353 usleep(1);
3354 ast_mutex_lock(&c0->lock);
3357 p0 = c0->tech_pvt;
3358 p1 = c1->tech_pvt;
3360 if (op0 == p0)
3361 i0 = zt_get_index(c0, p0, 1);
3362 if (op1 == p1)
3363 i1 = zt_get_index(c1, p1, 1);
3364 ast_mutex_unlock(&c0->lock);
3365 ast_mutex_unlock(&c1->lock);
3367 if (!timeoutms ||
3368 (op0 != p0) ||
3369 (op1 != p1) ||
3370 (ofd0 != c0->fds[0]) ||
3371 (ofd1 != c1->fds[0]) ||
3372 (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) ||
3373 (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) ||
3374 (oc0 != p0->owner) ||
3375 (oc1 != p1->owner) ||
3376 (t0 != p0->subs[SUB_REAL].inthreeway) ||
3377 (t1 != p1->subs[SUB_REAL].inthreeway) ||
3378 (oi0 != i0) ||
3379 (oi1 != i1)) {
3380 ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
3381 op0->channel, oi0, op1->channel, oi1);
3382 res = AST_BRIDGE_RETRY;
3383 goto return_from_bridge;
3386 #ifdef PRI_2BCT
3387 q931c0 = p0->call;
3388 q931c1 = p1->call;
3389 if (p0->transfer && p1->transfer
3390 && q931c0 && q931c1
3391 && !triedtopribridge) {
3392 pri_channel_bridge(q931c0, q931c1);
3393 triedtopribridge = 1;
3395 #endif
3397 who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
3398 if (!who) {
3399 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
3400 continue;
3402 f = ast_read(who);
3403 if (!f || (f->frametype == AST_FRAME_CONTROL)) {
3404 *fo = f;
3405 *rc = who;
3406 res = AST_BRIDGE_COMPLETE;
3407 goto return_from_bridge;
3409 if (f->frametype == AST_FRAME_DTMF) {
3410 if ((who == c0) && p0->pulsedial) {
3411 ast_write(c1, f);
3412 } else if ((who == c1) && p1->pulsedial) {
3413 ast_write(c0, f);
3414 } else {
3415 *fo = f;
3416 *rc = who;
3417 res = AST_BRIDGE_COMPLETE;
3418 goto return_from_bridge;
3421 ast_frfree(f);
3423 /* Swap who gets priority */
3424 priority = !priority;
3427 return_from_bridge:
3428 if (op0 == p0)
3429 zt_enable_ec(p0);
3431 if (op1 == p1)
3432 zt_enable_ec(p1);
3434 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
3435 enable_dtmf_detect(op0);
3437 if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
3438 enable_dtmf_detect(op1);
3440 zt_unlink(slave, master, 1);
3442 return res;
3445 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3447 struct zt_pvt *p = newchan->tech_pvt;
3448 int x;
3449 ast_mutex_lock(&p->lock);
3450 ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
3451 if (p->owner == oldchan) {
3452 p->owner = newchan;
3454 for (x = 0; x < 3; x++)
3455 if (p->subs[x].owner == oldchan) {
3456 if (!x)
3457 zt_unlink(NULL, p, 0);
3458 p->subs[x].owner = newchan;
3460 if (newchan->_state == AST_STATE_RINGING)
3461 zt_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
3462 update_conf(p);
3463 ast_mutex_unlock(&p->lock);
3464 return 0;
3467 static int zt_ring_phone(struct zt_pvt *p)
3469 int x;
3470 int res;
3471 /* Make sure our transmit state is on hook */
3472 x = 0;
3473 x = ZT_ONHOOK;
3474 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3475 do {
3476 x = ZT_RING;
3477 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3478 if (res) {
3479 switch (errno) {
3480 case EBUSY:
3481 case EINTR:
3482 /* Wait just in case */
3483 usleep(10000);
3484 continue;
3485 case EINPROGRESS:
3486 res = 0;
3487 break;
3488 default:
3489 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
3490 res = 0;
3493 } while (res);
3494 return res;
3497 static void *ss_thread(void *data);
3499 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
3501 static int attempt_transfer(struct zt_pvt *p)
3503 /* In order to transfer, we need at least one of the channels to
3504 actually be in a call bridge. We can't conference two applications
3505 together (but then, why would we want to?) */
3506 if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
3507 /* The three-way person we're about to transfer to could still be in MOH, so
3508 stop if now if appropriate */
3509 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
3510 ast_queue_control(p->subs[SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
3511 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
3512 ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
3514 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RING) {
3515 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, ZT_TONE_RINGTONE);
3517 if (p->subs[SUB_REAL].owner->cdr) {
3518 /* Move CDR from second channel to current one */
3519 p->subs[SUB_THREEWAY].owner->cdr =
3520 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, p->subs[SUB_REAL].owner->cdr);
3521 p->subs[SUB_REAL].owner->cdr = NULL;
3523 if (ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr) {
3524 /* Move CDR from second channel's bridge to current one */
3525 p->subs[SUB_THREEWAY].owner->cdr =
3526 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr);
3527 ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr = NULL;
3529 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
3530 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3531 ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
3532 return -1;
3534 /* Orphan the channel after releasing the lock */
3535 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3536 unalloc_sub(p, SUB_THREEWAY);
3537 } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
3538 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
3539 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
3540 ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
3542 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RING) {
3543 tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
3545 if (p->subs[SUB_THREEWAY].owner->cdr) {
3546 /* Move CDR from second channel to current one */
3547 p->subs[SUB_REAL].owner->cdr =
3548 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, p->subs[SUB_THREEWAY].owner->cdr);
3549 p->subs[SUB_THREEWAY].owner->cdr = NULL;
3551 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr) {
3552 /* Move CDR from second channel's bridge to current one */
3553 p->subs[SUB_REAL].owner->cdr =
3554 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr);
3555 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr = NULL;
3557 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
3558 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3559 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
3560 return -1;
3562 /* Three-way is now the REAL */
3563 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3564 ast_mutex_unlock(&p->subs[SUB_REAL].owner->lock);
3565 unalloc_sub(p, SUB_THREEWAY);
3566 /* Tell the caller not to hangup */
3567 return 1;
3568 } else {
3569 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
3570 p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
3571 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3572 return -1;
3574 return 0;
3577 static int check_for_conference(struct zt_pvt *p)
3579 ZT_CONFINFO ci;
3580 /* Fine if we already have a master, etc */
3581 if (p->master || (p->confno > -1))
3582 return 0;
3583 memset(&ci, 0, sizeof(ci));
3584 if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
3585 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
3586 return 0;
3588 /* If we have no master and don't have a confno, then
3589 if we're in a conference, it's probably a MeetMe room or
3590 some such, so don't let us 3-way out! */
3591 if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
3592 if (option_verbose > 2)
3593 ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
3594 return 1;
3596 return 0;
3599 static int get_alarms(struct zt_pvt *p)
3601 int res;
3602 ZT_SPANINFO zi;
3603 memset(&zi, 0, sizeof(zi));
3604 zi.spanno = p->span;
3605 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
3606 if (res < 0) {
3607 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
3608 return 0;
3610 return zi.alarms;
3613 static void zt_handle_dtmfup(struct ast_channel *ast, int index, struct ast_frame **dest)
3615 struct zt_pvt *p = ast->tech_pvt;
3616 struct ast_frame *f = *dest;
3618 if (option_debug)
3619 ast_log(LOG_DEBUG, "DTMF digit: %c on %s\n", f->subclass, ast->name);
3621 if (p->confirmanswer) {
3622 if (option_debug)
3623 ast_log(LOG_DEBUG, "Confirm answer on %s!\n", ast->name);
3624 /* Upon receiving a DTMF digit, consider this an answer confirmation instead
3625 of a DTMF digit */
3626 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3627 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3628 *dest = &p->subs[index].f;
3629 /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
3630 p->confirmanswer = 0;
3631 } else if (p->callwaitcas) {
3632 if ((f->subclass == 'A') || (f->subclass == 'D')) {
3633 if (option_debug)
3634 ast_log(LOG_DEBUG, "Got some DTMF, but it's for the CAS\n");
3635 if (p->cidspill)
3636 free(p->cidspill);
3637 send_cwcidspill(p);
3639 if ((f->subclass != 'm') && (f->subclass != 'u'))
3640 p->callwaitcas = 0;
3641 p->subs[index].f.frametype = AST_FRAME_NULL;
3642 p->subs[index].f.subclass = 0;
3643 *dest = &p->subs[index].f;
3644 } else if (f->subclass == 'f') {
3645 /* Fax tone -- Handle and return NULL */
3646 if ((p->callprogress & 0x6) && !p->faxhandled) {
3647 p->faxhandled++;
3648 if (strcmp(ast->exten, "fax")) {
3649 const char *target_context = S_OR(ast->macrocontext, ast->context);
3651 if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
3652 if (option_verbose > 2)
3653 ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
3654 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
3655 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
3656 if (ast_async_goto(ast, target_context, "fax", 1))
3657 ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
3658 } else
3659 ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
3660 } else if (option_debug)
3661 ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
3662 } else if (option_debug)
3663 ast_log(LOG_DEBUG, "Fax already handled\n");
3664 zt_confmute(p, 0);
3665 p->subs[index].f.frametype = AST_FRAME_NULL;
3666 p->subs[index].f.subclass = 0;
3667 *dest = &p->subs[index].f;
3668 } else if (f->subclass == 'm') {
3669 /* Confmute request */
3670 zt_confmute(p, 1);
3671 p->subs[index].f.frametype = AST_FRAME_NULL;
3672 p->subs[index].f.subclass = 0;
3673 *dest = &p->subs[index].f;
3674 } else if (f->subclass == 'u') {
3675 /* Unmute */
3676 zt_confmute(p, 0);
3677 p->subs[index].f.frametype = AST_FRAME_NULL;
3678 p->subs[index].f.subclass = 0;
3679 *dest = &p->subs[index].f;
3680 } else
3681 zt_confmute(p, 0);
3684 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
3686 int res, x;
3687 int index, mysig;
3688 char *c;
3689 struct zt_pvt *p = ast->tech_pvt;
3690 pthread_t threadid;
3691 pthread_attr_t attr;
3692 struct ast_channel *chan;
3693 struct ast_frame *f;
3695 index = zt_get_index(ast, p, 0);
3696 mysig = p->sig;
3697 if (p->outsigmod > -1)
3698 mysig = p->outsigmod;
3699 p->subs[index].f.frametype = AST_FRAME_NULL;
3700 p->subs[index].f.subclass = 0;
3701 p->subs[index].f.datalen = 0;
3702 p->subs[index].f.samples = 0;
3703 p->subs[index].f.mallocd = 0;
3704 p->subs[index].f.offset = 0;
3705 p->subs[index].f.src = "zt_handle_event";
3706 p->subs[index].f.data = NULL;
3707 f = &p->subs[index].f;
3709 if (index < 0)
3710 return &p->subs[index].f;
3711 if (p->fake_event) {
3712 res = p->fake_event;
3713 p->fake_event = 0;
3714 } else
3715 res = zt_get_event(p->subs[index].zfd);
3717 if (option_debug)
3718 ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
3720 if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFUP)) {
3721 p->pulsedial = (res & ZT_EVENT_PULSEDIGIT) ? 1 : 0;
3723 ast_log(LOG_DEBUG, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
3724 #ifdef HAVE_PRI
3725 if (!p->proceeding && p->sig == SIG_PRI && p->pri && p->pri->overlapdial) {
3726 /* absorb event */
3727 } else {
3728 #endif
3729 p->subs[index].f.frametype = AST_FRAME_DTMF_END;
3730 p->subs[index].f.subclass = res & 0xff;
3731 #ifdef HAVE_PRI
3733 #endif
3734 zt_handle_dtmfup(ast, index, &f);
3735 return f;
3738 if (res & ZT_EVENT_DTMFDOWN) {
3739 if (option_debug)
3740 ast_log(LOG_DEBUG, "DTMF Down '%c'\n", res & 0xff);
3741 /* Mute conference */
3742 zt_confmute(p, 1);
3743 p->subs[index].f.frametype = AST_FRAME_DTMF_BEGIN;
3744 p->subs[index].f.subclass = res & 0xff;
3745 return &p->subs[index].f;
3748 switch (res) {
3749 #ifdef ZT_EVENT_EC_DISABLED
3750 case ZT_EVENT_EC_DISABLED:
3751 if (option_verbose > 2)
3752 ast_verbose(VERBOSE_PREFIX_3 "Channel %d echo canceler disabled due to CED detection\n", p->channel);
3753 p->echocanon = 0;
3754 break;
3755 #endif
3756 case ZT_EVENT_BITSCHANGED:
3757 ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
3758 case ZT_EVENT_PULSE_START:
3759 /* Stop tone if there's a pulse start and the PBX isn't started */
3760 if (!ast->pbx)
3761 tone_zone_play_tone(p->subs[index].zfd, -1);
3762 break;
3763 case ZT_EVENT_DIALCOMPLETE:
3764 if (p->inalarm) break;
3765 if ((p->radio || (p->oprmode < 0))) break;
3766 if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
3767 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
3768 return NULL;
3770 if (!x) { /* if not still dialing in driver */
3771 zt_enable_ec(p);
3772 if (p->echobreak) {
3773 zt_train_ec(p);
3774 ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
3775 p->dop.op = ZT_DIAL_OP_REPLACE;
3776 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
3777 p->echobreak = 0;
3778 } else {
3779 p->dialing = 0;
3780 if ((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) {
3781 /* if thru with dialing after offhook */
3782 if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
3783 ast_setstate(ast, AST_STATE_UP);
3784 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3785 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3786 break;
3787 } else { /* if to state wait for offhook to dial rest */
3788 /* we now wait for off hook */
3789 ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
3792 if (ast->_state == AST_STATE_DIALING) {
3793 if ((p->callprogress & 1) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
3794 ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
3795 } 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)))) {
3796 ast_setstate(ast, AST_STATE_RINGING);
3797 } else if (!p->answeronpolarityswitch) {
3798 ast_setstate(ast, AST_STATE_UP);
3799 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3800 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3801 /* If aops=0 and hops=1, this is necessary */
3802 p->polarity = POLARITY_REV;
3803 } else {
3804 /* Start clean, so we can catch the change to REV polarity when party answers */
3805 p->polarity = POLARITY_IDLE;
3810 break;
3811 case ZT_EVENT_ALARM:
3812 #ifdef HAVE_PRI
3813 if (!p->pri || !p->pri->pri || (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0)) {
3814 /* T309 is not enabled : hangup calls when alarm occurs */
3815 if (p->call) {
3816 if (p->pri && p->pri->pri) {
3817 if (!pri_grab(p, p->pri)) {
3818 pri_hangup(p->pri->pri, p->call, -1);
3819 pri_destroycall(p->pri->pri, p->call);
3820 p->call = NULL;
3821 pri_rel(p->pri);
3822 } else
3823 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
3824 } else
3825 ast_log(LOG_WARNING, "The PRI Call has not been destroyed\n");
3827 if (p->owner)
3828 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3830 if (p->bearer)
3831 p->bearer->inalarm = 1;
3832 else
3833 #endif
3834 p->inalarm = 1;
3835 res = get_alarms(p);
3836 do {
3837 const char *alarm_str = alarm2str(res);
3839 /* hack alert! Zaptel 1.4 now exposes FXO battery as an alarm, but asterisk 1.4
3840 * doesn't know what to do with it. Don't confuse users with log messages. */
3841 if (!strcasecmp(alarm_str, "No Alarm") || !strcasecmp(alarm_str, "Unknown Alarm")) {
3842 p->unknown_alarm = 1;
3843 break;
3844 } else {
3845 p->unknown_alarm = 0;
3848 ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm_str);
3849 manager_event(EVENT_FLAG_SYSTEM, "Alarm",
3850 "Alarm: %s\r\n"
3851 "Channel: %d\r\n",
3852 alarm_str, p->channel);
3853 } while (0);
3854 #ifdef HAVE_LIBPRI
3855 if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
3856 /* fall through intentionally */
3857 } else {
3858 break;
3860 #endif
3861 case ZT_EVENT_ONHOOK:
3862 if (p->radio) {
3863 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3864 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
3865 break;
3867 if (p->oprmode < 0)
3869 if (p->oprmode != -1) break;
3870 if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
3872 /* Make sure it starts ringing */
3873 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RINGOFF);
3874 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RING);
3875 save_conference(p->oprpeer);
3876 tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
3878 break;
3880 switch (p->sig) {
3881 case SIG_FXOLS:
3882 case SIG_FXOGS:
3883 case SIG_FXOKS:
3884 p->onhooktime = time(NULL);
3885 p->msgstate = -1;
3886 /* Check for some special conditions regarding call waiting */
3887 if (index == SUB_REAL) {
3888 /* The normal line was hung up */
3889 if (p->subs[SUB_CALLWAIT].owner) {
3890 /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
3891 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
3892 if (option_verbose > 2)
3893 ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
3894 unalloc_sub(p, SUB_CALLWAIT);
3895 #if 0
3896 p->subs[index].needanswer = 0;
3897 p->subs[index].needringing = 0;
3898 #endif
3899 p->callwaitingrepeat = 0;
3900 p->cidcwexpire = 0;
3901 p->owner = NULL;
3902 /* Don't start streaming audio yet if the incoming call isn't up yet */
3903 if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
3904 p->dialing = 1;
3905 zt_ring_phone(p);
3906 } else if (p->subs[SUB_THREEWAY].owner) {
3907 unsigned int mssinceflash;
3908 /* Here we have to retain the lock on both the main channel, the 3-way channel, and
3909 the private structure -- not especially easy or clean */
3910 while (p->subs[SUB_THREEWAY].owner && ast_mutex_trylock(&p->subs[SUB_THREEWAY].owner->lock)) {
3911 /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
3912 ast_mutex_unlock(&p->lock);
3913 ast_mutex_unlock(&ast->lock);
3914 usleep(1);
3915 /* We can grab ast and p in that order, without worry. We should make sure
3916 nothing seriously bad has happened though like some sort of bizarre double
3917 masquerade! */
3918 ast_mutex_lock(&ast->lock);
3919 ast_mutex_lock(&p->lock);
3920 if (p->owner != ast) {
3921 ast_log(LOG_WARNING, "This isn't good...\n");
3922 return NULL;
3925 if (!p->subs[SUB_THREEWAY].owner) {
3926 ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
3927 return NULL;
3929 mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
3930 ast_log(LOG_DEBUG, "Last flash was %d ms ago\n", mssinceflash);
3931 if (mssinceflash < MIN_MS_SINCE_FLASH) {
3932 /* It hasn't been long enough since the last flashook. This is probably a bounce on
3933 hanging up. Hangup both channels now */
3934 if (p->subs[SUB_THREEWAY].owner)
3935 ast_queue_hangup(p->subs[SUB_THREEWAY].owner);
3936 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3937 ast_log(LOG_DEBUG, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
3938 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3939 } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
3940 if (p->transfer) {
3941 /* In any case this isn't a threeway call anymore */
3942 p->subs[SUB_REAL].inthreeway = 0;
3943 p->subs[SUB_THREEWAY].inthreeway = 0;
3944 /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
3945 if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
3946 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3947 /* Swap subs and dis-own channel */
3948 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3949 p->owner = NULL;
3950 /* Ring the phone */
3951 zt_ring_phone(p);
3952 } else {
3953 if ((res = attempt_transfer(p)) < 0) {
3954 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3955 if (p->subs[SUB_THREEWAY].owner)
3956 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3957 } else if (res) {
3958 /* Don't actually hang up at this point */
3959 if (p->subs[SUB_THREEWAY].owner)
3960 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3961 break;
3964 } else {
3965 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3966 if (p->subs[SUB_THREEWAY].owner)
3967 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3969 } else {
3970 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3971 /* Swap subs and dis-own channel */
3972 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3973 p->owner = NULL;
3974 /* Ring the phone */
3975 zt_ring_phone(p);
3978 } else {
3979 ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
3981 /* Fall through */
3982 default:
3983 zt_disable_ec(p);
3984 return NULL;
3986 break;
3987 case ZT_EVENT_RINGOFFHOOK:
3988 if (p->inalarm) break;
3989 if (p->oprmode < 0)
3991 if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
3993 /* Make sure it stops ringing */
3994 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_RINGOFF);
3995 tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].zfd, -1);
3996 restore_conference(p->oprpeer);
3998 break;
4000 if (p->radio)
4002 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4003 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
4004 break;
4006 /* for E911, its supposed to wait for offhook then dial
4007 the second half of the dial string */
4008 if (((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
4009 c = strchr(p->dialdest, '/');
4010 if (c)
4011 c++;
4012 else
4013 c = p->dialdest;
4014 if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
4015 else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
4016 if (strlen(p->dop.dialstr) > 4) {
4017 memset(p->echorest, 'w', sizeof(p->echorest) - 1);
4018 strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
4019 p->echorest[sizeof(p->echorest) - 1] = '\0';
4020 p->echobreak = 1;
4021 p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
4022 } else
4023 p->echobreak = 0;
4024 if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
4025 x = ZT_ONHOOK;
4026 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
4027 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
4028 return NULL;
4030 p->dialing = 1;
4031 return &p->subs[index].f;
4033 switch (p->sig) {
4034 case SIG_FXOLS:
4035 case SIG_FXOGS:
4036 case SIG_FXOKS:
4037 switch (ast->_state) {
4038 case AST_STATE_RINGING:
4039 zt_enable_ec(p);
4040 zt_train_ec(p);
4041 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4042 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
4043 /* Make sure it stops ringing */
4044 zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
4045 ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
4046 if (p->cidspill) {
4047 /* Cancel any running CallerID spill */
4048 free(p->cidspill);
4049 p->cidspill = NULL;
4051 p->dialing = 0;
4052 p->callwaitcas = 0;
4053 if (p->confirmanswer) {
4054 /* Ignore answer if "confirm answer" is enabled */
4055 p->subs[index].f.frametype = AST_FRAME_NULL;
4056 p->subs[index].f.subclass = 0;
4057 } else if (!ast_strlen_zero(p->dop.dialstr)) {
4058 /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
4059 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
4060 if (res < 0) {
4061 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
4062 p->dop.dialstr[0] = '\0';
4063 return NULL;
4064 } else {
4065 ast_log(LOG_DEBUG, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
4066 p->subs[index].f.frametype = AST_FRAME_NULL;
4067 p->subs[index].f.subclass = 0;
4068 p->dialing = 1;
4070 p->dop.dialstr[0] = '\0';
4071 ast_setstate(ast, AST_STATE_DIALING);
4072 } else
4073 ast_setstate(ast, AST_STATE_UP);
4074 return &p->subs[index].f;
4075 case AST_STATE_DOWN:
4076 ast_setstate(ast, AST_STATE_RING);
4077 ast->rings = 1;
4078 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4079 p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
4080 ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
4081 return &p->subs[index].f;
4082 case AST_STATE_UP:
4083 /* Make sure it stops ringing */
4084 zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
4085 /* Okay -- probably call waiting*/
4086 if (ast_bridged_channel(p->owner))
4087 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4088 p->subs[index].needunhold = 1;
4089 break;
4090 case AST_STATE_RESERVED:
4091 /* Start up dialtone */
4092 if (has_voicemail(p))
4093 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_STUTTER);
4094 else
4095 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALTONE);
4096 break;
4097 default:
4098 ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
4100 break;
4101 case SIG_FXSLS:
4102 case SIG_FXSGS:
4103 case SIG_FXSKS:
4104 if (ast->_state == AST_STATE_RING) {
4105 p->ringt = p->ringt_base;
4108 /* Fall through */
4109 case SIG_EM:
4110 case SIG_EM_E1:
4111 case SIG_EMWINK:
4112 case SIG_FEATD:
4113 case SIG_FEATDMF:
4114 case SIG_FEATDMF_TA:
4115 case SIG_E911:
4116 case SIG_FGC_CAMA:
4117 case SIG_FGC_CAMAMF:
4118 case SIG_FEATB:
4119 case SIG_SF:
4120 case SIG_SFWINK:
4121 case SIG_SF_FEATD:
4122 case SIG_SF_FEATDMF:
4123 case SIG_SF_FEATB:
4124 if (ast->_state == AST_STATE_PRERING)
4125 ast_setstate(ast, AST_STATE_RING);
4126 if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
4127 if (option_debug)
4128 ast_log(LOG_DEBUG, "Ring detected\n");
4129 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4130 p->subs[index].f.subclass = AST_CONTROL_RING;
4131 } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
4132 if (option_debug)
4133 ast_log(LOG_DEBUG, "Line answered\n");
4134 if (p->confirmanswer) {
4135 p->subs[index].f.frametype = AST_FRAME_NULL;
4136 p->subs[index].f.subclass = 0;
4137 } else {
4138 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4139 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
4140 ast_setstate(ast, AST_STATE_UP);
4142 } else if (ast->_state != AST_STATE_RING)
4143 ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
4144 break;
4145 default:
4146 ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
4148 break;
4149 #ifdef ZT_EVENT_RINGBEGIN
4150 case ZT_EVENT_RINGBEGIN:
4151 switch (p->sig) {
4152 case SIG_FXSLS:
4153 case SIG_FXSGS:
4154 case SIG_FXSKS:
4155 if (ast->_state == AST_STATE_RING) {
4156 p->ringt = p->ringt_base;
4158 break;
4160 break;
4161 #endif
4162 case ZT_EVENT_RINGEROFF:
4163 if (p->inalarm) break;
4164 if ((p->radio || (p->oprmode < 0))) break;
4165 ast->rings++;
4166 if ((ast->rings > p->cidrings) && (p->cidspill)) {
4167 ast_log(LOG_WARNING, "Didn't finish Caller-ID spill. Cancelling.\n");
4168 free(p->cidspill);
4169 p->cidspill = NULL;
4170 p->callwaitcas = 0;
4172 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4173 p->subs[index].f.subclass = AST_CONTROL_RINGING;
4174 break;
4175 case ZT_EVENT_RINGERON:
4176 break;
4177 case ZT_EVENT_NOALARM:
4178 p->inalarm = 0;
4179 #ifdef HAVE_PRI
4180 /* Extremely unlikely but just in case */
4181 if (p->bearer)
4182 p->bearer->inalarm = 0;
4183 #endif
4184 if (!p->unknown_alarm) {
4185 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
4186 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
4187 "Channel: %d\r\n", p->channel);
4188 } else {
4189 p->unknown_alarm = 0;
4191 break;
4192 case ZT_EVENT_WINKFLASH:
4193 if (p->inalarm) break;
4194 if (p->radio) break;
4195 if (p->oprmode < 0) break;
4196 if (p->oprmode > 1)
4198 struct zt_params par;
4200 if (ioctl(p->oprpeer->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par) != -1)
4202 if (!par.rxisoffhook)
4204 /* Make sure it stops ringing */
4205 zt_set_hook(p->oprpeer->subs[SUB_REAL].zfd, ZT_RINGOFF);
4206 zt_set_hook(p->oprpeer->subs[SUB_REAL].zfd, ZT_RING);
4207 save_conference(p);
4208 tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
4211 break;
4213 /* Remember last time we got a flash-hook */
4214 gettimeofday(&p->flashtime, NULL);
4215 switch (mysig) {
4216 case SIG_FXOLS:
4217 case SIG_FXOGS:
4218 case SIG_FXOKS:
4219 ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
4220 index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
4221 p->callwaitcas = 0;
4223 if (index != SUB_REAL) {
4224 ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", index, p->channel);
4225 goto winkflashdone;
4228 if (p->subs[SUB_CALLWAIT].owner) {
4229 /* Swap to call-wait */
4230 swap_subs(p, SUB_REAL, SUB_CALLWAIT);
4231 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
4232 p->owner = p->subs[SUB_REAL].owner;
4233 ast_log(LOG_DEBUG, "Making %s the new owner\n", p->owner->name);
4234 if (p->owner->_state == AST_STATE_RINGING) {
4235 ast_setstate(p->owner, AST_STATE_UP);
4236 p->subs[SUB_REAL].needanswer = 1;
4238 p->callwaitingrepeat = 0;
4239 p->cidcwexpire = 0;
4240 /* Start music on hold if appropriate */
4241 if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
4242 ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
4243 S_OR(p->mohsuggest, NULL),
4244 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4246 p->subs[SUB_CALLWAIT].needhold = 1;
4247 if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
4248 ast_queue_control_data(p->subs[SUB_REAL].owner, AST_CONTROL_HOLD,
4249 S_OR(p->mohsuggest, NULL),
4250 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4252 p->subs[SUB_REAL].needunhold = 1;
4253 } else if (!p->subs[SUB_THREEWAY].owner) {
4254 char cid_num[256];
4255 char cid_name[256];
4257 if (!p->threewaycalling) {
4258 /* Just send a flash if no 3-way calling */
4259 p->subs[SUB_REAL].needflash = 1;
4260 goto winkflashdone;
4261 } else if (!check_for_conference(p)) {
4262 if (p->zaptrcallerid && p->owner) {
4263 if (p->owner->cid.cid_num)
4264 ast_copy_string(cid_num, p->owner->cid.cid_num, sizeof(cid_num));
4265 if (p->owner->cid.cid_name)
4266 ast_copy_string(cid_name, p->owner->cid.cid_name, sizeof(cid_name));
4268 /* XXX This section needs much more error checking!!! XXX */
4269 /* Start a 3-way call if feasible */
4270 if (!((ast->pbx) ||
4271 (ast->_state == AST_STATE_UP) ||
4272 (ast->_state == AST_STATE_RING))) {
4273 ast_log(LOG_DEBUG, "Flash when call not up or ringing\n");
4274 goto winkflashdone;
4276 if (alloc_sub(p, SUB_THREEWAY)) {
4277 ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
4278 goto winkflashdone;
4280 /* Make new channel */
4281 chan = zt_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, 0);
4282 if (p->zaptrcallerid) {
4283 if (!p->origcid_num)
4284 p->origcid_num = ast_strdup(p->cid_num);
4285 if (!p->origcid_name)
4286 p->origcid_name = ast_strdup(p->cid_name);
4287 ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
4288 ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
4290 /* Swap things around between the three-way and real call */
4291 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4292 /* Disable echo canceller for better dialing */
4293 zt_disable_ec(p);
4294 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALRECALL);
4295 if (res)
4296 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
4297 p->owner = chan;
4298 pthread_attr_init(&attr);
4299 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
4300 if (!chan) {
4301 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
4302 } else if (ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
4303 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
4304 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
4305 zt_enable_ec(p);
4306 ast_hangup(chan);
4307 } else {
4308 if (option_verbose > 2)
4309 ast_verbose(VERBOSE_PREFIX_3 "Started three way call on channel %d\n", p->channel);
4310 /* Start music on hold if appropriate */
4311 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
4312 ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
4313 S_OR(p->mohsuggest, NULL),
4314 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
4316 p->subs[SUB_THREEWAY].needhold = 1;
4318 pthread_attr_destroy(&attr);
4320 } else {
4321 /* Already have a 3 way call */
4322 if (p->subs[SUB_THREEWAY].inthreeway) {
4323 /* Call is already up, drop the last person */
4324 if (option_debug)
4325 ast_log(LOG_DEBUG, "Got flash with three way call up, dropping last call on %d\n", p->channel);
4326 /* If the primary call isn't answered yet, use it */
4327 if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
4328 /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
4329 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4330 p->owner = p->subs[SUB_REAL].owner;
4332 /* Drop the last call and stop the conference */
4333 if (option_verbose > 2)
4334 ast_verbose(VERBOSE_PREFIX_3 "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
4335 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
4336 p->subs[SUB_REAL].inthreeway = 0;
4337 p->subs[SUB_THREEWAY].inthreeway = 0;
4338 } else {
4339 /* Lets see what we're up to */
4340 if (((ast->pbx) || (ast->_state == AST_STATE_UP)) &&
4341 (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
4342 int otherindex = SUB_THREEWAY;
4344 if (option_verbose > 2)
4345 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);
4346 /* Put them in the threeway, and flip */
4347 p->subs[SUB_THREEWAY].inthreeway = 1;
4348 p->subs[SUB_REAL].inthreeway = 1;
4349 if (ast->_state == AST_STATE_UP) {
4350 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4351 otherindex = SUB_REAL;
4353 if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
4354 ast_queue_control(p->subs[otherindex].owner, AST_CONTROL_UNHOLD);
4355 p->subs[otherindex].needunhold = 1;
4356 p->owner = p->subs[SUB_REAL].owner;
4357 if (ast->_state == AST_STATE_RINGING) {
4358 ast_log(LOG_DEBUG, "Enabling ringtone on real and threeway\n");
4359 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
4360 res = tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, ZT_TONE_RINGTONE);
4362 } else {
4363 if (option_verbose > 2)
4364 ast_verbose(VERBOSE_PREFIX_3 "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
4365 swap_subs(p, SUB_THREEWAY, SUB_REAL);
4366 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
4367 p->owner = p->subs[SUB_REAL].owner;
4368 if (p->subs[SUB_REAL].owner && ast_bridged_channel(p->subs[SUB_REAL].owner))
4369 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
4370 p->subs[SUB_REAL].needunhold = 1;
4371 zt_enable_ec(p);
4376 winkflashdone:
4377 update_conf(p);
4378 break;
4379 case SIG_EM:
4380 case SIG_EM_E1:
4381 case SIG_EMWINK:
4382 case SIG_FEATD:
4383 case SIG_SF:
4384 case SIG_SFWINK:
4385 case SIG_SF_FEATD:
4386 case SIG_FXSLS:
4387 case SIG_FXSGS:
4388 if (p->dialing)
4389 ast_log(LOG_DEBUG, "Ignoring wink on channel %d\n", p->channel);
4390 else
4391 ast_log(LOG_DEBUG, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
4392 break;
4393 case SIG_FEATDMF_TA:
4394 switch (p->whichwink) {
4395 case 0:
4396 ast_log(LOG_DEBUG, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
4397 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
4398 break;
4399 case 1:
4400 ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
4401 break;
4402 case 2:
4403 ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
4404 return NULL;
4406 p->whichwink++;
4407 /* Fall through */
4408 case SIG_FEATDMF:
4409 case SIG_E911:
4410 case SIG_FGC_CAMAMF:
4411 case SIG_FGC_CAMA:
4412 case SIG_FEATB:
4413 case SIG_SF_FEATDMF:
4414 case SIG_SF_FEATB:
4415 /* FGD MF *Must* wait for wink */
4416 if (!ast_strlen_zero(p->dop.dialstr)) {
4417 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
4418 if (res < 0) {
4419 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
4420 p->dop.dialstr[0] = '\0';
4421 return NULL;
4422 } else
4423 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
4425 p->dop.dialstr[0] = '\0';
4426 break;
4427 default:
4428 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
4430 break;
4431 case ZT_EVENT_HOOKCOMPLETE:
4432 if (p->inalarm) break;
4433 if ((p->radio || (p->oprmode < 0))) break;
4434 switch (mysig) {
4435 case SIG_FXSLS: /* only interesting for FXS */
4436 case SIG_FXSGS:
4437 case SIG_FXSKS:
4438 case SIG_EM:
4439 case SIG_EM_E1:
4440 case SIG_EMWINK:
4441 case SIG_FEATD:
4442 case SIG_SF:
4443 case SIG_SFWINK:
4444 case SIG_SF_FEATD:
4445 if (!ast_strlen_zero(p->dop.dialstr)) {
4446 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
4447 if (res < 0) {
4448 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
4449 p->dop.dialstr[0] = '\0';
4450 return NULL;
4451 } else
4452 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
4454 p->dop.dialstr[0] = '\0';
4455 p->dop.op = ZT_DIAL_OP_REPLACE;
4456 break;
4457 case SIG_FEATDMF:
4458 case SIG_FEATDMF_TA:
4459 case SIG_E911:
4460 case SIG_FGC_CAMA:
4461 case SIG_FGC_CAMAMF:
4462 case SIG_FEATB:
4463 case SIG_SF_FEATDMF:
4464 case SIG_SF_FEATB:
4465 ast_log(LOG_DEBUG, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
4466 break;
4467 default:
4468 break;
4470 break;
4471 case ZT_EVENT_POLARITY:
4473 * If we get a Polarity Switch event, check to see
4474 * if we should change the polarity state and
4475 * mark the channel as UP or if this is an indication
4476 * of remote end disconnect.
4478 if (p->polarity == POLARITY_IDLE) {
4479 p->polarity = POLARITY_REV;
4480 if (p->answeronpolarityswitch &&
4481 ((ast->_state == AST_STATE_DIALING) ||
4482 (ast->_state == AST_STATE_RINGING))) {
4483 ast_log(LOG_DEBUG, "Answering on polarity switch!\n");
4484 ast_setstate(p->owner, AST_STATE_UP);
4485 if (p->hanguponpolarityswitch) {
4486 gettimeofday(&p->polaritydelaytv, NULL);
4488 } else
4489 ast_log(LOG_DEBUG, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
4491 /* Removed else statement from here as it was preventing hangups from ever happening*/
4492 /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
4493 if (p->hanguponpolarityswitch &&
4494 (p->polarityonanswerdelay > 0) &&
4495 (p->polarity == POLARITY_REV) &&
4496 ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
4497 /* Added log_debug information below to provide a better indication of what is going on */
4498 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) );
4500 if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
4501 ast_log(LOG_DEBUG, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
4502 ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
4503 p->polarity = POLARITY_IDLE;
4504 } else {
4505 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);
4507 } else {
4508 p->polarity = POLARITY_IDLE;
4509 ast_log(LOG_DEBUG, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
4511 /* Added more log_debug information below to provide a better indication of what is going on */
4512 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) );
4513 break;
4514 default:
4515 ast_log(LOG_DEBUG, "Dunno what to do with event %d on channel %d\n", res, p->channel);
4517 return &p->subs[index].f;
4520 static struct ast_frame *__zt_exception(struct ast_channel *ast)
4522 struct zt_pvt *p = ast->tech_pvt;
4523 int res;
4524 int usedindex=-1;
4525 int index;
4526 struct ast_frame *f;
4529 index = zt_get_index(ast, p, 1);
4531 p->subs[index].f.frametype = AST_FRAME_NULL;
4532 p->subs[index].f.datalen = 0;
4533 p->subs[index].f.samples = 0;
4534 p->subs[index].f.mallocd = 0;
4535 p->subs[index].f.offset = 0;
4536 p->subs[index].f.subclass = 0;
4537 p->subs[index].f.delivery = ast_tv(0,0);
4538 p->subs[index].f.src = "zt_exception";
4539 p->subs[index].f.data = NULL;
4542 if ((!p->owner) && (!(p->radio || (p->oprmode < 0)))) {
4543 /* If nobody owns us, absorb the event appropriately, otherwise
4544 we loop indefinitely. This occurs when, during call waiting, the
4545 other end hangs up our channel so that it no longer exists, but we
4546 have neither FLASH'd nor ONHOOK'd to signify our desire to
4547 change to the other channel. */
4548 if (p->fake_event) {
4549 res = p->fake_event;
4550 p->fake_event = 0;
4551 } else
4552 res = zt_get_event(p->subs[SUB_REAL].zfd);
4553 /* Switch to real if there is one and this isn't something really silly... */
4554 if ((res != ZT_EVENT_RINGEROFF) && (res != ZT_EVENT_RINGERON) &&
4555 (res != ZT_EVENT_HOOKCOMPLETE)) {
4556 ast_log(LOG_DEBUG, "Restoring owner of channel %d on event %d\n", p->channel, res);
4557 p->owner = p->subs[SUB_REAL].owner;
4558 if (p->owner && ast_bridged_channel(p->owner))
4559 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4560 p->subs[SUB_REAL].needunhold = 1;
4562 switch (res) {
4563 case ZT_EVENT_ONHOOK:
4564 zt_disable_ec(p);
4565 if (p->owner) {
4566 if (option_verbose > 2)
4567 ast_verbose(VERBOSE_PREFIX_3 "Channel %s still has call, ringing phone\n", p->owner->name);
4568 zt_ring_phone(p);
4569 p->callwaitingrepeat = 0;
4570 p->cidcwexpire = 0;
4571 } else
4572 ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
4573 update_conf(p);
4574 break;
4575 case ZT_EVENT_RINGOFFHOOK:
4576 zt_enable_ec(p);
4577 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
4578 if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
4579 p->subs[SUB_REAL].needanswer = 1;
4580 p->dialing = 0;
4582 break;
4583 case ZT_EVENT_HOOKCOMPLETE:
4584 case ZT_EVENT_RINGERON:
4585 case ZT_EVENT_RINGEROFF:
4586 /* Do nothing */
4587 break;
4588 case ZT_EVENT_WINKFLASH:
4589 gettimeofday(&p->flashtime, NULL);
4590 if (p->owner) {
4591 if (option_verbose > 2)
4592 ast_verbose(VERBOSE_PREFIX_3 "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
4593 if (p->owner->_state != AST_STATE_UP) {
4594 /* Answer if necessary */
4595 usedindex = zt_get_index(p->owner, p, 0);
4596 if (usedindex > -1) {
4597 p->subs[usedindex].needanswer = 1;
4599 ast_setstate(p->owner, AST_STATE_UP);
4601 p->callwaitingrepeat = 0;
4602 p->cidcwexpire = 0;
4603 if (ast_bridged_channel(p->owner))
4604 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
4605 p->subs[SUB_REAL].needunhold = 1;
4606 } else
4607 ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
4608 update_conf(p);
4609 break;
4610 default:
4611 ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
4613 f = &p->subs[index].f;
4614 return f;
4616 if (!(p->radio || (p->oprmode < 0)) && option_debug)
4617 ast_log(LOG_DEBUG, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
4618 /* If it's not us, return NULL immediately */
4619 if (ast != p->owner) {
4620 ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
4621 f = &p->subs[index].f;
4622 return f;
4624 f = zt_handle_event(ast);
4625 return f;
4628 static struct ast_frame *zt_exception(struct ast_channel *ast)
4630 struct zt_pvt *p = ast->tech_pvt;
4631 struct ast_frame *f;
4632 ast_mutex_lock(&p->lock);
4633 f = __zt_exception(ast);
4634 ast_mutex_unlock(&p->lock);
4635 return f;
4638 static struct ast_frame *zt_read(struct ast_channel *ast)
4640 struct zt_pvt *p = ast->tech_pvt;
4641 int res;
4642 int index;
4643 void *readbuf;
4644 struct ast_frame *f;
4647 ast_mutex_lock(&p->lock);
4649 index = zt_get_index(ast, p, 0);
4651 /* Hang up if we don't really exist */
4652 if (index < 0) {
4653 ast_log(LOG_WARNING, "We dont exist?\n");
4654 ast_mutex_unlock(&p->lock);
4655 return NULL;
4658 if ((p->radio || (p->oprmode < 0)) && p->inalarm) return NULL;
4660 p->subs[index].f.frametype = AST_FRAME_NULL;
4661 p->subs[index].f.datalen = 0;
4662 p->subs[index].f.samples = 0;
4663 p->subs[index].f.mallocd = 0;
4664 p->subs[index].f.offset = 0;
4665 p->subs[index].f.subclass = 0;
4666 p->subs[index].f.delivery = ast_tv(0,0);
4667 p->subs[index].f.src = "zt_read";
4668 p->subs[index].f.data = NULL;
4670 /* make sure it sends initial key state as first frame */
4671 if ((p->radio || (p->oprmode < 0)) && (!p->firstradio))
4673 ZT_PARAMS ps;
4675 ps.channo = p->channel;
4676 if (ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps) < 0) {
4677 ast_mutex_unlock(&p->lock);
4678 return NULL;
4680 p->firstradio = 1;
4681 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4682 if (ps.rxisoffhook)
4684 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
4686 else
4688 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
4690 ast_mutex_unlock(&p->lock);
4691 return &p->subs[index].f;
4693 if (p->ringt == 1) {
4694 ast_mutex_unlock(&p->lock);
4695 return NULL;
4697 else if (p->ringt > 0)
4698 p->ringt--;
4700 if (p->subs[index].needringing) {
4701 /* Send ringing frame if requested */
4702 p->subs[index].needringing = 0;
4703 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4704 p->subs[index].f.subclass = AST_CONTROL_RINGING;
4705 ast_setstate(ast, AST_STATE_RINGING);
4706 ast_mutex_unlock(&p->lock);
4707 return &p->subs[index].f;
4710 if (p->subs[index].needbusy) {
4711 /* Send busy frame if requested */
4712 p->subs[index].needbusy = 0;
4713 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4714 p->subs[index].f.subclass = AST_CONTROL_BUSY;
4715 ast_mutex_unlock(&p->lock);
4716 return &p->subs[index].f;
4719 if (p->subs[index].needcongestion) {
4720 /* Send congestion frame if requested */
4721 p->subs[index].needcongestion = 0;
4722 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4723 p->subs[index].f.subclass = AST_CONTROL_CONGESTION;
4724 ast_mutex_unlock(&p->lock);
4725 return &p->subs[index].f;
4728 if (p->subs[index].needcallerid) {
4729 ast_set_callerid(ast, S_OR(p->lastcid_num, NULL),
4730 S_OR(p->lastcid_name, NULL),
4731 S_OR(p->lastcid_num, NULL)
4733 p->subs[index].needcallerid = 0;
4736 if (p->subs[index].needanswer) {
4737 /* Send answer frame if requested */
4738 p->subs[index].needanswer = 0;
4739 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4740 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
4741 ast_mutex_unlock(&p->lock);
4742 return &p->subs[index].f;
4745 if (p->subs[index].needflash) {
4746 /* Send answer frame if requested */
4747 p->subs[index].needflash = 0;
4748 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4749 p->subs[index].f.subclass = AST_CONTROL_FLASH;
4750 ast_mutex_unlock(&p->lock);
4751 return &p->subs[index].f;
4754 if (p->subs[index].needhold) {
4755 /* Send answer frame if requested */
4756 p->subs[index].needhold = 0;
4757 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4758 p->subs[index].f.subclass = AST_CONTROL_HOLD;
4759 ast_mutex_unlock(&p->lock);
4760 ast_log(LOG_DEBUG, "Sending hold on '%s'\n", ast->name);
4761 return &p->subs[index].f;
4764 if (p->subs[index].needunhold) {
4765 /* Send answer frame if requested */
4766 p->subs[index].needunhold = 0;
4767 p->subs[index].f.frametype = AST_FRAME_CONTROL;
4768 p->subs[index].f.subclass = AST_CONTROL_UNHOLD;
4769 ast_mutex_unlock(&p->lock);
4770 ast_log(LOG_DEBUG, "Sending unhold on '%s'\n", ast->name);
4771 return &p->subs[index].f;
4774 if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
4775 if (!p->subs[index].linear) {
4776 p->subs[index].linear = 1;
4777 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4778 if (res)
4779 ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, index);
4781 } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
4782 (ast->rawreadformat == AST_FORMAT_ALAW)) {
4783 if (p->subs[index].linear) {
4784 p->subs[index].linear = 0;
4785 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
4786 if (res)
4787 ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, index);
4789 } else {
4790 ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
4791 ast_mutex_unlock(&p->lock);
4792 return NULL;
4794 readbuf = ((unsigned char *)p->subs[index].buffer) + AST_FRIENDLY_OFFSET;
4795 CHECK_BLOCKING(ast);
4796 res = read(p->subs[index].zfd, readbuf, p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE);
4797 ast_clear_flag(ast, AST_FLAG_BLOCKING);
4798 /* Check for hangup */
4799 if (res < 0) {
4800 f = NULL;
4801 if (res == -1) {
4802 if (errno == EAGAIN) {
4803 /* Return "NULL" frame if there is nobody there */
4804 ast_mutex_unlock(&p->lock);
4805 return &p->subs[index].f;
4806 } else if (errno == ELAST) {
4807 f = __zt_exception(ast);
4808 } else
4809 ast_log(LOG_WARNING, "zt_rec: %s\n", strerror(errno));
4811 ast_mutex_unlock(&p->lock);
4812 return f;
4814 if (res != (p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE)) {
4815 ast_log(LOG_DEBUG, "Short read (%d/%d), must be an event...\n", res, p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE);
4816 f = __zt_exception(ast);
4817 ast_mutex_unlock(&p->lock);
4818 return f;
4820 if (p->tdd) { /* if in TDD mode, see if we receive that */
4821 int c;
4823 c = tdd_feed(p->tdd,readbuf,READ_SIZE);
4824 if (c < 0) {
4825 ast_log(LOG_DEBUG,"tdd_feed failed\n");
4826 ast_mutex_unlock(&p->lock);
4827 return NULL;
4829 if (c) { /* if a char to return */
4830 p->subs[index].f.subclass = 0;
4831 p->subs[index].f.frametype = AST_FRAME_TEXT;
4832 p->subs[index].f.mallocd = 0;
4833 p->subs[index].f.offset = AST_FRIENDLY_OFFSET;
4834 p->subs[index].f.data = p->subs[index].buffer + AST_FRIENDLY_OFFSET;
4835 p->subs[index].f.datalen = 1;
4836 *((char *) p->subs[index].f.data) = c;
4837 ast_mutex_unlock(&p->lock);
4838 return &p->subs[index].f;
4841 if (p->callwaitingrepeat)
4842 p->callwaitingrepeat--;
4843 if (p->cidcwexpire)
4844 p->cidcwexpire--;
4845 /* Repeat callwaiting */
4846 if (p->callwaitingrepeat == 1) {
4847 p->callwaitrings++;
4848 zt_callwait(ast);
4850 /* Expire CID/CW */
4851 if (p->cidcwexpire == 1) {
4852 if (option_verbose > 2)
4853 ast_verbose(VERBOSE_PREFIX_3 "CPE does not support Call Waiting Caller*ID.\n");
4854 restore_conference(p);
4856 if (p->subs[index].linear) {
4857 p->subs[index].f.datalen = READ_SIZE * 2;
4858 } else
4859 p->subs[index].f.datalen = READ_SIZE;
4861 /* Handle CallerID Transmission */
4862 if ((p->owner == ast) && p->cidspill &&((ast->_state == AST_STATE_UP) || (ast->rings == p->cidrings))) {
4863 send_callerid(p);
4866 p->subs[index].f.frametype = AST_FRAME_VOICE;
4867 p->subs[index].f.subclass = ast->rawreadformat;
4868 p->subs[index].f.samples = READ_SIZE;
4869 p->subs[index].f.mallocd = 0;
4870 p->subs[index].f.offset = AST_FRIENDLY_OFFSET;
4871 p->subs[index].f.data = p->subs[index].buffer + AST_FRIENDLY_OFFSET / sizeof(p->subs[index].buffer[0]);
4872 #if 0
4873 ast_log(LOG_DEBUG, "Read %d of voice on %s\n", p->subs[index].f.datalen, ast->name);
4874 #endif
4875 if (p->dialing || /* Transmitting something */
4876 (index && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
4877 ((index == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
4879 /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
4880 don't send anything */
4881 p->subs[index].f.frametype = AST_FRAME_NULL;
4882 p->subs[index].f.subclass = 0;
4883 p->subs[index].f.samples = 0;
4884 p->subs[index].f.mallocd = 0;
4885 p->subs[index].f.offset = 0;
4886 p->subs[index].f.data = NULL;
4887 p->subs[index].f.datalen= 0;
4889 if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect || p->callprogress) && !index) {
4890 /* Perform busy detection. etc on the zap line */
4891 f = ast_dsp_process(ast, p->dsp, &p->subs[index].f);
4892 if (f) {
4893 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_BUSY)) {
4894 if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
4895 /* Treat this as a "hangup" instead of a "busy" on the assumption that
4896 a busy */
4897 f = NULL;
4899 } else if (f->frametype == AST_FRAME_DTMF) {
4900 #ifdef HAVE_PRI
4901 if (!p->proceeding && p->sig==SIG_PRI && p->pri && p->pri->overlapdial) {
4902 /* Don't accept in-band DTMF when in overlap dial mode */
4903 f->frametype = AST_FRAME_NULL;
4904 f->subclass = 0;
4906 #endif
4907 /* DSP clears us of being pulse */
4908 p->pulsedial = 0;
4911 } else
4912 f = &p->subs[index].f;
4914 if (f && (f->frametype == AST_FRAME_DTMF))
4915 zt_handle_dtmfup(ast, index, &f);
4917 /* If we have a fake_event, trigger exception to handle it */
4918 if (p->fake_event)
4919 ast_set_flag(ast, AST_FLAG_EXCEPTION);
4921 ast_mutex_unlock(&p->lock);
4922 return f;
4925 static int my_zt_write(struct zt_pvt *p, unsigned char *buf, int len, int index, int linear)
4927 int sent=0;
4928 int size;
4929 int res;
4930 int fd;
4931 fd = p->subs[index].zfd;
4932 while (len) {
4933 size = len;
4934 if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
4935 size = (linear ? READ_SIZE * 2 : READ_SIZE);
4936 res = write(fd, buf, size);
4937 if (res != size) {
4938 if (option_debug)
4939 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
4940 return sent;
4942 len -= size;
4943 buf += size;
4945 return sent;
4948 static int zt_write(struct ast_channel *ast, struct ast_frame *frame)
4950 struct zt_pvt *p = ast->tech_pvt;
4951 int res;
4952 int index;
4953 index = zt_get_index(ast, p, 0);
4954 if (index < 0) {
4955 ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
4956 return -1;
4959 #if 0
4960 #ifdef HAVE_PRI
4961 ast_mutex_lock(&p->lock);
4962 if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
4963 if (p->pri->pri) {
4964 if (!pri_grab(p, p->pri)) {
4965 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
4966 pri_rel(p->pri);
4967 } else
4968 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
4970 p->proceeding=1;
4972 ast_mutex_unlock(&p->lock);
4973 #endif
4974 #endif
4975 /* Write a frame of (presumably voice) data */
4976 if (frame->frametype != AST_FRAME_VOICE) {
4977 if (frame->frametype != AST_FRAME_IMAGE)
4978 ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
4979 return 0;
4981 if ((frame->subclass != AST_FORMAT_SLINEAR) &&
4982 (frame->subclass != AST_FORMAT_ULAW) &&
4983 (frame->subclass != AST_FORMAT_ALAW)) {
4984 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
4985 return -1;
4987 if (p->dialing) {
4988 if (option_debug)
4989 ast_log(LOG_DEBUG, "Dropping frame since I'm still dialing on %s...\n",ast->name);
4990 return 0;
4992 if (!p->owner) {
4993 if (option_debug)
4994 ast_log(LOG_DEBUG, "Dropping frame since there is no active owner on %s...\n",ast->name);
4995 return 0;
4997 if (p->cidspill) {
4998 if (option_debug)
4999 ast_log(LOG_DEBUG, "Dropping frame since I've still got a callerid spill\n");
5000 return 0;
5002 /* Return if it's not valid data */
5003 if (!frame->data || !frame->datalen)
5004 return 0;
5006 if (frame->subclass == AST_FORMAT_SLINEAR) {
5007 if (!p->subs[index].linear) {
5008 p->subs[index].linear = 1;
5009 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
5010 if (res)
5011 ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
5013 res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, index, 1);
5014 } else {
5015 /* x-law already */
5016 if (p->subs[index].linear) {
5017 p->subs[index].linear = 0;
5018 res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
5019 if (res)
5020 ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
5022 res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, index, 0);
5024 if (res < 0) {
5025 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
5026 return -1;
5028 return 0;
5031 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
5033 struct zt_pvt *p = chan->tech_pvt;
5034 int res=-1;
5035 int index;
5036 int func = ZT_FLASH;
5037 ast_mutex_lock(&p->lock);
5038 index = zt_get_index(chan, p, 0);
5039 if (option_debug)
5040 ast_log(LOG_DEBUG, "Requested indication %d on channel %s\n", condition, chan->name);
5041 if (index == SUB_REAL) {
5042 switch (condition) {
5043 case AST_CONTROL_BUSY:
5044 #ifdef HAVE_PRI
5045 if (p->priindication_oob && p->sig == SIG_PRI) {
5046 chan->hangupcause = AST_CAUSE_USER_BUSY;
5047 chan->_softhangup |= AST_SOFTHANGUP_DEV;
5048 res = 0;
5049 } else if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5050 if (p->pri->pri) {
5051 if (!pri_grab(p, p->pri)) {
5052 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5053 pri_rel(p->pri);
5055 else
5056 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5058 p->progress = 1;
5059 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_BUSY);
5060 } else
5061 #endif
5062 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_BUSY);
5063 break;
5064 case AST_CONTROL_RINGING:
5065 #ifdef HAVE_PRI
5066 if ((!p->alerting) && p->sig==SIG_PRI && p->pri && !p->outgoing && (chan->_state != AST_STATE_UP)) {
5067 if (p->pri->pri) {
5068 if (!pri_grab(p, p->pri)) {
5069 pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
5070 pri_rel(p->pri);
5072 else
5073 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5075 p->alerting = 1;
5077 #endif
5078 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_RINGTONE);
5079 if (chan->_state != AST_STATE_UP) {
5080 if ((chan->_state != AST_STATE_RING) ||
5081 ((p->sig != SIG_FXSKS) &&
5082 (p->sig != SIG_FXSLS) &&
5083 (p->sig != SIG_FXSGS)))
5084 ast_setstate(chan, AST_STATE_RINGING);
5086 break;
5087 case AST_CONTROL_PROCEEDING:
5088 ast_log(LOG_DEBUG,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
5089 #ifdef HAVE_PRI
5090 if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5091 if (p->pri->pri) {
5092 if (!pri_grab(p, p->pri)) {
5093 pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
5094 pri_rel(p->pri);
5096 else
5097 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5099 p->proceeding = 1;
5101 #endif
5102 /* don't continue in ast_indicate */
5103 res = 0;
5104 break;
5105 case AST_CONTROL_PROGRESS:
5106 ast_log(LOG_DEBUG,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
5107 #ifdef HAVE_PRI
5108 p->digital = 0; /* Digital-only calls isn't allows any inband progress messages */
5109 if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5110 if (p->pri->pri) {
5111 if (!pri_grab(p, p->pri)) {
5112 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5113 pri_rel(p->pri);
5115 else
5116 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5118 p->progress = 1;
5120 #endif
5121 /* don't continue in ast_indicate */
5122 res = 0;
5123 break;
5124 case AST_CONTROL_CONGESTION:
5125 chan->hangupcause = AST_CAUSE_CONGESTION;
5126 #ifdef HAVE_PRI
5127 if (p->priindication_oob && p->sig == SIG_PRI) {
5128 chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
5129 chan->_softhangup |= AST_SOFTHANGUP_DEV;
5130 res = 0;
5131 } else if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
5132 if (p->pri) {
5133 if (!pri_grab(p, p->pri)) {
5134 pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
5135 pri_rel(p->pri);
5136 } else
5137 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5139 p->progress = 1;
5140 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5141 } else
5142 #endif
5143 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5144 break;
5145 case AST_CONTROL_HOLD:
5146 #ifdef HAVE_PRI
5147 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
5148 if (!pri_grab(p, p->pri)) {
5149 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
5150 pri_rel(p->pri);
5151 } else
5152 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5153 } else
5154 #endif
5155 ast_moh_start(chan, data, p->mohinterpret);
5156 break;
5157 case AST_CONTROL_UNHOLD:
5158 #ifdef HAVE_PRI
5159 if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
5160 if (!pri_grab(p, p->pri)) {
5161 res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
5162 pri_rel(p->pri);
5163 } else
5164 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
5165 } else
5166 #endif
5167 ast_moh_stop(chan);
5168 break;
5169 case AST_CONTROL_RADIO_KEY:
5170 if (p->radio)
5171 res = zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
5172 res = 0;
5173 break;
5174 case AST_CONTROL_RADIO_UNKEY:
5175 if (p->radio)
5176 res = zt_set_hook(p->subs[index].zfd, ZT_RINGOFF);
5177 res = 0;
5178 break;
5179 case AST_CONTROL_FLASH:
5180 /* flash hookswitch */
5181 if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
5182 /* Clear out the dial buffer */
5183 p->dop.dialstr[0] = '\0';
5184 if ((ioctl(p->subs[SUB_REAL].zfd,ZT_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
5185 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
5186 chan->name, strerror(errno));
5187 } else
5188 res = 0;
5189 } else
5190 res = 0;
5191 break;
5192 case AST_CONTROL_SRCUPDATE:
5193 res = 0;
5194 break;
5195 case -1:
5196 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5197 break;
5199 } else
5200 res = 0;
5201 ast_mutex_unlock(&p->lock);
5202 return res;
5205 static struct ast_channel *zt_new(struct zt_pvt *i, int state, int startpbx, int index, int law, int transfercapability)
5207 struct ast_channel *tmp;
5208 int deflaw;
5209 int res;
5210 int x,y;
5211 int features;
5212 char *b2 = NULL;
5213 ZT_PARAMS ps;
5214 if (i->subs[index].owner) {
5215 ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[index]);
5216 return NULL;
5218 y = 1;
5219 do {
5220 if (b2)
5221 free(b2);
5222 #ifdef HAVE_PRI
5223 if (i->bearer || (i->pri && (i->sig == SIG_FXSKS)))
5224 b2 = ast_safe_string_alloc("%d:%d-%d", i->pri->trunkgroup, i->channel, y);
5225 else
5226 #endif
5227 if (i->channel == CHAN_PSEUDO)
5228 b2 = ast_safe_string_alloc("pseudo-%ld", ast_random());
5229 else
5230 b2 = ast_safe_string_alloc("%d-%d", i->channel, y);
5231 for (x = 0; x < 3; x++) {
5232 if ((index != x) && i->subs[x].owner && !strcasecmp(b2, i->subs[x].owner->name))
5233 break;
5235 y++;
5236 } while (x < 3);
5237 tmp = ast_channel_alloc(0, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "Zap/%s", b2);
5238 if (b2) /*!> b2 can be freed now, it's been copied into the channel structure */
5239 free(b2);
5240 if (!tmp)
5241 return NULL;
5242 tmp->tech = &zap_tech;
5243 ps.channo = i->channel;
5244 res = ioctl(i->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps);
5245 if (res) {
5246 ast_log(LOG_WARNING, "Unable to get parameters, assuming MULAW\n");
5247 ps.curlaw = ZT_LAW_MULAW;
5249 if (ps.curlaw == ZT_LAW_ALAW)
5250 deflaw = AST_FORMAT_ALAW;
5251 else
5252 deflaw = AST_FORMAT_ULAW;
5253 if (law) {
5254 if (law == ZT_LAW_ALAW)
5255 deflaw = AST_FORMAT_ALAW;
5256 else
5257 deflaw = AST_FORMAT_ULAW;
5259 tmp->fds[0] = i->subs[index].zfd;
5260 tmp->nativeformats = AST_FORMAT_SLINEAR | deflaw;
5261 /* Start out assuming ulaw since it's smaller :) */
5262 tmp->rawreadformat = deflaw;
5263 tmp->readformat = deflaw;
5264 tmp->rawwriteformat = deflaw;
5265 tmp->writeformat = deflaw;
5266 i->subs[index].linear = 0;
5267 zt_setlinear(i->subs[index].zfd, i->subs[index].linear);
5268 features = 0;
5269 if (index == SUB_REAL) {
5270 if (i->busydetect && CANBUSYDETECT(i))
5271 features |= DSP_FEATURE_BUSY_DETECT;
5272 if ((i->callprogress & 1) && CANPROGRESSDETECT(i))
5273 features |= DSP_FEATURE_CALL_PROGRESS;
5274 if ((!i->outgoing && (i->callprogress & 4)) ||
5275 (i->outgoing && (i->callprogress & 2))) {
5276 features |= DSP_FEATURE_FAX_DETECT;
5278 #ifdef ZT_TONEDETECT
5279 x = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
5280 if (ioctl(i->subs[index].zfd, ZT_TONEDETECT, &x)) {
5281 #endif
5282 i->hardwaredtmf = 0;
5283 features |= DSP_FEATURE_DTMF_DETECT;
5284 #ifdef ZT_TONEDETECT
5285 } else if (NEED_MFDETECT(i)) {
5286 i->hardwaredtmf = 1;
5287 features |= DSP_FEATURE_DTMF_DETECT;
5289 #endif
5291 if (features) {
5292 if (i->dsp) {
5293 ast_log(LOG_DEBUG, "Already have a dsp on %s?\n", tmp->name);
5294 } else {
5295 if (i->channel != CHAN_PSEUDO)
5296 i->dsp = ast_dsp_new();
5297 else
5298 i->dsp = NULL;
5299 if (i->dsp) {
5300 i->dsp_features = features & ~DSP_PROGRESS_TALK;
5301 #ifdef HAVE_PRI
5302 /* We cannot do progress detection until receives PROGRESS message */
5303 if (i->outgoing && (i->sig == SIG_PRI)) {
5304 /* Remember requested DSP features, don't treat
5305 talking as ANSWER */
5306 features = 0;
5308 #endif
5309 ast_dsp_set_features(i->dsp, features);
5310 ast_dsp_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
5311 if (!ast_strlen_zero(progzone))
5312 ast_dsp_set_call_progress_zone(i->dsp, progzone);
5313 if (i->busydetect && CANBUSYDETECT(i)) {
5314 ast_dsp_set_busy_count(i->dsp, i->busycount);
5315 ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
5321 if (state == AST_STATE_RING)
5322 tmp->rings = 1;
5323 tmp->tech_pvt = i;
5324 if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
5325 /* Only FXO signalled stuff can be picked up */
5326 tmp->callgroup = i->callgroup;
5327 tmp->pickupgroup = i->pickupgroup;
5329 if (!ast_strlen_zero(i->language))
5330 ast_string_field_set(tmp, language, i->language);
5331 if (!i->owner)
5332 i->owner = tmp;
5333 if (!ast_strlen_zero(i->accountcode))
5334 ast_string_field_set(tmp, accountcode, i->accountcode);
5335 if (i->amaflags)
5336 tmp->amaflags = i->amaflags;
5337 i->subs[index].owner = tmp;
5338 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
5339 ast_string_field_set(tmp, call_forward, i->call_forward);
5340 /* If we've been told "no ADSI" then enforce it */
5341 if (!i->adsi)
5342 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
5343 if (!ast_strlen_zero(i->exten))
5344 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
5345 if (!ast_strlen_zero(i->rdnis))
5346 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
5347 if (!ast_strlen_zero(i->dnid))
5348 tmp->cid.cid_dnid = ast_strdup(i->dnid);
5350 /* Don't use ast_set_callerid() here because it will
5351 * generate a needless NewCallerID event */
5352 #ifdef PRI_ANI
5353 if (!ast_strlen_zero(i->cid_ani))
5354 tmp->cid.cid_ani = ast_strdup(i->cid_ani);
5355 else
5356 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5357 #else
5358 tmp->cid.cid_ani = ast_strdup(i->cid_num);
5359 #endif
5360 tmp->cid.cid_pres = i->callingpres;
5361 tmp->cid.cid_ton = i->cid_ton;
5362 #ifdef HAVE_PRI
5363 tmp->transfercapability = transfercapability;
5364 pbx_builtin_setvar_helper(tmp, "TRANSFERCAPABILITY", ast_transfercapability2str(transfercapability));
5365 if (transfercapability & PRI_TRANS_CAP_DIGITAL)
5366 i->digital = 1;
5367 /* Assume calls are not idle calls unless we're told differently */
5368 i->isidlecall = 0;
5369 i->alreadyhungup = 0;
5370 #endif
5371 /* clear the fake event in case we posted one before we had ast_channel */
5372 i->fake_event = 0;
5373 /* Assure there is no confmute on this channel */
5374 zt_confmute(i, 0);
5375 /* Configure the new channel jb */
5376 ast_jb_configure(tmp, &global_jbconf);
5377 if (startpbx) {
5378 if (ast_pbx_start(tmp)) {
5379 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
5380 ast_hangup(tmp);
5381 i->owner = NULL;
5382 return NULL;
5386 ast_module_ref(ast_module_info->self);
5388 return tmp;
5392 static int my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
5394 char c;
5396 *str = 0; /* start with empty output buffer */
5397 for (;;)
5399 /* Wait for the first digit (up to specified ms). */
5400 c = ast_waitfordigit(chan, ms);
5401 /* if timeout, hangup or error, return as such */
5402 if (c < 1)
5403 return c;
5404 *str++ = c;
5405 *str = 0;
5406 if (strchr(term, c))
5407 return 1;
5411 static int zt_wink(struct zt_pvt *p, int index)
5413 int j;
5414 zt_set_hook(p->subs[index].zfd, ZT_WINK);
5415 for (;;)
5417 /* set bits of interest */
5418 j = ZT_IOMUX_SIGEVENT;
5419 /* wait for some happening */
5420 if (ioctl(p->subs[index].zfd,ZT_IOMUX,&j) == -1) return(-1);
5421 /* exit loop if we have it */
5422 if (j & ZT_IOMUX_SIGEVENT) break;
5424 /* get the event info */
5425 if (ioctl(p->subs[index].zfd,ZT_GETEVENT,&j) == -1) return(-1);
5426 return 0;
5429 static void *ss_thread(void *data)
5431 struct ast_channel *chan = data;
5432 struct zt_pvt *p = chan->tech_pvt;
5433 char exten[AST_MAX_EXTENSION] = "";
5434 char exten2[AST_MAX_EXTENSION] = "";
5435 unsigned char buf[256];
5436 char dtmfcid[300];
5437 char dtmfbuf[300];
5438 struct callerid_state *cs = NULL;
5439 char *name = NULL, *number = NULL;
5440 int distMatches;
5441 int curRingData[3];
5442 int receivedRingT;
5443 int counter1;
5444 int counter;
5445 int samples = 0;
5446 struct ast_smdi_md_message *smdi_msg = NULL;
5447 int flags;
5448 int i;
5449 int timeout;
5450 int getforward = 0;
5451 char *s1, *s2;
5452 int len = 0;
5453 int res;
5454 int index;
5456 /* in the bizarre case where the channel has become a zombie before we
5457 even get started here, abort safely
5459 if (!p) {
5460 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
5461 ast_hangup(chan);
5462 return NULL;
5465 if (option_verbose > 2)
5466 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s'\n", chan->name);
5467 index = zt_get_index(chan, p, 1);
5468 if (index < 0) {
5469 ast_log(LOG_WARNING, "Huh?\n");
5470 ast_hangup(chan);
5471 return NULL;
5473 if (p->dsp)
5474 ast_dsp_digitreset(p->dsp);
5475 switch (p->sig) {
5476 #ifdef HAVE_PRI
5477 case SIG_PRI:
5478 /* Now loop looking for an extension */
5479 ast_copy_string(exten, p->exten, sizeof(exten));
5480 len = strlen(exten);
5481 res = 0;
5482 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
5483 if (len && !ast_ignore_pattern(chan->context, exten))
5484 tone_zone_play_tone(p->subs[index].zfd, -1);
5485 else
5486 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5487 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
5488 timeout = matchdigittimeout;
5489 else
5490 timeout = gendigittimeout;
5491 res = ast_waitfordigit(chan, timeout);
5492 if (res < 0) {
5493 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5494 ast_hangup(chan);
5495 return NULL;
5496 } else if (res) {
5497 exten[len++] = res;
5498 exten[len] = '\0';
5499 } else
5500 break;
5502 /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
5503 if (ast_strlen_zero(exten)) {
5504 if (option_verbose > 2)
5505 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of empty extension received on overlap call\n");
5506 exten[0] = 's';
5507 exten[1] = '\0';
5509 tone_zone_play_tone(p->subs[index].zfd, -1);
5510 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
5511 /* Start the real PBX */
5512 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5513 if (p->dsp) ast_dsp_digitreset(p->dsp);
5514 zt_enable_ec(p);
5515 ast_setstate(chan, AST_STATE_RING);
5516 res = ast_pbx_run(chan);
5517 if (res) {
5518 ast_log(LOG_WARNING, "PBX exited non-zero!\n");
5520 } else {
5521 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
5522 chan->hangupcause = AST_CAUSE_UNALLOCATED;
5523 ast_hangup(chan);
5524 p->exten[0] = '\0';
5525 /* Since we send release complete here, we won't get one */
5526 p->call = NULL;
5528 return NULL;
5529 break;
5530 #endif
5531 case SIG_FEATD:
5532 case SIG_FEATDMF:
5533 case SIG_FEATDMF_TA:
5534 case SIG_E911:
5535 case SIG_FGC_CAMAMF:
5536 case SIG_FEATB:
5537 case SIG_EMWINK:
5538 case SIG_SF_FEATD:
5539 case SIG_SF_FEATDMF:
5540 case SIG_SF_FEATB:
5541 case SIG_SFWINK:
5542 if (zt_wink(p, index))
5543 return NULL;
5544 /* Fall through */
5545 case SIG_EM:
5546 case SIG_EM_E1:
5547 case SIG_SF:
5548 case SIG_FGC_CAMA:
5549 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5550 if (p->dsp)
5551 ast_dsp_digitreset(p->dsp);
5552 /* set digit mode appropriately */
5553 if (p->dsp) {
5554 if (NEED_MFDETECT(p))
5555 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MF | p->dtmfrelax);
5556 else
5557 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5559 memset(dtmfbuf, 0, sizeof(dtmfbuf));
5560 /* Wait for the first digit only if immediate=no */
5561 if (!p->immediate)
5562 /* Wait for the first digit (up to 5 seconds). */
5563 res = ast_waitfordigit(chan, 5000);
5564 else
5565 res = 0;
5566 if (res > 0) {
5567 /* save first char */
5568 dtmfbuf[0] = res;
5569 switch (p->sig) {
5570 case SIG_FEATD:
5571 case SIG_SF_FEATD:
5572 res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
5573 if (res > 0)
5574 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
5575 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5576 break;
5577 case SIG_FEATDMF_TA:
5578 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5579 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5580 if (zt_wink(p, index)) return NULL;
5581 dtmfbuf[0] = 0;
5582 /* Wait for the first digit (up to 5 seconds). */
5583 res = ast_waitfordigit(chan, 5000);
5584 if (res <= 0) break;
5585 dtmfbuf[0] = res;
5586 /* fall through intentionally */
5587 case SIG_FEATDMF:
5588 case SIG_E911:
5589 case SIG_FGC_CAMAMF:
5590 case SIG_SF_FEATDMF:
5591 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5592 /* if international caca, do it again to get real ANO */
5593 if ((p->sig == SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
5595 if (zt_wink(p, index)) return NULL;
5596 dtmfbuf[0] = 0;
5597 /* Wait for the first digit (up to 5 seconds). */
5598 res = ast_waitfordigit(chan, 5000);
5599 if (res <= 0) break;
5600 dtmfbuf[0] = res;
5601 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5603 if (res > 0) {
5604 /* if E911, take off hook */
5605 if (p->sig == SIG_E911)
5606 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
5607 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
5609 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5610 break;
5611 case SIG_FEATB:
5612 case SIG_SF_FEATB:
5613 res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
5614 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5615 break;
5616 case SIG_EMWINK:
5617 /* if we received a '*', we are actually receiving Feature Group D
5618 dial syntax, so use that mode; otherwise, fall through to normal
5619 mode
5621 if (res == '*') {
5622 res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
5623 if (res > 0)
5624 res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
5625 if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
5626 break;
5628 default:
5629 /* If we got the first digit, get the rest */
5630 len = 1;
5631 dtmfbuf[len] = '\0';
5632 while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
5633 if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
5634 timeout = matchdigittimeout;
5635 } else {
5636 timeout = gendigittimeout;
5638 res = ast_waitfordigit(chan, timeout);
5639 if (res < 0) {
5640 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5641 ast_hangup(chan);
5642 return NULL;
5643 } else if (res) {
5644 dtmfbuf[len++] = res;
5645 dtmfbuf[len] = '\0';
5646 } else {
5647 break;
5650 break;
5653 if (res == -1) {
5654 ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
5655 ast_hangup(chan);
5656 return NULL;
5657 } else if (res < 0) {
5658 ast_log(LOG_DEBUG, "Got hung up before digits finished\n");
5659 ast_hangup(chan);
5660 return NULL;
5663 if (p->sig == SIG_FGC_CAMA) {
5664 char anibuf[100];
5666 if (ast_safe_sleep(chan,1000) == -1) {
5667 ast_hangup(chan);
5668 return NULL;
5670 zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
5671 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MF | p->dtmfrelax);
5672 res = my_getsigstr(chan, anibuf, "#", 10000);
5673 if ((res > 0) && (strlen(anibuf) > 2)) {
5674 if (anibuf[strlen(anibuf) - 1] == '#')
5675 anibuf[strlen(anibuf) - 1] = 0;
5676 ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
5678 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5681 ast_copy_string(exten, dtmfbuf, sizeof(exten));
5682 if (ast_strlen_zero(exten))
5683 ast_copy_string(exten, "s", sizeof(exten));
5684 if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
5685 /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
5686 if (exten[0] == '*') {
5687 char *stringp=NULL;
5688 ast_copy_string(exten2, exten, sizeof(exten2));
5689 /* Parse out extension and callerid */
5690 stringp=exten2 +1;
5691 s1 = strsep(&stringp, "*");
5692 s2 = strsep(&stringp, "*");
5693 if (s2) {
5694 if (!ast_strlen_zero(p->cid_num))
5695 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5696 else
5697 ast_set_callerid(chan, s1, NULL, s1);
5698 ast_copy_string(exten, s2, sizeof(exten));
5699 } else
5700 ast_copy_string(exten, s1, sizeof(exten));
5701 } else if (p->sig == SIG_FEATD)
5702 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d. Assuming E&M Wink instead\n", p->channel);
5704 if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
5705 if (exten[0] == '*') {
5706 char *stringp=NULL;
5707 ast_copy_string(exten2, exten, sizeof(exten2));
5708 /* Parse out extension and callerid */
5709 stringp=exten2 +1;
5710 s1 = strsep(&stringp, "#");
5711 s2 = strsep(&stringp, "#");
5712 if (s2) {
5713 if (!ast_strlen_zero(p->cid_num))
5714 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5715 else
5716 if (*(s1 + 2))
5717 ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
5718 ast_copy_string(exten, s2 + 1, sizeof(exten));
5719 } else
5720 ast_copy_string(exten, s1 + 2, sizeof(exten));
5721 } else
5722 ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d. Assuming E&M Wink instead\n", p->channel);
5724 if ((p->sig == SIG_E911) || (p->sig == SIG_FGC_CAMAMF)) {
5725 if (exten[0] == '*') {
5726 char *stringp=NULL;
5727 ast_copy_string(exten2, exten, sizeof(exten2));
5728 /* Parse out extension and callerid */
5729 stringp=exten2 +1;
5730 s1 = strsep(&stringp, "#");
5731 s2 = strsep(&stringp, "#");
5732 if (s2 && (*(s2 + 1) == '0')) {
5733 if (*(s2 + 2))
5734 ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
5736 if (s1) ast_copy_string(exten, s1, sizeof(exten));
5737 else ast_copy_string(exten, "911", sizeof(exten));
5738 } else
5739 ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d. Assuming E&M Wink instead\n", p->channel);
5741 if (p->sig == SIG_FEATB) {
5742 if (exten[0] == '*') {
5743 char *stringp=NULL;
5744 ast_copy_string(exten2, exten, sizeof(exten2));
5745 /* Parse out extension and callerid */
5746 stringp=exten2 +1;
5747 s1 = strsep(&stringp, "#");
5748 ast_copy_string(exten, exten2 + 1, sizeof(exten));
5749 } else
5750 ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d. Assuming E&M Wink instead\n", p->channel);
5752 if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
5753 zt_wink(p, index);
5754 /* some switches require a minimum guard time between
5755 the last FGD wink and something that answers
5756 immediately. This ensures it */
5757 if (ast_safe_sleep(chan,100)) return NULL;
5759 zt_enable_ec(p);
5760 if (NEED_MFDETECT(p)) {
5761 if (p->dsp) {
5762 if (!p->hardwaredtmf)
5763 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
5764 else {
5765 ast_dsp_free(p->dsp);
5766 p->dsp = NULL;
5771 if (ast_exists_extension(chan, chan->context, exten, 1, chan->cid.cid_num)) {
5772 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5773 if (p->dsp) ast_dsp_digitreset(p->dsp);
5774 res = ast_pbx_run(chan);
5775 if (res) {
5776 ast_log(LOG_WARNING, "PBX exited non-zero\n");
5777 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5779 return NULL;
5780 } else {
5781 if (option_verbose > 2)
5782 ast_verbose(VERBOSE_PREFIX_2 "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
5783 sleep(2);
5784 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_INFO);
5785 if (res < 0)
5786 ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
5787 else
5788 sleep(1);
5789 res = ast_streamfile(chan, "ss-noservice", chan->language);
5790 if (res >= 0)
5791 ast_waitstream(chan, "");
5792 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5793 ast_hangup(chan);
5794 return NULL;
5796 break;
5797 case SIG_FXOLS:
5798 case SIG_FXOGS:
5799 case SIG_FXOKS:
5800 /* Read the first digit */
5801 timeout = firstdigittimeout;
5802 /* If starting a threeway call, never timeout on the first digit so someone
5803 can use flash-hook as a "hold" feature */
5804 if (p->subs[SUB_THREEWAY].owner)
5805 timeout = 999999;
5806 while (len < AST_MAX_EXTENSION-1) {
5807 /* Read digit unless it's supposed to be immediate, in which case the
5808 only answer is 's' */
5809 if (p->immediate)
5810 res = 's';
5811 else
5812 res = ast_waitfordigit(chan, timeout);
5813 timeout = 0;
5814 if (res < 0) {
5815 ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
5816 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5817 ast_hangup(chan);
5818 return NULL;
5819 } else if (res) {
5820 exten[len++]=res;
5821 exten[len] = '\0';
5823 if (!ast_ignore_pattern(chan->context, exten))
5824 tone_zone_play_tone(p->subs[index].zfd, -1);
5825 else
5826 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5827 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && strcmp(exten, ast_parking_ext())) {
5828 if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
5829 if (getforward) {
5830 /* Record this as the forwarding extension */
5831 ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
5832 if (option_verbose > 2)
5833 ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
5834 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5835 if (res)
5836 break;
5837 usleep(500000);
5838 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5839 sleep(1);
5840 memset(exten, 0, sizeof(exten));
5841 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
5842 len = 0;
5843 getforward = 0;
5844 } else {
5845 res = tone_zone_play_tone(p->subs[index].zfd, -1);
5846 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
5847 if (!ast_strlen_zero(p->cid_num)) {
5848 if (!p->hidecallerid)
5849 ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
5850 else
5851 ast_set_callerid(chan, NULL, NULL, p->cid_num);
5853 if (!ast_strlen_zero(p->cid_name)) {
5854 if (!p->hidecallerid)
5855 ast_set_callerid(chan, NULL, p->cid_name, NULL);
5857 ast_setstate(chan, AST_STATE_RING);
5858 zt_enable_ec(p);
5859 res = ast_pbx_run(chan);
5860 if (res) {
5861 ast_log(LOG_WARNING, "PBX exited non-zero\n");
5862 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5864 return NULL;
5866 } else {
5867 /* It's a match, but they just typed a digit, and there is an ambiguous match,
5868 so just set the timeout to matchdigittimeout and wait some more */
5869 timeout = matchdigittimeout;
5871 } else if (res == 0) {
5872 ast_log(LOG_DEBUG, "not enough digits (and no ambiguous match)...\n");
5873 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5874 zt_wait_event(p->subs[index].zfd);
5875 ast_hangup(chan);
5876 return NULL;
5877 } else if (p->callwaiting && !strcmp(exten, "*70")) {
5878 if (option_verbose > 2)
5879 ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
5880 /* Disable call waiting if enabled */
5881 p->callwaiting = 0;
5882 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5883 if (res) {
5884 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
5885 chan->name, strerror(errno));
5887 len = 0;
5888 ioctl(p->subs[index].zfd,ZT_CONFDIAG,&len);
5889 memset(exten, 0, sizeof(exten));
5890 timeout = firstdigittimeout;
5892 } else if (!strcmp(exten,ast_pickup_ext())) {
5893 /* Scan all channels and see if there are any
5894 * ringing channels that have call groups
5895 * that equal this channels pickup group
5897 if (index == SUB_REAL) {
5898 /* Switch us from Third call to Call Wait */
5899 if (p->subs[SUB_THREEWAY].owner) {
5900 /* If you make a threeway call and the *8# a call, it should actually
5901 look like a callwait */
5902 alloc_sub(p, SUB_CALLWAIT);
5903 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
5904 unalloc_sub(p, SUB_THREEWAY);
5906 zt_enable_ec(p);
5907 if (ast_pickup_call(chan)) {
5908 ast_log(LOG_DEBUG, "No call pickup possible...\n");
5909 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
5910 zt_wait_event(p->subs[index].zfd);
5912 ast_hangup(chan);
5913 return NULL;
5914 } else {
5915 ast_log(LOG_WARNING, "Huh? Got *8# on call not on real\n");
5916 ast_hangup(chan);
5917 return NULL;
5920 } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
5921 if (option_verbose > 2)
5922 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
5923 /* Disable Caller*ID if enabled */
5924 p->hidecallerid = 1;
5925 if (chan->cid.cid_num)
5926 free(chan->cid.cid_num);
5927 chan->cid.cid_num = NULL;
5928 if (chan->cid.cid_name)
5929 free(chan->cid.cid_name);
5930 chan->cid.cid_name = NULL;
5931 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5932 if (res) {
5933 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
5934 chan->name, strerror(errno));
5936 len = 0;
5937 memset(exten, 0, sizeof(exten));
5938 timeout = firstdigittimeout;
5939 } else if (p->callreturn && !strcmp(exten, "*69")) {
5940 res = 0;
5941 if (!ast_strlen_zero(p->lastcid_num)) {
5942 res = ast_say_digit_str(chan, p->lastcid_num, "", chan->language);
5944 if (!res)
5945 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5946 break;
5947 } else if (!strcmp(exten, "*78")) {
5948 /* Do not disturb */
5949 if (option_verbose > 2)
5950 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %d\n", p->channel);
5951 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
5952 "Channel: Zap/%d\r\n"
5953 "Status: enabled\r\n", p->channel);
5954 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5955 p->dnd = 1;
5956 getforward = 0;
5957 memset(exten, 0, sizeof(exten));
5958 len = 0;
5959 } else if (!strcmp(exten, "*79")) {
5960 /* Do not disturb */
5961 if (option_verbose > 2)
5962 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %d\n", p->channel);
5963 manager_event(EVENT_FLAG_SYSTEM, "DNDState",
5964 "Channel: Zap/%d\r\n"
5965 "Status: disabled\r\n", p->channel);
5966 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5967 p->dnd = 0;
5968 getforward = 0;
5969 memset(exten, 0, sizeof(exten));
5970 len = 0;
5971 } else if (p->cancallforward && !strcmp(exten, "*72")) {
5972 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5973 getforward = 1;
5974 memset(exten, 0, sizeof(exten));
5975 len = 0;
5976 } else if (p->cancallforward && !strcmp(exten, "*73")) {
5977 if (option_verbose > 2)
5978 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %d\n", p->channel);
5979 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5980 memset(p->call_forward, 0, sizeof(p->call_forward));
5981 getforward = 0;
5982 memset(exten, 0, sizeof(exten));
5983 len = 0;
5984 } else if ((p->transfer || p->canpark) && !strcmp(exten, ast_parking_ext()) &&
5985 p->subs[SUB_THREEWAY].owner &&
5986 ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
5987 /* This is a three way call, the main call being a real channel,
5988 and we're parking the first call. */
5989 ast_masq_park_call(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), chan, 0, NULL);
5990 if (option_verbose > 2)
5991 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
5992 break;
5993 } else if (!ast_strlen_zero(p->lastcid_num) && !strcmp(exten, "*60")) {
5994 if (option_verbose > 2)
5995 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", p->lastcid_num);
5996 res = ast_db_put("blacklist", p->lastcid_num, "1");
5997 if (!res) {
5998 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
5999 memset(exten, 0, sizeof(exten));
6000 len = 0;
6002 } else if (p->hidecallerid && !strcmp(exten, "*82")) {
6003 if (option_verbose > 2)
6004 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
6005 /* Enable Caller*ID if enabled */
6006 p->hidecallerid = 0;
6007 if (chan->cid.cid_num)
6008 free(chan->cid.cid_num);
6009 chan->cid.cid_num = NULL;
6010 if (chan->cid.cid_name)
6011 free(chan->cid.cid_name);
6012 chan->cid.cid_name = NULL;
6013 ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
6014 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
6015 if (res) {
6016 ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
6017 chan->name, strerror(errno));
6019 len = 0;
6020 memset(exten, 0, sizeof(exten));
6021 timeout = firstdigittimeout;
6022 } else if (!strcmp(exten, "*0")) {
6023 struct ast_channel *nbridge =
6024 p->subs[SUB_THREEWAY].owner;
6025 struct zt_pvt *pbridge = NULL;
6026 /* set up the private struct of the bridged one, if any */
6027 if (nbridge && ast_bridged_channel(nbridge))
6028 pbridge = ast_bridged_channel(nbridge)->tech_pvt;
6029 if (nbridge && pbridge &&
6030 (nbridge->tech == &zap_tech) &&
6031 (ast_bridged_channel(nbridge)->tech == &zap_tech) &&
6032 ISTRUNK(pbridge)) {
6033 int func = ZT_FLASH;
6034 /* Clear out the dial buffer */
6035 p->dop.dialstr[0] = '\0';
6036 /* flash hookswitch */
6037 if ((ioctl(pbridge->subs[SUB_REAL].zfd,ZT_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
6038 ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
6039 nbridge->name, strerror(errno));
6041 swap_subs(p, SUB_REAL, SUB_THREEWAY);
6042 unalloc_sub(p, SUB_THREEWAY);
6043 p->owner = p->subs[SUB_REAL].owner;
6044 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
6045 ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
6046 ast_hangup(chan);
6047 return NULL;
6048 } else {
6049 tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
6050 zt_wait_event(p->subs[index].zfd);
6051 tone_zone_play_tone(p->subs[index].zfd, -1);
6052 swap_subs(p, SUB_REAL, SUB_THREEWAY);
6053 unalloc_sub(p, SUB_THREEWAY);
6054 p->owner = p->subs[SUB_REAL].owner;
6055 ast_hangup(chan);
6056 return NULL;
6058 } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
6059 ((exten[0] != '*') || (strlen(exten) > 2))) {
6060 if (option_debug)
6061 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);
6062 break;
6064 if (!timeout)
6065 timeout = gendigittimeout;
6066 if (len && !ast_ignore_pattern(chan->context, exten))
6067 tone_zone_play_tone(p->subs[index].zfd, -1);
6069 break;
6070 case SIG_FXSLS:
6071 case SIG_FXSGS:
6072 case SIG_FXSKS:
6073 #ifdef HAVE_PRI
6074 if (p->pri) {
6075 /* This is a GR-303 trunk actually. Wait for the first ring... */
6076 struct ast_frame *f;
6077 int res;
6078 time_t start;
6080 time(&start);
6081 ast_setstate(chan, AST_STATE_RING);
6082 while (time(NULL) < start + 3) {
6083 res = ast_waitfor(chan, 1000);
6084 if (res) {
6085 f = ast_read(chan);
6086 if (!f) {
6087 ast_log(LOG_WARNING, "Whoa, hangup while waiting for first ring!\n");
6088 ast_hangup(chan);
6089 return NULL;
6090 } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_RING)) {
6091 res = 1;
6092 } else
6093 res = 0;
6094 ast_frfree(f);
6095 if (res) {
6096 ast_log(LOG_DEBUG, "Got ring!\n");
6097 res = 0;
6098 break;
6103 #endif
6104 /* check for SMDI messages */
6105 if (p->use_smdi && p->smdi_iface) {
6106 smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, SMDI_MD_WAIT_TIMEOUT);
6108 if (smdi_msg != NULL) {
6109 ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
6111 if (smdi_msg->type == 'B')
6112 pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
6113 else if (smdi_msg->type == 'N')
6114 pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
6116 ast_log(LOG_DEBUG, "Recieved SMDI message on %s\n", chan->name);
6117 } else {
6118 ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
6122 if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
6123 number = smdi_msg->calling_st;
6125 /* If we want caller id, we're in a prering state due to a polarity reversal
6126 * and we're set to use a polarity reversal to trigger the start of caller id,
6127 * grab the caller id and wait for ringing to start... */
6128 } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING && p->cid_start == CID_START_POLARITY)) {
6129 /* If set to use DTMF CID signalling, listen for DTMF */
6130 if (p->cid_signalling == CID_SIG_DTMF) {
6131 int i = 0;
6132 cs = NULL;
6133 ast_log(LOG_DEBUG, "Receiving DTMF cid on "
6134 "channel %s\n", chan->name);
6135 zt_setlinear(p->subs[index].zfd, 0);
6136 res = 2000;
6137 for (;;) {
6138 struct ast_frame *f;
6139 res = ast_waitfor(chan, res);
6140 if (res <= 0) {
6141 ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
6142 "Exiting simple switch\n");
6143 ast_hangup(chan);
6144 return NULL;
6146 f = ast_read(chan);
6147 if (!f)
6148 break;
6149 if (f->frametype == AST_FRAME_DTMF) {
6150 dtmfbuf[i++] = f->subclass;
6151 ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass);
6152 res = 2000;
6154 ast_frfree(f);
6155 if (chan->_state == AST_STATE_RING ||
6156 chan->_state == AST_STATE_RINGING)
6157 break; /* Got ring */
6159 dtmfbuf[i] = '\0';
6160 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6161 /* Got cid and ring. */
6162 ast_log(LOG_DEBUG, "CID got string '%s'\n", dtmfbuf);
6163 callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
6164 ast_log(LOG_DEBUG, "CID is '%s', flags %d\n",
6165 dtmfcid, flags);
6166 /* If first byte is NULL, we have no cid */
6167 if (!ast_strlen_zero(dtmfcid))
6168 number = dtmfcid;
6169 else
6170 number = NULL;
6171 /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
6172 } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
6173 cs = callerid_new(p->cid_signalling);
6174 if (cs) {
6175 samples = 0;
6176 #if 1
6177 bump_gains(p);
6178 #endif
6179 /* Take out of linear mode for Caller*ID processing */
6180 zt_setlinear(p->subs[index].zfd, 0);
6182 /* First we wait and listen for the Caller*ID */
6183 for (;;) {
6184 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6185 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6186 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6187 callerid_free(cs);
6188 ast_hangup(chan);
6189 return NULL;
6191 if (i & ZT_IOMUX_SIGEVENT) {
6192 res = zt_get_event(p->subs[index].zfd);
6193 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6195 if (p->cid_signalling == CID_SIG_V23_JP) {
6196 #ifdef ZT_EVENT_RINGBEGIN
6197 if (res == ZT_EVENT_RINGBEGIN) {
6198 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6199 usleep(1);
6201 #endif
6202 } else {
6203 res = 0;
6204 break;
6206 } else if (i & ZT_IOMUX_READ) {
6207 res = read(p->subs[index].zfd, buf, sizeof(buf));
6208 if (res < 0) {
6209 if (errno != ELAST) {
6210 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6211 callerid_free(cs);
6212 ast_hangup(chan);
6213 return NULL;
6215 break;
6217 samples += res;
6219 if (p->cid_signalling == CID_SIG_V23_JP) {
6220 res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
6221 } else {
6222 res = callerid_feed(cs, buf, res, AST_LAW(p));
6225 if (res < 0) {
6226 ast_log(LOG_WARNING, "CallerID feed failed on channel '%s'\n", chan->name);
6227 break;
6228 } else if (res)
6229 break;
6230 else if (samples > (8000 * 10))
6231 break;
6234 if (res == 1) {
6235 callerid_get(cs, &name, &number, &flags);
6236 ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
6239 if (p->cid_signalling == CID_SIG_V23_JP) {
6240 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
6241 usleep(1);
6242 res = 4000;
6243 } else {
6245 /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
6246 res = 2000;
6249 for (;;) {
6250 struct ast_frame *f;
6251 res = ast_waitfor(chan, res);
6252 if (res <= 0) {
6253 ast_log(LOG_WARNING, "CID timed out waiting for ring. "
6254 "Exiting simple switch\n");
6255 ast_hangup(chan);
6256 return NULL;
6258 f = ast_read(chan);
6259 ast_frfree(f);
6260 if (chan->_state == AST_STATE_RING ||
6261 chan->_state == AST_STATE_RINGING)
6262 break; /* Got ring */
6265 /* We must have a ring by now, so, if configured, lets try to listen for
6266 * distinctive ringing */
6267 if (p->usedistinctiveringdetection == 1) {
6268 len = 0;
6269 distMatches = 0;
6270 /* Clear the current ring data array so we dont have old data in it. */
6271 for (receivedRingT = 0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
6272 curRingData[receivedRingT] = 0;
6273 receivedRingT = 0;
6274 counter = 0;
6275 counter1 = 0;
6276 /* Check to see if context is what it should be, if not set to be. */
6277 if (strcmp(p->context,p->defcontext) != 0) {
6278 ast_copy_string(p->context, p->defcontext, sizeof(p->context));
6279 ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
6282 for (;;) {
6283 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6284 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6285 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6286 callerid_free(cs);
6287 ast_hangup(chan);
6288 return NULL;
6290 if (i & ZT_IOMUX_SIGEVENT) {
6291 res = zt_get_event(p->subs[index].zfd);
6292 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6293 res = 0;
6294 /* Let us detect distinctive ring */
6296 curRingData[receivedRingT] = p->ringt;
6298 if (p->ringt < p->ringt_base/2)
6299 break;
6300 /* Increment the ringT counter so we can match it against
6301 values in zapata.conf for distinctive ring */
6302 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6303 break;
6304 } else if (i & ZT_IOMUX_READ) {
6305 res = read(p->subs[index].zfd, buf, sizeof(buf));
6306 if (res < 0) {
6307 if (errno != ELAST) {
6308 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6309 callerid_free(cs);
6310 ast_hangup(chan);
6311 return NULL;
6313 break;
6315 if (p->ringt)
6316 p->ringt--;
6317 if (p->ringt == 1) {
6318 res = -1;
6319 break;
6323 if (option_verbose > 2)
6324 /* this only shows up if you have n of the dring patterns filled in */
6325 ast_verbose( VERBOSE_PREFIX_3 "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
6327 for (counter = 0; counter < 3; counter++) {
6328 /* Check to see if the rings we received match any of the ones in zapata.conf for this
6329 channel */
6330 distMatches = 0;
6331 for (counter1 = 0; counter1 < 3; counter1++) {
6332 if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1]+10) && curRingData[counter1] >=
6333 (p->drings.ringnum[counter].ring[counter1]-10)) {
6334 distMatches++;
6337 if (distMatches == 3) {
6338 /* The ring matches, set the context to whatever is for distinctive ring.. */
6339 ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
6340 ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
6341 if (option_verbose > 2)
6342 ast_verbose( VERBOSE_PREFIX_3 "Distinctive Ring matched context %s\n",p->context);
6343 break;
6347 /* Restore linear mode (if appropriate) for Caller*ID processing */
6348 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6349 #if 1
6350 restore_gains(p);
6351 #endif
6352 } else
6353 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
6354 } else {
6355 ast_log(LOG_WARNING, "Channel %s in prering "
6356 "state, but I have nothing to do. "
6357 "Terminating simple switch, should be "
6358 "restarted by the actual ring.\n",
6359 chan->name);
6360 ast_hangup(chan);
6361 return NULL;
6363 } else if (p->use_callerid && p->cid_start == CID_START_RING) {
6364 /* FSK Bell202 callerID */
6365 cs = callerid_new(p->cid_signalling);
6366 if (cs) {
6367 #if 1
6368 bump_gains(p);
6369 #endif
6370 samples = 0;
6371 len = 0;
6372 distMatches = 0;
6373 /* Clear the current ring data array so we dont have old data in it. */
6374 for (receivedRingT = 0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
6375 curRingData[receivedRingT] = 0;
6376 receivedRingT = 0;
6377 counter = 0;
6378 counter1 = 0;
6379 /* Check to see if context is what it should be, if not set to be. */
6380 if (strcmp(p->context,p->defcontext) != 0) {
6381 ast_copy_string(p->context, p->defcontext, sizeof(p->context));
6382 ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
6385 /* Take out of linear mode for Caller*ID processing */
6386 zt_setlinear(p->subs[index].zfd, 0);
6387 for (;;) {
6388 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6389 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6390 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6391 callerid_free(cs);
6392 ast_hangup(chan);
6393 return NULL;
6395 if (i & ZT_IOMUX_SIGEVENT) {
6396 res = zt_get_event(p->subs[index].zfd);
6397 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6398 /* If we get a PR event, they hung up while processing calerid */
6399 if ( res == ZT_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
6400 ast_log(LOG_DEBUG, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
6401 p->polarity = POLARITY_IDLE;
6402 callerid_free(cs);
6403 ast_hangup(chan);
6404 return NULL;
6406 res = 0;
6407 /* Let us detect callerid when the telco uses distinctive ring */
6409 curRingData[receivedRingT] = p->ringt;
6411 if (p->ringt < p->ringt_base/2)
6412 break;
6413 /* Increment the ringT counter so we can match it against
6414 values in zapata.conf for distinctive ring */
6415 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6416 break;
6417 } else if (i & ZT_IOMUX_READ) {
6418 res = read(p->subs[index].zfd, buf, sizeof(buf));
6419 if (res < 0) {
6420 if (errno != ELAST) {
6421 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6422 callerid_free(cs);
6423 ast_hangup(chan);
6424 return NULL;
6426 break;
6428 if (p->ringt)
6429 p->ringt--;
6430 if (p->ringt == 1) {
6431 res = -1;
6432 break;
6434 samples += res;
6435 res = callerid_feed(cs, buf, res, AST_LAW(p));
6436 if (res < 0) {
6437 ast_log(LOG_WARNING, "CallerID feed failed: %s\n", strerror(errno));
6438 break;
6439 } else if (res)
6440 break;
6441 else if (samples > (8000 * 10))
6442 break;
6445 if (res == 1) {
6446 callerid_get(cs, &name, &number, &flags);
6447 if (option_debug)
6448 ast_log(LOG_DEBUG, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
6450 if (distinctiveringaftercid == 1) {
6451 /* Clear the current ring data array so we dont have old data in it. */
6452 for (receivedRingT = 0; receivedRingT < 3; receivedRingT++) {
6453 curRingData[receivedRingT] = 0;
6455 receivedRingT = 0;
6456 if (option_verbose > 2)
6457 ast_verbose( VERBOSE_PREFIX_3 "Detecting post-CID distinctive ring\n");
6458 for (;;) {
6459 i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
6460 if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i))) {
6461 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
6462 callerid_free(cs);
6463 ast_hangup(chan);
6464 return NULL;
6466 if (i & ZT_IOMUX_SIGEVENT) {
6467 res = zt_get_event(p->subs[index].zfd);
6468 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
6469 res = 0;
6470 /* Let us detect callerid when the telco uses distinctive ring */
6472 curRingData[receivedRingT] = p->ringt;
6474 if (p->ringt < p->ringt_base/2)
6475 break;
6476 /* Increment the ringT counter so we can match it against
6477 values in zapata.conf for distinctive ring */
6478 if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
6479 break;
6480 } else if (i & ZT_IOMUX_READ) {
6481 res = read(p->subs[index].zfd, buf, sizeof(buf));
6482 if (res < 0) {
6483 if (errno != ELAST) {
6484 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
6485 callerid_free(cs);
6486 ast_hangup(chan);
6487 return NULL;
6489 break;
6491 if (p->ringt)
6492 p->ringt--;
6493 if (p->ringt == 1) {
6494 res = -1;
6495 break;
6500 if (p->usedistinctiveringdetection == 1) {
6501 if (option_verbose > 2)
6502 /* this only shows up if you have n of the dring patterns filled in */
6503 ast_verbose( VERBOSE_PREFIX_3 "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
6505 for (counter = 0; counter < 3; counter++) {
6506 /* Check to see if the rings we received match any of the ones in zapata.conf for this
6507 channel */
6508 if (option_verbose > 2)
6509 /* this only shows up if you have n of the dring patterns filled in */
6510 ast_verbose( VERBOSE_PREFIX_3 "Checking %d,%d,%d\n",
6511 p->drings.ringnum[counter].ring[0],
6512 p->drings.ringnum[counter].ring[1],
6513 p->drings.ringnum[counter].ring[2]);
6514 distMatches = 0;
6515 for (counter1 = 0; counter1 < 3; counter1++) {
6516 if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1]+10) && curRingData[counter1] >=
6517 (p->drings.ringnum[counter].ring[counter1]-10)) {
6518 distMatches++;
6521 if (distMatches == 3) {
6522 /* The ring matches, set the context to whatever is for distinctive ring.. */
6523 ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
6524 ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
6525 if (option_verbose > 2)
6526 ast_verbose( VERBOSE_PREFIX_3 "Distinctive Ring matched context %s\n",p->context);
6527 break;
6531 /* Restore linear mode (if appropriate) for Caller*ID processing */
6532 zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
6533 #if 1
6534 restore_gains(p);
6535 #endif
6536 if (res < 0) {
6537 ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
6539 } else
6540 ast_log(LOG_WARNING, "Unable to get caller ID space\n");
6542 else
6543 cs = NULL;
6545 if (number)
6546 ast_shrink_phone_number(number);
6547 ast_set_callerid(chan, number, name, number);
6549 if (smdi_msg)
6550 ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
6552 if (cs)
6553 callerid_free(cs);
6555 ast_setstate(chan, AST_STATE_RING);
6556 chan->rings = 1;
6557 p->ringt = p->ringt_base;
6558 res = ast_pbx_run(chan);
6559 if (res) {
6560 ast_hangup(chan);
6561 ast_log(LOG_WARNING, "PBX exited non-zero\n");
6563 return NULL;
6564 default:
6565 ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", sig2str(p->sig), p->channel);
6566 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
6567 if (res < 0)
6568 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
6570 res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
6571 if (res < 0)
6572 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
6573 ast_hangup(chan);
6574 return NULL;
6577 /* destroy a zaptel channel, identified by its number */
6578 static int zap_destroy_channel_bynum(int channel)
6580 struct zt_pvt *tmp = NULL;
6581 struct zt_pvt *prev = NULL;
6583 tmp = iflist;
6584 while (tmp) {
6585 if (tmp->channel == channel) {
6586 destroy_channel(prev, tmp, 1);
6587 return RESULT_SUCCESS;
6589 prev = tmp;
6590 tmp = tmp->next;
6592 return RESULT_FAILURE;
6595 static int handle_init_event(struct zt_pvt *i, int event)
6597 int res;
6598 pthread_t threadid;
6599 pthread_attr_t attr;
6600 struct ast_channel *chan;
6601 pthread_attr_init(&attr);
6602 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6603 /* Handle an event on a given channel for the monitor thread. */
6604 switch (event) {
6605 case ZT_EVENT_NONE:
6606 case ZT_EVENT_BITSCHANGED:
6607 break;
6608 case ZT_EVENT_WINKFLASH:
6609 case ZT_EVENT_RINGOFFHOOK:
6610 if (i->inalarm) break;
6611 if (i->radio) break;
6612 /* Got a ring/answer. What kind of channel are we? */
6613 switch (i->sig) {
6614 case SIG_FXOLS:
6615 case SIG_FXOGS:
6616 case SIG_FXOKS:
6617 res = zt_set_hook(i->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6618 if (res && (errno == EBUSY))
6619 break;
6620 if (i->cidspill) {
6621 /* Cancel VMWI spill */
6622 free(i->cidspill);
6623 i->cidspill = NULL;
6625 if (i->immediate) {
6626 zt_enable_ec(i);
6627 /* The channel is immediately up. Start right away */
6628 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
6629 chan = zt_new(i, AST_STATE_RING, 1, SUB_REAL, 0, 0);
6630 if (!chan) {
6631 ast_log(LOG_WARNING, "Unable to start PBX on channel %d\n", i->channel);
6632 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6633 if (res < 0)
6634 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6636 } else {
6637 /* Check for callerid, digits, etc */
6638 chan = zt_new(i, AST_STATE_RESERVED, 0, SUB_REAL, 0, 0);
6639 if (chan) {
6640 if (has_voicemail(i))
6641 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_STUTTER);
6642 else
6643 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_DIALTONE);
6644 if (res < 0)
6645 ast_log(LOG_WARNING, "Unable to play dialtone on channel %d, do you have defaultzone and loadzone defined?\n", i->channel);
6646 if (ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6647 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6648 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6649 if (res < 0)
6650 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6651 ast_hangup(chan);
6653 } else
6654 ast_log(LOG_WARNING, "Unable to create channel\n");
6656 break;
6657 case SIG_FXSLS:
6658 case SIG_FXSGS:
6659 case SIG_FXSKS:
6660 i->ringt = i->ringt_base;
6661 /* Fall through */
6662 case SIG_EMWINK:
6663 case SIG_FEATD:
6664 case SIG_FEATDMF:
6665 case SIG_FEATDMF_TA:
6666 case SIG_E911:
6667 case SIG_FGC_CAMA:
6668 case SIG_FGC_CAMAMF:
6669 case SIG_FEATB:
6670 case SIG_EM:
6671 case SIG_EM_E1:
6672 case SIG_SFWINK:
6673 case SIG_SF_FEATD:
6674 case SIG_SF_FEATDMF:
6675 case SIG_SF_FEATB:
6676 case SIG_SF:
6677 /* Check for callerid, digits, etc */
6678 chan = zt_new(i, AST_STATE_RING, 0, SUB_REAL, 0, 0);
6679 if (chan && ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6680 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6681 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6682 if (res < 0)
6683 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6684 ast_hangup(chan);
6685 } else if (!chan) {
6686 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
6688 break;
6689 default:
6690 ast_log(LOG_WARNING, "Don't know how to handle ring/answer with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
6691 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
6692 if (res < 0)
6693 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
6694 return -1;
6696 break;
6697 case ZT_EVENT_NOALARM:
6698 i->inalarm = 0;
6699 if (!i->unknown_alarm) {
6700 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", i->channel);
6701 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
6702 "Channel: %d\r\n", i->channel);
6703 } else {
6704 i->unknown_alarm = 0;
6706 break;
6707 case ZT_EVENT_ALARM:
6708 i->inalarm = 1;
6709 res = get_alarms(i);
6710 do {
6711 const char *alarm_str = alarm2str(res);
6713 /* hack alert! Zaptel 1.4 now exposes FXO battery as an alarm, but asterisk 1.4
6714 * doesn't know what to do with it. Don't confuse users with log messages. */
6715 if (!strcasecmp(alarm_str, "No Alarm") || !strcasecmp(alarm_str, "Unknown Alarm")) {
6716 i->unknown_alarm = 1;
6717 break;
6718 } else {
6719 i->unknown_alarm = 0;
6722 ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", i->channel, alarm_str);
6723 manager_event(EVENT_FLAG_SYSTEM, "Alarm",
6724 "Alarm: %s\r\n"
6725 "Channel: %d\r\n",
6726 alarm_str, i->channel);
6727 } while (0);
6728 /* fall thru intentionally */
6729 case ZT_EVENT_ONHOOK:
6730 if (i->radio)
6731 break;
6732 /* Back on hook. Hang up. */
6733 switch (i->sig) {
6734 case SIG_FXOLS:
6735 case SIG_FXOGS:
6736 case SIG_FEATD:
6737 case SIG_FEATDMF:
6738 case SIG_FEATDMF_TA:
6739 case SIG_E911:
6740 case SIG_FGC_CAMA:
6741 case SIG_FGC_CAMAMF:
6742 case SIG_FEATB:
6743 case SIG_EM:
6744 case SIG_EM_E1:
6745 case SIG_EMWINK:
6746 case SIG_SF_FEATD:
6747 case SIG_SF_FEATDMF:
6748 case SIG_SF_FEATB:
6749 case SIG_SF:
6750 case SIG_SFWINK:
6751 case SIG_FXSLS:
6752 case SIG_FXSGS:
6753 case SIG_FXSKS:
6754 case SIG_GR303FXSKS:
6755 zt_disable_ec(i);
6756 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6757 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_ONHOOK);
6758 break;
6759 case SIG_GR303FXOKS:
6760 case SIG_FXOKS:
6761 zt_disable_ec(i);
6762 /* Diddle the battery for the zhone */
6763 #ifdef ZHONE_HACK
6764 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_OFFHOOK);
6765 usleep(1);
6766 #endif
6767 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6768 zt_set_hook(i->subs[SUB_REAL].zfd, ZT_ONHOOK);
6769 break;
6770 case SIG_PRI:
6771 zt_disable_ec(i);
6772 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6773 break;
6774 default:
6775 ast_log(LOG_WARNING, "Don't know how to handle on hook with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
6776 res = tone_zone_play_tone(i->subs[SUB_REAL].zfd, -1);
6777 return -1;
6779 break;
6780 case ZT_EVENT_POLARITY:
6781 switch (i->sig) {
6782 case SIG_FXSLS:
6783 case SIG_FXSKS:
6784 case SIG_FXSGS:
6785 /* We have already got a PR before the channel was
6786 created, but it wasn't handled. We need polarity
6787 to be REV for remote hangup detection to work.
6788 At least in Spain */
6789 if (i->hanguponpolarityswitch)
6790 i->polarity = POLARITY_REV;
6792 if (i->cid_start == CID_START_POLARITY) {
6793 i->polarity = POLARITY_REV;
6794 ast_verbose(VERBOSE_PREFIX_2 "Starting post polarity "
6795 "CID detection on channel %d\n",
6796 i->channel);
6797 chan = zt_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, 0);
6798 if (chan && ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
6799 ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
6802 break;
6803 default:
6804 ast_log(LOG_WARNING, "handle_init_event detected "
6805 "polarity reversal on non-FXO (SIG_FXS) "
6806 "interface %d\n", i->channel);
6808 break;
6809 case ZT_EVENT_REMOVED: /* destroy channel */
6810 ast_log(LOG_NOTICE,
6811 "Got ZT_EVENT_REMOVED. Destroying channel %d\n",
6812 i->channel);
6813 zap_destroy_channel_bynum(i->channel);
6814 break;
6816 pthread_attr_destroy(&attr);
6817 return 0;
6820 static void *do_monitor(void *data)
6822 int count, res, res2, spoint, pollres=0;
6823 struct zt_pvt *i;
6824 struct zt_pvt *last = NULL;
6825 time_t thispass = 0, lastpass = 0;
6826 int found;
6827 char buf[1024];
6828 struct pollfd *pfds=NULL;
6829 int lastalloc = -1;
6830 /* This thread monitors all the frame relay interfaces which are not yet in use
6831 (and thus do not have a separate thread) indefinitely */
6832 /* From here on out, we die whenever asked */
6833 #if 0
6834 if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
6835 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
6836 return NULL;
6838 ast_log(LOG_DEBUG, "Monitor starting...\n");
6839 #endif
6840 for (;;) {
6841 /* Lock the interface list */
6842 ast_mutex_lock(&iflock);
6843 if (!pfds || (lastalloc != ifcount)) {
6844 if (pfds) {
6845 free(pfds);
6846 pfds = NULL;
6848 if (ifcount) {
6849 if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
6850 ast_mutex_unlock(&iflock);
6851 return NULL;
6854 lastalloc = ifcount;
6856 /* Build the stuff we're going to poll on, that is the socket of every
6857 zt_pvt that does not have an associated owner channel */
6858 count = 0;
6859 i = iflist;
6860 while (i) {
6861 if ((i->subs[SUB_REAL].zfd > -1) && i->sig && (!i->radio)) {
6862 if (!i->owner && !i->subs[SUB_REAL].owner) {
6863 /* This needs to be watched, as it lacks an owner */
6864 pfds[count].fd = i->subs[SUB_REAL].zfd;
6865 pfds[count].events = POLLPRI;
6866 pfds[count].revents = 0;
6867 /* Message waiting or r2 channels also get watched for reading */
6868 if (i->cidspill)
6869 pfds[count].events |= POLLIN;
6870 count++;
6873 i = i->next;
6875 /* Okay, now that we know what to do, release the interface lock */
6876 ast_mutex_unlock(&iflock);
6878 pthread_testcancel();
6879 /* Wait at least a second for something to happen */
6880 res = poll(pfds, count, 1000);
6881 pthread_testcancel();
6882 /* Okay, poll has finished. Let's see what happened. */
6883 if (res < 0) {
6884 if ((errno != EAGAIN) && (errno != EINTR))
6885 ast_log(LOG_WARNING, "poll return %d: %s\n", res, strerror(errno));
6886 continue;
6888 /* Alright, lock the interface list again, and let's look and see what has
6889 happened */
6890 ast_mutex_lock(&iflock);
6891 found = 0;
6892 spoint = 0;
6893 lastpass = thispass;
6894 thispass = time(NULL);
6895 i = iflist;
6896 while (i) {
6897 if (thispass != lastpass) {
6898 if (!found && ((i == last) || ((i == iflist) && !last))) {
6899 last = i;
6900 if (last) {
6901 if (!last->cidspill && !last->owner && !ast_strlen_zero(last->mailbox) && (thispass - last->onhooktime > 3) &&
6902 (last->sig & __ZT_SIG_FXO)) {
6903 res = ast_app_has_voicemail(last->mailbox, NULL);
6904 if (last->msgstate != res) {
6905 int x;
6906 ast_log(LOG_DEBUG, "Message status for %s changed from %d to %d on %d\n", last->mailbox, last->msgstate, res, last->channel);
6907 x = ZT_FLUSH_BOTH;
6908 res2 = ioctl(last->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
6909 if (res2)
6910 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", last->channel);
6911 if ((last->cidspill = ast_calloc(1, MAX_CALLERID_SIZE))) {
6912 /* Turn on on hook transfer for 4 seconds */
6913 x = 4000;
6914 ioctl(last->subs[SUB_REAL].zfd, ZT_ONHOOKTRANSFER, &x);
6915 last->cidlen = vmwi_generate(last->cidspill, res, 1, AST_LAW(last));
6916 last->cidpos = 0;
6917 last->msgstate = res;
6918 last->onhooktime = thispass;
6920 found ++;
6923 last = last->next;
6927 if ((i->subs[SUB_REAL].zfd > -1) && i->sig) {
6928 if (i->radio && !i->owner)
6930 res = zt_get_event(i->subs[SUB_REAL].zfd);
6931 if (res)
6933 if (option_debug)
6934 ast_log(LOG_DEBUG, "Monitor doohicky got event %s on radio channel %d\n", event2str(res), i->channel);
6935 /* Don't hold iflock while handling init events */
6936 ast_mutex_unlock(&iflock);
6937 handle_init_event(i, res);
6938 ast_mutex_lock(&iflock);
6940 i = i->next;
6941 continue;
6943 pollres = ast_fdisset(pfds, i->subs[SUB_REAL].zfd, count, &spoint);
6944 if (pollres & POLLIN) {
6945 if (i->owner || i->subs[SUB_REAL].owner) {
6946 #ifdef HAVE_PRI
6947 if (!i->pri)
6948 #endif
6949 ast_log(LOG_WARNING, "Whoa.... I'm owned but found (%d) in read...\n", i->subs[SUB_REAL].zfd);
6950 i = i->next;
6951 continue;
6953 if (!i->cidspill) {
6954 ast_log(LOG_WARNING, "Whoa.... I'm reading but have no cidspill (%d)...\n", i->subs[SUB_REAL].zfd);
6955 i = i->next;
6956 continue;
6958 res = read(i->subs[SUB_REAL].zfd, buf, sizeof(buf));
6959 if (res > 0) {
6960 /* We read some number of bytes. Write an equal amount of data */
6961 if (res > i->cidlen - i->cidpos)
6962 res = i->cidlen - i->cidpos;
6963 res2 = write(i->subs[SUB_REAL].zfd, i->cidspill + i->cidpos, res);
6964 if (res2 > 0) {
6965 i->cidpos += res2;
6966 if (i->cidpos >= i->cidlen) {
6967 free(i->cidspill);
6968 i->cidspill = 0;
6969 i->cidpos = 0;
6970 i->cidlen = 0;
6972 } else {
6973 ast_log(LOG_WARNING, "Write failed: %s\n", strerror(errno));
6974 i->msgstate = -1;
6976 } else {
6977 ast_log(LOG_WARNING, "Read failed with %d: %s\n", res, strerror(errno));
6980 if (pollres & POLLPRI) {
6981 if (i->owner || i->subs[SUB_REAL].owner) {
6982 #ifdef HAVE_PRI
6983 if (!i->pri)
6984 #endif
6985 ast_log(LOG_WARNING, "Whoa.... I'm owned but found (%d)...\n", i->subs[SUB_REAL].zfd);
6986 i = i->next;
6987 continue;
6989 res = zt_get_event(i->subs[SUB_REAL].zfd);
6990 if (option_debug)
6991 ast_log(LOG_DEBUG, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
6992 /* Don't hold iflock while handling init events */
6993 ast_mutex_unlock(&iflock);
6994 handle_init_event(i, res);
6995 ast_mutex_lock(&iflock);
6998 i=i->next;
7000 ast_mutex_unlock(&iflock);
7002 /* Never reached */
7003 return NULL;
7007 static int restart_monitor(void)
7009 pthread_attr_t attr;
7010 pthread_attr_init(&attr);
7011 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
7012 /* If we're supposed to be stopped -- stay stopped */
7013 if (monitor_thread == AST_PTHREADT_STOP)
7014 return 0;
7015 ast_mutex_lock(&monlock);
7016 if (monitor_thread == pthread_self()) {
7017 ast_mutex_unlock(&monlock);
7018 ast_log(LOG_WARNING, "Cannot kill myself\n");
7019 return -1;
7021 if (monitor_thread != AST_PTHREADT_NULL) {
7022 /* Wake up the thread */
7023 pthread_kill(monitor_thread, SIGURG);
7024 } else {
7025 /* Start a new monitor */
7026 if (ast_pthread_create_background(&monitor_thread, &attr, do_monitor, NULL) < 0) {
7027 ast_mutex_unlock(&monlock);
7028 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
7029 pthread_attr_destroy(&attr);
7030 return -1;
7033 ast_mutex_unlock(&monlock);
7034 pthread_attr_destroy(&attr);
7035 return 0;
7038 #ifdef HAVE_PRI
7039 static int pri_resolve_span(int *span, int channel, int offset, struct zt_spaninfo *si)
7041 int x;
7042 int trunkgroup;
7043 /* Get appropriate trunk group if there is one */
7044 trunkgroup = pris[*span].mastertrunkgroup;
7045 if (trunkgroup) {
7046 /* Select a specific trunk group */
7047 for (x = 0; x < NUM_SPANS; x++) {
7048 if (pris[x].trunkgroup == trunkgroup) {
7049 *span = x;
7050 return 0;
7053 ast_log(LOG_WARNING, "Channel %d on span %d configured to use nonexistent trunk group %d\n", channel, *span, trunkgroup);
7054 *span = -1;
7055 } else {
7056 if (pris[*span].trunkgroup) {
7057 ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is trunk group %d (please use spanmap)\n", *span, pris[*span].trunkgroup);
7058 *span = -1;
7059 } else if (pris[*span].mastertrunkgroup) {
7060 ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is already part of trunk group %d\n", *span, pris[*span].mastertrunkgroup);
7061 *span = -1;
7062 } else {
7063 if (si->totalchans == 31) { /* if it's an E1 */
7064 pris[*span].dchannels[0] = 16 + offset;
7065 } else {
7066 pris[*span].dchannels[0] = 24 + offset;
7068 pris[*span].dchanavail[0] |= DCHAN_PROVISIONED;
7069 pris[*span].offset = offset;
7070 pris[*span].span = *span + 1;
7073 return 0;
7076 static int pri_create_trunkgroup(int trunkgroup, int *channels)
7078 struct zt_spaninfo si;
7079 ZT_PARAMS p;
7080 int fd;
7081 int span;
7082 int ospan=0;
7083 int x,y;
7084 for (x = 0; x < NUM_SPANS; x++) {
7085 if (pris[x].trunkgroup == trunkgroup) {
7086 ast_log(LOG_WARNING, "Trunk group %d already exists on span %d, Primary d-channel %d\n", trunkgroup, x + 1, pris[x].dchannels[0]);
7087 return -1;
7090 for (y = 0; y < NUM_DCHANS; y++) {
7091 if (!channels[y])
7092 break;
7093 memset(&si, 0, sizeof(si));
7094 memset(&p, 0, sizeof(p));
7095 fd = open("/dev/zap/channel", O_RDWR);
7096 if (fd < 0) {
7097 ast_log(LOG_WARNING, "Failed to open channel: %s\n", strerror(errno));
7098 return -1;
7100 x = channels[y];
7101 if (ioctl(fd, ZT_SPECIFY, &x)) {
7102 ast_log(LOG_WARNING, "Failed to specify channel %d: %s\n", channels[y], strerror(errno));
7103 zt_close(fd);
7104 return -1;
7106 if (ioctl(fd, ZT_GET_PARAMS, &p)) {
7107 ast_log(LOG_WARNING, "Failed to get channel parameters for channel %d: %s\n", channels[y], strerror(errno));
7108 return -1;
7110 if (ioctl(fd, ZT_SPANSTAT, &si)) {
7111 ast_log(LOG_WARNING, "Failed go get span information on channel %d (span %d)\n", channels[y], p.spanno);
7112 zt_close(fd);
7113 return -1;
7115 span = p.spanno - 1;
7116 if (pris[span].trunkgroup) {
7117 ast_log(LOG_WARNING, "Span %d is already provisioned for trunk group %d\n", span + 1, pris[span].trunkgroup);
7118 zt_close(fd);
7119 return -1;
7121 if (pris[span].pvts[0]) {
7122 ast_log(LOG_WARNING, "Span %d is already provisioned with channels (implicit PRI maybe?)\n", span + 1);
7123 zt_close(fd);
7124 return -1;
7126 if (!y) {
7127 pris[span].trunkgroup = trunkgroup;
7128 pris[span].offset = channels[y] - p.chanpos;
7129 ospan = span;
7131 pris[ospan].dchannels[y] = channels[y];
7132 pris[ospan].dchanavail[y] |= DCHAN_PROVISIONED;
7133 pris[span].span = span + 1;
7134 zt_close(fd);
7136 return 0;
7139 static int pri_create_spanmap(int span, int trunkgroup, int logicalspan)
7141 if (pris[span].mastertrunkgroup) {
7142 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);
7143 return -1;
7145 pris[span].mastertrunkgroup = trunkgroup;
7146 pris[span].prilogicalspan = logicalspan;
7147 return 0;
7150 #endif
7152 static struct zt_pvt *mkintf(int channel, const struct zt_chan_conf *conf, struct zt_pri *pri, int reloading)
7154 /* Make a zt_pvt structure for this interface (or CRV if "pri" is specified) */
7155 struct zt_pvt *tmp = NULL, *tmp2, *prev = NULL;
7156 char fn[80];
7157 #if 1
7158 struct zt_bufferinfo bi;
7159 #endif
7160 struct zt_spaninfo si;
7161 int res;
7162 int span=0;
7163 int here = 0;
7164 int x;
7165 struct zt_pvt **wlist;
7166 struct zt_pvt **wend;
7167 ZT_PARAMS p;
7169 wlist = &iflist;
7170 wend = &ifend;
7172 #ifdef HAVE_PRI
7173 if (pri) {
7174 wlist = &pri->crvs;
7175 wend = &pri->crvend;
7177 #endif
7179 tmp2 = *wlist;
7180 prev = NULL;
7182 while (tmp2) {
7183 if (!tmp2->destroy) {
7184 if (tmp2->channel == channel) {
7185 tmp = tmp2;
7186 here = 1;
7187 break;
7189 if (tmp2->channel > channel) {
7190 break;
7193 prev = tmp2;
7194 tmp2 = tmp2->next;
7197 if (!here && !reloading) {
7198 if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
7199 destroy_zt_pvt(&tmp);
7200 return NULL;
7202 ast_mutex_init(&tmp->lock);
7203 ifcount++;
7204 for (x = 0; x < 3; x++)
7205 tmp->subs[x].zfd = -1;
7206 tmp->channel = channel;
7209 if (tmp) {
7210 int chan_sig = conf->chan.sig;
7211 if (!here) {
7212 if ((channel != CHAN_PSEUDO) && !pri) {
7213 snprintf(fn, sizeof(fn), "%d", channel);
7214 /* Open non-blocking */
7215 if (!here)
7216 tmp->subs[SUB_REAL].zfd = zt_open(fn);
7217 /* Allocate a zapata structure */
7218 if (tmp->subs[SUB_REAL].zfd < 0) {
7219 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);
7220 destroy_zt_pvt(&tmp);
7221 return NULL;
7223 memset(&p, 0, sizeof(p));
7224 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &p);
7225 if (res < 0) {
7226 ast_log(LOG_ERROR, "Unable to get parameters\n");
7227 destroy_zt_pvt(&tmp);
7228 return NULL;
7230 if (p.sigtype != (conf->chan.sig & 0x3ffff)) {
7231 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));
7232 destroy_zt_pvt(&tmp);
7233 return NULL;
7235 tmp->law = p.curlaw;
7236 tmp->span = p.spanno;
7237 span = p.spanno - 1;
7238 } else {
7239 if (channel == CHAN_PSEUDO)
7240 chan_sig = 0;
7241 else if ((chan_sig != SIG_FXOKS) && (chan_sig != SIG_FXSKS)) {
7242 ast_log(LOG_ERROR, "CRV's must use FXO/FXS Kewl Start (fxo_ks/fxs_ks) signalling only.\n");
7243 return NULL;
7246 #ifdef HAVE_PRI
7247 if ((conf->chan.sig == SIG_PRI) || (conf->chan.sig == SIG_GR303FXOKS) || (conf->chan.sig == SIG_GR303FXSKS)) {
7248 int offset;
7249 int myswitchtype;
7250 int matchesdchan;
7251 int x,y;
7252 offset = 0;
7253 if ((conf->chan.sig == SIG_PRI) && ioctl(tmp->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &offset)) {
7254 ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
7255 destroy_zt_pvt(&tmp);
7256 return NULL;
7258 if (span >= NUM_SPANS) {
7259 ast_log(LOG_ERROR, "Channel %d does not lie on a span I know of (%d)\n", channel, span);
7260 destroy_zt_pvt(&tmp);
7261 return NULL;
7262 } else {
7263 si.spanno = 0;
7264 if (ioctl(tmp->subs[SUB_REAL].zfd,ZT_SPANSTAT,&si) == -1) {
7265 ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
7266 destroy_zt_pvt(&tmp);
7267 return NULL;
7269 /* Store the logical span first based upon the real span */
7270 tmp->logicalspan = pris[span].prilogicalspan;
7271 pri_resolve_span(&span, channel, (channel - p.chanpos), &si);
7272 if (span < 0) {
7273 ast_log(LOG_WARNING, "Channel %d: Unable to find locate channel/trunk group!\n", channel);
7274 destroy_zt_pvt(&tmp);
7275 return NULL;
7277 if (conf->chan.sig == SIG_PRI)
7278 myswitchtype = conf->pri.switchtype;
7279 else
7280 myswitchtype = PRI_SWITCH_GR303_TMC;
7281 /* Make sure this isn't a d-channel */
7282 matchesdchan=0;
7283 for (x = 0; x < NUM_SPANS; x++) {
7284 for (y = 0; y < NUM_DCHANS; y++) {
7285 if (pris[x].dchannels[y] == tmp->channel) {
7286 matchesdchan = 1;
7287 break;
7291 offset = p.chanpos;
7292 if (!matchesdchan) {
7293 if (pris[span].nodetype && (pris[span].nodetype != conf->pri.nodetype)) {
7294 ast_log(LOG_ERROR, "Span %d is already a %s node\n", span + 1, pri_node2str(pris[span].nodetype));
7295 destroy_zt_pvt(&tmp);
7296 return NULL;
7298 if (pris[span].switchtype && (pris[span].switchtype != myswitchtype)) {
7299 ast_log(LOG_ERROR, "Span %d is already a %s switch\n", span + 1, pri_switch2str(pris[span].switchtype));
7300 destroy_zt_pvt(&tmp);
7301 return NULL;
7303 if ((pris[span].dialplan) && (pris[span].dialplan != conf->pri.dialplan)) {
7304 ast_log(LOG_ERROR, "Span %d is already a %s dialing plan\n", span + 1, dialplan2str(pris[span].dialplan));
7305 destroy_zt_pvt(&tmp);
7306 return NULL;
7308 if (!ast_strlen_zero(pris[span].idledial) && strcmp(pris[span].idledial, conf->pri.idledial)) {
7309 ast_log(LOG_ERROR, "Span %d already has idledial '%s'.\n", span + 1, conf->pri.idledial);
7310 destroy_zt_pvt(&tmp);
7311 return NULL;
7313 if (!ast_strlen_zero(pris[span].idleext) && strcmp(pris[span].idleext, conf->pri.idleext)) {
7314 ast_log(LOG_ERROR, "Span %d already has idleext '%s'.\n", span + 1, conf->pri.idleext);
7315 destroy_zt_pvt(&tmp);
7316 return NULL;
7318 if (pris[span].minunused && (pris[span].minunused != conf->pri.minunused)) {
7319 ast_log(LOG_ERROR, "Span %d already has minunused of %d.\n", span + 1, conf->pri.minunused);
7320 destroy_zt_pvt(&tmp);
7321 return NULL;
7323 if (pris[span].minidle && (pris[span].minidle != conf->pri.minidle)) {
7324 ast_log(LOG_ERROR, "Span %d already has minidle of %d.\n", span + 1, conf->pri.minidle);
7325 destroy_zt_pvt(&tmp);
7326 return NULL;
7328 if (pris[span].numchans >= MAX_CHANNELS) {
7329 ast_log(LOG_ERROR, "Unable to add channel %d: Too many channels in trunk group %d!\n", channel,
7330 pris[span].trunkgroup);
7331 destroy_zt_pvt(&tmp);
7332 return NULL;
7334 pris[span].nodetype = conf->pri.nodetype;
7335 pris[span].switchtype = myswitchtype;
7336 pris[span].nsf = conf->pri.nsf;
7337 pris[span].dialplan = conf->pri.dialplan;
7338 pris[span].localdialplan = conf->pri.localdialplan;
7339 pris[span].pvts[pris[span].numchans++] = tmp;
7340 pris[span].minunused = conf->pri.minunused;
7341 pris[span].minidle = conf->pri.minidle;
7342 pris[span].overlapdial = conf->pri.overlapdial;
7343 pris[span].facilityenable = conf->pri.facilityenable;
7344 ast_copy_string(pris[span].idledial, conf->pri.idledial, sizeof(pris[span].idledial));
7345 ast_copy_string(pris[span].idleext, conf->pri.idleext, sizeof(pris[span].idleext));
7346 ast_copy_string(pris[span].internationalprefix, conf->pri.internationalprefix, sizeof(pris[span].internationalprefix));
7347 ast_copy_string(pris[span].nationalprefix, conf->pri.nationalprefix, sizeof(pris[span].nationalprefix));
7348 ast_copy_string(pris[span].localprefix, conf->pri.localprefix, sizeof(pris[span].localprefix));
7349 ast_copy_string(pris[span].privateprefix, conf->pri.privateprefix, sizeof(pris[span].privateprefix));
7350 ast_copy_string(pris[span].unknownprefix, conf->pri.unknownprefix, sizeof(pris[span].unknownprefix));
7351 pris[span].resetinterval = conf->pri.resetinterval;
7353 tmp->pri = &pris[span];
7354 tmp->prioffset = offset;
7355 tmp->call = NULL;
7356 } else {
7357 ast_log(LOG_ERROR, "Channel %d is reserved for D-channel.\n", offset);
7358 destroy_zt_pvt(&tmp);
7359 return NULL;
7362 } else {
7363 tmp->prioffset = 0;
7365 #endif
7366 } else {
7367 chan_sig = tmp->sig;
7368 memset(&p, 0, sizeof(p));
7369 if (tmp->subs[SUB_REAL].zfd > -1)
7370 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &p);
7372 /* Adjust starttime on loopstart and kewlstart trunks to reasonable values */
7373 switch (chan_sig) {
7374 case SIG_FXSKS:
7375 case SIG_FXSLS:
7376 case SIG_EM:
7377 case SIG_EM_E1:
7378 case SIG_EMWINK:
7379 case SIG_FEATD:
7380 case SIG_FEATDMF:
7381 case SIG_FEATDMF_TA:
7382 case SIG_FEATB:
7383 case SIG_E911:
7384 case SIG_SF:
7385 case SIG_SFWINK:
7386 case SIG_FGC_CAMA:
7387 case SIG_FGC_CAMAMF:
7388 case SIG_SF_FEATD:
7389 case SIG_SF_FEATDMF:
7390 case SIG_SF_FEATB:
7391 p.starttime = 250;
7392 break;
7395 if (tmp->radio) {
7396 /* XXX Waiting to hear back from Jim if these should be adjustable XXX */
7397 p.channo = channel;
7398 p.rxwinktime = 1;
7399 p.rxflashtime = 1;
7400 p.starttime = 1;
7401 p.debouncetime = 5;
7403 if (!tmp->radio) {
7404 p.channo = channel;
7405 /* Override timing settings based on config file */
7406 if (conf->timing.prewinktime >= 0)
7407 p.prewinktime = conf->timing.prewinktime;
7408 if (conf->timing.preflashtime >= 0)
7409 p.preflashtime = conf->timing.preflashtime;
7410 if (conf->timing.winktime >= 0)
7411 p.winktime = conf->timing.winktime;
7412 if (conf->timing.flashtime >= 0)
7413 p.flashtime = conf->timing.flashtime;
7414 if (conf->timing.starttime >= 0)
7415 p.starttime = conf->timing.starttime;
7416 if (conf->timing.rxwinktime >= 0)
7417 p.rxwinktime = conf->timing.rxwinktime;
7418 if (conf->timing.rxflashtime >= 0)
7419 p.rxflashtime = conf->timing.rxflashtime;
7420 if (conf->timing.debouncetime >= 0)
7421 p.debouncetime = conf->timing.debouncetime;
7424 /* dont set parms on a pseudo-channel (or CRV) */
7425 if (tmp->subs[SUB_REAL].zfd >= 0)
7427 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_SET_PARAMS, &p);
7428 if (res < 0) {
7429 ast_log(LOG_ERROR, "Unable to set parameters\n");
7430 destroy_zt_pvt(&tmp);
7431 return NULL;
7434 #if 1
7435 if (!here && (tmp->subs[SUB_REAL].zfd > -1)) {
7436 memset(&bi, 0, sizeof(bi));
7437 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_BUFINFO, &bi);
7438 if (!res) {
7439 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
7440 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
7441 bi.numbufs = numbufs;
7442 res = ioctl(tmp->subs[SUB_REAL].zfd, ZT_SET_BUFINFO, &bi);
7443 if (res < 0) {
7444 ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", channel);
7446 } else
7447 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", channel);
7449 #endif
7450 tmp->immediate = conf->chan.immediate;
7451 tmp->transfertobusy = conf->chan.transfertobusy;
7452 tmp->sig = chan_sig;
7453 tmp->outsigmod = conf->chan.outsigmod;
7454 tmp->ringt_base = ringt_base;
7455 tmp->firstradio = 0;
7456 if ((chan_sig == SIG_FXOKS) || (chan_sig == SIG_FXOLS) || (chan_sig == SIG_FXOGS))
7457 tmp->permcallwaiting = conf->chan.callwaiting;
7458 else
7459 tmp->permcallwaiting = 0;
7460 /* Flag to destroy the channel must be cleared on new mkif. Part of changes for reload to work */
7461 tmp->destroy = 0;
7462 tmp->drings = drings;
7463 tmp->usedistinctiveringdetection = conf->chan.usedistinctiveringdetection;
7464 tmp->callwaitingcallerid = conf->chan.callwaitingcallerid;
7465 tmp->threewaycalling = conf->chan.threewaycalling;
7466 tmp->adsi = conf->chan.adsi;
7467 tmp->use_smdi = conf->chan.use_smdi;
7468 tmp->permhidecallerid = conf->chan.hidecallerid;
7469 tmp->callreturn = conf->chan.callreturn;
7470 tmp->echocancel = conf->chan.echocancel;
7471 tmp->echotraining = conf->chan.echotraining;
7472 tmp->pulse = conf->chan.pulse;
7473 if (tmp->echocancel)
7474 tmp->echocanbridged = conf->chan.echocanbridged;
7475 else {
7476 if (conf->chan.echocanbridged)
7477 ast_log(LOG_NOTICE, "echocancelwhenbridged requires echocancel to be enabled; ignoring\n");
7478 tmp->echocanbridged = 0;
7480 tmp->busydetect = conf->chan.busydetect;
7481 tmp->busycount = conf->chan.busycount;
7482 tmp->busy_tonelength = conf->chan.busy_tonelength;
7483 tmp->busy_quietlength = conf->chan.busy_quietlength;
7484 tmp->callprogress = conf->chan.callprogress;
7485 tmp->cancallforward = conf->chan.cancallforward;
7486 tmp->dtmfrelax = conf->chan.dtmfrelax;
7487 tmp->callwaiting = tmp->permcallwaiting;
7488 tmp->hidecallerid = tmp->permhidecallerid;
7489 tmp->channel = channel;
7490 tmp->stripmsd = conf->chan.stripmsd;
7491 tmp->use_callerid = conf->chan.use_callerid;
7492 tmp->cid_signalling = conf->chan.cid_signalling;
7493 tmp->cid_start = conf->chan.cid_start;
7494 tmp->zaptrcallerid = conf->chan.zaptrcallerid;
7495 tmp->restrictcid = conf->chan.restrictcid;
7496 tmp->use_callingpres = conf->chan.use_callingpres;
7497 tmp->priindication_oob = conf->chan.priindication_oob;
7498 tmp->priexclusive = conf->chan.priexclusive;
7499 if (tmp->usedistinctiveringdetection) {
7500 if (!tmp->use_callerid) {
7501 ast_log(LOG_NOTICE, "Distinctive Ring detect requires 'usecallerid' be on\n");
7502 tmp->use_callerid = 1;
7506 if (tmp->cid_signalling == CID_SIG_SMDI) {
7507 if (!tmp->use_smdi) {
7508 ast_log(LOG_WARNING, "SMDI callerid requires SMDI to be enabled, enabling...\n");
7509 tmp->use_smdi = 1;
7512 if (tmp->use_smdi) {
7513 tmp->smdi_iface = ast_smdi_interface_find(conf->smdi_port);
7514 if (!(tmp->smdi_iface)) {
7515 ast_log(LOG_ERROR, "Invalid SMDI port specfied, disabling SMDI support\n");
7516 tmp->use_smdi = 0;
7520 ast_copy_string(tmp->accountcode, conf->chan.accountcode, sizeof(tmp->accountcode));
7521 tmp->amaflags = conf->chan.amaflags;
7522 if (!here) {
7523 tmp->confno = -1;
7524 tmp->propconfno = -1;
7526 tmp->canpark = conf->chan.canpark;
7527 tmp->transfer = conf->chan.transfer;
7528 ast_copy_string(tmp->defcontext,conf->chan.context,sizeof(tmp->defcontext));
7529 ast_copy_string(tmp->language, conf->chan.language, sizeof(tmp->language));
7530 ast_copy_string(tmp->mohinterpret, conf->chan.mohinterpret, sizeof(tmp->mohinterpret));
7531 ast_copy_string(tmp->mohsuggest, conf->chan.mohsuggest, sizeof(tmp->mohsuggest));
7532 ast_copy_string(tmp->context, conf->chan.context, sizeof(tmp->context));
7533 ast_copy_string(tmp->cid_num, conf->chan.cid_num, sizeof(tmp->cid_num));
7534 tmp->cid_ton = 0;
7535 ast_copy_string(tmp->cid_name, conf->chan.cid_name, sizeof(tmp->cid_name));
7536 ast_copy_string(tmp->mailbox, conf->chan.mailbox, sizeof(tmp->mailbox));
7537 tmp->msgstate = -1;
7538 tmp->group = conf->chan.group;
7539 tmp->callgroup = conf->chan.callgroup;
7540 tmp->pickupgroup= conf->chan.pickupgroup;
7541 tmp->rxgain = conf->chan.rxgain;
7542 tmp->txgain = conf->chan.txgain;
7543 tmp->tonezone = conf->chan.tonezone;
7544 tmp->onhooktime = time(NULL);
7545 if (tmp->subs[SUB_REAL].zfd > -1) {
7546 set_actual_gain(tmp->subs[SUB_REAL].zfd, 0, tmp->rxgain, tmp->txgain, tmp->law);
7547 if (tmp->dsp)
7548 ast_dsp_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
7549 update_conf(tmp);
7550 if (!here) {
7551 if (chan_sig != SIG_PRI)
7552 /* Hang it up to be sure it's good */
7553 zt_set_hook(tmp->subs[SUB_REAL].zfd, ZT_ONHOOK);
7555 ioctl(tmp->subs[SUB_REAL].zfd,ZT_SETTONEZONE,&tmp->tonezone);
7556 #ifdef HAVE_PRI
7557 /* the dchannel is down so put the channel in alarm */
7558 if (tmp->pri && !pri_is_up(tmp->pri))
7559 tmp->inalarm = 1;
7560 else
7561 tmp->inalarm = 0;
7562 #endif
7563 memset(&si, 0, sizeof(si));
7564 if (ioctl(tmp->subs[SUB_REAL].zfd,ZT_SPANSTAT,&si) == -1) {
7565 ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
7566 destroy_zt_pvt(&tmp);
7567 return NULL;
7569 if (si.alarms) tmp->inalarm = 1;
7572 tmp->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
7573 tmp->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
7574 tmp->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
7575 tmp->sendcalleridafter = conf->chan.sendcalleridafter;
7578 if (tmp && !here) {
7579 /* nothing on the iflist */
7580 if (!*wlist) {
7581 *wlist = tmp;
7582 tmp->prev = NULL;
7583 tmp->next = NULL;
7584 *wend = tmp;
7585 } else {
7586 /* at least one member on the iflist */
7587 struct zt_pvt *working = *wlist;
7589 /* check if we maybe have to put it on the begining */
7590 if (working->channel > tmp->channel) {
7591 tmp->next = *wlist;
7592 tmp->prev = NULL;
7593 (*wlist)->prev = tmp;
7594 *wlist = tmp;
7595 } else {
7596 /* go through all the members and put the member in the right place */
7597 while (working) {
7598 /* in the middle */
7599 if (working->next) {
7600 if (working->channel < tmp->channel && working->next->channel > tmp->channel) {
7601 tmp->next = working->next;
7602 tmp->prev = working;
7603 working->next->prev = tmp;
7604 working->next = tmp;
7605 break;
7607 } else {
7608 /* the last */
7609 if (working->channel < tmp->channel) {
7610 working->next = tmp;
7611 tmp->next = NULL;
7612 tmp->prev = working;
7613 *wend = tmp;
7614 break;
7617 working = working->next;
7622 return tmp;
7625 static inline int available(struct zt_pvt *p, int channelmatch, ast_group_t groupmatch, int *busy, int *channelmatched, int *groupmatched)
7627 int res;
7628 ZT_PARAMS par;
7630 /* First, check group matching */
7631 if (groupmatch) {
7632 if ((p->group & groupmatch) != groupmatch)
7633 return 0;
7634 *groupmatched = 1;
7636 /* Check to see if we have a channel match */
7637 if (channelmatch != -1) {
7638 if (p->channel != channelmatch)
7639 return 0;
7640 *channelmatched = 1;
7642 /* We're at least busy at this point */
7643 if (busy) {
7644 if ((p->sig == SIG_FXOKS) || (p->sig == SIG_FXOLS) || (p->sig == SIG_FXOGS))
7645 *busy = 1;
7647 /* If do not disturb, definitely not */
7648 if (p->dnd)
7649 return 0;
7650 /* If guard time, definitely not */
7651 if (p->guardtime && (time(NULL) < p->guardtime))
7652 return 0;
7654 /* If no owner definitely available */
7655 if (!p->owner) {
7656 #ifdef HAVE_PRI
7657 /* Trust PRI */
7658 if (p->pri) {
7659 if (p->resetting || p->call)
7660 return 0;
7661 else
7662 return 1;
7664 #endif
7665 if (!(p->radio || (p->oprmode < 0)))
7667 if (!p->sig || (p->sig == SIG_FXSLS))
7668 return 1;
7669 /* Check hook state */
7670 if (p->subs[SUB_REAL].zfd > -1)
7671 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
7672 else {
7673 /* Assume not off hook on CVRS */
7674 res = 0;
7675 par.rxisoffhook = 0;
7677 if (res) {
7678 ast_log(LOG_WARNING, "Unable to check hook state on channel %d\n", p->channel);
7679 } else if ((p->sig == SIG_FXSKS) || (p->sig == SIG_FXSGS)) {
7680 /* When "onhook" that means no battery on the line, and thus
7681 it is out of service..., if it's on a TDM card... If it's a channel
7682 bank, there is no telling... */
7683 if (par.rxbits > -1)
7684 return 1;
7685 if (par.rxisoffhook)
7686 return 1;
7687 else
7688 #ifdef ZAP_CHECK_HOOKSTATE
7689 return 0;
7690 #else
7691 return 1;
7692 #endif
7693 } else if (par.rxisoffhook) {
7694 ast_log(LOG_DEBUG, "Channel %d off hook, can't use\n", p->channel);
7695 /* Not available when the other end is off hook */
7696 return 0;
7699 return 1;
7702 /* If it's not an FXO, forget about call wait */
7703 if ((p->sig != SIG_FXOKS) && (p->sig != SIG_FXOLS) && (p->sig != SIG_FXOGS))
7704 return 0;
7706 if (!p->callwaiting) {
7707 /* If they don't have call waiting enabled, then for sure they're unavailable at this point */
7708 return 0;
7711 if (p->subs[SUB_CALLWAIT].zfd > -1) {
7712 /* If there is already a call waiting call, then we can't take a second one */
7713 return 0;
7716 if ((p->owner->_state != AST_STATE_UP) &&
7717 ((p->owner->_state != AST_STATE_RINGING) || p->outgoing)) {
7718 /* If the current call is not up, then don't allow the call */
7719 return 0;
7721 if ((p->subs[SUB_THREEWAY].owner) && (!p->subs[SUB_THREEWAY].inthreeway)) {
7722 /* Can't take a call wait when the three way calling hasn't been merged yet. */
7723 return 0;
7725 /* We're cool */
7726 return 1;
7729 static struct zt_pvt *chandup(struct zt_pvt *src)
7731 struct zt_pvt *p;
7732 ZT_BUFFERINFO bi;
7733 int res;
7735 if ((p = ast_malloc(sizeof(*p)))) {
7736 memcpy(p, src, sizeof(struct zt_pvt));
7737 ast_mutex_init(&p->lock);
7738 p->subs[SUB_REAL].zfd = zt_open("/dev/zap/pseudo");
7739 /* Allocate a zapata structure */
7740 if (p->subs[SUB_REAL].zfd < 0) {
7741 ast_log(LOG_ERROR, "Unable to dup channel: %s\n", strerror(errno));
7742 destroy_zt_pvt(&p);
7743 return NULL;
7745 res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_BUFINFO, &bi);
7746 if (!res) {
7747 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
7748 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
7749 bi.numbufs = numbufs;
7750 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SET_BUFINFO, &bi);
7751 if (res < 0) {
7752 ast_log(LOG_WARNING, "Unable to set buffer policy on dup channel\n");
7754 } else
7755 ast_log(LOG_WARNING, "Unable to check buffer policy on dup channel\n");
7757 p->destroy = 1;
7758 p->next = iflist;
7759 p->prev = NULL;
7760 iflist = p;
7761 if (iflist->next)
7762 iflist->next->prev = p;
7763 return p;
7767 #ifdef HAVE_PRI
7768 static int pri_find_empty_chan(struct zt_pri *pri, int backwards)
7770 int x;
7771 if (backwards)
7772 x = pri->numchans;
7773 else
7774 x = 0;
7775 for (;;) {
7776 if (backwards && (x < 0))
7777 break;
7778 if (!backwards && (x >= pri->numchans))
7779 break;
7780 if (pri->pvts[x] && !pri->pvts[x]->inalarm && !pri->pvts[x]->owner) {
7781 ast_log(LOG_DEBUG, "Found empty available channel %d/%d\n",
7782 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
7783 return x;
7785 if (backwards)
7786 x--;
7787 else
7788 x++;
7790 return -1;
7792 #endif
7794 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause)
7796 ast_group_t groupmatch = 0;
7797 int channelmatch = -1;
7798 int roundrobin = 0;
7799 int callwait = 0;
7800 int busy = 0;
7801 struct zt_pvt *p;
7802 struct ast_channel *tmp = NULL;
7803 char *dest=NULL;
7804 int x;
7805 char *s;
7806 char opt=0;
7807 int res=0, y=0;
7808 int backwards = 0;
7809 #ifdef HAVE_PRI
7810 int crv;
7811 int bearer = -1;
7812 int trunkgroup;
7813 struct zt_pri *pri=NULL;
7814 #endif
7815 struct zt_pvt *exit, *start, *end;
7816 ast_mutex_t *lock;
7817 int channelmatched = 0;
7818 int groupmatched = 0;
7820 /* Assume we're locking the iflock */
7821 lock = &iflock;
7822 start = iflist;
7823 end = ifend;
7824 if (data) {
7825 dest = ast_strdupa((char *)data);
7826 } else {
7827 ast_log(LOG_WARNING, "Channel requested with no data\n");
7828 return NULL;
7830 if (toupper(dest[0]) == 'G' || toupper(dest[0])=='R') {
7831 /* Retrieve the group number */
7832 char *stringp=NULL;
7833 stringp=dest + 1;
7834 s = strsep(&stringp, "/");
7835 if ((res = sscanf(s, "%d%c%d", &x, &opt, &y)) < 1) {
7836 ast_log(LOG_WARNING, "Unable to determine group for data %s\n", (char *)data);
7837 return NULL;
7839 groupmatch = ((ast_group_t) 1 << x);
7840 if (toupper(dest[0]) == 'G') {
7841 if (dest[0] == 'G') {
7842 backwards = 1;
7843 p = ifend;
7844 } else
7845 p = iflist;
7846 } else {
7847 if (dest[0] == 'R') {
7848 backwards = 1;
7849 p = round_robin[x]?round_robin[x]->prev:ifend;
7850 if (!p)
7851 p = ifend;
7852 } else {
7853 p = round_robin[x]?round_robin[x]->next:iflist;
7854 if (!p)
7855 p = iflist;
7857 roundrobin = 1;
7859 } else {
7860 char *stringp=NULL;
7861 stringp=dest;
7862 s = strsep(&stringp, "/");
7863 p = iflist;
7864 if (!strcasecmp(s, "pseudo")) {
7865 /* Special case for pseudo */
7866 x = CHAN_PSEUDO;
7867 channelmatch = x;
7869 #ifdef HAVE_PRI
7870 else if ((res = sscanf(s, "%d:%d%c%d", &trunkgroup, &crv, &opt, &y)) > 1) {
7871 if ((trunkgroup < 1) || (crv < 1)) {
7872 ast_log(LOG_WARNING, "Unable to determine trunk group and CRV for data %s\n", (char *)data);
7873 return NULL;
7875 res--;
7876 for (x = 0; x < NUM_SPANS; x++) {
7877 if (pris[x].trunkgroup == trunkgroup) {
7878 pri = pris + x;
7879 lock = &pri->lock;
7880 start = pri->crvs;
7881 end = pri->crvend;
7882 break;
7885 if (!pri) {
7886 ast_log(LOG_WARNING, "Unable to find trunk group %d\n", trunkgroup);
7887 return NULL;
7889 channelmatch = crv;
7890 p = pris[x].crvs;
7892 #endif
7893 else if ((res = sscanf(s, "%d%c%d", &x, &opt, &y)) < 1) {
7894 ast_log(LOG_WARNING, "Unable to determine channel for data %s\n", (char *)data);
7895 return NULL;
7896 } else {
7897 channelmatch = x;
7900 /* Search for an unowned channel */
7901 ast_mutex_lock(lock);
7902 exit = p;
7903 while (p && !tmp) {
7904 if (roundrobin)
7905 round_robin[x] = p;
7906 #if 0
7907 ast_verbose("name = %s, %d, %d, %d\n",p->owner ? p->owner->name : "<none>", p->channel, channelmatch, groupmatch);
7908 #endif
7910 if (p && available(p, channelmatch, groupmatch, &busy, &channelmatched, &groupmatched)) {
7911 if (option_debug)
7912 ast_log(LOG_DEBUG, "Using channel %d\n", p->channel);
7913 if (p->inalarm)
7914 goto next;
7916 callwait = (p->owner != NULL);
7917 #ifdef HAVE_PRI
7918 if (pri && (p->subs[SUB_REAL].zfd < 0)) {
7919 if (p->sig != SIG_FXSKS) {
7920 /* Gotta find an actual channel to use for this
7921 CRV if this isn't a callwait */
7922 bearer = pri_find_empty_chan(pri, 0);
7923 if (bearer < 0) {
7924 ast_log(LOG_NOTICE, "Out of bearer channels on span %d for call to CRV %d:%d\n", pri->span, trunkgroup, crv);
7925 p = NULL;
7926 break;
7928 pri_assign_bearer(p, pri, pri->pvts[bearer]);
7929 } else {
7930 if (alloc_sub(p, 0)) {
7931 ast_log(LOG_NOTICE, "Failed to allocate place holder pseudo channel!\n");
7932 p = NULL;
7933 break;
7934 } else
7935 ast_log(LOG_DEBUG, "Allocated placeholder pseudo channel\n");
7936 p->pri = pri;
7939 #endif
7940 if (p->channel == CHAN_PSEUDO) {
7941 p = chandup(p);
7942 if (!p) {
7943 break;
7946 if (p->owner) {
7947 if (alloc_sub(p, SUB_CALLWAIT)) {
7948 p = NULL;
7949 break;
7952 p->outgoing = 1;
7953 tmp = zt_new(p, AST_STATE_RESERVED, 0, p->owner ? SUB_CALLWAIT : SUB_REAL, 0, 0);
7954 #ifdef HAVE_PRI
7955 if (p->bearer) {
7956 /* Log owner to bearer channel, too */
7957 p->bearer->owner = tmp;
7959 #endif
7960 /* Make special notes */
7961 if (res > 1) {
7962 if (opt == 'c') {
7963 /* Confirm answer */
7964 p->confirmanswer = 1;
7965 } else if (opt == 'r') {
7966 /* Distinctive ring */
7967 if (res < 3)
7968 ast_log(LOG_WARNING, "Distinctive ring missing identifier in '%s'\n", (char *)data);
7969 else
7970 p->distinctivering = y;
7971 } else if (opt == 'd') {
7972 /* If this is an ISDN call, make it digital */
7973 p->digital = 1;
7974 if (tmp)
7975 tmp->transfercapability = AST_TRANS_CAP_DIGITAL;
7976 } else {
7977 ast_log(LOG_WARNING, "Unknown option '%c' in '%s'\n", opt, (char *)data);
7980 /* Note if the call is a call waiting call */
7981 if (tmp && callwait)
7982 tmp->cdrflags |= AST_CDR_CALLWAIT;
7983 break;
7985 next:
7986 if (backwards) {
7987 p = p->prev;
7988 if (!p)
7989 p = end;
7990 } else {
7991 p = p->next;
7992 if (!p)
7993 p = start;
7995 /* stop when you roll to the one that we started from */
7996 if (p == exit)
7997 break;
7999 ast_mutex_unlock(lock);
8000 restart_monitor();
8001 if (callwait)
8002 *cause = AST_CAUSE_BUSY;
8003 else if (!tmp) {
8004 if (channelmatched) {
8005 if (busy)
8006 *cause = AST_CAUSE_BUSY;
8007 } else if (groupmatched) {
8008 *cause = AST_CAUSE_CONGESTION;
8012 return tmp;
8016 #ifdef HAVE_PRI
8017 static struct zt_pvt *pri_find_crv(struct zt_pri *pri, int crv)
8019 struct zt_pvt *p;
8020 p = pri->crvs;
8021 while (p) {
8022 if (p->channel == crv)
8023 return p;
8024 p = p->next;
8026 return NULL;
8030 static int pri_find_principle(struct zt_pri *pri, int channel)
8032 int x;
8033 int span = PRI_SPAN(channel);
8034 int spanfd;
8035 ZT_PARAMS param;
8036 int principle = -1;
8037 int explicit = PRI_EXPLICIT(channel);
8038 channel = PRI_CHANNEL(channel);
8040 if (!explicit) {
8041 spanfd = pri_active_dchan_fd(pri);
8042 if (ioctl(spanfd, ZT_GET_PARAMS, &param))
8043 return -1;
8044 span = pris[param.spanno - 1].prilogicalspan;
8047 for (x = 0; x < pri->numchans; x++) {
8048 if (pri->pvts[x] && (pri->pvts[x]->prioffset == channel) && (pri->pvts[x]->logicalspan == span)) {
8049 principle = x;
8050 break;
8054 return principle;
8057 static int pri_fixup_principle(struct zt_pri *pri, int principle, q931_call *c)
8059 int x;
8060 struct zt_pvt *crv;
8061 if (!c) {
8062 if (principle < 0)
8063 return -1;
8064 return principle;
8066 if ((principle > -1) &&
8067 (principle < pri->numchans) &&
8068 (pri->pvts[principle]) &&
8069 (pri->pvts[principle]->call == c))
8070 return principle;
8071 /* First, check for other bearers */
8072 for (x = 0; x < pri->numchans; x++) {
8073 if (!pri->pvts[x])
8074 continue;
8075 if (pri->pvts[x]->call == c) {
8076 /* Found our call */
8077 if (principle != x) {
8078 struct zt_pvt *new = pri->pvts[principle], *old = pri->pvts[x];
8080 if (option_verbose > 2)
8081 ast_verbose(VERBOSE_PREFIX_3 "Moving call from channel %d to channel %d\n",
8082 old->channel, new->channel);
8083 if (new->owner) {
8084 ast_log(LOG_WARNING, "Can't fix up channel from %d to %d because %d is already in use\n",
8085 old->channel, new->channel, new->channel);
8086 return -1;
8088 /* Fix it all up now */
8089 new->owner = old->owner;
8090 old->owner = NULL;
8091 if (new->owner) {
8092 ast_string_field_build(new->owner, name,
8093 "Zap/%d:%d-%d", pri->trunkgroup,
8094 new->channel, 1);
8095 new->owner->tech_pvt = new;
8096 new->owner->fds[0] = new->subs[SUB_REAL].zfd;
8097 new->subs[SUB_REAL].owner = old->subs[SUB_REAL].owner;
8098 old->subs[SUB_REAL].owner = NULL;
8099 } else
8100 ast_log(LOG_WARNING, "Whoa, there's no owner, and we're having to fix up channel %d to channel %d\n", old->channel, new->channel);
8101 new->call = old->call;
8102 old->call = NULL;
8104 /* Copy any DSP that may be present */
8105 new->dsp = old->dsp;
8106 new->dsp_features = old->dsp_features;
8107 old->dsp = NULL;
8108 old->dsp_features = 0;
8110 return principle;
8113 /* Now check for a CRV with no bearer */
8114 crv = pri->crvs;
8115 while (crv) {
8116 if (crv->call == c) {
8117 /* This is our match... Perform some basic checks */
8118 if (crv->bearer)
8119 ast_log(LOG_WARNING, "Trying to fix up call which already has a bearer which isn't the one we think it is\n");
8120 else if (pri->pvts[principle]->owner)
8121 ast_log(LOG_WARNING, "Tring to fix up a call to a bearer which already has an owner!\n");
8122 else {
8123 /* Looks good. Drop the pseudo channel now, clear up the assignment, and
8124 wakeup the potential sleeper */
8125 zt_close(crv->subs[SUB_REAL].zfd);
8126 pri->pvts[principle]->call = crv->call;
8127 pri_assign_bearer(crv, pri, pri->pvts[principle]);
8128 ast_log(LOG_DEBUG, "Assigning bearer %d/%d to CRV %d:%d\n",
8129 pri->pvts[principle]->logicalspan, pri->pvts[principle]->prioffset,
8130 pri->trunkgroup, crv->channel);
8131 wakeup_sub(crv, SUB_REAL, pri);
8133 return principle;
8135 crv = crv->next;
8137 ast_log(LOG_WARNING, "Call specified, but not found?\n");
8138 return -1;
8141 static void *do_idle_thread(void *vchan)
8143 struct ast_channel *chan = vchan;
8144 struct zt_pvt *pvt = chan->tech_pvt;
8145 struct ast_frame *f;
8146 char ex[80];
8147 /* Wait up to 30 seconds for an answer */
8148 int newms, ms = 30000;
8149 if (option_verbose > 2)
8150 ast_verbose(VERBOSE_PREFIX_3 "Initiating idle call on channel %s\n", chan->name);
8151 snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
8152 if (ast_call(chan, ex, 0)) {
8153 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
8154 ast_hangup(chan);
8155 return NULL;
8157 while ((newms = ast_waitfor(chan, ms)) > 0) {
8158 f = ast_read(chan);
8159 if (!f) {
8160 /* Got hangup */
8161 break;
8163 if (f->frametype == AST_FRAME_CONTROL) {
8164 switch (f->subclass) {
8165 case AST_CONTROL_ANSWER:
8166 /* Launch the PBX */
8167 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
8168 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
8169 chan->priority = 1;
8170 if (option_verbose > 3)
8171 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
8172 ast_pbx_run(chan);
8173 /* It's already hungup, return immediately */
8174 return NULL;
8175 case AST_CONTROL_BUSY:
8176 if (option_verbose > 3)
8177 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' busy, waiting...\n", chan->name);
8178 break;
8179 case AST_CONTROL_CONGESTION:
8180 if (option_verbose > 3)
8181 ast_verbose(VERBOSE_PREFIX_3 "Idle channel '%s' congested, waiting...\n", chan->name);
8182 break;
8185 ast_frfree(f);
8186 ms = newms;
8188 /* Hangup the channel since nothing happend */
8189 ast_hangup(chan);
8190 return NULL;
8193 #ifndef PRI_RESTART
8194 #error "Upgrade your libpri"
8195 #endif
8196 static void zt_pri_message(struct pri *pri, char *s)
8198 int x, y;
8199 int dchan = -1, span = -1;
8200 int dchancount = 0;
8202 if (pri) {
8203 for (x = 0; x < NUM_SPANS; x++) {
8204 for (y = 0; y < NUM_DCHANS; y++) {
8205 if (pris[x].dchans[y])
8206 dchancount++;
8208 if (pris[x].dchans[y] == pri)
8209 dchan = y;
8211 if (dchan >= 0) {
8212 span = x;
8213 break;
8215 dchancount = 0;
8217 if ((dchan >= 0) && (span >= 0)) {
8218 if (dchancount > 1)
8219 ast_verbose("[Span %d D-Channel %d]%s", span, dchan, s);
8220 else
8221 ast_verbose("%s", s);
8222 } else
8223 ast_log(LOG_ERROR, "PRI debug error: could not find pri associated it with debug message output\n");
8224 } else
8225 ast_verbose("%s", s);
8227 ast_mutex_lock(&pridebugfdlock);
8229 if (pridebugfd >= 0)
8230 write(pridebugfd, s, strlen(s));
8232 ast_mutex_unlock(&pridebugfdlock);
8235 static void zt_pri_error(struct pri *pri, char *s)
8237 int x, y;
8238 int dchan = -1, span = -1;
8239 int dchancount = 0;
8241 if (pri) {
8242 for (x = 0; x < NUM_SPANS; x++) {
8243 for (y = 0; y < NUM_DCHANS; y++) {
8244 if (pris[x].dchans[y])
8245 dchancount++;
8247 if (pris[x].dchans[y] == pri)
8248 dchan = y;
8250 if (dchan >= 0) {
8251 span = x;
8252 break;
8254 dchancount = 0;
8256 if ((dchan >= 0) && (span >= 0)) {
8257 if (dchancount > 1)
8258 ast_log(LOG_ERROR, "[Span %d D-Channel %d] PRI: %s", span, dchan, s);
8259 else
8260 ast_log(LOG_ERROR, "%s", s);
8261 } else
8262 ast_log(LOG_ERROR, "PRI debug error: could not find pri associated it with debug message output\n");
8263 } else
8264 ast_log(LOG_ERROR, "%s", s);
8266 ast_mutex_lock(&pridebugfdlock);
8268 if (pridebugfd >= 0)
8269 write(pridebugfd, s, strlen(s));
8271 ast_mutex_unlock(&pridebugfdlock);
8274 static int pri_check_restart(struct zt_pri *pri)
8276 do {
8277 pri->resetpos++;
8278 } while ((pri->resetpos < pri->numchans) &&
8279 (!pri->pvts[pri->resetpos] ||
8280 pri->pvts[pri->resetpos]->call ||
8281 pri->pvts[pri->resetpos]->resetting));
8282 if (pri->resetpos < pri->numchans) {
8283 /* Mark the channel as resetting and restart it */
8284 pri->pvts[pri->resetpos]->resetting = 1;
8285 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
8286 } else {
8287 pri->resetting = 0;
8288 time(&pri->lastreset);
8290 return 0;
8293 static int pri_hangup_all(struct zt_pvt *p, struct zt_pri *pri)
8295 int x;
8296 int redo;
8297 ast_mutex_unlock(&pri->lock);
8298 ast_mutex_lock(&p->lock);
8299 do {
8300 redo = 0;
8301 for (x = 0; x < 3; x++) {
8302 while (p->subs[x].owner && ast_mutex_trylock(&p->subs[x].owner->lock)) {
8303 redo++;
8304 ast_mutex_unlock(&p->lock);
8305 usleep(1);
8306 ast_mutex_lock(&p->lock);
8308 if (p->subs[x].owner) {
8309 ast_queue_hangup(p->subs[x].owner);
8310 ast_mutex_unlock(&p->subs[x].owner->lock);
8313 } while (redo);
8314 ast_mutex_unlock(&p->lock);
8315 ast_mutex_lock(&pri->lock);
8316 return 0;
8319 static char * redirectingreason2str(int redirectingreason)
8321 switch (redirectingreason) {
8322 case 0:
8323 return "UNKNOWN";
8324 case 1:
8325 return "BUSY";
8326 case 2:
8327 return "NO_REPLY";
8328 case 0xF:
8329 return "UNCONDITIONAL";
8330 default:
8331 return "NOREDIRECT";
8335 static void apply_plan_to_number(char *buf, size_t size, const struct zt_pri *pri, const char *number, const int plan)
8337 switch (plan) {
8338 case PRI_INTERNATIONAL_ISDN: /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
8339 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
8340 break;
8341 case PRI_NATIONAL_ISDN: /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
8342 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
8343 break;
8344 case PRI_LOCAL_ISDN: /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
8345 snprintf(buf, size, "%s%s", pri->localprefix, number);
8346 break;
8347 case PRI_PRIVATE: /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
8348 snprintf(buf, size, "%s%s", pri->privateprefix, number);
8349 break;
8350 case PRI_UNKNOWN: /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
8351 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
8352 break;
8353 default: /* other Q.931 dialplan => don't twiddle with callingnum */
8354 snprintf(buf, size, "%s", number);
8355 break;
8359 static int zt_setlaw(int zfd, int law)
8361 int res;
8362 res = ioctl(zfd, ZT_SETLAW, &law);
8363 if (res)
8364 return res;
8365 return 0;
8368 static void *pri_dchannel(void *vpri)
8370 struct zt_pri *pri = vpri;
8371 pri_event *e;
8372 struct pollfd fds[NUM_DCHANS];
8373 int res;
8374 int chanpos = 0;
8375 int x;
8376 int haveidles;
8377 int activeidles;
8378 int nextidle = -1;
8379 struct ast_channel *c;
8380 struct timeval tv, lowest, *next;
8381 struct timeval lastidle = { 0, 0 };
8382 int doidling=0;
8383 char *cc;
8384 char idlen[80];
8385 struct ast_channel *idle;
8386 pthread_t p;
8387 time_t t;
8388 int i, which=-1;
8389 int numdchans;
8390 int cause=0;
8391 struct zt_pvt *crv;
8392 pthread_t threadid;
8393 pthread_attr_t attr;
8394 char ani2str[6];
8395 char plancallingnum[256];
8396 char plancallingani[256];
8397 char calledtonstr[10];
8399 gettimeofday(&lastidle, NULL);
8400 if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
8401 /* Need to do idle dialing, check to be sure though */
8402 cc = strchr(pri->idleext, '@');
8403 if (cc) {
8404 *cc = '\0';
8405 cc++;
8406 ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
8407 #if 0
8408 /* Extensions may not be loaded yet */
8409 if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
8410 ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
8411 else
8412 #endif
8413 doidling = 1;
8414 } else
8415 ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
8417 for (;;) {
8418 for (i = 0; i < NUM_DCHANS; i++) {
8419 if (!pri->dchannels[i])
8420 break;
8421 fds[i].fd = pri->fds[i];
8422 fds[i].events = POLLIN | POLLPRI;
8423 fds[i].revents = 0;
8425 numdchans = i;
8426 time(&t);
8427 ast_mutex_lock(&pri->lock);
8428 if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->resetinterval > 0)) {
8429 if (pri->resetting && pri_is_up(pri)) {
8430 if (pri->resetpos < 0)
8431 pri_check_restart(pri);
8432 } else {
8433 if (!pri->resetting && (t - pri->lastreset) >= pri->resetinterval) {
8434 pri->resetting = 1;
8435 pri->resetpos = -1;
8439 /* Look for any idle channels if appropriate */
8440 if (doidling && pri_is_up(pri)) {
8441 nextidle = -1;
8442 haveidles = 0;
8443 activeidles = 0;
8444 for (x = pri->numchans; x >= 0; x--) {
8445 if (pri->pvts[x] && !pri->pvts[x]->owner &&
8446 !pri->pvts[x]->call) {
8447 if (haveidles < pri->minunused) {
8448 haveidles++;
8449 } else if (!pri->pvts[x]->resetting) {
8450 nextidle = x;
8451 break;
8453 } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
8454 activeidles++;
8456 if (nextidle > -1) {
8457 if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
8458 /* Don't create a new idle call more than once per second */
8459 snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
8460 idle = zt_request("Zap", AST_FORMAT_ULAW, idlen, &cause);
8461 if (idle) {
8462 pri->pvts[nextidle]->isidlecall = 1;
8463 if (ast_pthread_create_background(&p, NULL, do_idle_thread, idle)) {
8464 ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
8465 zt_hangup(idle);
8467 } else
8468 ast_log(LOG_WARNING, "Unable to request channel 'Zap/%s' for idle call\n", idlen);
8469 gettimeofday(&lastidle, NULL);
8471 } else if ((haveidles < pri->minunused) &&
8472 (activeidles > pri->minidle)) {
8473 /* Mark something for hangup if there is something
8474 that can be hungup */
8475 for (x = pri->numchans; x >= 0; x--) {
8476 /* find a candidate channel */
8477 if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
8478 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8479 haveidles++;
8480 /* Stop if we have enough idle channels or
8481 can't spare any more active idle ones */
8482 if ((haveidles >= pri->minunused) ||
8483 (activeidles <= pri->minidle))
8484 break;
8489 /* Start with reasonable max */
8490 lowest = ast_tv(60, 0);
8491 for (i = 0; i < NUM_DCHANS; i++) {
8492 /* Find lowest available d-channel */
8493 if (!pri->dchannels[i])
8494 break;
8495 if ((next = pri_schedule_next(pri->dchans[i]))) {
8496 /* We need relative time here */
8497 tv = ast_tvsub(*next, ast_tvnow());
8498 if (tv.tv_sec < 0) {
8499 tv = ast_tv(0,0);
8501 if (doidling || pri->resetting) {
8502 if (tv.tv_sec > 1) {
8503 tv = ast_tv(1, 0);
8505 } else {
8506 if (tv.tv_sec > 60) {
8507 tv = ast_tv(60, 0);
8510 } else if (doidling || pri->resetting) {
8511 /* Make sure we stop at least once per second if we're
8512 monitoring idle channels */
8513 tv = ast_tv(1,0);
8514 } else {
8515 /* Don't poll for more than 60 seconds */
8516 tv = ast_tv(60, 0);
8518 if (!i || ast_tvcmp(tv, lowest) < 0) {
8519 lowest = tv;
8522 ast_mutex_unlock(&pri->lock);
8524 e = NULL;
8525 res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
8527 ast_mutex_lock(&pri->lock);
8528 if (!res) {
8529 for (which = 0; which < NUM_DCHANS; which++) {
8530 if (!pri->dchans[which])
8531 break;
8532 /* Just a timeout, run the scheduler */
8533 e = pri_schedule_run(pri->dchans[which]);
8534 if (e)
8535 break;
8537 } else if (res > -1) {
8538 for (which = 0; which < NUM_DCHANS; which++) {
8539 if (!pri->dchans[which])
8540 break;
8541 if (fds[which].revents & POLLPRI) {
8542 /* Check for an event */
8543 x = 0;
8544 res = ioctl(pri->fds[which], ZT_GETEVENT, &x);
8545 if (x)
8546 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);
8547 /* Keep track of alarm state */
8548 if (x == ZT_EVENT_ALARM) {
8549 pri->dchanavail[which] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
8550 pri_find_dchan(pri);
8551 } else if (x == ZT_EVENT_NOALARM) {
8552 pri->dchanavail[which] |= DCHAN_NOTINALARM;
8553 pri_restart(pri->dchans[which]);
8556 if (option_debug)
8557 ast_log(LOG_DEBUG, "Got event %s (%d) on D-channel for span %d\n", event2str(x), x, pri->span);
8558 } else if (fds[which].revents & POLLIN) {
8559 e = pri_check_event(pri->dchans[which]);
8561 if (e)
8562 break;
8564 } else if (errno != EINTR)
8565 ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
8567 if (e) {
8568 if (pri->debug)
8569 pri_dump_event(pri->dchans[which], e);
8571 if (e->e != PRI_EVENT_DCHAN_DOWN) {
8572 if (!(pri->dchanavail[which] & DCHAN_UP)) {
8573 if (option_verbose > 1)
8574 ast_verbose(VERBOSE_PREFIX_2 "%s D-Channel on span %d up\n", pri_order(which), pri->span);
8576 pri->dchanavail[which] |= DCHAN_UP;
8577 } else {
8578 if (pri->dchanavail[which] & DCHAN_UP) {
8579 if (option_verbose > 1)
8580 ast_verbose(VERBOSE_PREFIX_2 "%s D-Channel on span %d down\n", pri_order(which), pri->span);
8582 pri->dchanavail[which] &= ~DCHAN_UP;
8585 if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
8586 /* Must be an NFAS group that has the secondary dchan active */
8587 pri->pri = pri->dchans[which];
8589 switch (e->e) {
8590 case PRI_EVENT_DCHAN_UP:
8591 if (!pri->pri) pri_find_dchan(pri);
8593 /* Note presense of D-channel */
8594 time(&pri->lastreset);
8596 /* Restart in 5 seconds */
8597 if (pri->resetinterval > -1) {
8598 pri->lastreset -= pri->resetinterval;
8599 pri->lastreset += 5;
8601 pri->resetting = 0;
8602 /* Take the channels from inalarm condition */
8603 for (i = 0; i < pri->numchans; i++)
8604 if (pri->pvts[i]) {
8605 pri->pvts[i]->inalarm = 0;
8607 break;
8608 case PRI_EVENT_DCHAN_DOWN:
8609 pri_find_dchan(pri);
8610 if (!pri_is_up(pri)) {
8611 pri->resetting = 0;
8612 /* Hangup active channels and put them in alarm mode */
8613 for (i = 0; i < pri->numchans; i++) {
8614 struct zt_pvt *p = pri->pvts[i];
8615 if (p) {
8616 if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
8617 /* T309 is not enabled : hangup calls when alarm occurs */
8618 if (p->call) {
8619 if (p->pri && p->pri->pri) {
8620 pri_hangup(p->pri->pri, p->call, -1);
8621 pri_destroycall(p->pri->pri, p->call);
8622 p->call = NULL;
8623 } else
8624 ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
8626 if (p->realcall) {
8627 pri_hangup_all(p->realcall, pri);
8628 } else if (p->owner)
8629 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8631 p->inalarm = 1;
8635 break;
8636 case PRI_EVENT_RESTART:
8637 if (e->restart.channel > -1) {
8638 chanpos = pri_find_principle(pri, e->restart.channel);
8639 if (chanpos < 0)
8640 ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
8641 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
8642 else {
8643 if (option_verbose > 2)
8644 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d restarted on span %d\n",
8645 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
8646 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8647 if (pri->pvts[chanpos]->call) {
8648 pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
8649 pri->pvts[chanpos]->call = NULL;
8651 /* Force soft hangup if appropriate */
8652 if (pri->pvts[chanpos]->realcall)
8653 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
8654 else if (pri->pvts[chanpos]->owner)
8655 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8656 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8658 } else {
8659 if (option_verbose > 2)
8660 ast_verbose(VERBOSE_PREFIX_2 "Restart on requested on entire span %d\n", pri->span);
8661 for (x = 0; x < pri->numchans; x++)
8662 if (pri->pvts[x]) {
8663 ast_mutex_lock(&pri->pvts[x]->lock);
8664 if (pri->pvts[x]->call) {
8665 pri_destroycall(pri->pri, pri->pvts[x]->call);
8666 pri->pvts[x]->call = NULL;
8668 if (pri->pvts[chanpos]->realcall)
8669 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
8670 else if (pri->pvts[x]->owner)
8671 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8672 ast_mutex_unlock(&pri->pvts[x]->lock);
8675 break;
8676 case PRI_EVENT_KEYPAD_DIGIT:
8677 chanpos = pri_find_principle(pri, e->digit.channel);
8678 if (chanpos < 0) {
8679 ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
8680 PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
8681 } else {
8682 chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
8683 if (chanpos > -1) {
8684 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8685 /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
8686 if (pri->overlapdial && pri->pvts[chanpos]->call==e->digit.call && pri->pvts[chanpos]->owner) {
8687 /* how to do that */
8688 int digitlen = strlen(e->digit.digits);
8689 char digit;
8690 int i;
8691 for (i = 0; i < digitlen; i++) {
8692 digit = e->digit.digits[i];
8694 struct ast_frame f = { AST_FRAME_DTMF, digit, };
8695 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8699 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8702 break;
8704 case PRI_EVENT_INFO_RECEIVED:
8705 chanpos = pri_find_principle(pri, e->ring.channel);
8706 if (chanpos < 0) {
8707 ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
8708 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8709 } else {
8710 chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
8711 if (chanpos > -1) {
8712 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8713 /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
8714 if (pri->overlapdial && pri->pvts[chanpos]->call==e->ring.call && pri->pvts[chanpos]->owner) {
8715 /* how to do that */
8716 int digitlen = strlen(e->ring.callednum);
8717 char digit;
8718 int i;
8719 for (i = 0; i < digitlen; i++) {
8720 digit = e->ring.callednum[i];
8722 struct ast_frame f = { AST_FRAME_DTMF, digit, };
8723 zap_queue_frame(pri->pvts[chanpos], &f, pri);
8727 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8730 break;
8731 case PRI_EVENT_RING:
8732 crv = NULL;
8733 if (e->ring.channel == -1)
8734 chanpos = pri_find_empty_chan(pri, 1);
8735 else
8736 chanpos = pri_find_principle(pri, e->ring.channel);
8737 /* if no channel specified find one empty */
8738 if (chanpos < 0) {
8739 ast_log(LOG_WARNING, "Ring requested on unconfigured channel %d/%d span %d\n",
8740 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8741 } else {
8742 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8743 if (pri->pvts[chanpos]->owner) {
8744 if (pri->pvts[chanpos]->call == e->ring.call) {
8745 ast_log(LOG_WARNING, "Duplicate setup requested on channel %d/%d already in use on span %d\n",
8746 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8747 break;
8748 } else {
8749 /* This is where we handle initial glare */
8750 ast_log(LOG_DEBUG, "Ring requested on channel %d/%d already in use or previously requested on span %d. Attempting to renegotiating channel.\n",
8751 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
8752 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8753 chanpos = -1;
8756 if (chanpos > -1)
8757 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8759 if ((chanpos < 0) && (e->ring.flexible))
8760 chanpos = pri_find_empty_chan(pri, 1);
8761 if (chanpos > -1) {
8762 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8763 if (pri->switchtype == PRI_SWITCH_GR303_TMC) {
8764 /* Should be safe to lock CRV AFAIK while bearer is still locked */
8765 crv = pri_find_crv(pri, pri_get_crv(pri->pri, e->ring.call, NULL));
8766 if (crv)
8767 ast_mutex_lock(&crv->lock);
8768 if (!crv || crv->owner) {
8769 pri->pvts[chanpos]->call = NULL;
8770 if (crv) {
8771 if (crv->owner)
8772 crv->owner->_softhangup |= AST_SOFTHANGUP_DEV;
8773 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);
8774 } else
8775 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);
8776 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_INVALID_CALL_REFERENCE);
8777 if (crv)
8778 ast_mutex_unlock(&crv->lock);
8779 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8780 break;
8783 pri->pvts[chanpos]->call = e->ring.call;
8784 apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri, e->ring.callingnum, e->ring.callingplan);
8785 if (pri->pvts[chanpos]->use_callerid) {
8786 ast_shrink_phone_number(plancallingnum);
8787 ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
8788 #ifdef PRI_ANI
8789 if (!ast_strlen_zero(e->ring.callingani)) {
8790 apply_plan_to_number(plancallingani, sizeof(plancallingani), pri, e->ring.callingani, e->ring.callingplanani);
8791 ast_shrink_phone_number(plancallingani);
8792 ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani, sizeof(pri->pvts[chanpos]->cid_ani));
8793 } else {
8794 pri->pvts[chanpos]->cid_ani[0] = '\0';
8796 #endif
8797 ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
8798 pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
8799 } else {
8800 pri->pvts[chanpos]->cid_num[0] = '\0';
8801 pri->pvts[chanpos]->cid_ani[0] = '\0';
8802 pri->pvts[chanpos]->cid_name[0] = '\0';
8803 pri->pvts[chanpos]->cid_ton = 0;
8805 apply_plan_to_number(pri->pvts[chanpos]->rdnis, sizeof(pri->pvts[chanpos]->rdnis), pri,
8806 e->ring.redirectingnum, e->ring.callingplanrdnis);
8807 /* If immediate=yes go to s|1 */
8808 if (pri->pvts[chanpos]->immediate) {
8809 if (option_verbose > 2)
8810 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of immediate=yes\n");
8811 pri->pvts[chanpos]->exten[0] = 's';
8812 pri->pvts[chanpos]->exten[1] = '\0';
8814 /* Get called number */
8815 else if (!ast_strlen_zero(e->ring.callednum)) {
8816 ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
8817 ast_copy_string(pri->pvts[chanpos]->dnid, e->ring.callednum, sizeof(pri->pvts[chanpos]->dnid));
8818 } else if (pri->overlapdial)
8819 pri->pvts[chanpos]->exten[0] = '\0';
8820 else {
8821 /* Some PRI circuits are set up to send _no_ digits. Handle them as 's'. */
8822 pri->pvts[chanpos]->exten[0] = 's';
8823 pri->pvts[chanpos]->exten[1] = '\0';
8825 /* Set DNID on all incoming calls -- even immediate */
8826 if (!ast_strlen_zero(e->ring.callednum))
8827 ast_copy_string(pri->pvts[chanpos]->dnid, e->ring.callednum, sizeof(pri->pvts[chanpos]->dnid));
8828 /* No number yet, but received "sending complete"? */
8829 if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
8830 if (option_verbose > 2)
8831 ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of Complete received\n");
8832 pri->pvts[chanpos]->exten[0] = 's';
8833 pri->pvts[chanpos]->exten[1] = '\0';
8835 /* Make sure extension exists (or in overlap dial mode, can exist) */
8836 if ((pri->overlapdial && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
8837 ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
8838 /* Setup law */
8839 int law;
8840 if (pri->switchtype != PRI_SWITCH_GR303_TMC) {
8841 /* Set to audio mode at this point */
8842 law = 1;
8843 if (ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &law) == -1)
8844 ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", pri->pvts[chanpos]->channel, law);
8846 if (e->ring.layer1 == PRI_LAYER_1_ALAW)
8847 law = ZT_LAW_ALAW;
8848 else
8849 law = ZT_LAW_MULAW;
8850 res = zt_setlaw(pri->pvts[chanpos]->subs[SUB_REAL].zfd, law);
8851 if (res < 0)
8852 ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pri->pvts[chanpos]->channel);
8853 res = set_actual_gain(pri->pvts[chanpos]->subs[SUB_REAL].zfd, 0, pri->pvts[chanpos]->rxgain, pri->pvts[chanpos]->txgain, law);
8854 if (res < 0)
8855 ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pri->pvts[chanpos]->channel);
8856 if (e->ring.complete || !pri->overlapdial) {
8857 /* Just announce proceeding */
8858 pri->pvts[chanpos]->proceeding = 1;
8859 pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
8860 } else {
8861 if (pri->switchtype != PRI_SWITCH_GR303_TMC)
8862 pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
8863 else
8864 pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
8866 /* Get the use_callingpres state */
8867 pri->pvts[chanpos]->callingpres = e->ring.callingpres;
8869 /* Start PBX */
8870 if (!e->ring.complete && pri->overlapdial && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
8871 /* Release the PRI lock while we create the channel */
8872 ast_mutex_unlock(&pri->lock);
8873 if (crv) {
8874 /* Set bearer and such */
8875 pri_assign_bearer(crv, pri, pri->pvts[chanpos]);
8876 c = zt_new(crv, AST_STATE_RESERVED, 0, SUB_REAL, law, e->ring.ctype);
8877 pri->pvts[chanpos]->owner = &inuse;
8878 ast_log(LOG_DEBUG, "Started up crv %d:%d on bearer channel %d\n", pri->trunkgroup, crv->channel, crv->bearer->channel);
8879 } else {
8880 c = zt_new(pri->pvts[chanpos], AST_STATE_RESERVED, 0, SUB_REAL, law, e->ring.ctype);
8883 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8885 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
8886 pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
8888 if (e->ring.ani2 >= 0) {
8889 snprintf(ani2str, 5, "%.2d", e->ring.ani2);
8890 pbx_builtin_setvar_helper(c, "ANI2", ani2str);
8893 #ifdef SUPPORT_USERUSER
8894 if (!ast_strlen_zero(e->ring.useruserinfo)) {
8895 pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
8897 #endif
8899 snprintf(calledtonstr, sizeof(calledtonstr)-1, "%d", e->ring.calledplan);
8900 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
8901 if (e->ring.redirectingreason >= 0)
8902 pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
8904 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8905 ast_mutex_lock(&pri->lock);
8907 pthread_attr_init(&attr);
8908 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
8909 if (c && !ast_pthread_create(&threadid, &attr, ss_thread, c)) {
8910 if (option_verbose > 2)
8911 ast_verbose(VERBOSE_PREFIX_3 "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
8912 plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
8913 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8914 } else {
8915 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
8916 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8917 if (c)
8918 ast_hangup(c);
8919 else {
8920 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
8921 pri->pvts[chanpos]->call = NULL;
8924 pthread_attr_destroy(&attr);
8925 } else {
8926 ast_mutex_unlock(&pri->lock);
8927 /* Release PRI lock while we create the channel */
8928 c = zt_new(pri->pvts[chanpos], AST_STATE_RING, 1, SUB_REAL, law, e->ring.ctype);
8929 if (c) {
8930 char calledtonstr[10];
8932 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8934 if (e->ring.ani2 >= 0) {
8935 snprintf(ani2str, 5, "%d", e->ring.ani2);
8936 pbx_builtin_setvar_helper(c, "ANI2", ani2str);
8939 #ifdef SUPPORT_USERUSER
8940 if (!ast_strlen_zero(e->ring.useruserinfo)) {
8941 pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
8943 #endif
8945 if (e->ring.redirectingreason >= 0)
8946 pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
8948 snprintf(calledtonstr, sizeof(calledtonstr)-1, "%d", e->ring.calledplan);
8949 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
8951 ast_mutex_lock(&pri->pvts[chanpos]->lock);
8952 ast_mutex_lock(&pri->lock);
8954 if (option_verbose > 2)
8955 ast_verbose(VERBOSE_PREFIX_3 "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
8956 plancallingnum, pri->pvts[chanpos]->exten,
8957 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8958 zt_enable_ec(pri->pvts[chanpos]);
8959 } else {
8961 ast_mutex_lock(&pri->lock);
8963 ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
8964 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
8965 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
8966 pri->pvts[chanpos]->call = NULL;
8969 } else {
8970 if (option_verbose > 2)
8971 ast_verbose(VERBOSE_PREFIX_3 "Extension '%s' in context '%s' from '%s' does not exist. Rejecting call on channel %d/%d, span %d\n",
8972 pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context, pri->pvts[chanpos]->cid_num, pri->pvts[chanpos]->logicalspan,
8973 pri->pvts[chanpos]->prioffset, pri->span);
8974 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
8975 pri->pvts[chanpos]->call = NULL;
8976 pri->pvts[chanpos]->exten[0] = '\0';
8978 if (crv)
8979 ast_mutex_unlock(&crv->lock);
8980 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
8981 } else {
8982 if (e->ring.flexible)
8983 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
8984 else
8985 pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
8987 break;
8988 case PRI_EVENT_RINGING:
8989 chanpos = pri_find_principle(pri, e->ringing.channel);
8990 if (chanpos < 0) {
8991 ast_log(LOG_WARNING, "Ringing requested on unconfigured channel %d/%d span %d\n",
8992 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
8993 } else {
8994 chanpos = pri_fixup_principle(pri, chanpos, e->ringing.call);
8995 if (chanpos < 0) {
8996 ast_log(LOG_WARNING, "Ringing requested on channel %d/%d not in use on span %d\n",
8997 PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
8998 } else {
8999 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9000 if (ast_strlen_zero(pri->pvts[chanpos]->dop.dialstr)) {
9001 zt_enable_ec(pri->pvts[chanpos]);
9002 pri->pvts[chanpos]->subs[SUB_REAL].needringing = 1;
9003 pri->pvts[chanpos]->alerting = 1;
9004 } else
9005 ast_log(LOG_DEBUG, "Deferring ringing notification because of extra digits to dial...\n");
9006 #ifdef PRI_PROGRESS_MASK
9007 if (e->ringing.progressmask & PRI_PROG_INBAND_AVAILABLE) {
9008 #else
9009 if (e->ringing.progress == 8) {
9010 #endif
9011 /* Now we can do call progress detection */
9012 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
9013 /* RINGING detection isn't required because we got ALERTING signal */
9014 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features & ~DSP_PROGRESS_RINGING);
9015 pri->pvts[chanpos]->dsp_features = 0;
9019 #ifdef SUPPORT_USERUSER
9020 if (!ast_strlen_zero(e->ringing.useruserinfo)) {
9021 struct ast_channel *owner = pri->pvts[chanpos]->owner;
9022 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9023 pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->ringing.useruserinfo);
9024 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9026 #endif
9028 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9031 break;
9032 case PRI_EVENT_PROGRESS:
9033 /* Get chan value if e->e is not PRI_EVNT_RINGING */
9034 chanpos = pri_find_principle(pri, e->proceeding.channel);
9035 if (chanpos > -1) {
9036 #ifdef PRI_PROGRESS_MASK
9037 if ((!pri->pvts[chanpos]->progress) || (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE)) {
9038 #else
9039 if ((!pri->pvts[chanpos]->progress) || (e->proceeding.progress == 8)) {
9040 #endif
9041 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, };
9043 if (e->proceeding.cause > -1) {
9044 if (option_verbose > 2)
9045 ast_verbose(VERBOSE_PREFIX_3 "PROGRESS with cause code %d received\n", e->proceeding.cause);
9047 /* Work around broken, out of spec USER_BUSY cause in a progress message */
9048 if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
9049 if (pri->pvts[chanpos]->owner) {
9050 if (option_verbose > 2)
9051 ast_verbose(VERBOSE_PREFIX_3 "PROGRESS with 'user busy' received, signaling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
9053 pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
9054 f.subclass = AST_CONTROL_BUSY;
9059 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9060 ast_log(LOG_DEBUG, "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
9061 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
9062 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9063 #ifdef PRI_PROGRESS_MASK
9064 if (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE) {
9065 #else
9066 if (e->proceeding.progress == 8) {
9067 #endif
9068 /* Now we can do call progress detection */
9069 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
9070 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
9071 pri->pvts[chanpos]->dsp_features = 0;
9074 pri->pvts[chanpos]->progress = 1;
9075 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9078 break;
9079 case PRI_EVENT_PROCEEDING:
9080 chanpos = pri_find_principle(pri, e->proceeding.channel);
9081 if (chanpos > -1) {
9082 if (!pri->pvts[chanpos]->proceeding) {
9083 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROCEEDING, };
9085 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9086 ast_log(LOG_DEBUG, "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
9087 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
9088 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9089 #ifdef PRI_PROGRESS_MASK
9090 if (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE) {
9091 #else
9092 if (e->proceeding.progress == 8) {
9093 #endif
9094 /* Now we can do call progress detection */
9095 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
9096 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
9097 pri->pvts[chanpos]->dsp_features = 0;
9099 /* Bring voice path up */
9100 f.subclass = AST_CONTROL_PROGRESS;
9101 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9103 pri->pvts[chanpos]->proceeding = 1;
9104 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9107 break;
9108 case PRI_EVENT_FACNAME:
9109 chanpos = pri_find_principle(pri, e->facname.channel);
9110 if (chanpos < 0) {
9111 ast_log(LOG_WARNING, "Facility Name requested on unconfigured channel %d/%d span %d\n",
9112 PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
9113 } else {
9114 chanpos = pri_fixup_principle(pri, chanpos, e->facname.call);
9115 if (chanpos < 0) {
9116 ast_log(LOG_WARNING, "Facility Name requested on channel %d/%d not in use on span %d\n",
9117 PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
9118 } else {
9119 /* Re-use *69 field for PRI */
9120 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9121 ast_copy_string(pri->pvts[chanpos]->lastcid_num, e->facname.callingnum, sizeof(pri->pvts[chanpos]->lastcid_num));
9122 ast_copy_string(pri->pvts[chanpos]->lastcid_name, e->facname.callingname, sizeof(pri->pvts[chanpos]->lastcid_name));
9123 pri->pvts[chanpos]->subs[SUB_REAL].needcallerid =1;
9124 zt_enable_ec(pri->pvts[chanpos]);
9125 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9128 break;
9129 case PRI_EVENT_ANSWER:
9130 chanpos = pri_find_principle(pri, e->answer.channel);
9131 if (chanpos < 0) {
9132 ast_log(LOG_WARNING, "Answer on unconfigured channel %d/%d span %d\n",
9133 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
9134 } else {
9135 chanpos = pri_fixup_principle(pri, chanpos, e->answer.call);
9136 if (chanpos < 0) {
9137 ast_log(LOG_WARNING, "Answer requested on channel %d/%d not in use on span %d\n",
9138 PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
9139 } else {
9140 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9141 /* Now we can do call progress detection */
9143 /* We changed this so it turns on the DSP no matter what... progress or no progress.
9144 * By this time, we need DTMF detection and other features that were previously disabled
9145 * -- Matt F */
9146 if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
9147 ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
9148 pri->pvts[chanpos]->dsp_features = 0;
9150 if (pri->pvts[chanpos]->realcall && (pri->pvts[chanpos]->realcall->sig == SIG_FXSKS)) {
9151 ast_log(LOG_DEBUG, "Starting up GR-303 trunk now that we got CONNECT...\n");
9152 x = ZT_START;
9153 res = ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_HOOK, &x);
9154 if (res < 0) {
9155 if (errno != EINPROGRESS) {
9156 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
9159 } else if (!ast_strlen_zero(pri->pvts[chanpos]->dop.dialstr)) {
9160 pri->pvts[chanpos]->dialing = 1;
9161 /* Send any "w" waited stuff */
9162 res = ioctl(pri->pvts[chanpos]->subs[SUB_REAL].zfd, ZT_DIAL, &pri->pvts[chanpos]->dop);
9163 if (res < 0) {
9164 ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", pri->pvts[chanpos]->channel);
9165 pri->pvts[chanpos]->dop.dialstr[0] = '\0';
9166 } else
9167 ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", pri->pvts[chanpos]->dop.dialstr);
9168 pri->pvts[chanpos]->dop.dialstr[0] = '\0';
9169 } else if (pri->pvts[chanpos]->confirmanswer) {
9170 ast_log(LOG_DEBUG, "Waiting on answer confirmation on channel %d!\n", pri->pvts[chanpos]->channel);
9171 } else {
9172 pri->pvts[chanpos]->subs[SUB_REAL].needanswer =1;
9173 /* Enable echo cancellation if it's not on already */
9174 zt_enable_ec(pri->pvts[chanpos]);
9177 #ifdef SUPPORT_USERUSER
9178 if (!ast_strlen_zero(e->answer.useruserinfo)) {
9179 struct ast_channel *owner = pri->pvts[chanpos]->owner;
9180 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9181 pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->answer.useruserinfo);
9182 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9184 #endif
9186 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9189 break;
9190 case PRI_EVENT_HANGUP:
9191 chanpos = pri_find_principle(pri, e->hangup.channel);
9192 if (chanpos < 0) {
9193 ast_log(LOG_WARNING, "Hangup requested on unconfigured channel %d/%d span %d\n",
9194 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9195 } else {
9196 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9197 if (chanpos > -1) {
9198 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9199 if (!pri->pvts[chanpos]->alreadyhungup) {
9200 /* we're calling here zt_hangup so once we get there we need to clear p->call after calling pri_hangup */
9201 pri->pvts[chanpos]->alreadyhungup = 1;
9202 if (pri->pvts[chanpos]->realcall)
9203 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9204 else if (pri->pvts[chanpos]->owner) {
9205 /* Queue a BUSY instead of a hangup if our cause is appropriate */
9206 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
9207 if (pri->pvts[chanpos]->owner->_state == AST_STATE_UP)
9208 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9209 else {
9210 switch (e->hangup.cause) {
9211 case PRI_CAUSE_USER_BUSY:
9212 pri->pvts[chanpos]->subs[SUB_REAL].needbusy =1;
9213 break;
9214 case PRI_CAUSE_CALL_REJECTED:
9215 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
9216 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
9217 case PRI_CAUSE_SWITCH_CONGESTION:
9218 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
9219 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
9220 pri->pvts[chanpos]->subs[SUB_REAL].needcongestion =1;
9221 break;
9222 default:
9223 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9227 if (option_verbose > 2)
9228 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d got hangup, cause %d\n",
9229 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, e->hangup.cause);
9230 } else {
9231 pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
9232 pri->pvts[chanpos]->call = NULL;
9234 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
9235 if (option_verbose > 2)
9236 ast_verbose(VERBOSE_PREFIX_3 "Forcing restart of channel %d/%d on span %d since channel reported in use\n",
9237 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9238 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
9239 pri->pvts[chanpos]->resetting = 1;
9241 if (e->hangup.aoc_units > -1)
9242 if (option_verbose > 2)
9243 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
9244 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
9246 #ifdef SUPPORT_USERUSER
9247 if (pri->pvts[chanpos]->owner && !ast_strlen_zero(e->hangup.useruserinfo)) {
9248 struct ast_channel *owner = pri->pvts[chanpos]->owner;
9249 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9250 pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->hangup.useruserinfo);
9251 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9253 #endif
9255 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9256 } else {
9257 ast_log(LOG_WARNING, "Hangup on bad channel %d/%d on span %d\n",
9258 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9261 break;
9262 #ifndef PRI_EVENT_HANGUP_REQ
9263 #error please update libpri
9264 #endif
9265 case PRI_EVENT_HANGUP_REQ:
9266 chanpos = pri_find_principle(pri, e->hangup.channel);
9267 if (chanpos < 0) {
9268 ast_log(LOG_WARNING, "Hangup REQ requested on unconfigured channel %d/%d span %d\n",
9269 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9270 } else {
9271 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9272 if (chanpos > -1) {
9273 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9274 if (pri->pvts[chanpos]->realcall)
9275 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9276 else if (pri->pvts[chanpos]->owner) {
9277 pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
9278 if (pri->pvts[chanpos]->owner->_state == AST_STATE_UP)
9279 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9280 else {
9281 switch (e->hangup.cause) {
9282 case PRI_CAUSE_USER_BUSY:
9283 pri->pvts[chanpos]->subs[SUB_REAL].needbusy =1;
9284 break;
9285 case PRI_CAUSE_CALL_REJECTED:
9286 case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
9287 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
9288 case PRI_CAUSE_SWITCH_CONGESTION:
9289 case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
9290 case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
9291 pri->pvts[chanpos]->subs[SUB_REAL].needcongestion =1;
9292 break;
9293 default:
9294 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9297 if (option_verbose > 2)
9298 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d got hangup request, cause %d\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span, e->hangup.cause);
9299 if (e->hangup.aoc_units > -1)
9300 if (option_verbose > 2)
9301 ast_verbose(VERBOSE_PREFIX_3 "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
9302 pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
9303 } else {
9304 pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
9305 pri->pvts[chanpos]->call = NULL;
9307 if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
9308 if (option_verbose > 2)
9309 ast_verbose(VERBOSE_PREFIX_3 "Forcing restart of channel %d/%d span %d since channel reported in use\n",
9310 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9311 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
9312 pri->pvts[chanpos]->resetting = 1;
9315 #ifdef SUPPORT_USERUSER
9316 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
9317 struct ast_channel *owner = pri->pvts[chanpos]->owner;
9318 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9319 pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->hangup.useruserinfo);
9320 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9322 #endif
9324 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9325 } else {
9326 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);
9329 break;
9330 case PRI_EVENT_HANGUP_ACK:
9331 chanpos = pri_find_principle(pri, e->hangup.channel);
9332 if (chanpos < 0) {
9333 ast_log(LOG_WARNING, "Hangup ACK requested on unconfigured channel number %d/%d span %d\n",
9334 PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
9335 } else {
9336 chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
9337 if (chanpos > -1) {
9338 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9339 pri->pvts[chanpos]->call = NULL;
9340 pri->pvts[chanpos]->resetting = 0;
9341 if (pri->pvts[chanpos]->owner) {
9342 if (option_verbose > 2)
9343 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);
9346 #ifdef SUPPORT_USERUSER
9347 if (!ast_strlen_zero(e->hangup.useruserinfo)) {
9348 struct ast_channel *owner = pri->pvts[chanpos]->owner;
9349 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9350 pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->hangup.useruserinfo);
9351 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9353 #endif
9355 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9358 break;
9359 case PRI_EVENT_CONFIG_ERR:
9360 ast_log(LOG_WARNING, "PRI Error on span %d: %s\n", pri->trunkgroup, e->err.err);
9361 break;
9362 case PRI_EVENT_RESTART_ACK:
9363 chanpos = pri_find_principle(pri, e->restartack.channel);
9364 if (chanpos < 0) {
9365 /* Sometime switches (e.g. I421 / British Telecom) don't give us the
9366 channel number, so we have to figure it out... This must be why
9367 everybody resets exactly a channel at a time. */
9368 for (x = 0; x < pri->numchans; x++) {
9369 if (pri->pvts[x] && pri->pvts[x]->resetting) {
9370 chanpos = x;
9371 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9372 ast_log(LOG_DEBUG, "Assuming restart ack is really for channel %d/%d span %d\n", pri->pvts[chanpos]->logicalspan,
9373 pri->pvts[chanpos]->prioffset, pri->span);
9374 if (pri->pvts[chanpos]->realcall)
9375 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9376 else if (pri->pvts[chanpos]->owner) {
9377 ast_log(LOG_WARNING, "Got restart ack on channel %d/%d with owner on span %d\n", pri->pvts[chanpos]->logicalspan,
9378 pri->pvts[chanpos]->prioffset, pri->span);
9379 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9381 pri->pvts[chanpos]->resetting = 0;
9382 if (option_verbose > 2)
9383 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
9384 pri->pvts[chanpos]->prioffset, pri->span);
9385 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9386 if (pri->resetting)
9387 pri_check_restart(pri);
9388 break;
9391 if (chanpos < 0) {
9392 ast_log(LOG_WARNING, "Restart ACK requested on strange channel %d/%d span %d\n",
9393 PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
9395 } else {
9396 if (pri->pvts[chanpos]) {
9397 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9398 if (pri->pvts[chanpos]->realcall)
9399 pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
9400 else if (pri->pvts[chanpos]->owner) {
9401 ast_log(LOG_WARNING, "Got restart ack on channel %d/%d span %d with owner\n",
9402 PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
9403 pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
9405 pri->pvts[chanpos]->resetting = 0;
9406 if (option_verbose > 2)
9407 ast_verbose(VERBOSE_PREFIX_3 "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
9408 pri->pvts[chanpos]->prioffset, pri->span);
9409 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9410 if (pri->resetting)
9411 pri_check_restart(pri);
9414 break;
9415 case PRI_EVENT_SETUP_ACK:
9416 chanpos = pri_find_principle(pri, e->setup_ack.channel);
9417 if (chanpos < 0) {
9418 ast_log(LOG_WARNING, "Received SETUP_ACKNOWLEDGE on unconfigured channel %d/%d span %d\n",
9419 PRI_SPAN(e->setup_ack.channel), PRI_CHANNEL(e->setup_ack.channel), pri->span);
9420 } else {
9421 chanpos = pri_fixup_principle(pri, chanpos, e->setup_ack.call);
9422 if (chanpos > -1) {
9423 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9424 pri->pvts[chanpos]->setup_ack = 1;
9425 /* Send any queued digits */
9426 for (x = 0;x < strlen(pri->pvts[chanpos]->dialdest); x++) {
9427 ast_log(LOG_DEBUG, "Sending pending digit '%c'\n", pri->pvts[chanpos]->dialdest[x]);
9428 pri_information(pri->pri, pri->pvts[chanpos]->call,
9429 pri->pvts[chanpos]->dialdest[x]);
9431 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9432 } else
9433 ast_log(LOG_WARNING, "Unable to move channel %d!\n", e->setup_ack.channel);
9435 break;
9436 case PRI_EVENT_NOTIFY:
9437 chanpos = pri_find_principle(pri, e->notify.channel);
9438 if (chanpos < 0) {
9439 ast_log(LOG_WARNING, "Received NOTIFY on unconfigured channel %d/%d span %d\n",
9440 PRI_SPAN(e->notify.channel), PRI_CHANNEL(e->notify.channel), pri->span);
9441 } else {
9442 struct ast_frame f = { AST_FRAME_CONTROL, };
9443 ast_mutex_lock(&pri->pvts[chanpos]->lock);
9444 switch (e->notify.info) {
9445 case PRI_NOTIFY_REMOTE_HOLD:
9446 f.subclass = AST_CONTROL_HOLD;
9447 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9448 break;
9449 case PRI_NOTIFY_REMOTE_RETRIEVAL:
9450 f.subclass = AST_CONTROL_UNHOLD;
9451 zap_queue_frame(pri->pvts[chanpos], &f, pri);
9452 break;
9454 ast_mutex_unlock(&pri->pvts[chanpos]->lock);
9456 break;
9457 default:
9458 ast_log(LOG_DEBUG, "Event: %d\n", e->e);
9461 ast_mutex_unlock(&pri->lock);
9463 /* Never reached */
9464 return NULL;
9467 static int start_pri(struct zt_pri *pri)
9469 int res, x;
9470 ZT_PARAMS p;
9471 ZT_BUFFERINFO bi;
9472 struct zt_spaninfo si;
9473 int i;
9475 for (i = 0; i < NUM_DCHANS; i++) {
9476 if (!pri->dchannels[i])
9477 break;
9478 pri->fds[i] = open("/dev/zap/channel", O_RDWR, 0600);
9479 x = pri->dchannels[i];
9480 if ((pri->fds[i] < 0) || (ioctl(pri->fds[i],ZT_SPECIFY,&x) == -1)) {
9481 ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
9482 return -1;
9484 res = ioctl(pri->fds[i], ZT_GET_PARAMS, &p);
9485 if (res) {
9486 zt_close(pri->fds[i]);
9487 pri->fds[i] = -1;
9488 ast_log(LOG_ERROR, "Unable to get parameters for D-channel %d (%s)\n", x, strerror(errno));
9489 return -1;
9491 if ((p.sigtype != ZT_SIG_HDLCFCS) && (p.sigtype != ZT_SIG_HARDHDLC)) {
9492 zt_close(pri->fds[i]);
9493 pri->fds[i] = -1;
9494 ast_log(LOG_ERROR, "D-channel %d is not in HDLC/FCS mode. See /etc/zaptel.conf\n", x);
9495 return -1;
9497 memset(&si, 0, sizeof(si));
9498 res = ioctl(pri->fds[i], ZT_SPANSTAT, &si);
9499 if (res) {
9500 zt_close(pri->fds[i]);
9501 pri->fds[i] = -1;
9502 ast_log(LOG_ERROR, "Unable to get span state for D-channel %d (%s)\n", x, strerror(errno));
9504 if (!si.alarms)
9505 pri->dchanavail[i] |= DCHAN_NOTINALARM;
9506 else
9507 pri->dchanavail[i] &= ~DCHAN_NOTINALARM;
9508 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
9509 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
9510 bi.numbufs = 32;
9511 bi.bufsize = 1024;
9512 if (ioctl(pri->fds[i], ZT_SET_BUFINFO, &bi)) {
9513 ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d\n", x);
9514 zt_close(pri->fds[i]);
9515 pri->fds[i] = -1;
9516 return -1;
9518 pri->dchans[i] = pri_new(pri->fds[i], pri->nodetype, pri->switchtype);
9519 /* Force overlap dial if we're doing GR-303! */
9520 if (pri->switchtype == PRI_SWITCH_GR303_TMC)
9521 pri->overlapdial = 1;
9522 pri_set_overlapdial(pri->dchans[i],pri->overlapdial);
9523 /* Enslave to master if appropriate */
9524 if (i)
9525 pri_enslave(pri->dchans[0], pri->dchans[i]);
9526 if (!pri->dchans[i]) {
9527 zt_close(pri->fds[i]);
9528 pri->fds[i] = -1;
9529 ast_log(LOG_ERROR, "Unable to create PRI structure\n");
9530 return -1;
9532 pri_set_debug(pri->dchans[i], DEFAULT_PRI_DEBUG);
9533 pri_set_nsf(pri->dchans[i], pri->nsf);
9534 #ifdef PRI_GETSET_TIMERS
9535 for (x = 0; x < PRI_MAX_TIMERS; x++) {
9536 if (pritimers[x] != 0)
9537 pri_set_timer(pri->dchans[i], x, pritimers[x]);
9539 #endif
9541 /* Assume primary is the one we use */
9542 pri->pri = pri->dchans[0];
9543 pri->resetpos = -1;
9544 if (ast_pthread_create_background(&pri->master, NULL, pri_dchannel, pri)) {
9545 for (i = 0; i < NUM_DCHANS; i++) {
9546 if (!pri->dchannels[i])
9547 break;
9548 zt_close(pri->fds[i]);
9549 pri->fds[i] = -1;
9551 ast_log(LOG_ERROR, "Unable to spawn D-channel: %s\n", strerror(errno));
9552 return -1;
9554 return 0;
9557 static char *complete_span_helper(const char *line, const char *word, int pos, int state, int rpos)
9559 int which, span;
9560 char *ret = NULL;
9562 if (pos != rpos)
9563 return ret;
9565 for (which = span = 0; span < NUM_SPANS; span++) {
9566 if (pris[span].pri && ++which > state) {
9567 asprintf(&ret, "%d", span + 1); /* user indexes start from 1 */
9568 break;
9571 return ret;
9574 static char *complete_span_4(const char *line, const char *word, int pos, int state)
9576 return complete_span_helper(line,word,pos,state,3);
9579 static char *complete_span_5(const char *line, const char *word, int pos, int state)
9581 return complete_span_helper(line,word,pos,state,4);
9584 static int handle_pri_set_debug_file(int fd, int argc, char **argv)
9586 int myfd;
9588 if (!strncasecmp(argv[1], "set", 3)) {
9589 if (argc < 5)
9590 return RESULT_SHOWUSAGE;
9592 if (ast_strlen_zero(argv[4]))
9593 return RESULT_SHOWUSAGE;
9595 myfd = open(argv[4], O_CREAT|O_WRONLY, 0600);
9596 if (myfd < 0) {
9597 ast_cli(fd, "Unable to open '%s' for writing\n", argv[4]);
9598 return RESULT_SUCCESS;
9601 ast_mutex_lock(&pridebugfdlock);
9603 if (pridebugfd >= 0)
9604 close(pridebugfd);
9606 pridebugfd = myfd;
9607 ast_copy_string(pridebugfilename,argv[4],sizeof(pridebugfilename));
9609 ast_mutex_unlock(&pridebugfdlock);
9611 ast_cli(fd, "PRI debug output will be sent to '%s'\n", argv[4]);
9612 } else {
9613 /* Assume it is unset */
9614 ast_mutex_lock(&pridebugfdlock);
9615 close(pridebugfd);
9616 pridebugfd = -1;
9617 ast_cli(fd, "PRI debug output to file disabled\n");
9618 ast_mutex_unlock(&pridebugfdlock);
9621 return RESULT_SUCCESS;
9624 #ifdef HAVE_PRI_VERSION
9625 static int handle_pri_version(int fd, int agc, char *argv[]) {
9626 ast_cli(fd, "libpri version: %s\n", pri_get_version());
9627 return RESULT_SUCCESS;
9629 #endif
9631 static int handle_pri_debug(int fd, int argc, char *argv[])
9633 int span;
9634 int x;
9635 if (argc < 4) {
9636 return RESULT_SHOWUSAGE;
9638 span = atoi(argv[3]);
9639 if ((span < 1) || (span > NUM_SPANS)) {
9640 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[3], 1, NUM_SPANS);
9641 return RESULT_SUCCESS;
9643 if (!pris[span-1].pri) {
9644 ast_cli(fd, "No PRI running on span %d\n", span);
9645 return RESULT_SUCCESS;
9647 for (x = 0; x < NUM_DCHANS; x++) {
9648 if (pris[span-1].dchans[x])
9649 pri_set_debug(pris[span-1].dchans[x], PRI_DEBUG_APDU |
9650 PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q931_STATE |
9651 PRI_DEBUG_Q921_STATE);
9653 ast_cli(fd, "Enabled debugging on span %d\n", span);
9654 return RESULT_SUCCESS;
9659 static int handle_pri_no_debug(int fd, int argc, char *argv[])
9661 int span;
9662 int x;
9663 if (argc < 5)
9664 return RESULT_SHOWUSAGE;
9665 span = atoi(argv[4]);
9666 if ((span < 1) || (span > NUM_SPANS)) {
9667 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[4], 1, NUM_SPANS);
9668 return RESULT_SUCCESS;
9670 if (!pris[span-1].pri) {
9671 ast_cli(fd, "No PRI running on span %d\n", span);
9672 return RESULT_SUCCESS;
9674 for (x = 0; x < NUM_DCHANS; x++) {
9675 if (pris[span-1].dchans[x])
9676 pri_set_debug(pris[span-1].dchans[x], 0);
9678 ast_cli(fd, "Disabled debugging on span %d\n", span);
9679 return RESULT_SUCCESS;
9682 static int handle_pri_really_debug(int fd, int argc, char *argv[])
9684 int span;
9685 int x;
9686 if (argc < 5)
9687 return RESULT_SHOWUSAGE;
9688 span = atoi(argv[4]);
9689 if ((span < 1) || (span > NUM_SPANS)) {
9690 ast_cli(fd, "Invalid span %s. Should be a number %d to %d\n", argv[4], 1, NUM_SPANS);
9691 return RESULT_SUCCESS;
9693 if (!pris[span-1].pri) {
9694 ast_cli(fd, "No PRI running on span %d\n", span);
9695 return RESULT_SUCCESS;
9697 for (x = 0; x < NUM_DCHANS; x++) {
9698 if (pris[span-1].dchans[x])
9699 pri_set_debug(pris[span-1].dchans[x], PRI_DEBUG_APDU |
9700 PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q931_STATE |
9701 PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_STATE);
9703 ast_cli(fd, "Enabled EXTENSIVE debugging on span %d\n", span);
9704 return RESULT_SUCCESS;
9707 static void build_status(char *s, size_t len, int status, int active)
9709 if (!s || len < 1) {
9710 return;
9712 s[0] = '\0';
9713 if (status & DCHAN_PROVISIONED)
9714 strncat(s, "Provisioned, ", len - strlen(s) - 1);
9715 if (!(status & DCHAN_NOTINALARM))
9716 strncat(s, "In Alarm, ", len - strlen(s) - 1);
9717 if (status & DCHAN_UP)
9718 strncat(s, "Up", len - strlen(s) - 1);
9719 else
9720 strncat(s, "Down", len - strlen(s) - 1);
9721 if (active)
9722 strncat(s, ", Active", len - strlen(s) - 1);
9723 else
9724 strncat(s, ", Standby", len - strlen(s) - 1);
9725 s[len - 1] = '\0';
9728 static int handle_pri_show_spans(int fd, int argc, char *argv[])
9730 int span;
9731 int x;
9732 char status[256];
9733 if (argc != 3)
9734 return RESULT_SHOWUSAGE;
9736 for (span = 0; span < NUM_SPANS; span++) {
9737 if (pris[span].pri) {
9738 for (x = 0; x < NUM_DCHANS; x++) {
9739 if (pris[span].dchannels[x]) {
9740 build_status(status, sizeof(status), pris[span].dchanavail[x], pris[span].dchans[x] == pris[span].pri);
9741 ast_cli(fd, "PRI span %d/%d: %s\n", span + 1, x, status);
9746 return RESULT_SUCCESS;
9749 static int handle_pri_show_span(int fd, int argc, char *argv[])
9751 int span;
9752 int x;
9753 char status[256];
9754 if (argc < 4)
9755 return RESULT_SHOWUSAGE;
9756 span = atoi(argv[3]);
9757 if ((span < 1) || (span > NUM_SPANS)) {
9758 ast_cli(fd, "Invalid span '%s'. Should be a number from %d to %d\n", argv[3], 1, NUM_SPANS);
9759 return RESULT_SUCCESS;
9761 if (!pris[span-1].pri) {
9762 ast_cli(fd, "No PRI running on span %d\n", span);
9763 return RESULT_SUCCESS;
9765 for (x = 0; x < NUM_DCHANS; x++) {
9766 if (pris[span-1].dchannels[x]) {
9767 #ifdef PRI_DUMP_INFO_STR
9768 char *info_str = NULL;
9769 #endif
9770 ast_cli(fd, "%s D-channel: %d\n", pri_order(x), pris[span-1].dchannels[x]);
9771 build_status(status, sizeof(status), pris[span-1].dchanavail[x], pris[span-1].dchans[x] == pris[span-1].pri);
9772 ast_cli(fd, "Status: %s\n", status);
9773 #ifdef PRI_DUMP_INFO_STR
9774 info_str = pri_dump_info_str(pris[span-1].pri);
9775 if (info_str) {
9776 ast_cli(fd, "%s", info_str);
9777 free(info_str);
9779 #else
9780 pri_dump_info(pris[span-1].pri);
9781 #endif
9782 ast_cli(fd, "\n");
9785 return RESULT_SUCCESS;
9788 static int handle_pri_show_debug(int fd, int argc, char *argv[])
9790 int x;
9791 int span;
9792 int count=0;
9793 int debug=0;
9795 for (span = 0; span < NUM_SPANS; span++) {
9796 if (pris[span].pri) {
9797 for (x = 0; x < NUM_DCHANS; x++) {
9798 debug = 0;
9799 if (pris[span].dchans[x]) {
9800 debug = pri_get_debug(pris[span].dchans[x]);
9801 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" );
9802 count++;
9808 ast_mutex_lock(&pridebugfdlock);
9809 if (pridebugfd >= 0)
9810 ast_cli(fd, "Logging PRI debug to file %s\n", pridebugfilename);
9811 ast_mutex_unlock(&pridebugfdlock);
9813 if (!count)
9814 ast_cli(fd, "No debug set or no PRI running\n");
9815 return RESULT_SUCCESS;
9818 static const char pri_debug_help[] =
9819 "Usage: pri debug span <span>\n"
9820 " Enables debugging on a given PRI span\n";
9822 static const char pri_no_debug_help[] =
9823 "Usage: pri no debug span <span>\n"
9824 " Disables debugging on a given PRI span\n";
9826 static const char pri_really_debug_help[] =
9827 "Usage: pri intensive debug span <span>\n"
9828 " Enables debugging down to the Q.921 level\n";
9830 static const char pri_show_span_help[] =
9831 "Usage: pri show span <span>\n"
9832 " Displays PRI Information on a given PRI span\n";
9834 static const char pri_show_spans_help[] =
9835 "Usage: pri show spans\n"
9836 " Displays PRI Information\n";
9838 static struct ast_cli_entry zap_pri_cli[] = {
9839 { { "pri", "debug", "span", NULL },
9840 handle_pri_debug, "Enables PRI debugging on a span",
9841 pri_debug_help, complete_span_4 },
9843 { { "pri", "no", "debug", "span", NULL },
9844 handle_pri_no_debug, "Disables PRI debugging on a span",
9845 pri_no_debug_help, complete_span_5 },
9847 { { "pri", "intense", "debug", "span", NULL },
9848 handle_pri_really_debug, "Enables REALLY INTENSE PRI debugging",
9849 pri_really_debug_help, complete_span_5 },
9851 { { "pri", "show", "spans", NULL },
9852 handle_pri_show_spans, "Displays PRI Information",
9853 pri_show_spans_help },
9855 { { "pri", "show", "span", NULL },
9856 handle_pri_show_span, "Displays PRI Information",
9857 pri_show_span_help, complete_span_4 },
9859 { { "pri", "show", "debug", NULL },
9860 handle_pri_show_debug, "Displays current PRI debug settings" },
9862 { { "pri", "set", "debug", "file", NULL },
9863 handle_pri_set_debug_file, "Sends PRI debug output to the specified file" },
9865 { { "pri", "unset", "debug", "file", NULL },
9866 handle_pri_set_debug_file, "Ends PRI debug output to file" },
9868 #ifdef HAVE_PRI_VERSION
9869 { { "pri", "show", "version", NULL },
9870 handle_pri_version, "Displays version of libpri" },
9871 #endif
9874 #endif /* HAVE_PRI */
9876 static int zap_destroy_channel(int fd, int argc, char **argv)
9878 int channel;
9880 if (argc != 4)
9881 return RESULT_SHOWUSAGE;
9883 channel = atoi(argv[3]);
9885 return zap_destroy_channel_bynum(channel);
9888 static int setup_zap(int reload);
9889 static int zap_restart(void)
9891 if (option_verbose > 0)
9892 ast_verbose(VERBOSE_PREFIX_1 "Destroying channels and reloading zaptel configuration.\n");
9893 while (iflist) {
9894 if (option_debug)
9895 ast_log(LOG_DEBUG, "Destroying zaptel channel no. %d\n", iflist->channel);
9896 /* Also updates iflist: */
9897 destroy_channel(NULL, iflist, 1);
9899 if (option_debug)
9900 ast_log(LOG_DEBUG, "Channels destroyed. Now re-reading config.\n");
9901 if (setup_zap(0) != 0) {
9902 ast_log(LOG_WARNING, "Reload channels from zap config failed!\n");
9903 return 1;
9905 return 0;
9908 static int zap_restart_cmd(int fd, int argc, char **argv)
9910 if (argc != 2) {
9911 return RESULT_SHOWUSAGE;
9914 if (zap_restart() != 0)
9915 return RESULT_FAILURE;
9916 return RESULT_SUCCESS;
9919 static int action_zaprestart(struct mansession *s, const struct message *m)
9921 if (zap_restart() != 0) {
9922 astman_send_error(s, m, "Failed rereading zaptel configuration");
9923 return 1;
9925 astman_send_ack(s, m, "ZapRestart: Success");
9926 return 0;
9929 static int zap_show_channels(int fd, int argc, char **argv)
9931 #define FORMAT "%7s %-10.10s %-15.15s %-10.10s %-20.20s\n"
9932 #define FORMAT2 "%7s %-10.10s %-15.15s %-10.10s %-20.20s\n"
9933 struct zt_pvt *tmp = NULL;
9934 char tmps[20] = "";
9935 ast_mutex_t *lock;
9936 struct zt_pvt *start;
9937 #ifdef HAVE_PRI
9938 int trunkgroup;
9939 struct zt_pri *pri = NULL;
9940 int x;
9941 #endif
9943 lock = &iflock;
9944 start = iflist;
9946 #ifdef HAVE_PRI
9947 if (argc == 4) {
9948 if ((trunkgroup = atoi(argv[3])) < 1)
9949 return RESULT_SHOWUSAGE;
9950 for (x = 0; x < NUM_SPANS; x++) {
9951 if (pris[x].trunkgroup == trunkgroup) {
9952 pri = pris + x;
9953 break;
9956 if (pri) {
9957 start = pri->crvs;
9958 lock = &pri->lock;
9959 } else {
9960 ast_cli(fd, "No such trunk group %d\n", trunkgroup);
9961 return RESULT_FAILURE;
9963 } else
9964 #endif
9965 if (argc != 3)
9966 return RESULT_SHOWUSAGE;
9968 ast_mutex_lock(lock);
9969 #ifdef HAVE_PRI
9970 ast_cli(fd, FORMAT2, pri ? "CRV" : "Chan", "Extension", "Context", "Language", "MOH Interpret");
9971 #else
9972 ast_cli(fd, FORMAT2, "Chan", "Extension", "Context", "Language", "MOH Interpret");
9973 #endif
9975 tmp = start;
9976 while (tmp) {
9977 if (tmp->channel > 0) {
9978 snprintf(tmps, sizeof(tmps), "%d", tmp->channel);
9979 } else
9980 ast_copy_string(tmps, "pseudo", sizeof(tmps));
9981 ast_cli(fd, FORMAT, tmps, tmp->exten, tmp->context, tmp->language, tmp->mohinterpret);
9982 tmp = tmp->next;
9984 ast_mutex_unlock(lock);
9985 return RESULT_SUCCESS;
9986 #undef FORMAT
9987 #undef FORMAT2
9990 static int zap_show_channel(int fd, int argc, char **argv)
9992 int channel;
9993 struct zt_pvt *tmp = NULL;
9994 ZT_CONFINFO ci;
9995 ZT_PARAMS ps;
9996 int x;
9997 ast_mutex_t *lock;
9998 struct zt_pvt *start;
9999 #ifdef HAVE_PRI
10000 char *c;
10001 int trunkgroup;
10002 struct zt_pri *pri=NULL;
10003 #endif
10005 lock = &iflock;
10006 start = iflist;
10008 if (argc != 4)
10009 return RESULT_SHOWUSAGE;
10010 #ifdef HAVE_PRI
10011 if ((c = strchr(argv[3], ':'))) {
10012 if (sscanf(argv[3], "%d:%d", &trunkgroup, &channel) != 2)
10013 return RESULT_SHOWUSAGE;
10014 if ((trunkgroup < 1) || (channel < 1))
10015 return RESULT_SHOWUSAGE;
10016 for (x = 0; x < NUM_SPANS; x++) {
10017 if (pris[x].trunkgroup == trunkgroup) {
10018 pri = pris + x;
10019 break;
10022 if (pri) {
10023 start = pri->crvs;
10024 lock = &pri->lock;
10025 } else {
10026 ast_cli(fd, "No such trunk group %d\n", trunkgroup);
10027 return RESULT_FAILURE;
10029 } else
10030 #endif
10031 channel = atoi(argv[3]);
10033 ast_mutex_lock(lock);
10034 tmp = start;
10035 while (tmp) {
10036 if (tmp->channel == channel) {
10037 #ifdef HAVE_PRI
10038 if (pri)
10039 ast_cli(fd, "Trunk/CRV: %d/%d\n", trunkgroup, tmp->channel);
10040 else
10041 #endif
10042 ast_cli(fd, "Channel: %d\n", tmp->channel);
10043 ast_cli(fd, "File Descriptor: %d\n", tmp->subs[SUB_REAL].zfd);
10044 ast_cli(fd, "Span: %d\n", tmp->span);
10045 ast_cli(fd, "Extension: %s\n", tmp->exten);
10046 ast_cli(fd, "Dialing: %s\n", tmp->dialing ? "yes" : "no");
10047 ast_cli(fd, "Context: %s\n", tmp->context);
10048 ast_cli(fd, "Caller ID: %s\n", tmp->cid_num);
10049 ast_cli(fd, "Calling TON: %d\n", tmp->cid_ton);
10050 ast_cli(fd, "Caller ID name: %s\n", tmp->cid_name);
10051 ast_cli(fd, "Destroy: %d\n", tmp->destroy);
10052 ast_cli(fd, "InAlarm: %d\n", tmp->inalarm);
10053 ast_cli(fd, "Signalling Type: %s\n", sig2str(tmp->sig));
10054 ast_cli(fd, "Radio: %d\n", tmp->radio);
10055 ast_cli(fd, "Owner: %s\n", tmp->owner ? tmp->owner->name : "<None>");
10056 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)" : "");
10057 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)" : "");
10058 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)" : "");
10059 ast_cli(fd, "Confno: %d\n", tmp->confno);
10060 ast_cli(fd, "Propagated Conference: %d\n", tmp->propconfno);
10061 ast_cli(fd, "Real in conference: %d\n", tmp->inconference);
10062 ast_cli(fd, "DSP: %s\n", tmp->dsp ? "yes" : "no");
10063 ast_cli(fd, "Relax DTMF: %s\n", tmp->dtmfrelax ? "yes" : "no");
10064 ast_cli(fd, "Dialing/CallwaitCAS: %d/%d\n", tmp->dialing, tmp->callwaitcas);
10065 ast_cli(fd, "Default law: %s\n", tmp->law == ZT_LAW_MULAW ? "ulaw" : tmp->law == ZT_LAW_ALAW ? "alaw" : "unknown");
10066 ast_cli(fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
10067 ast_cli(fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
10068 ast_cli(fd, "Echo Cancellation: %d taps%s, currently %s\n", tmp->echocancel, tmp->echocanbridged ? "" : " unless TDM bridged", tmp->echocanon ? "ON" : "OFF");
10069 if (tmp->master)
10070 ast_cli(fd, "Master Channel: %d\n", tmp->master->channel);
10071 for (x = 0; x < MAX_SLAVES; x++) {
10072 if (tmp->slaves[x])
10073 ast_cli(fd, "Slave Channel: %d\n", tmp->slaves[x]->channel);
10075 #ifdef HAVE_PRI
10076 if (tmp->pri) {
10077 ast_cli(fd, "PRI Flags: ");
10078 if (tmp->resetting)
10079 ast_cli(fd, "Resetting ");
10080 if (tmp->call)
10081 ast_cli(fd, "Call ");
10082 if (tmp->bearer)
10083 ast_cli(fd, "Bearer ");
10084 ast_cli(fd, "\n");
10085 if (tmp->logicalspan)
10086 ast_cli(fd, "PRI Logical Span: %d\n", tmp->logicalspan);
10087 else
10088 ast_cli(fd, "PRI Logical Span: Implicit\n");
10091 #endif
10092 memset(&ci, 0, sizeof(ci));
10093 ps.channo = tmp->channel;
10094 if (tmp->subs[SUB_REAL].zfd > -1) {
10095 if (!ioctl(tmp->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
10096 ast_cli(fd, "Actual Confinfo: Num/%d, Mode/0x%04x\n", ci.confno, ci.confmode);
10098 #ifdef ZT_GETCONFMUTE
10099 if (!ioctl(tmp->subs[SUB_REAL].zfd, ZT_GETCONFMUTE, &x)) {
10100 ast_cli(fd, "Actual Confmute: %s\n", x ? "Yes" : "No");
10102 #endif
10103 if (ioctl(tmp->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps) < 0) {
10104 ast_log(LOG_WARNING, "Failed to get parameters on channel %d\n", tmp->channel);
10105 } else {
10106 ast_cli(fd, "Hookstate (FXS only): %s\n", ps.rxisoffhook ? "Offhook" : "Onhook");
10109 ast_mutex_unlock(lock);
10110 return RESULT_SUCCESS;
10112 tmp = tmp->next;
10115 ast_cli(fd, "Unable to find given channel %d\n", channel);
10116 ast_mutex_unlock(lock);
10117 return RESULT_FAILURE;
10120 static char zap_show_cadences_help[] =
10121 "Usage: zap show cadences\n"
10122 " Shows all cadences currently defined\n";
10124 static int handle_zap_show_cadences(int fd, int argc, char *argv[])
10126 int i, j;
10127 for (i = 0; i < num_cadence; i++) {
10128 char output[1024];
10129 char tmp[16], tmp2[64];
10130 snprintf(tmp, sizeof(tmp), "r%d: ", i + 1);
10131 term_color(output, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(output));
10133 for (j = 0; j < 16; j++) {
10134 if (cadences[i].ringcadence[j] == 0)
10135 break;
10136 snprintf(tmp, sizeof(tmp), "%d", cadences[i].ringcadence[j]);
10137 if (cidrings[i] * 2 - 1 == j)
10138 term_color(tmp2, tmp, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp2) - 1);
10139 else
10140 term_color(tmp2, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(tmp2) - 1);
10141 if (j != 0)
10142 strncat(output, ",", sizeof(output) - strlen(output) - 1);
10143 strncat(output, tmp2, sizeof(output) - strlen(output) - 1);
10145 ast_cli(fd,"%s\n",output);
10147 return 0;
10150 /* Based on irqmiss.c */
10151 static int zap_show_status(int fd, int argc, char *argv[]) {
10152 #define FORMAT "%-40.40s %-10.10s %-10d %-10d %-10d\n"
10153 #define FORMAT2 "%-40.40s %-10.10s %-10.10s %-10.10s %-10.10s\n"
10155 int span;
10156 int res;
10157 char alarms[50];
10159 int ctl;
10160 ZT_SPANINFO s;
10162 ctl = open("/dev/zap/ctl", O_RDWR);
10163 if (ctl < 0) {
10164 ast_log(LOG_WARNING, "Unable to open /dev/zap/ctl: %s\n", strerror(errno));
10165 ast_cli(fd, "No Zaptel interface found.\n");
10166 return RESULT_FAILURE;
10168 ast_cli(fd, FORMAT2, "Description", "Alarms", "IRQ", "bpviol", "CRC4");
10170 for (span = 1; span < ZT_MAX_SPANS; ++span) {
10171 s.spanno = span;
10172 res = ioctl(ctl, ZT_SPANSTAT, &s);
10173 if (res) {
10174 continue;
10176 alarms[0] = '\0';
10177 if (s.alarms > 0) {
10178 if (s.alarms & ZT_ALARM_BLUE)
10179 strcat(alarms, "BLU/");
10180 if (s.alarms & ZT_ALARM_YELLOW)
10181 strcat(alarms, "YEL/");
10182 if (s.alarms & ZT_ALARM_RED)
10183 strcat(alarms, "RED/");
10184 if (s.alarms & ZT_ALARM_LOOPBACK)
10185 strcat(alarms, "LB/");
10186 if (s.alarms & ZT_ALARM_RECOVER)
10187 strcat(alarms, "REC/");
10188 if (s.alarms & ZT_ALARM_NOTOPEN)
10189 strcat(alarms, "NOP/");
10190 if (!strlen(alarms))
10191 strcat(alarms, "UUU/");
10192 if (strlen(alarms)) {
10193 /* Strip trailing / */
10194 alarms[strlen(alarms) - 1] = '\0';
10196 } else {
10197 if (s.numchans)
10198 strcpy(alarms, "OK");
10199 else
10200 strcpy(alarms, "UNCONFIGURED");
10203 ast_cli(fd, FORMAT, s.desc, alarms, s.irqmisses, s.bpvcount, s.crc4count);
10205 close(ctl);
10207 return RESULT_SUCCESS;
10208 #undef FORMAT
10209 #undef FORMAT2
10212 static char show_channels_usage[] =
10213 "Usage: zap show channels\n"
10214 " Shows a list of available channels\n";
10216 static char show_channel_usage[] =
10217 "Usage: zap show channel <chan num>\n"
10218 " Detailed information about a given channel\n";
10220 static char zap_show_status_usage[] =
10221 "Usage: zap show status\n"
10222 " Shows a list of Zaptel cards with status\n";
10224 static char destroy_channel_usage[] =
10225 "Usage: zap destroy channel <chan num>\n"
10226 " DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING. Immediately removes a given channel, whether it is in use or not\n";
10228 static char zap_restart_usage[] =
10229 "Usage: zap restart\n"
10230 " Restarts the zaptel channels: destroys them all and then\n"
10231 " re-reads them from zapata.conf.\n"
10232 " Note that this will STOP any running CALL on zaptel channels.\n"
10235 static struct ast_cli_entry zap_cli[] = {
10236 { { "zap", "show", "cadences", NULL },
10237 handle_zap_show_cadences, "List cadences",
10238 zap_show_cadences_help },
10240 { { "zap", "show", "channels", NULL},
10241 zap_show_channels, "Show active zapata channels",
10242 show_channels_usage },
10244 { { "zap", "show", "channel", NULL},
10245 zap_show_channel, "Show information on a channel",
10246 show_channel_usage },
10248 { { "zap", "destroy", "channel", NULL},
10249 zap_destroy_channel, "Destroy a channel",
10250 destroy_channel_usage },
10252 { { "zap", "restart", NULL},
10253 zap_restart_cmd, "Fully restart zaptel channels",
10254 zap_restart_usage },
10256 { { "zap", "show", "status", NULL},
10257 zap_show_status, "Show all Zaptel cards status",
10258 zap_show_status_usage },
10261 #define TRANSFER 0
10262 #define HANGUP 1
10264 static int zap_fake_event(struct zt_pvt *p, int mode)
10266 if (p) {
10267 switch (mode) {
10268 case TRANSFER:
10269 p->fake_event = ZT_EVENT_WINKFLASH;
10270 break;
10271 case HANGUP:
10272 p->fake_event = ZT_EVENT_ONHOOK;
10273 break;
10274 default:
10275 ast_log(LOG_WARNING, "I don't know how to handle transfer event with this: %d on channel %s\n",mode, p->owner->name);
10278 return 0;
10280 static struct zt_pvt *find_channel(int channel)
10282 struct zt_pvt *p = iflist;
10283 while (p) {
10284 if (p->channel == channel) {
10285 break;
10287 p = p->next;
10289 return p;
10292 static int action_zapdndon(struct mansession *s, const struct message *m)
10294 struct zt_pvt *p = NULL;
10295 const char *channel = astman_get_header(m, "ZapChannel");
10297 if (ast_strlen_zero(channel)) {
10298 astman_send_error(s, m, "No channel specified");
10299 return 0;
10301 p = find_channel(atoi(channel));
10302 if (!p) {
10303 astman_send_error(s, m, "No such channel");
10304 return 0;
10306 p->dnd = 1;
10307 astman_send_ack(s, m, "DND Enabled");
10308 return 0;
10311 static int action_zapdndoff(struct mansession *s, const struct message *m)
10313 struct zt_pvt *p = NULL;
10314 const char *channel = astman_get_header(m, "ZapChannel");
10316 if (ast_strlen_zero(channel)) {
10317 astman_send_error(s, m, "No channel specified");
10318 return 0;
10320 p = find_channel(atoi(channel));
10321 if (!p) {
10322 astman_send_error(s, m, "No such channel");
10323 return 0;
10325 p->dnd = 0;
10326 astman_send_ack(s, m, "DND Disabled");
10327 return 0;
10330 static int action_transfer(struct mansession *s, const struct message *m)
10332 struct zt_pvt *p = NULL;
10333 const char *channel = astman_get_header(m, "ZapChannel");
10335 if (ast_strlen_zero(channel)) {
10336 astman_send_error(s, m, "No channel specified");
10337 return 0;
10339 p = find_channel(atoi(channel));
10340 if (!p) {
10341 astman_send_error(s, m, "No such channel");
10342 return 0;
10344 zap_fake_event(p,TRANSFER);
10345 astman_send_ack(s, m, "ZapTransfer");
10346 return 0;
10349 static int action_transferhangup(struct mansession *s, const struct message *m)
10351 struct zt_pvt *p = NULL;
10352 const char *channel = astman_get_header(m, "ZapChannel");
10354 if (ast_strlen_zero(channel)) {
10355 astman_send_error(s, m, "No channel specified");
10356 return 0;
10358 p = find_channel(atoi(channel));
10359 if (!p) {
10360 astman_send_error(s, m, "No such channel");
10361 return 0;
10363 zap_fake_event(p,HANGUP);
10364 astman_send_ack(s, m, "ZapHangup");
10365 return 0;
10368 static int action_zapdialoffhook(struct mansession *s, const struct message *m)
10370 struct zt_pvt *p = NULL;
10371 const char *channel = astman_get_header(m, "ZapChannel");
10372 const char *number = astman_get_header(m, "Number");
10373 int i;
10375 if (ast_strlen_zero(channel)) {
10376 astman_send_error(s, m, "No channel specified");
10377 return 0;
10379 if (ast_strlen_zero(number)) {
10380 astman_send_error(s, m, "No number specified");
10381 return 0;
10383 p = find_channel(atoi(channel));
10384 if (!p) {
10385 astman_send_error(s, m, "No such channel");
10386 return 0;
10388 if (!p->owner) {
10389 astman_send_error(s, m, "Channel does not have it's owner");
10390 return 0;
10392 for (i = 0; i < strlen(number); i++) {
10393 struct ast_frame f = { AST_FRAME_DTMF, number[i] };
10394 zap_queue_frame(p, &f, NULL);
10396 astman_send_ack(s, m, "ZapDialOffhook");
10397 return 0;
10400 static int action_zapshowchannels(struct mansession *s, const struct message *m)
10402 struct zt_pvt *tmp = NULL;
10403 const char *id = astman_get_header(m, "ActionID");
10404 char idText[256] = "";
10406 astman_send_ack(s, m, "Zapata channel status will follow");
10407 if (!ast_strlen_zero(id))
10408 snprintf(idText, sizeof(idText) - 1, "ActionID: %s\r\n", id);
10410 ast_mutex_lock(&iflock);
10412 tmp = iflist;
10413 while (tmp) {
10414 if (tmp->channel > 0) {
10415 int alarm = get_alarms(tmp);
10416 astman_append(s,
10417 "Event: ZapShowChannels\r\n"
10418 "Channel: %d\r\n"
10419 "Signalling: %s\r\n"
10420 "Context: %s\r\n"
10421 "DND: %s\r\n"
10422 "Alarm: %s\r\n"
10423 "%s"
10424 "\r\n",
10425 tmp->channel, sig2str(tmp->sig), tmp->context,
10426 tmp->dnd ? "Enabled" : "Disabled",
10427 alarm2str(alarm), idText);
10430 tmp = tmp->next;
10433 ast_mutex_unlock(&iflock);
10435 astman_append(s,
10436 "Event: ZapShowChannelsComplete\r\n"
10437 "%s"
10438 "\r\n",
10439 idText);
10440 return 0;
10443 static int __unload_module(void)
10445 int x;
10446 struct zt_pvt *p, *pl;
10448 #ifdef HAVE_PRI
10449 int i;
10450 for (i = 0; i < NUM_SPANS; i++) {
10451 if (pris[i].master != AST_PTHREADT_NULL)
10452 pthread_cancel(pris[i].master);
10454 ast_cli_unregister_multiple(zap_pri_cli, sizeof(zap_pri_cli) / sizeof(struct ast_cli_entry));
10455 ast_unregister_application(zap_send_keypad_facility_app);
10456 #endif
10457 ast_cli_unregister_multiple(zap_cli, sizeof(zap_cli) / sizeof(struct ast_cli_entry));
10458 ast_manager_unregister( "ZapDialOffhook" );
10459 ast_manager_unregister( "ZapHangup" );
10460 ast_manager_unregister( "ZapTransfer" );
10461 ast_manager_unregister( "ZapDNDoff" );
10462 ast_manager_unregister( "ZapDNDon" );
10463 ast_manager_unregister("ZapShowChannels");
10464 ast_manager_unregister("ZapRestart");
10465 ast_channel_unregister(&zap_tech);
10466 ast_mutex_lock(&iflock);
10467 /* Hangup all interfaces if they have an owner */
10468 p = iflist;
10469 while (p) {
10470 if (p->owner)
10471 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
10472 p = p->next;
10474 ast_mutex_unlock(&iflock);
10475 ast_mutex_lock(&monlock);
10476 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
10477 pthread_cancel(monitor_thread);
10478 pthread_kill(monitor_thread, SIGURG);
10479 pthread_join(monitor_thread, NULL);
10481 monitor_thread = AST_PTHREADT_STOP;
10482 ast_mutex_unlock(&monlock);
10484 ast_mutex_lock(&iflock);
10485 /* Destroy all the interfaces and free their memory */
10486 p = iflist;
10487 while (p) {
10488 /* Free any callerid */
10489 if (p->cidspill)
10490 free(p->cidspill);
10491 /* Close the zapata thingy */
10492 if (p->subs[SUB_REAL].zfd > -1)
10493 zt_close(p->subs[SUB_REAL].zfd);
10494 pl = p;
10495 p = p->next;
10496 x = pl->channel;
10497 /* Free associated memory */
10498 if (pl)
10499 destroy_zt_pvt(&pl);
10500 ast_verbose(VERBOSE_PREFIX_3 "Unregistered channel %d\n", x);
10502 iflist = NULL;
10503 ifcount = 0;
10504 ast_mutex_unlock(&iflock);
10505 #ifdef HAVE_PRI
10506 for (i = 0; i < NUM_SPANS; i++) {
10507 if (pris[i].master && (pris[i].master != AST_PTHREADT_NULL))
10508 pthread_join(pris[i].master, NULL);
10509 zt_close(pris[i].fds[i]);
10511 #endif
10512 return 0;
10515 static int unload_module(void)
10517 #ifdef HAVE_PRI
10518 int y;
10519 for (y = 0; y < NUM_SPANS; y++)
10520 ast_mutex_destroy(&pris[y].lock);
10521 #endif
10522 return __unload_module();
10525 static int build_channels(struct zt_chan_conf *conf, int iscrv, const char *value, int reload, int lineno, int *found_pseudo)
10527 char *c, *chan;
10528 int x, start, finish;
10529 struct zt_pvt *tmp;
10530 #ifdef HAVE_PRI
10531 struct zt_pri *pri;
10532 int trunkgroup, y;
10533 #endif
10535 if ((reload == 0) && (conf->chan.sig < 0)) {
10536 ast_log(LOG_ERROR, "Signalling must be specified before any channels are.\n");
10537 return -1;
10540 c = ast_strdupa(value);
10542 #ifdef HAVE_PRI
10543 pri = NULL;
10544 if (iscrv) {
10545 if (sscanf(c, "%d:%n", &trunkgroup, &y) != 1) {
10546 ast_log(LOG_WARNING, "CRV must begin with trunkgroup followed by a colon at line %d\n", lineno);
10547 return -1;
10549 if (trunkgroup < 1) {
10550 ast_log(LOG_WARNING, "CRV trunk group must be a positive number at line %d\n", lineno);
10551 return -1;
10553 c += y;
10554 for (y = 0; y < NUM_SPANS; y++) {
10555 if (pris[y].trunkgroup == trunkgroup) {
10556 pri = pris + y;
10557 break;
10560 if (!pri) {
10561 ast_log(LOG_WARNING, "No such trunk group %d at CRV declaration at line %d\n", trunkgroup, lineno);
10562 return -1;
10565 #endif
10567 while ((chan = strsep(&c, ","))) {
10568 if (sscanf(chan, "%d-%d", &start, &finish) == 2) {
10569 /* Range */
10570 } else if (sscanf(chan, "%d", &start)) {
10571 /* Just one */
10572 finish = start;
10573 } else if (!strcasecmp(chan, "pseudo")) {
10574 finish = start = CHAN_PSEUDO;
10575 if (found_pseudo)
10576 *found_pseudo = 1;
10577 } else {
10578 ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
10579 return -1;
10581 if (finish < start) {
10582 ast_log(LOG_WARNING, "Sillyness: %d < %d\n", start, finish);
10583 x = finish;
10584 finish = start;
10585 start = x;
10588 for (x = start; x <= finish; x++) {
10589 #ifdef HAVE_PRI
10590 tmp = mkintf(x, conf, pri, reload);
10591 #else
10592 tmp = mkintf(x, conf, NULL, reload);
10593 #endif
10595 if (tmp) {
10596 if (option_verbose > 2) {
10597 #ifdef HAVE_PRI
10598 if (pri)
10599 ast_verbose(VERBOSE_PREFIX_3 "%s CRV %d:%d, %s signalling\n", reload ? "Reconfigured" : "Registered", trunkgroup, x, sig2str(tmp->sig));
10600 else
10601 #endif
10602 ast_verbose(VERBOSE_PREFIX_3 "%s channel %d, %s signalling\n", reload ? "Reconfigured" : "Registered", x, sig2str(tmp->sig));
10604 } else {
10605 ast_log(LOG_ERROR, "Unable to %s channel '%s'\n",
10606 (reload == 1) ? "reconfigure" : "register", value);
10607 return -1;
10612 return 0;
10615 /** The length of the parameters list of 'zapchan'.
10616 * \todo Move definition of MAX_CHANLIST_LEN to a proper place. */
10617 #define MAX_CHANLIST_LEN 80
10618 static int process_zap(struct zt_chan_conf *confp, struct ast_variable *v, int reload, int skipchannels)
10620 struct zt_pvt *tmp;
10621 char *ringc; /* temporary string for parsing the dring number. */
10622 int y;
10623 int found_pseudo = 0;
10624 char zapchan[MAX_CHANLIST_LEN] = {};
10626 for (; v; v = v->next) {
10627 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
10628 continue;
10630 /* Create the interface list */
10631 if (!strcasecmp(v->name, "channel")
10632 #ifdef HAVE_PRI
10633 || !strcasecmp(v->name, "crv")
10634 #endif
10636 int iscrv;
10637 if (skipchannels)
10638 continue;
10639 iscrv = !strcasecmp(v->name, "crv");
10640 if (build_channels(confp, iscrv, v->value, reload, v->lineno, &found_pseudo))
10641 return -1;
10642 } else if (!strcasecmp(v->name, "zapchan")) {
10643 ast_copy_string(zapchan, v->value, sizeof(zapchan));
10644 } else if (!strcasecmp(v->name, "usedistinctiveringdetection")) {
10645 if (ast_true(v->value))
10646 confp->chan.usedistinctiveringdetection = 1;
10647 } else if (!strcasecmp(v->name, "distinctiveringaftercid")) {
10648 if (ast_true(v->value))
10649 distinctiveringaftercid = 1;
10650 } else if (!strcasecmp(v->name, "dring1context")) {
10651 ast_copy_string(drings.ringContext[0].contextData, v->value, sizeof(drings.ringContext[0].contextData));
10652 } else if (!strcasecmp(v->name, "dring2context")) {
10653 ast_copy_string(drings.ringContext[1].contextData, v->value, sizeof(drings.ringContext[1].contextData));
10654 } else if (!strcasecmp(v->name, "dring3context")) {
10655 ast_copy_string(drings.ringContext[2].contextData, v->value, sizeof(drings.ringContext[2].contextData));
10656 } else if (!strcasecmp(v->name, "dring1")) {
10657 ringc = v->value;
10658 sscanf(ringc, "%d,%d,%d", &drings.ringnum[0].ring[0], &drings.ringnum[0].ring[1], &drings.ringnum[0].ring[2]);
10659 } else if (!strcasecmp(v->name, "dring2")) {
10660 ringc = v->value;
10661 sscanf(ringc, "%d,%d,%d", &drings.ringnum[1].ring[0], &drings.ringnum[1].ring[1], &drings.ringnum[1].ring[2]);
10662 } else if (!strcasecmp(v->name, "dring3")) {
10663 ringc = v->value;
10664 sscanf(ringc, "%d,%d,%d", &drings.ringnum[2].ring[0], &drings.ringnum[2].ring[1], &drings.ringnum[2].ring[2]);
10665 } else if (!strcasecmp(v->name, "usecallerid")) {
10666 confp->chan.use_callerid = ast_true(v->value);
10667 } else if (!strcasecmp(v->name, "cidsignalling")) {
10668 if (!strcasecmp(v->value, "bell"))
10669 confp->chan.cid_signalling = CID_SIG_BELL;
10670 else if (!strcasecmp(v->value, "v23"))
10671 confp->chan.cid_signalling = CID_SIG_V23;
10672 else if (!strcasecmp(v->value, "dtmf"))
10673 confp->chan.cid_signalling = CID_SIG_DTMF;
10674 else if (!strcasecmp(v->value, "smdi"))
10675 confp->chan.cid_signalling = CID_SIG_SMDI;
10676 else if (!strcasecmp(v->value, "v23_jp"))
10677 confp->chan.cid_signalling = CID_SIG_V23_JP;
10678 else if (ast_true(v->value))
10679 confp->chan.cid_signalling = CID_SIG_BELL;
10680 } else if (!strcasecmp(v->name, "cidstart")) {
10681 if (!strcasecmp(v->value, "ring"))
10682 confp->chan.cid_start = CID_START_RING;
10683 else if (!strcasecmp(v->value, "polarity"))
10684 confp->chan.cid_start = CID_START_POLARITY;
10685 else if (ast_true(v->value))
10686 confp->chan.cid_start = CID_START_RING;
10687 } else if (!strcasecmp(v->name, "threewaycalling")) {
10688 confp->chan.threewaycalling = ast_true(v->value);
10689 } else if (!strcasecmp(v->name, "cancallforward")) {
10690 confp->chan.cancallforward = ast_true(v->value);
10691 } else if (!strcasecmp(v->name, "relaxdtmf")) {
10692 if (ast_true(v->value))
10693 confp->chan.dtmfrelax = DSP_DIGITMODE_RELAXDTMF;
10694 else
10695 confp->chan.dtmfrelax = 0;
10696 } else if (!strcasecmp(v->name, "mailbox")) {
10697 ast_copy_string(confp->chan.mailbox, v->value, sizeof(confp->chan.mailbox));
10698 } else if (!strcasecmp(v->name, "adsi")) {
10699 confp->chan.adsi = ast_true(v->value);
10700 } else if (!strcasecmp(v->name, "usesmdi")) {
10701 confp->chan.use_smdi = ast_true(v->value);
10702 } else if (!strcasecmp(v->name, "smdiport")) {
10703 ast_copy_string(confp->smdi_port, v->value, sizeof(confp->smdi_port));
10704 } else if (!strcasecmp(v->name, "transfer")) {
10705 confp->chan.transfer = ast_true(v->value);
10706 } else if (!strcasecmp(v->name, "canpark")) {
10707 confp->chan.canpark = ast_true(v->value);
10708 } else if (!strcasecmp(v->name, "echocancelwhenbridged")) {
10709 confp->chan.echocanbridged = ast_true(v->value);
10710 } else if (!strcasecmp(v->name, "busydetect")) {
10711 confp->chan.busydetect = ast_true(v->value);
10712 } else if (!strcasecmp(v->name, "busycount")) {
10713 confp->chan.busycount = atoi(v->value);
10714 } else if (!strcasecmp(v->name, "busypattern")) {
10715 if (sscanf(v->value, "%d,%d", &confp->chan.busy_tonelength, &confp->chan.busy_quietlength) != 2) {
10716 ast_log(LOG_ERROR, "busypattern= expects busypattern=tonelength,quietlength\n");
10718 } else if (!strcasecmp(v->name, "callprogress")) {
10719 if (ast_true(v->value))
10720 confp->chan.callprogress |= 1;
10721 else
10722 confp->chan.callprogress &= ~1;
10723 } else if (!strcasecmp(v->name, "faxdetect")) {
10724 if (!strcasecmp(v->value, "incoming")) {
10725 confp->chan.callprogress |= 4;
10726 confp->chan.callprogress &= ~2;
10727 } else if (!strcasecmp(v->value, "outgoing")) {
10728 confp->chan.callprogress &= ~4;
10729 confp->chan.callprogress |= 2;
10730 } else if (!strcasecmp(v->value, "both") || ast_true(v->value))
10731 confp->chan.callprogress |= 6;
10732 else
10733 confp->chan.callprogress &= ~6;
10734 } else if (!strcasecmp(v->name, "echocancel")) {
10735 if (!ast_strlen_zero(v->value)) {
10736 y = atoi(v->value);
10737 } else
10738 y = 0;
10739 if ((y == 32) || (y == 64) || (y == 128) || (y == 256) || (y == 512) || (y == 1024))
10740 confp->chan.echocancel = y;
10741 else {
10742 confp->chan.echocancel = ast_true(v->value);
10743 if (confp->chan.echocancel)
10744 confp->chan.echocancel=128;
10746 } else if (!strcasecmp(v->name, "echotraining")) {
10747 if (sscanf(v->value, "%d", &y) == 1) {
10748 if ((y < 10) || (y > 4000)) {
10749 ast_log(LOG_WARNING, "Echo training time must be within the range of 10 to 4000 ms at line %d\n", v->lineno);
10750 } else {
10751 confp->chan.echotraining = y;
10753 } else if (ast_true(v->value)) {
10754 confp->chan.echotraining = 400;
10755 } else
10756 confp->chan.echotraining = 0;
10757 } else if (!strcasecmp(v->name, "hidecallerid")) {
10758 confp->chan.hidecallerid = ast_true(v->value);
10759 } else if (!strcasecmp(v->name, "hidecalleridname")) {
10760 confp->chan.hidecalleridname = ast_true(v->value);
10761 } else if (!strcasecmp(v->name, "pulsedial")) {
10762 confp->chan.pulse = ast_true(v->value);
10763 } else if (!strcasecmp(v->name, "callreturn")) {
10764 confp->chan.callreturn = ast_true(v->value);
10765 } else if (!strcasecmp(v->name, "callwaiting")) {
10766 confp->chan.callwaiting = ast_true(v->value);
10767 } else if (!strcasecmp(v->name, "callwaitingcallerid")) {
10768 confp->chan.callwaitingcallerid = ast_true(v->value);
10769 } else if (!strcasecmp(v->name, "context")) {
10770 ast_copy_string(confp->chan.context, v->value, sizeof(confp->chan.context));
10771 } else if (!strcasecmp(v->name, "language")) {
10772 ast_copy_string(confp->chan.language, v->value, sizeof(confp->chan.language));
10773 } else if (!strcasecmp(v->name, "progzone")) {
10774 ast_copy_string(progzone, v->value, sizeof(progzone));
10775 } else if (!strcasecmp(v->name, "mohinterpret")
10776 ||!strcasecmp(v->name, "musiconhold") || !strcasecmp(v->name, "musicclass")) {
10777 ast_copy_string(confp->chan.mohinterpret, v->value, sizeof(confp->chan.mohinterpret));
10778 } else if (!strcasecmp(v->name, "mohsuggest")) {
10779 ast_copy_string(confp->chan.mohsuggest, v->value, sizeof(confp->chan.mohsuggest));
10780 } else if (!strcasecmp(v->name, "stripmsd")) {
10781 confp->chan.stripmsd = atoi(v->value);
10782 } else if (!strcasecmp(v->name, "jitterbuffers")) {
10783 numbufs = atoi(v->value);
10784 } else if (!strcasecmp(v->name, "group")) {
10785 confp->chan.group = ast_get_group(v->value);
10786 } else if (!strcasecmp(v->name, "callgroup")) {
10787 confp->chan.callgroup = ast_get_group(v->value);
10788 } else if (!strcasecmp(v->name, "pickupgroup")) {
10789 confp->chan.pickupgroup = ast_get_group(v->value);
10790 } else if (!strcasecmp(v->name, "immediate")) {
10791 confp->chan.immediate = ast_true(v->value);
10792 } else if (!strcasecmp(v->name, "transfertobusy")) {
10793 confp->chan.transfertobusy = ast_true(v->value);
10794 } else if (!strcasecmp(v->name, "rxgain")) {
10795 if (sscanf(v->value, "%f", &confp->chan.rxgain) != 1) {
10796 ast_log(LOG_WARNING, "Invalid rxgain: %s\n", v->value);
10798 } else if (!strcasecmp(v->name, "txgain")) {
10799 if (sscanf(v->value, "%f", &confp->chan.txgain) != 1) {
10800 ast_log(LOG_WARNING, "Invalid txgain: %s\n", v->value);
10802 } else if (!strcasecmp(v->name, "tonezone")) {
10803 if (sscanf(v->value, "%d", &confp->chan.tonezone) != 1) {
10804 ast_log(LOG_WARNING, "Invalid tonezone: %s\n", v->value);
10806 } else if (!strcasecmp(v->name, "callerid")) {
10807 if (!strcasecmp(v->value, "asreceived")) {
10808 confp->chan.cid_num[0] = '\0';
10809 confp->chan.cid_name[0] = '\0';
10810 } else {
10811 ast_callerid_split(v->value, confp->chan.cid_name, sizeof(confp->chan.cid_name), confp->chan.cid_num, sizeof(confp->chan.cid_num));
10813 } else if (!strcasecmp(v->name, "fullname")) {
10814 ast_copy_string(confp->chan.cid_name, v->value, sizeof(confp->chan.cid_name));
10815 } else if (!strcasecmp(v->name, "cid_number")) {
10816 ast_copy_string(confp->chan.cid_num, v->value, sizeof(confp->chan.cid_num));
10817 } else if (!strcasecmp(v->name, "useincomingcalleridonzaptransfer")) {
10818 confp->chan.zaptrcallerid = ast_true(v->value);
10819 } else if (!strcasecmp(v->name, "restrictcid")) {
10820 confp->chan.restrictcid = ast_true(v->value);
10821 } else if (!strcasecmp(v->name, "usecallingpres")) {
10822 confp->chan.use_callingpres = ast_true(v->value);
10823 } else if (!strcasecmp(v->name, "accountcode")) {
10824 ast_copy_string(confp->chan.accountcode, v->value, sizeof(confp->chan.accountcode));
10825 } else if (!strcasecmp(v->name, "amaflags")) {
10826 y = ast_cdr_amaflags2int(v->value);
10827 if (y < 0)
10828 ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
10829 else
10830 confp->chan.amaflags = y;
10831 } else if (!strcasecmp(v->name, "polarityonanswerdelay")) {
10832 confp->chan.polarityonanswerdelay = atoi(v->value);
10833 } else if (!strcasecmp(v->name, "answeronpolarityswitch")) {
10834 confp->chan.answeronpolarityswitch = ast_true(v->value);
10835 } else if (!strcasecmp(v->name, "hanguponpolarityswitch")) {
10836 confp->chan.hanguponpolarityswitch = ast_true(v->value);
10837 } else if (!strcasecmp(v->name, "sendcalleridafter")) {
10838 confp->chan.sendcalleridafter = atoi(v->value);
10839 } else if (!reload){
10840 if (!strcasecmp(v->name, "signalling")) {
10841 confp->chan.outsigmod = -1;
10842 if (!strcasecmp(v->value, "em")) {
10843 confp->chan.sig = SIG_EM;
10844 } else if (!strcasecmp(v->value, "em_e1")) {
10845 confp->chan.sig = SIG_EM_E1;
10846 } else if (!strcasecmp(v->value, "em_w")) {
10847 confp->chan.sig = SIG_EMWINK;
10848 confp->chan.radio = 0;
10849 } else if (!strcasecmp(v->value, "fxs_ls")) {
10850 confp->chan.sig = SIG_FXSLS;
10851 confp->chan.radio = 0;
10852 } else if (!strcasecmp(v->value, "fxs_gs")) {
10853 confp->chan.sig = SIG_FXSGS;
10854 confp->chan.radio = 0;
10855 } else if (!strcasecmp(v->value, "fxs_ks")) {
10856 confp->chan.sig = SIG_FXSKS;
10857 confp->chan.radio = 0;
10858 } else if (!strcasecmp(v->value, "fxo_ls")) {
10859 confp->chan.sig = SIG_FXOLS;
10860 confp->chan.radio = 0;
10861 } else if (!strcasecmp(v->value, "fxo_gs")) {
10862 confp->chan.sig = SIG_FXOGS;
10863 confp->chan.radio = 0;
10864 } else if (!strcasecmp(v->value, "fxo_ks")) {
10865 confp->chan.sig = SIG_FXOKS;
10866 confp->chan.radio = 0;
10867 } else if (!strcasecmp(v->value, "fxs_rx")) {
10868 confp->chan.sig = SIG_FXSKS;
10869 confp->chan.radio = 1;
10870 } else if (!strcasecmp(v->value, "fxo_rx")) {
10871 confp->chan.sig = SIG_FXOLS;
10872 confp->chan.radio = 1;
10873 } else if (!strcasecmp(v->value, "fxs_tx")) {
10874 confp->chan.sig = SIG_FXSLS;
10875 confp->chan.radio = 1;
10876 } else if (!strcasecmp(v->value, "fxo_tx")) {
10877 confp->chan.sig = SIG_FXOGS;
10878 confp->chan.radio = 1;
10879 } else if (!strcasecmp(v->value, "em_rx")) {
10880 confp->chan.sig = SIG_EM;
10881 confp->chan.radio = 1;
10882 } else if (!strcasecmp(v->value, "em_tx")) {
10883 confp->chan.sig = SIG_EM;
10884 confp->chan.radio = 1;
10885 } else if (!strcasecmp(v->value, "em_rxtx")) {
10886 confp->chan.sig = SIG_EM;
10887 confp->chan.radio = 2;
10888 } else if (!strcasecmp(v->value, "em_txrx")) {
10889 confp->chan.sig = SIG_EM;
10890 confp->chan.radio = 2;
10891 } else if (!strcasecmp(v->value, "sf")) {
10892 confp->chan.sig = SIG_SF;
10893 confp->chan.radio = 0;
10894 } else if (!strcasecmp(v->value, "sf_w")) {
10895 confp->chan.sig = SIG_SFWINK;
10896 confp->chan.radio = 0;
10897 } else if (!strcasecmp(v->value, "sf_featd")) {
10898 confp->chan.sig = SIG_FEATD;
10899 confp->chan.radio = 0;
10900 } else if (!strcasecmp(v->value, "sf_featdmf")) {
10901 confp->chan.sig = SIG_FEATDMF;
10902 confp->chan.radio = 0;
10903 } else if (!strcasecmp(v->value, "sf_featb")) {
10904 confp->chan.sig = SIG_SF_FEATB;
10905 confp->chan.radio = 0;
10906 } else if (!strcasecmp(v->value, "sf")) {
10907 confp->chan.sig = SIG_SF;
10908 confp->chan.radio = 0;
10909 } else if (!strcasecmp(v->value, "sf_rx")) {
10910 confp->chan.sig = SIG_SF;
10911 confp->chan.radio = 1;
10912 } else if (!strcasecmp(v->value, "sf_tx")) {
10913 confp->chan.sig = SIG_SF;
10914 confp->chan.radio = 1;
10915 } else if (!strcasecmp(v->value, "sf_rxtx")) {
10916 confp->chan.sig = SIG_SF;
10917 confp->chan.radio = 2;
10918 } else if (!strcasecmp(v->value, "sf_txrx")) {
10919 confp->chan.sig = SIG_SF;
10920 confp->chan.radio = 2;
10921 } else if (!strcasecmp(v->value, "featd")) {
10922 confp->chan.sig = SIG_FEATD;
10923 confp->chan.radio = 0;
10924 } else if (!strcasecmp(v->value, "featdmf")) {
10925 confp->chan.sig = SIG_FEATDMF;
10926 confp->chan.radio = 0;
10927 } else if (!strcasecmp(v->value, "featdmf_ta")) {
10928 confp->chan.sig = SIG_FEATDMF_TA;
10929 confp->chan.radio = 0;
10930 } else if (!strcasecmp(v->value, "e911")) {
10931 confp->chan.sig = SIG_E911;
10932 confp->chan.radio = 0;
10933 } else if (!strcasecmp(v->value, "fgccama")) {
10934 confp->chan.sig = SIG_FGC_CAMA;
10935 confp->chan.radio = 0;
10936 } else if (!strcasecmp(v->value, "fgccamamf")) {
10937 confp->chan.sig = SIG_FGC_CAMAMF;
10938 confp->chan.radio = 0;
10939 } else if (!strcasecmp(v->value, "featb")) {
10940 confp->chan.sig = SIG_FEATB;
10941 confp->chan.radio = 0;
10942 #ifdef HAVE_PRI
10943 } else if (!strcasecmp(v->value, "pri_net")) {
10944 confp->chan.radio = 0;
10945 confp->chan.sig = SIG_PRI;
10946 confp->pri.nodetype = PRI_NETWORK;
10947 } else if (!strcasecmp(v->value, "pri_cpe")) {
10948 confp->chan.sig = SIG_PRI;
10949 confp->chan.radio = 0;
10950 confp->pri.nodetype = PRI_CPE;
10951 } else if (!strcasecmp(v->value, "gr303fxoks_net")) {
10952 confp->chan.sig = SIG_GR303FXOKS;
10953 confp->chan.radio = 0;
10954 confp->pri.nodetype = PRI_NETWORK;
10955 } else if (!strcasecmp(v->value, "gr303fxsks_cpe")) {
10956 confp->chan.sig = SIG_GR303FXSKS;
10957 confp->chan.radio = 0;
10958 confp->pri.nodetype = PRI_CPE;
10959 #endif
10960 } else {
10961 ast_log(LOG_ERROR, "Unknown signalling method '%s'\n", v->value);
10963 } else if (!strcasecmp(v->name, "outsignalling")) {
10964 if (!strcasecmp(v->value, "em")) {
10965 confp->chan.outsigmod = SIG_EM;
10966 } else if (!strcasecmp(v->value, "em_e1")) {
10967 confp->chan.outsigmod = SIG_EM_E1;
10968 } else if (!strcasecmp(v->value, "em_w")) {
10969 confp->chan.outsigmod = SIG_EMWINK;
10970 } else if (!strcasecmp(v->value, "sf")) {
10971 confp->chan.outsigmod = SIG_SF;
10972 } else if (!strcasecmp(v->value, "sf_w")) {
10973 confp->chan.outsigmod = SIG_SFWINK;
10974 } else if (!strcasecmp(v->value, "sf_featd")) {
10975 confp->chan.outsigmod = SIG_FEATD;
10976 } else if (!strcasecmp(v->value, "sf_featdmf")) {
10977 confp->chan.outsigmod = SIG_FEATDMF;
10978 } else if (!strcasecmp(v->value, "sf_featb")) {
10979 confp->chan.outsigmod = SIG_SF_FEATB;
10980 } else if (!strcasecmp(v->value, "sf")) {
10981 confp->chan.outsigmod = SIG_SF;
10982 } else if (!strcasecmp(v->value, "featd")) {
10983 confp->chan.outsigmod = SIG_FEATD;
10984 } else if (!strcasecmp(v->value, "featdmf")) {
10985 confp->chan.outsigmod = SIG_FEATDMF;
10986 } else if (!strcasecmp(v->value, "featdmf_ta")) {
10987 confp->chan.outsigmod = SIG_FEATDMF_TA;
10988 } else if (!strcasecmp(v->value, "e911")) {
10989 confp->chan.outsigmod = SIG_E911;
10990 } else if (!strcasecmp(v->value, "fgccama")) {
10991 confp->chan.outsigmod = SIG_FGC_CAMA;
10992 } else if (!strcasecmp(v->value, "fgccamamf")) {
10993 confp->chan.outsigmod = SIG_FGC_CAMAMF;
10994 } else if (!strcasecmp(v->value, "featb")) {
10995 confp->chan.outsigmod = SIG_FEATB;
10996 } else {
10997 ast_log(LOG_ERROR, "Unknown signalling method '%s'\n", v->value);
10999 #ifdef HAVE_PRI
11000 } else if (!strcasecmp(v->name, "pridialplan")) {
11001 if (!strcasecmp(v->value, "national")) {
11002 confp->pri.dialplan = PRI_NATIONAL_ISDN + 1;
11003 } else if (!strcasecmp(v->value, "unknown")) {
11004 confp->pri.dialplan = PRI_UNKNOWN + 1;
11005 } else if (!strcasecmp(v->value, "private")) {
11006 confp->pri.dialplan = PRI_PRIVATE + 1;
11007 } else if (!strcasecmp(v->value, "international")) {
11008 confp->pri.dialplan = PRI_INTERNATIONAL_ISDN + 1;
11009 } else if (!strcasecmp(v->value, "local")) {
11010 confp->pri.dialplan = PRI_LOCAL_ISDN + 1;
11011 } else if (!strcasecmp(v->value, "dynamic")) {
11012 confp->pri.dialplan = -1;
11013 } else {
11014 ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
11016 } else if (!strcasecmp(v->name, "prilocaldialplan")) {
11017 if (!strcasecmp(v->value, "national")) {
11018 confp->pri.localdialplan = PRI_NATIONAL_ISDN + 1;
11019 } else if (!strcasecmp(v->value, "unknown")) {
11020 confp->pri.localdialplan = PRI_UNKNOWN + 1;
11021 } else if (!strcasecmp(v->value, "private")) {
11022 confp->pri.localdialplan = PRI_PRIVATE + 1;
11023 } else if (!strcasecmp(v->value, "international")) {
11024 confp->pri.localdialplan = PRI_INTERNATIONAL_ISDN + 1;
11025 } else if (!strcasecmp(v->value, "local")) {
11026 confp->pri.localdialplan = PRI_LOCAL_ISDN + 1;
11027 } else if (!strcasecmp(v->value, "dynamic")) {
11028 confp->pri.localdialplan = -1;
11029 } else {
11030 ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
11032 } else if (!strcasecmp(v->name, "switchtype")) {
11033 if (!strcasecmp(v->value, "national"))
11034 confp->pri.switchtype = PRI_SWITCH_NI2;
11035 else if (!strcasecmp(v->value, "ni1"))
11036 confp->pri.switchtype = PRI_SWITCH_NI1;
11037 else if (!strcasecmp(v->value, "dms100"))
11038 confp->pri.switchtype = PRI_SWITCH_DMS100;
11039 else if (!strcasecmp(v->value, "4ess"))
11040 confp->pri.switchtype = PRI_SWITCH_ATT4ESS;
11041 else if (!strcasecmp(v->value, "5ess"))
11042 confp->pri.switchtype = PRI_SWITCH_LUCENT5E;
11043 else if (!strcasecmp(v->value, "euroisdn"))
11044 confp->pri.switchtype = PRI_SWITCH_EUROISDN_E1;
11045 else if (!strcasecmp(v->value, "qsig"))
11046 confp->pri.switchtype = PRI_SWITCH_QSIG;
11047 else {
11048 ast_log(LOG_ERROR, "Unknown switchtype '%s'\n", v->value);
11049 return -1;
11051 } else if (!strcasecmp(v->name, "nsf")) {
11052 if (!strcasecmp(v->value, "sdn"))
11053 confp->pri.nsf = PRI_NSF_SDN;
11054 else if (!strcasecmp(v->value, "megacom"))
11055 confp->pri.nsf = PRI_NSF_MEGACOM;
11056 else if (!strcasecmp(v->value, "tollfreemegacom"))
11057 confp->pri.nsf = PRI_NSF_TOLL_FREE_MEGACOM;
11058 else if (!strcasecmp(v->value, "accunet"))
11059 confp->pri.nsf = PRI_NSF_ACCUNET;
11060 else if (!strcasecmp(v->value, "none"))
11061 confp->pri.nsf = PRI_NSF_NONE;
11062 else {
11063 ast_log(LOG_WARNING, "Unknown network-specific facility '%s'\n", v->value);
11064 confp->pri.nsf = PRI_NSF_NONE;
11066 } else if (!strcasecmp(v->name, "priindication")) {
11067 if (!strcasecmp(v->value, "outofband"))
11068 confp->chan.priindication_oob = 1;
11069 else if (!strcasecmp(v->value, "inband"))
11070 confp->chan.priindication_oob = 0;
11071 else
11072 ast_log(LOG_WARNING, "'%s' is not a valid pri indication value, should be 'inband' or 'outofband' at line %d\n",
11073 v->value, v->lineno);
11074 } else if (!strcasecmp(v->name, "priexclusive")) {
11075 confp->chan.priexclusive = ast_true(v->value);
11076 } else if (!strcasecmp(v->name, "internationalprefix")) {
11077 ast_copy_string(confp->pri.internationalprefix, v->value, sizeof(confp->pri.internationalprefix));
11078 } else if (!strcasecmp(v->name, "nationalprefix")) {
11079 ast_copy_string(confp->pri.nationalprefix, v->value, sizeof(confp->pri.nationalprefix));
11080 } else if (!strcasecmp(v->name, "localprefix")) {
11081 ast_copy_string(confp->pri.localprefix, v->value, sizeof(confp->pri.localprefix));
11082 } else if (!strcasecmp(v->name, "privateprefix")) {
11083 ast_copy_string(confp->pri.privateprefix, v->value, sizeof(confp->pri.privateprefix));
11084 } else if (!strcasecmp(v->name, "unknownprefix")) {
11085 ast_copy_string(confp->pri.unknownprefix, v->value, sizeof(confp->pri.unknownprefix));
11086 } else if (!strcasecmp(v->name, "resetinterval")) {
11087 if (!strcasecmp(v->value, "never"))
11088 confp->pri.resetinterval = -1;
11089 else if (atoi(v->value) >= 60)
11090 confp->pri.resetinterval = atoi(v->value);
11091 else
11092 ast_log(LOG_WARNING, "'%s' is not a valid reset interval, should be >= 60 seconds or 'never' at line %d\n",
11093 v->value, v->lineno);
11094 } else if (!strcasecmp(v->name, "minunused")) {
11095 confp->pri.minunused = atoi(v->value);
11096 } else if (!strcasecmp(v->name, "minidle")) {
11097 confp->pri.minidle = atoi(v->value);
11098 } else if (!strcasecmp(v->name, "idleext")) {
11099 ast_copy_string(confp->pri.idleext, v->value, sizeof(confp->pri.idleext));
11100 } else if (!strcasecmp(v->name, "idledial")) {
11101 ast_copy_string(confp->pri.idledial, v->value, sizeof(confp->pri.idledial));
11102 } else if (!strcasecmp(v->name, "overlapdial")) {
11103 confp->pri.overlapdial = ast_true(v->value);
11104 } else if (!strcasecmp(v->name, "pritimer")) {
11105 #ifdef PRI_GETSET_TIMERS
11106 char *timerc, *c;
11107 int timer, timeridx;
11108 c = v->value;
11109 timerc = strsep(&c, ",");
11110 if (timerc) {
11111 timer = atoi(c);
11112 if (!timer)
11113 ast_log(LOG_WARNING, "'%s' is not a valid value for an ISDN timer\n", timerc);
11114 else {
11115 if ((timeridx = pri_timer2idx(timerc)) >= 0)
11116 pritimers[timeridx] = timer;
11117 else
11118 ast_log(LOG_WARNING, "'%s' is not a valid ISDN timer\n", timerc);
11120 } else
11121 ast_log(LOG_WARNING, "'%s' is not a valid ISDN timer configuration string\n", v->value);
11123 } else if (!strcasecmp(v->name, "facilityenable")) {
11124 confp->pri.facilityenable = ast_true(v->value);
11125 #endif /* PRI_GETSET_TIMERS */
11126 #endif /* HAVE_PRI */
11127 } else if (!strcasecmp(v->name, "cadence")) {
11128 /* setup to scan our argument */
11129 int element_count, c[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
11130 int i;
11131 struct zt_ring_cadence new_cadence;
11132 int cid_location = -1;
11133 int firstcadencepos = 0;
11134 char original_args[80];
11135 int cadence_is_ok = 1;
11137 ast_copy_string(original_args, v->value, sizeof(original_args));
11138 /* 16 cadences allowed (8 pairs) */
11139 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]);
11141 /* Cadence must be even (on/off) */
11142 if (element_count % 2 == 1) {
11143 ast_log(LOG_ERROR, "Must be a silence duration for each ring duration: %s\n",original_args);
11144 cadence_is_ok = 0;
11147 /* Ring cadences cannot be negative */
11148 for (i = 0; i < element_count; i++) {
11149 if (c[i] == 0) {
11150 ast_log(LOG_ERROR, "Ring or silence duration cannot be zero: %s\n", original_args);
11151 cadence_is_ok = 0;
11152 break;
11153 } else if (c[i] < 0) {
11154 if (i % 2 == 1) {
11155 /* Silence duration, negative possibly okay */
11156 if (cid_location == -1) {
11157 cid_location = i;
11158 c[i] *= -1;
11159 } else {
11160 ast_log(LOG_ERROR, "CID location specified twice: %s\n",original_args);
11161 cadence_is_ok = 0;
11162 break;
11164 } else {
11165 if (firstcadencepos == 0) {
11166 firstcadencepos = i; /* only recorded to avoid duplicate specification */
11167 /* duration will be passed negative to the zaptel driver */
11168 } else {
11169 ast_log(LOG_ERROR, "First cadence position specified twice: %s\n",original_args);
11170 cadence_is_ok = 0;
11171 break;
11177 /* Substitute our scanned cadence */
11178 for (i = 0; i < 16; i++) {
11179 new_cadence.ringcadence[i] = c[i];
11182 if (cadence_is_ok) {
11183 /* ---we scanned it without getting annoyed; now some sanity checks--- */
11184 if (element_count < 2) {
11185 ast_log(LOG_ERROR, "Minimum cadence is ring,pause: %s\n", original_args);
11186 } else {
11187 if (cid_location == -1) {
11188 /* user didn't say; default to first pause */
11189 cid_location = 1;
11190 } else {
11191 /* convert element_index to cidrings value */
11192 cid_location = (cid_location + 1) / 2;
11194 /* ---we like their cadence; try to install it--- */
11195 if (!user_has_defined_cadences++)
11196 /* this is the first user-defined cadence; clear the default user cadences */
11197 num_cadence = 0;
11198 if ((num_cadence+1) >= NUM_CADENCE_MAX)
11199 ast_log(LOG_ERROR, "Already %d cadences; can't add another: %s\n", NUM_CADENCE_MAX, original_args);
11200 else {
11201 cadences[num_cadence] = new_cadence;
11202 cidrings[num_cadence++] = cid_location;
11203 if (option_verbose > 2)
11204 ast_verbose(VERBOSE_PREFIX_3 "cadence 'r%d' added: %s\n",num_cadence,original_args);
11208 } else if (!strcasecmp(v->name, "ringtimeout")) {
11209 ringt_base = (atoi(v->value) * 8) / READ_SIZE;
11210 } else if (!strcasecmp(v->name, "prewink")) {
11211 confp->timing.prewinktime = atoi(v->value);
11212 } else if (!strcasecmp(v->name, "preflash")) {
11213 confp->timing.preflashtime = atoi(v->value);
11214 } else if (!strcasecmp(v->name, "wink")) {
11215 confp->timing.winktime = atoi(v->value);
11216 } else if (!strcasecmp(v->name, "flash")) {
11217 confp->timing.flashtime = atoi(v->value);
11218 } else if (!strcasecmp(v->name, "start")) {
11219 confp->timing.starttime = atoi(v->value);
11220 } else if (!strcasecmp(v->name, "rxwink")) {
11221 confp->timing.rxwinktime = atoi(v->value);
11222 } else if (!strcasecmp(v->name, "rxflash")) {
11223 confp->timing.rxflashtime = atoi(v->value);
11224 } else if (!strcasecmp(v->name, "debounce")) {
11225 confp->timing.debouncetime = atoi(v->value);
11226 } else if (!strcasecmp(v->name, "toneduration")) {
11227 int toneduration;
11228 int ctlfd;
11229 int res;
11230 struct zt_dialparams dps;
11232 ctlfd = open("/dev/zap/ctl", O_RDWR);
11233 if (ctlfd == -1) {
11234 ast_log(LOG_ERROR, "Unable to open /dev/zap/ctl to set toneduration\n");
11235 return -1;
11238 toneduration = atoi(v->value);
11239 if (toneduration > -1) {
11240 memset(&dps, 0, sizeof(dps));
11242 dps.dtmf_tonelen = dps.mfv1_tonelen = toneduration;
11243 res = ioctl(ctlfd, ZT_SET_DIALPARAMS, &dps);
11244 if (res < 0) {
11245 ast_log(LOG_ERROR, "Invalid tone duration: %d ms\n", toneduration);
11246 return -1;
11249 close(ctlfd);
11250 } else if (!strcasecmp(v->name, "defaultcic")) {
11251 ast_copy_string(defaultcic, v->value, sizeof(defaultcic));
11252 } else if (!strcasecmp(v->name, "defaultozz")) {
11253 ast_copy_string(defaultozz, v->value, sizeof(defaultozz));
11255 } else if (!skipchannels)
11256 ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
11258 if (zapchan[0]) {
11259 /* The user has set 'zapchan' */
11260 /*< \todo pass proper line number instead of 0 */
11261 if (build_channels(confp, 0, zapchan, reload, 0, &found_pseudo)) {
11262 return -1;
11265 /*< \todo why check for the pseudo in the per-channel section.
11266 * Any actual use for manual setup of the pseudo channel? */
11267 if (!found_pseudo && reload == 0) {
11268 /* Make sure pseudo isn't a member of any groups if
11269 we're automatically making it. */
11271 confp->chan.group = 0;
11272 confp->chan.callgroup = 0;
11273 confp->chan.pickupgroup = 0;
11275 tmp = mkintf(CHAN_PSEUDO, confp, NULL, reload);
11277 if (tmp) {
11278 if (option_verbose > 2)
11279 ast_verbose(VERBOSE_PREFIX_3 "Automatically generated pseudo channel\n");
11280 } else {
11281 ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
11284 return 0;
11287 static int setup_zap(int reload)
11289 struct ast_config *cfg;
11290 struct ast_variable *v;
11291 struct zt_chan_conf conf = zt_chan_conf_default();
11292 int res;
11294 #ifdef HAVE_PRI
11295 char *c;
11296 int spanno;
11297 int i, x;
11298 int logicalspan;
11299 int trunkgroup;
11300 int dchannels[NUM_DCHANS];
11301 #endif
11303 cfg = ast_config_load(config);
11305 /* Error if we have no config file */
11306 if (!cfg) {
11307 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
11308 return 0;
11311 /* It's a little silly to lock it, but we mind as well just to be sure */
11312 ast_mutex_lock(&iflock);
11313 #ifdef HAVE_PRI
11314 if (!reload) {
11315 /* Process trunkgroups first */
11316 v = ast_variable_browse(cfg, "trunkgroups");
11317 while (v) {
11318 if (!strcasecmp(v->name, "trunkgroup")) {
11319 trunkgroup = atoi(v->value);
11320 if (trunkgroup > 0) {
11321 if ((c = strchr(v->value, ','))) {
11322 i = 0;
11323 memset(dchannels, 0, sizeof(dchannels));
11324 while (c && (i < NUM_DCHANS)) {
11325 dchannels[i] = atoi(c + 1);
11326 if (dchannels[i] < 0) {
11327 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);
11328 } else
11329 i++;
11330 c = strchr(c + 1, ',');
11332 if (i) {
11333 if (pri_create_trunkgroup(trunkgroup, dchannels)) {
11334 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);
11335 } else if (option_verbose > 1)
11336 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");
11337 } else
11338 ast_log(LOG_WARNING, "Trunk group %d lacks any valid D-channels at line %d of zapata.conf\n", trunkgroup, v->lineno);
11339 } else
11340 ast_log(LOG_WARNING, "Trunk group %d lacks a primary D-channel at line %d of zapata.conf\n", trunkgroup, v->lineno);
11341 } else
11342 ast_log(LOG_WARNING, "Trunk group identifier must be a positive integer at line %d of zapata.conf\n", v->lineno);
11343 } else if (!strcasecmp(v->name, "spanmap")) {
11344 spanno = atoi(v->value);
11345 if (spanno > 0) {
11346 if ((c = strchr(v->value, ','))) {
11347 trunkgroup = atoi(c + 1);
11348 if (trunkgroup > 0) {
11349 if ((c = strchr(c + 1, ',')))
11350 logicalspan = atoi(c + 1);
11351 else
11352 logicalspan = 0;
11353 if (logicalspan >= 0) {
11354 if (pri_create_spanmap(spanno - 1, trunkgroup, logicalspan)) {
11355 ast_log(LOG_WARNING, "Failed to map span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
11356 } else if (option_verbose > 1)
11357 ast_verbose(VERBOSE_PREFIX_2 "Mapped span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
11358 } else
11359 ast_log(LOG_WARNING, "Logical span must be a postive number, or '0' (for unspecified) at line %d of zapata.conf\n", v->lineno);
11360 } else
11361 ast_log(LOG_WARNING, "Trunk group must be a postive number at line %d of zapata.conf\n", v->lineno);
11362 } else
11363 ast_log(LOG_WARNING, "Missing trunk group for span map at line %d of zapata.conf\n", v->lineno);
11364 } else
11365 ast_log(LOG_WARNING, "Span number must be a postive integer at line %d of zapata.conf\n", v->lineno);
11366 } else {
11367 ast_log(LOG_NOTICE, "Ignoring unknown keyword '%s' in trunkgroups\n", v->name);
11369 v = v->next;
11372 #endif
11374 /* Copy the default jb config over global_jbconf */
11375 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
11377 v = ast_variable_browse(cfg, "channels");
11378 res = process_zap(&conf, v, reload, 0);
11379 ast_mutex_unlock(&iflock);
11380 ast_config_destroy(cfg);
11381 if (res)
11382 return res;
11383 cfg = ast_config_load("users.conf");
11384 if (cfg) {
11385 char *cat;
11386 const char *chans;
11387 process_zap(&conf, ast_variable_browse(cfg, "general"), 1, 1);
11388 for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
11389 if (!strcasecmp(cat, "general"))
11390 continue;
11391 chans = ast_variable_retrieve(cfg, cat, "zapchan");
11392 if (!ast_strlen_zero(chans)) {
11393 struct zt_chan_conf sect_conf;
11394 memcpy(&sect_conf, &conf, sizeof(sect_conf));
11396 process_zap(&sect_conf, ast_variable_browse(cfg, cat), reload, 0);
11399 ast_config_destroy(cfg);
11401 #ifdef HAVE_PRI
11402 if (!reload) {
11403 for (x = 0; x < NUM_SPANS; x++) {
11404 if (pris[x].pvts[0]) {
11405 if (start_pri(pris + x)) {
11406 ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
11407 return -1;
11408 } else if (option_verbose > 1)
11409 ast_verbose(VERBOSE_PREFIX_2 "Starting D-Channel on span %d\n", x + 1);
11413 #endif
11414 /* And start the monitor for the first time */
11415 restart_monitor();
11416 return 0;
11419 static int load_module(void)
11421 int res;
11423 #ifdef HAVE_PRI
11424 int y,i;
11425 memset(pris, 0, sizeof(pris));
11426 for (y = 0; y < NUM_SPANS; y++) {
11427 ast_mutex_init(&pris[y].lock);
11428 pris[y].offset = -1;
11429 pris[y].master = AST_PTHREADT_NULL;
11430 for (i = 0; i < NUM_DCHANS; i++)
11431 pris[y].fds[i] = -1;
11433 pri_set_error(zt_pri_error);
11434 pri_set_message(zt_pri_message);
11435 ast_register_application(zap_send_keypad_facility_app, zap_send_keypad_facility_exec,
11436 zap_send_keypad_facility_synopsis, zap_send_keypad_facility_descrip);
11437 #endif
11438 res = setup_zap(0);
11439 /* Make sure we can register our Zap channel type */
11440 if (res)
11441 return AST_MODULE_LOAD_DECLINE;
11442 if (ast_channel_register(&zap_tech)) {
11443 ast_log(LOG_ERROR, "Unable to register channel class 'Zap'\n");
11444 __unload_module();
11445 return -1;
11447 #ifdef HAVE_PRI
11448 ast_string_field_init(&inuse, 16);
11449 ast_string_field_set(&inuse, name, "GR-303InUse");
11450 ast_cli_register_multiple(zap_pri_cli, sizeof(zap_pri_cli) / sizeof(struct ast_cli_entry));
11451 #endif
11452 ast_cli_register_multiple(zap_cli, sizeof(zap_cli) / sizeof(struct ast_cli_entry));
11454 memset(round_robin, 0, sizeof(round_robin));
11455 ast_manager_register( "ZapTransfer", 0, action_transfer, "Transfer Zap Channel" );
11456 ast_manager_register( "ZapHangup", 0, action_transferhangup, "Hangup Zap Channel" );
11457 ast_manager_register( "ZapDialOffhook", 0, action_zapdialoffhook, "Dial over Zap channel while offhook" );
11458 ast_manager_register( "ZapDNDon", 0, action_zapdndon, "Toggle Zap channel Do Not Disturb status ON" );
11459 ast_manager_register( "ZapDNDoff", 0, action_zapdndoff, "Toggle Zap channel Do Not Disturb status OFF" );
11460 ast_manager_register("ZapShowChannels", 0, action_zapshowchannels, "Show status zapata channels");
11461 ast_manager_register("ZapRestart", 0, action_zaprestart, "Fully Restart zaptel channels (terminates calls)");
11463 return res;
11466 static int zt_sendtext(struct ast_channel *c, const char *text)
11468 #define END_SILENCE_LEN 400
11469 #define HEADER_MS 50
11470 #define TRAILER_MS 5
11471 #define HEADER_LEN ((HEADER_MS + TRAILER_MS) * 8)
11472 #define ASCII_BYTES_PER_CHAR 80
11474 unsigned char *buf,*mybuf;
11475 struct zt_pvt *p = c->tech_pvt;
11476 struct pollfd fds[1];
11477 int size,res,fd,len,x;
11478 int bytes=0;
11479 /* Initial carrier (imaginary) */
11480 float cr = 1.0;
11481 float ci = 0.0;
11482 float scont = 0.0;
11483 int index;
11485 index = zt_get_index(c, p, 0);
11486 if (index < 0) {
11487 ast_log(LOG_WARNING, "Huh? I don't exist?\n");
11488 return -1;
11490 if (!text[0]) return(0); /* if nothing to send, dont */
11491 if ((!p->tdd) && (!p->mate)) return(0); /* if not in TDD mode, just return */
11492 if (p->mate)
11493 buf = ast_malloc(((strlen(text) + 1) * ASCII_BYTES_PER_CHAR) + END_SILENCE_LEN + HEADER_LEN);
11494 else
11495 buf = ast_malloc(((strlen(text) + 1) * TDD_BYTES_PER_CHAR) + END_SILENCE_LEN);
11496 if (!buf)
11497 return -1;
11498 mybuf = buf;
11499 if (p->mate) {
11500 int codec = AST_LAW(p);
11501 for (x = 0; x < HEADER_MS; x++) { /* 50 ms of Mark */
11502 PUT_CLID_MARKMS;
11504 /* Put actual message */
11505 for (x = 0; text[x]; x++) {
11506 PUT_CLID(text[x]);
11508 for (x = 0; x < TRAILER_MS; x++) { /* 5 ms of Mark */
11509 PUT_CLID_MARKMS;
11511 len = bytes;
11512 buf = mybuf;
11513 } else {
11514 len = tdd_generate(p->tdd, buf, text);
11515 if (len < 1) {
11516 ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
11517 free(mybuf);
11518 return -1;
11521 memset(buf + len, 0x7f, END_SILENCE_LEN);
11522 len += END_SILENCE_LEN;
11523 fd = p->subs[index].zfd;
11524 while (len) {
11525 if (ast_check_hangup(c)) {
11526 free(mybuf);
11527 return -1;
11529 size = len;
11530 if (size > READ_SIZE)
11531 size = READ_SIZE;
11532 fds[0].fd = fd;
11533 fds[0].events = POLLOUT | POLLPRI;
11534 fds[0].revents = 0;
11535 res = poll(fds, 1, -1);
11536 if (!res) {
11537 ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
11538 continue;
11540 /* if got exception */
11541 if (fds[0].revents & POLLPRI) {
11542 ast_free(mybuf);
11543 return -1;
11545 if (!(fds[0].revents & POLLOUT)) {
11546 ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
11547 continue;
11549 res = write(fd, buf, size);
11550 if (res != size) {
11551 if (res == -1) {
11552 free(mybuf);
11553 return -1;
11555 if (option_debug)
11556 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
11557 break;
11559 len -= size;
11560 buf += size;
11562 free(mybuf);
11563 return(0);
11567 static int reload(void)
11569 int res = 0;
11571 res = setup_zap(1);
11572 if (res) {
11573 ast_log(LOG_WARNING, "Reload of chan_zap.so is unsuccessful!\n");
11574 return -1;
11576 return 0;
11579 /* This is a workaround so that menuselect displays a proper description
11580 * AST_MODULE_INFO(, , "Zapata Telephony"
11583 #ifdef ZAPATA_PRI
11584 #define tdesc "Zapata Telephony w/PRI"
11585 #else
11586 #define tdesc "Zapata Telephony"
11587 #endif
11589 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, tdesc,
11590 .load = load_module,
11591 .unload = unload_module,
11592 .reload = reload,