Merged revisions 188646 via svnmerge from
[asterisk/asterisk.git] / channels / chan_dahdi.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief DAHDI for Pseudo TDM
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * Connects to the DAHDI telephony library as well as
26  * libpri. Libpri is optional and needed only if you are
27  * going to use ISDN connections.
28  *
29  * You need to install libraries before you attempt to compile
30  * and install the DAHDI channel.
31  *
32  * \par See also
33  * \arg \ref Config_dahdi
34  *
35  * \ingroup channel_drivers
36  *
37  * \todo Deprecate the "musiconhold" configuration option post 1.4
38  */
39
40 /*** MODULEINFO
41         <depend>res_smdi</depend>
42         <depend>dahdi</depend>
43         <depend>tonezone</depend>
44         <use>pri</use>
45         <use>ss7</use>
46         <use>openr2</use>
47  ***/
48
49 #include "asterisk.h"
50
51 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
52
53 #ifdef __NetBSD__
54 #include <pthread.h>
55 #include <signal.h>
56 #else
57 #include <sys/signal.h>
58 #endif
59 #include <sys/ioctl.h>
60 #include <math.h>
61 #include <ctype.h>
62
63 #include <dahdi/user.h>
64 #include <dahdi/tonezone.h>
65
66 #ifdef HAVE_PRI
67 #include <libpri.h>
68 #endif
69
70 #ifdef HAVE_SS7
71 #include <libss7.h>
72 #endif
73
74 #ifdef HAVE_OPENR2
75 #include <openr2.h>
76 #endif
77
78 #include "asterisk/lock.h"
79 #include "asterisk/channel.h"
80 #include "asterisk/config.h"
81 #include "asterisk/module.h"
82 #include "asterisk/pbx.h"
83 #include "asterisk/file.h"
84 #include "asterisk/ulaw.h"
85 #include "asterisk/alaw.h"
86 #include "asterisk/callerid.h"
87 #include "asterisk/adsi.h"
88 #include "asterisk/cli.h"
89 #include "asterisk/cdr.h"
90 #include "asterisk/features.h"
91 #include "asterisk/musiconhold.h"
92 #include "asterisk/say.h"
93 #include "asterisk/tdd.h"
94 #include "asterisk/app.h"
95 #include "asterisk/dsp.h"
96 #include "asterisk/astdb.h"
97 #include "asterisk/manager.h"
98 #include "asterisk/causes.h"
99 #include "asterisk/term.h"
100 #include "asterisk/utils.h"
101 #include "asterisk/transcap.h"
102 #include "asterisk/stringfields.h"
103 #include "asterisk/abstract_jb.h"
104 #include "asterisk/smdi.h"
105 #include "asterisk/astobj.h"
106 #include "asterisk/event.h"
107 #include "asterisk/devicestate.h"
108 #include "asterisk/paths.h"
109
110 /*** DOCUMENTATION
111         <application name="DAHDISendKeypadFacility" language="en_US">
112                 <synopsis>
113                         Send digits out of band over a PRI.
114                 </synopsis>
115                 <syntax>
116                         <parameter name="digits" required="true" />
117                 </syntax>
118                 <description>
119                         <para>This application will send the given string of digits in a Keypad
120                         Facility IE over the current channel.</para>
121                 </description>
122         </application>
123         <application name="DAHDISendCallreroutingFacility" language="en_US">
124                 <synopsis>
125                         Send QSIG call rerouting facility over a PRI.
126                 </synopsis>
127                 <syntax argsep=",">
128                         <parameter name="destination" required="true">
129                                 <para>Destination number.</para>
130                         </parameter>
131                         <parameter name="original">
132                                 <para>Original called number.</para>
133                         </parameter>
134                         <parameter name="reason">
135                                 <para>Diversion reason, if not specified defaults to <literal>unknown</literal></para>
136                         </parameter>
137                 </syntax>
138                 <description>
139                         <para>This application will send a Callrerouting Facility IE over the
140                         current channel.</para>
141                 </description>
142         </application>
143         <application name="DAHDIAcceptR2Call" language="en_US">
144                 <synopsis>
145                         Accept an R2 call if its not already accepted (you still need to answer it)
146                 </synopsis>
147                 <syntax>
148                         <parameter name="charge" required="true">
149                                 <para>Yes or No.</para>
150                                 <para>Whether you want to accept the call with charge or without charge.</para>
151                         </parameter>
152                 </syntax>
153                 <description>
154                         <para>This application will Accept the R2 call either with charge or no charge.</para>
155                 </description>
156         </application>
157  ***/
158
159 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
160
161 static const char *lbostr[] = {
162 "0 db (CSU)/0-133 feet (DSX-1)",
163 "133-266 feet (DSX-1)",
164 "266-399 feet (DSX-1)",
165 "399-533 feet (DSX-1)",
166 "533-655 feet (DSX-1)",
167 "-7.5db (CSU)",
168 "-15db (CSU)",
169 "-22.5db (CSU)"
170 };
171
172 /*! Global jitterbuffer configuration - by default, jb is disabled */
173 static struct ast_jb_conf default_jbconf =
174 {
175         .flags = 0,
176         .max_size = -1,
177         .resync_threshold = -1,
178         .impl = ""
179 };
180 static struct ast_jb_conf global_jbconf;
181
182 /* define this to send PRI user-user information elements */
183 #undef SUPPORT_USERUSER
184
185 /*!
186  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
187  * the user hangs up to reset the state machine so ring works properly.
188  * This is used to be able to support kewlstart by putting the zhone in
189  * groundstart mode since their forward disconnect supervision is entirely
190  * broken even though their documentation says it isn't and their support
191  * is entirely unwilling to provide any assistance with their channel banks
192  * even though their web site says they support their products for life.
193  */
194 /* #define ZHONE_HACK */
195
196 /*! \note
197  * Define if you want to check the hook state for an FXO (FXS signalled) interface
198  * before dialing on it.  Certain FXO interfaces always think they're out of
199  * service with this method however.
200  */
201 /* #define DAHDI_CHECK_HOOKSTATE */
202
203 /*! \brief Typically, how many rings before we should send Caller*ID */
204 #define DEFAULT_CIDRINGS 1
205
206 #define CHANNEL_PSEUDO -12
207
208 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
209
210
211 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
212 #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))
213
214 static const char tdesc[] = "DAHDI Telephony Driver"
215 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
216         " w/"
217 #endif
218 #ifdef HAVE_PRI
219         "PRI"
220 #endif
221 #ifdef HAVE_SS7
222         #ifdef HAVE_PRI
223         " & SS7"
224         #else
225         "SS7"
226         #endif
227 #endif
228 #ifdef HAVE_OPENR2
229         #if defined(HAVE_PRI) || defined(HAVE_SS7)
230         " & MFC/R2"
231         #else
232         "MFC/R2"
233         #endif
234 #endif
235 ;
236
237 static const char config[] = "chan_dahdi.conf";
238
239 #define SIG_EM          DAHDI_SIG_EM
240 #define SIG_EMWINK      (0x0100000 | DAHDI_SIG_EM)
241 #define SIG_FEATD       (0x0200000 | DAHDI_SIG_EM)
242 #define SIG_FEATDMF     (0x0400000 | DAHDI_SIG_EM)
243 #define SIG_FEATB       (0x0800000 | DAHDI_SIG_EM)
244 #define SIG_E911        (0x1000000 | DAHDI_SIG_EM)
245 #define SIG_FEATDMF_TA  (0x2000000 | DAHDI_SIG_EM)
246 #define SIG_FGC_CAMA    (0x4000000 | DAHDI_SIG_EM)
247 #define SIG_FGC_CAMAMF  (0x8000000 | DAHDI_SIG_EM)
248 #define SIG_FXSLS       DAHDI_SIG_FXSLS
249 #define SIG_FXSGS       DAHDI_SIG_FXSGS
250 #define SIG_FXSKS       DAHDI_SIG_FXSKS
251 #define SIG_FXOLS       DAHDI_SIG_FXOLS
252 #define SIG_FXOGS       DAHDI_SIG_FXOGS
253 #define SIG_FXOKS       DAHDI_SIG_FXOKS
254 #define SIG_PRI         DAHDI_SIG_CLEAR
255 #define SIG_BRI         (0x2000000 | DAHDI_SIG_CLEAR)
256 #define SIG_BRI_PTMP    (0X4000000 | DAHDI_SIG_CLEAR)
257 #define SIG_SS7         (0x1000000 | DAHDI_SIG_CLEAR)
258 #define SIG_MFCR2       DAHDI_SIG_CAS
259 #define SIG_SF          DAHDI_SIG_SF
260 #define SIG_SFWINK      (0x0100000 | DAHDI_SIG_SF)
261 #define SIG_SF_FEATD    (0x0200000 | DAHDI_SIG_SF)
262 #define SIG_SF_FEATDMF  (0x0400000 | DAHDI_SIG_SF)
263 #define SIG_SF_FEATB    (0x0800000 | DAHDI_SIG_SF)
264 #define SIG_EM_E1       DAHDI_SIG_EM_E1
265 #define SIG_GR303FXOKS  (0x0100000 | DAHDI_SIG_FXOKS)
266 #define SIG_GR303FXSKS  (0x0100000 | DAHDI_SIG_FXSKS)
267
268 #ifdef LOTS_OF_SPANS
269 #define NUM_SPANS       DAHDI_MAX_SPANS
270 #else
271 #define NUM_SPANS               32
272 #endif
273 #define NUM_DCHANS              4       /*!< No more than 4 d-channels */
274 #define MAX_CHANNELS    672             /*!< No more than a DS3 per trunk group */
275
276 #define CHAN_PSEUDO     -2
277
278 #define DCHAN_PROVISIONED (1 << 0)
279 #define DCHAN_NOTINALARM  (1 << 1)
280 #define DCHAN_UP          (1 << 2)
281
282 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
283
284 /* Overlap dialing option types */
285 #define DAHDI_OVERLAPDIAL_NONE 0
286 #define DAHDI_OVERLAPDIAL_OUTGOING 1
287 #define DAHDI_OVERLAPDIAL_INCOMING 2
288 #define DAHDI_OVERLAPDIAL_BOTH (DAHDI_OVERLAPDIAL_INCOMING|DAHDI_OVERLAPDIAL_OUTGOING)
289
290 #define CALLPROGRESS_PROGRESS           1
291 #define CALLPROGRESS_FAX_OUTGOING       2
292 #define CALLPROGRESS_FAX_INCOMING       4
293 #define CALLPROGRESS_FAX                (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
294
295 #ifdef HAVE_PRI_SERVICE_MESSAGES
296 /*! \brief Persistent Service State */
297 #define SRVST_DBKEY "service-state"
298 /*! \brief The out-of-service SERVICE state */
299 #define SRVST_TYPE_OOS "O"
300 /*! \brief SRVST_INITIALIZED is used to indicate a channel being out-of-service 
301  *  The SRVST_INITIALIZED is mostly used maintain backwards compatibility but also may
302  *  mean that the channel has not yet received a RESTART message.  If a channel is
303  *  out-of-service with this reason a RESTART message will result in the channel
304  *  being put into service. */
305 #define SRVST_INITIALIZED 0
306 /*! \brief SRVST_NEAREND is used to indicate that the near end was put out-of-service */
307 #define SRVST_NEAREND  (1 << 0)
308 /*! \brief SRVST_FAREND is used to indicate that the far end was taken out-of-service */
309 #define SRVST_FAREND   (1 << 1)
310 /*! \brief SRVST_BOTH is used to indicate that both sides of the channel are out-of-service */
311 #define SRVST_BOTH (SRVST_NEAREND | SRVST_FAREND)
312
313 /*! \brief The AstDB family */
314 static const char dahdi_db[] = "dahdi/registry";
315 #endif
316
317 static char defaultcic[64] = "";
318 static char defaultozz[64] = "";
319
320 static char parkinglot[AST_MAX_EXTENSION] = "";         /*!< Default parking lot for this channel */
321
322 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
323 static char mwimonitornotify[PATH_MAX] = "";
324 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI
325 static int  mwisend_rpas = 0;
326 #endif
327
328 static char progzone[10] = "";
329
330 static int usedistinctiveringdetection = 0;
331 static int distinctiveringaftercid = 0;
332
333 static int numbufs = 4;
334
335 static int mwilevel = 512;
336
337 #ifdef HAVE_PRI
338 static struct ast_channel inuse;
339 #ifdef PRI_GETSET_TIMERS
340 static int pritimers[PRI_MAX_TIMERS];
341 #endif
342 static int pridebugfd = -1;
343 static char pridebugfilename[1024] = "";
344 #endif
345
346 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
347 static int firstdigittimeout = 16000;
348
349 /*! \brief How long to wait for following digits (FXO logic) */
350 static int gendigittimeout = 8000;
351
352 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
353 static int matchdigittimeout = 3000;
354
355 /*! \brief Protect the interface list (of dahdi_pvt's) */
356 AST_MUTEX_DEFINE_STATIC(iflock);
357
358 /* QSIG channel mapping option types */
359 #define DAHDI_CHAN_MAPPING_PHYSICAL     0
360 #define DAHDI_CHAN_MAPPING_LOGICAL      1
361
362
363 static int ifcount = 0;
364
365 #ifdef HAVE_PRI
366 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
367 #endif
368
369 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
370    when it's doing something critical. */
371 AST_MUTEX_DEFINE_STATIC(monlock);
372
373 /*! \brief This is the thread for the monitor which checks for input on the channels
374    which are not currently in use. */
375 static pthread_t monitor_thread = AST_PTHREADT_NULL;
376 static ast_cond_t ss_thread_complete;
377 AST_MUTEX_DEFINE_STATIC(ss_thread_lock);
378 AST_MUTEX_DEFINE_STATIC(restart_lock);
379 static int ss_thread_count = 0;
380 static int num_restart_pending = 0;
381
382 static int restart_monitor(void);
383
384 static enum ast_bridge_result dahdi_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
385
386 static int dahdi_sendtext(struct ast_channel *c, const char *text);
387
388 static void mwi_event_cb(const struct ast_event *event, void *userdata)
389 {
390         /* This module does not handle MWI in an event-based manner.  However, it
391          * subscribes to MWI for each mailbox that is configured so that the core
392          * knows that we care about it.  Then, chan_dahdi will get the MWI from the
393          * event cache instead of checking the mailbox directly. */
394 }
395
396 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
397 static inline int dahdi_get_event(int fd)
398 {
399         int j;
400         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
401                 return -1;
402         return j;
403 }
404
405 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
406 static inline int dahdi_wait_event(int fd)
407 {
408         int i, j = 0;
409         i = DAHDI_IOMUX_SIGEVENT;
410         if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
411                 return -1;
412         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
413                 return -1;
414         return j;
415 }
416
417 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
418 #define READ_SIZE 160
419
420 #define MASK_AVAIL              (1 << 0)        /*!< Channel available for PRI use */
421 #define MASK_INUSE              (1 << 1)        /*!< Channel currently in use */
422
423 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /*!< 300 ms */
424 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /*!< 10,000 ms */
425 #define CIDCW_EXPIRE_SAMPLES            ( (500 * 8) / READ_SIZE) /*!< 500 ms */
426 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /*!< 2000 ms */
427 #define DEFAULT_RINGT                           ( (8000 * 8) / READ_SIZE) /*!< 8,000 ms */
428
429 struct dahdi_pvt;
430
431 /*!
432  * \brief Configured ring timeout base.
433  * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
434  */
435 static int ringt_base = DEFAULT_RINGT;
436
437 #ifdef HAVE_SS7
438
439 #define LINKSTATE_INALARM       (1 << 0)
440 #define LINKSTATE_STARTING      (1 << 1)
441 #define LINKSTATE_UP            (1 << 2)
442 #define LINKSTATE_DOWN          (1 << 3)
443
444 #define SS7_NAI_DYNAMIC         -1
445
446 #define LINKSET_FLAG_EXPLICITACM (1 << 0)
447
448 struct dahdi_ss7 {
449         pthread_t master;                                               /*!< Thread of master */
450         ast_mutex_t lock;
451         int fds[NUM_DCHANS];
452         int numsigchans;
453         int linkstate[NUM_DCHANS];
454         int numchans;
455         int type;
456         enum {
457                 LINKSET_STATE_DOWN = 0,
458                 LINKSET_STATE_UP
459         } state;
460         char called_nai;                                                /*!< Called Nature of Address Indicator */
461         char calling_nai;                                               /*!< Calling Nature of Address Indicator */
462         char internationalprefix[10];                                   /*!< country access code ('00' for european dialplans) */
463         char nationalprefix[10];                                        /*!< area access code ('0' for european dialplans) */
464         char subscriberprefix[20];                                      /*!< area access code + area code ('0'+area code for european dialplans) */
465         char unknownprefix[20];                                         /*!< for unknown dialplans */
466         struct ss7 *ss7;
467         struct dahdi_pvt *pvts[MAX_CHANNELS];                           /*!< Member channel pvt structs */
468         int flags;                                                      /*!< Linkset flags */
469 };
470
471 static struct dahdi_ss7 linksets[NUM_SPANS];
472
473 static int cur_ss7type = -1;
474 static int cur_linkset = -1;
475 static int cur_pointcode = -1;
476 static int cur_cicbeginswith = -1;
477 static int cur_adjpointcode = -1;
478 static int cur_networkindicator = -1;
479 static int cur_defaultdpc = -1;
480 #endif /* HAVE_SS7 */
481
482 #ifdef HAVE_OPENR2
483 struct dahdi_mfcr2 {
484         pthread_t r2master;                    /*!< Thread of master */
485         openr2_context_t *protocol_context;    /*!< OpenR2 context handle */
486         struct dahdi_pvt *pvts[MAX_CHANNELS];     /*!< Member channel pvt structs */
487         int numchans;                          /*!< Number of channels in this R2 block */
488         int monitored_count;                   /*!< Number of channels being monitored */
489         ast_mutex_t monitored_count_lock;      /*!< lock access to the counter */
490         ast_cond_t do_monitor;                 /*!< Condition to wake up the monitor thread when there's work to do */
491
492 };
493 struct dahdi_mfcr2_conf {
494         openr2_variant_t variant;
495         int mfback_timeout;
496         int metering_pulse_timeout;
497         int max_ani;
498         int max_dnis;
499         int get_ani_first:1;
500         int call_files:1;
501         int allow_collect_calls:1;
502         int charge_calls:1;
503         int accept_on_offer:1;
504         int forced_release:1;
505         int double_answer:1;
506         int immediate_accept:1;
507         char logdir[OR2_MAX_PATH];
508         char r2proto_file[OR2_MAX_PATH];
509         openr2_log_level_t loglevel;
510         openr2_calling_party_category_t category;
511 };
512
513 /* malloc'd array of malloc'd r2links */
514 static struct dahdi_mfcr2 **r2links;
515 /* how many r2links have been malloc'd */
516 static int r2links_count = 0;
517
518 #endif /* HAVE_OPENR2 */
519
520 #ifdef HAVE_PRI
521
522 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
523 #define PRI_CHANNEL(p) ((p) & 0xff)
524 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
525 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
526
527 struct dahdi_pri {
528         pthread_t master;                                               /*!< Thread of master */
529         ast_mutex_t lock;                                               /*!< Mutex */
530         char idleext[AST_MAX_EXTENSION];                                /*!< Where to idle extra calls */
531         char idlecontext[AST_MAX_CONTEXT];                              /*!< What context to use for idle */
532         char idledial[AST_MAX_EXTENSION];                               /*!< What to dial before dumping */
533         int minunused;                                                  /*!< Min # of channels to keep empty */
534         int minidle;                                                    /*!< Min # of "idling" calls to keep active */
535         int nodetype;                                                   /*!< Node type */
536         int switchtype;                                                 /*!< Type of switch to emulate */
537         int nsf;                                                        /*!< Network-Specific Facilities */
538         int dialplan;                                                   /*!< Dialing plan */
539         int localdialplan;                                              /*!< Local dialing plan */
540         char internationalprefix[10];                                   /*!< country access code ('00' for european dialplans) */
541         char nationalprefix[10];                                        /*!< area access code ('0' for european dialplans) */
542         char localprefix[20];                                           /*!< area access code + area code ('0'+area code for european dialplans) */
543         char privateprefix[20];                                         /*!< for private dialplans */
544         char unknownprefix[20];                                         /*!< for unknown dialplans */
545         int dchannels[NUM_DCHANS];                                      /*!< What channel are the dchannels on */
546         int trunkgroup;                                                 /*!< What our trunkgroup is */
547         int mastertrunkgroup;                                           /*!< What trunk group is our master */
548         int prilogicalspan;                                             /*!< Logical span number within trunk group */
549         int numchans;                                                   /*!< Num of channels we represent */
550         int overlapdial;                                                /*!< In overlap dialing mode */
551         int qsigchannelmapping;                                         /*!< QSIG channel mapping type */
552         int discardremoteholdretrieval;                                 /*!< shall remote hold or remote retrieval notifications be discarded? */
553         int facilityenable;                                             /*!< Enable facility IEs */
554         struct pri *dchans[NUM_DCHANS];                                 /*!< Actual d-channels */
555         int dchanavail[NUM_DCHANS];                                     /*!< Whether each channel is available */
556         struct pri *pri;                                                /*!< Currently active D-channel */
557         /*! \brief TRUE if to dump PRI event info (Tested but never set) */
558         int debug;
559         int fds[NUM_DCHANS];                                            /*!< FD's for d-channels */
560         /*! \brief Value set but not used */
561         int offset;
562         /*! \brief Span number put into user output messages */
563         int span;
564         /*! \brief TRUE if span is being reset/restarted */
565         int resetting;
566         /*! \brief Current position during a reset (-1 if not started) */
567         int resetpos;
568 #ifdef HAVE_PRI_SERVICE_MESSAGES
569         unsigned int enable_service_message_support:1;  /*!< enable SERVICE message support */
570 #endif
571 #ifdef HAVE_PRI_INBANDDISCONNECT
572         unsigned int inbanddisconnect:1;                                /*!< Should we support inband audio after receiving DISCONNECT? */
573 #endif
574         time_t lastreset;                                               /*!< time when unused channels were last reset */
575         long resetinterval;                                             /*!< Interval (in seconds) for resetting unused channels */
576         /*! \brief ISDN signalling type (SIG_PRI, SIG_BRI, SIG_BRI_PTMP, etc...) */
577         int sig;
578         struct dahdi_pvt *pvts[MAX_CHANNELS];                           /*!< Member channel pvt structs */
579         struct dahdi_pvt *crvs;                                         /*!< Member CRV structs */
580         struct dahdi_pvt *crvend;                                               /*!< Pointer to end of CRV structs */
581 };
582
583
584 static struct dahdi_pri pris[NUM_SPANS];
585
586 #if 0
587 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
588 #else
589 #define DEFAULT_PRI_DEBUG 0
590 #endif
591
592 static inline void pri_rel(struct dahdi_pri *pri)
593 {
594         ast_mutex_unlock(&pri->lock);
595 }
596
597 #else
598 /*! Shut up the compiler */
599 struct dahdi_pri;
600 #endif
601
602 #define SUB_REAL        0                       /*!< Active call */
603 #define SUB_CALLWAIT    1                       /*!< Call-Waiting call on hold */
604 #define SUB_THREEWAY    2                       /*!< Three-way call */
605
606 /* Polarity states */
607 #define POLARITY_IDLE   0
608 #define POLARITY_REV    1
609
610
611 struct distRingData {
612         int ring[3];
613         int range;
614 };
615 struct ringContextData {
616         char contextData[AST_MAX_CONTEXT];
617 };
618 struct dahdi_distRings {
619         struct distRingData ringnum[3];
620         struct ringContextData ringContext[3];
621 };
622
623 static char *subnames[] = {
624         "Real",
625         "Callwait",
626         "Threeway"
627 };
628
629 struct dahdi_subchannel {
630         int dfd;
631         struct ast_channel *owner;
632         int chan;
633         short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
634         struct ast_frame f;             /*!< One frame for each channel.  How did this ever work before? */
635         unsigned int needringing:1;
636         unsigned int needbusy:1;
637         unsigned int needcongestion:1;
638         unsigned int needcallerid:1;
639         unsigned int needanswer:1;
640         unsigned int needflash:1;
641         unsigned int needhold:1;
642         unsigned int needunhold:1;
643         unsigned int linear:1;
644         unsigned int inthreeway:1;
645         struct dahdi_confinfo curconf;
646 };
647
648 #define CONF_USER_REAL          (1 << 0)
649 #define CONF_USER_THIRDCALL     (1 << 1)
650
651 #define MAX_SLAVES      4
652
653 /* States for sending MWI message
654  * First three states are required for send Ring Pulse Alert Signal
655  */
656 typedef enum {
657         MWI_SEND_NULL = 0,
658         MWI_SEND_SA,
659         MWI_SEND_SA_WAIT,
660         MWI_SEND_PAUSE,
661         MWI_SEND_SPILL,
662         MWI_SEND_CLEANUP,
663         MWI_SEND_DONE,
664 } mwisend_states;
665
666 struct mwisend_info {
667         struct  timeval pause;
668         mwisend_states  mwisend_current;
669 };
670
671 static struct dahdi_pvt {
672         ast_mutex_t lock;
673         struct ast_channel *owner;                      /*!< Our current active owner (if applicable) */
674                                                         /*!< Up to three channels can be associated with this call */
675
676         struct dahdi_subchannel sub_unused;             /*!< Just a safety precaution */
677         struct dahdi_subchannel subs[3];                        /*!< Sub-channels */
678         struct dahdi_confinfo saveconf;                 /*!< Saved conference info */
679
680         struct dahdi_pvt *slaves[MAX_SLAVES];           /*!< Slave to us (follows our conferencing) */
681         struct dahdi_pvt *master;                               /*!< Master to us (we follow their conferencing) */
682         int inconference;                               /*!< If our real should be in the conference */
683
684         int bufsize;                /*!< Size of the buffers */
685         int buf_no;                                     /*!< Number of buffers */
686         int buf_policy;                         /*!< Buffer policy */
687         int faxbuf_no;              /*!< Number of Fax buffers */
688         int faxbuf_policy;          /*!< Fax buffer policy */
689         int sig;                                        /*!< Signalling style */
690         /*!
691          * \brief Nonzero if the signaling type is sent over a radio.
692          * \note Set to a couple of nonzero values but it is only tested like a boolean.
693          */
694         int radio;
695         int outsigmod;                                  /*!< Outbound Signalling style (modifier) */
696         int oprmode;                                    /*!< "Operator Services" mode */
697         struct dahdi_pvt *oprpeer;                              /*!< "Operator Services" peer tech_pvt ptr */
698         /*! \brief Amount of gain to increase during caller id */
699         float cid_rxgain;
700         /*! \brief Rx gain set by chan_dahdi.conf */
701         float rxgain;
702         /*! \brief Tx gain set by chan_dahdi.conf */
703         float txgain;
704         int tonezone;                                   /*!< tone zone for this chan, or -1 for default */
705         struct dahdi_pvt *next;                         /*!< Next channel in list */
706         struct dahdi_pvt *prev;                         /*!< Prev channel in list */
707
708         /* flags */
709
710         /*!
711          * \brief TRUE if ADSI (Analog Display Services Interface) available
712          * \note Set from the "adsi" value read in from chan_dahdi.conf
713          */
714         unsigned int adsi:1;
715         /*!
716          * \brief TRUE if we can use a polarity reversal to mark when an outgoing
717          * call is answered by the remote party.
718          * \note Set from the "answeronpolarityswitch" value read in from chan_dahdi.conf
719          */
720         unsigned int answeronpolarityswitch:1;
721         /*!
722          * \brief TRUE if busy detection is enabled.
723          * (Listens for the beep-beep busy pattern.)
724          * \note Set from the "busydetect" value read in from chan_dahdi.conf
725          */
726         unsigned int busydetect:1;
727         /*!
728          * \brief TRUE if call return is enabled.
729          * (*69, if your dialplan doesn't catch this first)
730          * \note Set from the "callreturn" value read in from chan_dahdi.conf
731          */
732         unsigned int callreturn:1;
733         /*!
734          * \brief TRUE if busy extensions will hear the call-waiting tone
735          * and can use hook-flash to switch between callers.
736          * \note Can be disabled by dialing *70.
737          * \note Initialized with the "callwaiting" value read in from chan_dahdi.conf
738          */
739         unsigned int callwaiting:1;
740         /*!
741          * \brief TRUE if send caller ID for Call Waiting
742          * \note Set from the "callwaitingcallerid" value read in from chan_dahdi.conf
743          */
744         unsigned int callwaitingcallerid:1;
745         /*!
746          * \brief TRUE if support for call forwarding enabled.
747          * Dial *72 to enable call forwarding.
748          * Dial *73 to disable call forwarding.
749          * \note Set from the "cancallforward" value read in from chan_dahdi.conf
750          */
751         unsigned int cancallforward:1;
752         /*!
753          * \brief TRUE if support for call parking is enabled.
754          * \note Set from the "canpark" value read in from chan_dahdi.conf
755          */
756         unsigned int canpark:1;
757         /*! \brief TRUE if to wait for a DTMF digit to confirm answer */
758         unsigned int confirmanswer:1;
759         /*!
760          * \brief TRUE if the channel is to be destroyed on hangup.
761          * (Used by pseudo channels.)
762          */
763         unsigned int destroy:1;
764         unsigned int didtdd:1;                          /*!< flag to say its done it once */
765         /*! \brief TRUE if analog type line dialed no digits in Dial() */
766         unsigned int dialednone:1;
767         /*! \brief TRUE if in the process of dialing digits or sending something. */
768         unsigned int dialing:1;
769         /*! \brief TRUE if the transfer capability of the call is digital. */
770         unsigned int digital:1;
771         /*! \brief TRUE if Do-Not-Disturb is enabled. */
772         unsigned int dnd:1;
773         /*! \brief XXX BOOLEAN Purpose??? */
774         unsigned int echobreak:1;
775         /*!
776          * \brief TRUE if echo cancellation enabled when bridged.
777          * \note Initialized with the "echocancelwhenbridged" value read in from chan_dahdi.conf
778          * \note Disabled if the echo canceller is not setup.
779          */
780         unsigned int echocanbridged:1;
781         /*! \brief TRUE if echo cancellation is turned on. */
782         unsigned int echocanon:1;
783         /*! \brief TRUE if a fax tone has already been handled. */
784         unsigned int faxhandled:1;
785         /*! \brief TRUE if dynamic faxbuffers are configured for use, default is OFF */
786         unsigned int usefaxbuffers:1;
787         /*! \brief TRUE while dynamic faxbuffers are in use */
788         unsigned int faxbuffersinuse:1;
789         /*! \brief TRUE if over a radio and dahdi_read() has been called. */
790         unsigned int firstradio:1;
791         /*!
792          * \brief TRUE if the call will be considered "hung up" on a polarity reversal.
793          * \note Set from the "hanguponpolarityswitch" value read in from chan_dahdi.conf
794          */
795         unsigned int hanguponpolarityswitch:1;
796         /*! \brief TRUE if DTMF detection needs to be done by hardware. */
797         unsigned int hardwaredtmf:1;
798         /*!
799          * \brief TRUE if the outgoing caller ID is blocked/hidden.
800          * \note Caller ID can be disabled by dialing *67.
801          * \note Caller ID can be enabled by dialing *82.
802          * \note Initialized with the "hidecallerid" value read in from chan_dahdi.conf
803          */
804         unsigned int hidecallerid:1;
805         /*!
806          * \brief TRUE if hide just the name not the number for legacy PBX use.
807          * \note Only applies to PRI channels.
808          * \note Set from the "hidecalleridname" value read in from chan_dahdi.conf
809          */
810         unsigned int hidecalleridname:1;
811         /*! \brief TRUE if DTMF detection is disabled. */
812         unsigned int ignoredtmf:1;
813         /*!
814          * \brief TRUE if the channel should be answered immediately
815          * without attempting to gather any digits.
816          * \note Set from the "immediate" value read in from chan_dahdi.conf
817          */
818         unsigned int immediate:1;
819         /*! \brief TRUE if in an alarm condition. */
820         unsigned int inalarm:1;
821         /*! \brief TRUE if TDD in MATE mode */
822         unsigned int mate:1;
823         /*! \brief TRUE if we originated the call leg. */
824         unsigned int outgoing:1;
825         /* unsigned int overlapdial:1;                  unused and potentially confusing */
826         /*!
827          * \brief TRUE if busy extensions will hear the call-waiting tone
828          * and can use hook-flash to switch between callers.
829          * \note Set from the "callwaiting" value read in from chan_dahdi.conf
830          */
831         unsigned int permcallwaiting:1;
832         /*!
833          * \brief TRUE if the outgoing caller ID is blocked/restricted/hidden.
834          * \note Set from the "hidecallerid" value read in from chan_dahdi.conf
835          */
836         unsigned int permhidecallerid:1;
837         /*!
838          * \brief TRUE if PRI congestion/busy indications are sent out-of-band.
839          * \note Set from the "priindication" value read in from chan_dahdi.conf
840          */
841         unsigned int priindication_oob:1;
842         /*!
843          * \brief TRUE if PRI B channels are always exclusively selected.
844          * \note Set from the "priexclusive" value read in from chan_dahdi.conf
845          */
846         unsigned int priexclusive:1;
847         /*!
848          * \brief TRUE if we will pulse dial.
849          * \note Set from the "pulsedial" value read in from chan_dahdi.conf
850          */
851         unsigned int pulse:1;
852         /*! \brief TRUE if a pulsed digit was detected. (Pulse dial phone detected) */
853         unsigned int pulsedial:1;
854         unsigned int restartpending:1;          /*!< flag to ensure counted only once for restart */
855         /*!
856          * \brief TRUE if caller ID is restricted.
857          * \note Set but not used.  Should be deleted.  Redundant with permhidecallerid.
858          * \note Set from the "restrictcid" value read in from chan_dahdi.conf
859          */
860         unsigned int restrictcid:1;
861         /*!
862          * \brief TRUE if three way calling is enabled
863          * \note Set from the "threewaycalling" value read in from chan_dahdi.conf
864          */
865         unsigned int threewaycalling:1;
866         /*!
867          * \brief TRUE if call transfer is enabled
868          * \note For FXS ports (either direct analog or over T1/E1):
869          *   Support flash-hook call transfer
870          * \note For digital ports using ISDN PRI protocols:
871          *   Support switch-side transfer (called 2BCT, RLT or other names)
872          * \note Set from the "transfer" value read in from chan_dahdi.conf
873          */
874         unsigned int transfer:1;
875         /*!
876          * \brief TRUE if caller ID is used on this channel.
877          * \note PRI and SS7 spans will save caller ID from the networking peer.
878          * \note FXS ports will generate the caller ID spill.
879          * \note FXO ports will listen for the caller ID spill.
880          * \note Set from the "usecallerid" value read in from chan_dahdi.conf
881          */
882         unsigned int use_callerid:1;
883         /*!
884          * \brief TRUE if we will use the calling presentation setting
885          * from the Asterisk channel for outgoing calls.
886          * \note Only applies to PRI and SS7 channels.
887          * \note Set from the "usecallingpres" value read in from chan_dahdi.conf
888          */
889         unsigned int use_callingpres:1;
890         /*!
891          * \brief TRUE if distinctive rings are to be detected.
892          * \note For FXO lines
893          * \note Set indirectly from the "usedistinctiveringdetection" value read in from chan_dahdi.conf
894          */
895         unsigned int usedistinctiveringdetection:1;
896         /*!
897          * \brief TRUE if we should use the callerid from incoming call on dahdi transfer.
898          * \note Set from the "useincomingcalleridondahditransfer" value read in from chan_dahdi.conf
899          */
900         unsigned int dahditrcallerid:1;
901         /*!
902          * \brief TRUE if allowed to flash-transfer to busy channels.
903          * \note Set from the "transfertobusy" value read in from chan_dahdi.conf
904          */
905         unsigned int transfertobusy:1;
906         /*!
907          * \brief TRUE if the FXO port monitors for neon type MWI indications from the other end.
908          * \note Set if the "mwimonitor" value read in contains "neon" from chan_dahdi.conf
909          */
910         unsigned int mwimonitor_neon:1;
911         /*!
912          * \brief TRUE if the FXO port monitors for fsk type MWI indications from the other end.
913          * \note Set if the "mwimonitor" value read in contains "fsk" from chan_dahdi.conf
914          */
915         unsigned int mwimonitor_fsk:1;
916         /*!
917          * \brief TRUE if the FXO port monitors for rpas precursor to fsk MWI indications from the other end.
918          * \note RPAS - Ring Pulse Alert Signal
919          * \note Set if the "mwimonitor" value read in contains "rpas" from chan_dahdi.conf
920          */
921         unsigned int mwimonitor_rpas:1;
922         /*! \brief TRUE if an MWI monitor thread is currently active */
923         unsigned int mwimonitoractive:1;
924         /*! \brief TRUE if a MWI message sending thread is active */
925         unsigned int mwisendactive:1;
926         /*!
927          * \brief TRUE if channel is out of reset and ready
928          * \note Set but not used.
929          */
930         unsigned int inservice:1;
931         /*!
932          * \brief TRUE if the channel is locally blocked.
933          * \note Applies to SS7 channels.
934          */
935         unsigned int locallyblocked:1;
936         /*!
937          * \brief TRUE if the channel is remotely blocked.
938          * \note Applies to SS7 channels.
939          */
940         unsigned int remotelyblocked:1;
941 #if defined(HAVE_PRI) || defined(HAVE_SS7)
942         /*!
943          * \brief XXX BOOLEAN Purpose???
944          * \note Applies to SS7 channels.
945          */
946         unsigned int rlt:1;
947         /*! \brief TRUE if channel is alerting/ringing */
948         unsigned int alerting:1;
949         /*! \brief TRUE if the call has already gone/hungup */
950         unsigned int alreadyhungup:1;
951         /*!
952          * \brief TRUE if this is an idle call
953          * \note Applies to PRI channels.
954          */
955         unsigned int isidlecall:1;
956         /*!
957          * \brief TRUE if call is in a proceeding state.
958          * The call has started working its way through the network.
959          */
960         unsigned int proceeding:1;
961         /*! \brief TRUE if the call has seen progress through the network. */
962         unsigned int progress:1;
963         /*!
964          * \brief TRUE if this channel is being reset/restarted
965          * \note Applies to PRI channels.
966          */
967         unsigned int resetting:1;
968         /*!
969          * \brief TRUE if this channel has received a SETUP_ACKNOWLEDGE
970          * \note Applies to PRI channels.
971          */
972         unsigned int setup_ack:1;
973 #endif
974         /*!
975          * \brief TRUE if SMDI (Simplified Message Desk Interface) is enabled
976          * \note Set from the "usesmdi" value read in from chan_dahdi.conf
977          */
978         unsigned int use_smdi:1;
979         struct mwisend_info mwisend_data;
980         /*! \brief The serial port to listen for SMDI data on */
981         struct ast_smdi_interface *smdi_iface;
982
983         /*! \brief Distinctive Ring data */
984         struct dahdi_distRings drings;
985
986         /*!
987          * \brief The configured context for incoming calls.
988          * \note The "context" string read in from chan_dahdi.conf
989          */
990         char context[AST_MAX_CONTEXT];
991         /*!
992          * \brief Saved context string.
993          */
994         char defcontext[AST_MAX_CONTEXT];
995         /*! \brief Extension to use in the dialplan. */
996         char exten[AST_MAX_EXTENSION];
997         /*!
998          * \brief Language configured for calls.
999          * \note The "language" string read in from chan_dahdi.conf
1000          */
1001         char language[MAX_LANGUAGE];
1002         /*!
1003          * \brief The configured music-on-hold class to use for calls.
1004          * \note The "musicclass" or "mohinterpret" or "musiconhold" string read in from chan_dahdi.conf
1005          */
1006         char mohinterpret[MAX_MUSICCLASS];
1007         /*!
1008          * \brief Sugggested music-on-hold class for peer channel to use for calls.
1009          * \note The "mohsuggest" string read in from chan_dahdi.conf
1010          */
1011         char mohsuggest[MAX_MUSICCLASS];
1012         char parkinglot[AST_MAX_EXTENSION]; /*!< Parking lot for this channel */
1013 #if defined(PRI_ANI) || defined(HAVE_SS7)
1014         /*! \brief Automatic Number Identification number (Alternate PRI caller ID number) */
1015         char cid_ani[AST_MAX_EXTENSION];
1016 #endif
1017         /*! \brief Automatic Number Identification code from PRI */
1018         int cid_ani2;
1019         /*! \brief Caller ID number from an incoming call. */
1020         char cid_num[AST_MAX_EXTENSION];
1021         /*! \brief Caller ID Q.931 TON/NPI field values.  Set by PRI. Zero otherwise. */
1022         int cid_ton;
1023         /*! \brief Caller ID name from an incoming call. */
1024         char cid_name[AST_MAX_EXTENSION];
1025         /*! \brief Last Caller ID number from an incoming call. */
1026         char lastcid_num[AST_MAX_EXTENSION];
1027         /*! \brief Last Caller ID name from an incoming call. */
1028         char lastcid_name[AST_MAX_EXTENSION];
1029         char *origcid_num;                              /*!< malloced original callerid */
1030         char *origcid_name;                             /*!< malloced original callerid */
1031         /*! \brief Call waiting number. */
1032         char callwait_num[AST_MAX_EXTENSION];
1033         /*! \brief Call waiting name. */
1034         char callwait_name[AST_MAX_EXTENSION];
1035         /*! \brief Redirecting Directory Number Information Service (RDNIS) number */
1036         char rdnis[AST_MAX_EXTENSION];
1037         /*! \brief Dialed Number Identifier */
1038         char dnid[AST_MAX_EXTENSION];
1039         /*!
1040          * \brief Bitmapped groups this belongs to.
1041          * \note The "group" bitmapped group string read in from chan_dahdi.conf
1042          */
1043         ast_group_t group;
1044         /*! \brief Active PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW */
1045         int law;
1046         int confno;                                     /*!< Our conference */
1047         int confusers;                                  /*!< Who is using our conference */
1048         int propconfno;                                 /*!< Propagated conference number */
1049         /*!
1050          * \brief Bitmapped call groups this belongs to.
1051          * \note The "callgroup" bitmapped group string read in from chan_dahdi.conf
1052          */
1053         ast_group_t callgroup;
1054         /*!
1055          * \brief Bitmapped pickup groups this belongs to.
1056          * \note The "pickupgroup" bitmapped group string read in from chan_dahdi.conf
1057          */
1058         ast_group_t pickupgroup;
1059         /*!
1060          * \brief Channel variable list with associated values to set when a channel is created.
1061          * \note The "setvar" strings read in from chan_dahdi.conf
1062          */
1063         struct ast_variable *vars;
1064         int channel;                                    /*!< Channel Number or CRV */
1065         int span;                                       /*!< Span number */
1066         time_t guardtime;                               /*!< Must wait this much time before using for new call */
1067         int cid_signalling;                             /*!< CID signalling type bell202 or v23 */
1068         int cid_start;                                  /*!< CID start indicator, polarity or ring */
1069         int callingpres;                                /*!< The value of calling presentation that we're going to use when placing a PRI call */
1070         int callwaitingrepeat;                          /*!< How many samples to wait before repeating call waiting */
1071         int cidcwexpire;                                /*!< When to expire our muting for CID/CW */
1072         /*! \brief Analog caller ID waveform sample buffer */
1073         unsigned char *cidspill;
1074         /*! \brief Position in the cidspill buffer to send out next. */
1075         int cidpos;
1076         /*! \brief Length of the cidspill buffer containing samples. */
1077         int cidlen;
1078         /*! \brief Ring timeout timer?? */
1079         int ringt;
1080         /*!
1081          * \brief Ring timeout base.
1082          * \note Value computed indirectly from "ringtimeout" read in from chan_dahdi.conf
1083          */
1084         int ringt_base;
1085         /*!
1086          * \brief Number of most significant digits/characters to strip from the dialed number.
1087          * \note Feature is deprecated.  Use dialplan logic.
1088          * \note The characters are stripped before the PRI TON/NPI prefix
1089          * characters are processed.
1090          */
1091         int stripmsd;
1092         /*! \brief BOOLEAN. XXX Meaning what?? */
1093         int callwaitcas;
1094         /*! \brief Number of call waiting rings. */
1095         int callwaitrings;
1096         /*! \brief Echo cancel parameters. */
1097         struct {
1098                 struct dahdi_echocanparams head;
1099                 struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
1100         } echocancel;
1101         /*!
1102          * \brief Echo training time. 0 = disabled
1103          * \note Set from the "echotraining" value read in from chan_dahdi.conf
1104          */
1105         int echotraining;
1106         /*! \brief Filled with 'w'.  XXX Purpose?? */
1107         char echorest[20];
1108         /*!
1109          * \brief Number of times to see "busy" tone before hanging up.
1110          * \note Set from the "busycount" value read in from chan_dahdi.conf
1111          */
1112         int busycount;
1113         /*!
1114          * \brief Length of "busy" tone on time.
1115          * \note Set from the "busypattern" value read in from chan_dahdi.conf
1116          */
1117         int busy_tonelength;
1118         /*!
1119          * \brief Length of "busy" tone off time.
1120          * \note Set from the "busypattern" value read in from chan_dahdi.conf
1121          */
1122         int busy_quietlength;
1123         /*!
1124          * \brief Bitmapped call progress detection flags. CALLPROGRESS_xxx values.
1125          * \note Bits set from the "callprogress" and "faxdetect" values read in from chan_dahdi.conf
1126          */
1127         int callprogress;
1128         /*!
1129          * \brief Number of milliseconds to wait for dialtone.
1130          * \note Set from the "waitfordialtone" value read in from chan_dahdi.conf
1131          */
1132         int waitfordialtone;
1133         struct timeval waitingfordt;                    /*!< Time we started waiting for dialtone */
1134         struct timeval flashtime;                       /*!< Last flash-hook time */
1135         /*! \brief Opaque DSP configuration structure. */
1136         struct ast_dsp *dsp;
1137         //int cref;                                     /*!< Call reference number (Not used) */
1138         /*! \brief DAHDI dial operation command struct for ioctl() call. */
1139         struct dahdi_dialoperation dop;
1140         int whichwink;                                  /*!< SIG_FEATDMF_TA Which wink are we on? */
1141         /*! \brief Second part of SIG_FEATDMF_TA wink operation. */
1142         char finaldial[64];
1143         char accountcode[AST_MAX_ACCOUNT_CODE];         /*!< Account code */
1144         int amaflags;                                   /*!< AMA Flags */
1145         struct tdd_state *tdd;                          /*!< TDD flag */
1146         /*! \brief Accumulated call forwarding number. */
1147         char call_forward[AST_MAX_EXTENSION];
1148         /*!
1149          * \brief Voice mailbox location.
1150          * \note Set from the "mailbox" string read in from chan_dahdi.conf
1151          */
1152         char mailbox[AST_MAX_EXTENSION];
1153         /*! \brief Opaque event subscription parameters for message waiting indication support. */
1154         struct ast_event_sub *mwi_event_sub;
1155         /*! \brief Delayed dialing for E911.  Overlap digits for ISDN. */
1156         char dialdest[256];
1157         /*! \brief Time the interface went on-hook. */
1158         int onhooktime;
1159         /*! \brief TRUE if the FXS port is off-hook */
1160         int fxsoffhookstate;
1161         /*! \brief -1 = unknown, 0 = no messages, 1 = new messages available */
1162         int msgstate;
1163 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
1164         struct dahdi_vmwi_info mwisend_setting;                         /*!< Which VMWI methods to use */
1165         unsigned int mwisend_fsk: 1;            /*! Variable for enabling FSK MWI handling in chan_dahdi */
1166         unsigned int mwisend_rpas:1;            /*! Variable for enabling Ring Pulse Alert before MWI FSK Spill */
1167 #endif
1168         int distinctivering;                            /*!< Which distinctivering to use */
1169         int cidrings;                                   /*!< Which ring to deliver CID on */
1170         int dtmfrelax;                                  /*!< whether to run in relaxed DTMF mode */
1171         /*! \brief Holding place for event injected from outside normal operation. */
1172         int fake_event;
1173         /*!
1174          * \brief Minimal time period (ms) between the answer polarity
1175          * switch and hangup polarity switch.
1176          */
1177         int polarityonanswerdelay;
1178         /*! \brief Start delay time if polarityonanswerdelay is nonzero. */
1179         struct timeval polaritydelaytv;
1180         /*!
1181          * \brief Send caller ID after this many rings.
1182          * \note Set from the "sendcalleridafter" value read in from chan_dahdi.conf
1183          */
1184         int sendcalleridafter;
1185 #ifdef HAVE_PRI
1186         /*! \brief DAHDI PRI control parameters */
1187         struct dahdi_pri *pri;
1188         /*! \brief XXX Purpose??? */
1189         struct dahdi_pvt *bearer;
1190         /*! \brief XXX Purpose??? */
1191         struct dahdi_pvt *realcall;
1192         /*! \brief Opaque libpri call control structure */
1193         q931_call *call;
1194         /*! \brief Channel number in span. */
1195         int prioffset;
1196         /*! \brief Logical span number within trunk group */
1197         int logicalspan;
1198 #endif
1199         /*! \brief Current line interface polarity. POLARITY_IDLE, POLARITY_REV */
1200         int polarity;
1201         /*! \brief DSP feature flags: DSP_FEATURE_xxx */
1202         int dsp_features;
1203 #ifdef HAVE_SS7
1204         /*! \brief SS7 control parameters */
1205         struct dahdi_ss7 *ss7;
1206         /*! \brief Opaque libss7 call control structure */
1207         struct isup_call *ss7call;
1208         char charge_number[50];
1209         char gen_add_number[50];
1210         char gen_dig_number[50];
1211         char orig_called_num[50];
1212         char redirecting_num[50];
1213         char generic_name[50];
1214         unsigned char gen_add_num_plan;
1215         unsigned char gen_add_nai;
1216         unsigned char gen_add_pres_ind;
1217         unsigned char gen_add_type;
1218         unsigned char gen_dig_type;
1219         unsigned char gen_dig_scheme;
1220         char jip_number[50];
1221         unsigned char lspi_type;
1222         unsigned char lspi_scheme;
1223         unsigned char lspi_context;
1224         char lspi_ident[50];
1225         unsigned int call_ref_ident;
1226         unsigned int call_ref_pc;
1227         unsigned char calling_party_cat;
1228         int transcap;
1229         int cic;                                                        /*!< CIC associated with channel */
1230         unsigned int dpc;                                               /*!< CIC's DPC */
1231         unsigned int loopedback:1;
1232 #endif
1233 #ifdef HAVE_OPENR2
1234         struct dahdi_mfcr2 *mfcr2;
1235         openr2_chan_t *r2chan;
1236         openr2_calling_party_category_t mfcr2_recvd_category;
1237         openr2_calling_party_category_t mfcr2_category;
1238         int mfcr2_dnis_index;
1239         int mfcr2_ani_index;
1240         int mfcr2call:1;
1241         int mfcr2_answer_pending:1;
1242         int mfcr2_charge_calls:1;
1243         int mfcr2_allow_collect_calls:1;
1244         int mfcr2_forced_release:1;
1245         int mfcr2_dnis_matched:1;
1246         int mfcr2_call_accepted:1;
1247         int mfcr2_accept_on_offer:1;
1248 #endif
1249         /*! \brief DTMF digit in progress.  0 when no digit in progress. */
1250         char begindigit;
1251         /*! \brief TRUE if confrence is muted. */
1252         int muting;
1253 } *iflist = NULL, *ifend = NULL;
1254
1255 /*! \brief Channel configuration from chan_dahdi.conf .
1256  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
1257  * Generally there is a field here for every possible configuration item.
1258  *
1259  * The state of fields is saved along the parsing and whenever a 'channel'
1260  * statement is reached, the current dahdi_chan_conf is used to configure the
1261  * channel (struct dahdi_pvt)
1262  *
1263  * \see dahdi_chan_init for the default values.
1264  */
1265 struct dahdi_chan_conf {
1266         struct dahdi_pvt chan;
1267 #ifdef HAVE_PRI
1268         struct dahdi_pri pri;
1269 #endif
1270
1271 #ifdef HAVE_SS7
1272         struct dahdi_ss7 ss7;
1273 #endif
1274
1275 #ifdef HAVE_OPENR2
1276         struct dahdi_mfcr2_conf mfcr2;
1277 #endif
1278         struct dahdi_params timing;
1279         int is_sig_auto; /*!< Use channel signalling from DAHDI? */
1280
1281         /*!
1282          * \brief The serial port to listen for SMDI data on
1283          * \note Set from the "smdiport" string read in from chan_dahdi.conf
1284          */
1285         char smdi_port[SMDI_MAX_FILENAME_LEN];
1286 };
1287
1288 /*! returns a new dahdi_chan_conf with default values (by-value) */
1289 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
1290 {
1291         /* recall that if a field is not included here it is initialized
1292          * to 0 or equivalent
1293          */
1294         struct dahdi_chan_conf conf = {
1295 #ifdef HAVE_PRI
1296                 .pri = {
1297                         .nsf = PRI_NSF_NONE,
1298                         .switchtype = PRI_SWITCH_NI2,
1299                         .dialplan = PRI_UNKNOWN + 1,
1300                         .localdialplan = PRI_NATIONAL_ISDN + 1,
1301                         .nodetype = PRI_CPE,
1302                         .qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL,
1303
1304                         .minunused = 2,
1305                         .idleext = "",
1306                         .idledial = "",
1307                         .internationalprefix = "",
1308                         .nationalprefix = "",
1309                         .localprefix = "",
1310                         .privateprefix = "",
1311                         .unknownprefix = "",
1312                         .resetinterval = -1,
1313                 },
1314 #endif
1315 #ifdef HAVE_SS7
1316                 .ss7 = {
1317                         .called_nai = SS7_NAI_NATIONAL,
1318                         .calling_nai = SS7_NAI_NATIONAL,
1319                         .internationalprefix = "",
1320                         .nationalprefix = "",
1321                         .subscriberprefix = "",
1322                         .unknownprefix = ""
1323                 },
1324 #endif
1325 #ifdef HAVE_OPENR2
1326                 .mfcr2 = {
1327                         .variant = OR2_VAR_ITU,
1328                         .mfback_timeout = -1,
1329                         .metering_pulse_timeout = -1,
1330                         .max_ani = 10,
1331                         .max_dnis = 4,
1332                         .get_ani_first = -1,
1333                         .call_files = 0,
1334                         .allow_collect_calls = 0,
1335                         .charge_calls = 1,
1336                         .accept_on_offer = 1,
1337                         .forced_release = 0,
1338                         .double_answer = 0,
1339                         .immediate_accept = -1,
1340                         .logdir = "",
1341                         .r2proto_file = "",
1342                         .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
1343                         .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
1344                 },
1345 #endif
1346                 .chan = {
1347                         .context = "default",
1348                         .cid_num = "",
1349                         .cid_name = "",
1350                         .mohinterpret = "default",
1351                         .mohsuggest = "",
1352                         .parkinglot = "",
1353                         .transfertobusy = 1,
1354
1355                         .cid_signalling = CID_SIG_BELL,
1356                         .cid_start = CID_START_RING,
1357                         .dahditrcallerid = 0,
1358                         .use_callerid = 1,
1359                         .sig = -1,
1360                         .outsigmod = -1,
1361
1362                         .cid_rxgain = +5.0,
1363
1364                         .tonezone = -1,
1365
1366                         .echocancel.head.tap_length = 1,
1367
1368                         .busycount = 3,
1369
1370                         .accountcode = "",
1371
1372                         .mailbox = "",
1373
1374 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
1375                         .mwisend_fsk = 1,
1376 #endif
1377                         .polarityonanswerdelay = 600,
1378
1379                         .sendcalleridafter = DEFAULT_CIDRINGS,
1380
1381                         .buf_policy = DAHDI_POLICY_IMMEDIATE,
1382                         .buf_no = numbufs,
1383                         .usefaxbuffers = 0,
1384                         .faxbuf_policy = DAHDI_POLICY_IMMEDIATE,
1385                         .faxbuf_no = numbufs,
1386                 },
1387                 .timing = {
1388                         .prewinktime = -1,
1389                         .preflashtime = -1,
1390                         .winktime = -1,
1391                         .flashtime = -1,
1392                         .starttime = -1,
1393                         .rxwinktime = -1,
1394                         .rxflashtime = -1,
1395                         .debouncetime = -1
1396                 },
1397                 .is_sig_auto = 1,
1398                 .smdi_port = "/dev/ttyS0",
1399         };
1400
1401         return conf;
1402 }
1403
1404
1405 static struct ast_channel *dahdi_request(const char *type, int format, void *data, int *cause);
1406 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
1407 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
1408 static int dahdi_sendtext(struct ast_channel *c, const char *text);
1409 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout);
1410 static int dahdi_hangup(struct ast_channel *ast);
1411 static int dahdi_answer(struct ast_channel *ast);
1412 static struct ast_frame *dahdi_read(struct ast_channel *ast);
1413 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
1414 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
1415 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
1416 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1417 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1418 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
1419 static int handle_init_event(struct dahdi_pvt *i, int event);
1420
1421 static const struct ast_channel_tech dahdi_tech = {
1422         .type = "DAHDI",
1423         .description = tdesc,
1424         .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
1425         .requester = dahdi_request,
1426         .send_digit_begin = dahdi_digit_begin,
1427         .send_digit_end = dahdi_digit_end,
1428         .send_text = dahdi_sendtext,
1429         .call = dahdi_call,
1430         .hangup = dahdi_hangup,
1431         .answer = dahdi_answer,
1432         .read = dahdi_read,
1433         .write = dahdi_write,
1434         .bridge = dahdi_bridge,
1435         .exception = dahdi_exception,
1436         .indicate = dahdi_indicate,
1437         .fixup = dahdi_fixup,
1438         .setoption = dahdi_setoption,
1439         .func_channel_read = dahdi_func_read,
1440 };
1441
1442 #ifdef HAVE_PRI
1443 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
1444 #else
1445 #define GET_CHANNEL(p) ((p)->channel)
1446 #endif
1447
1448 struct dahdi_pvt *round_robin[32];
1449
1450 #if defined(HAVE_PRI)
1451 static inline int pri_grab(struct dahdi_pvt *pvt, struct dahdi_pri *pri)
1452 {
1453         int res;
1454         /* Grab the lock first */
1455         do {
1456                 res = ast_mutex_trylock(&pri->lock);
1457                 if (res) {
1458                         DEADLOCK_AVOIDANCE(&pvt->lock);
1459                 }
1460         } while (res);
1461         /* Then break the poll */
1462         if (pri->master != AST_PTHREADT_NULL)
1463                 pthread_kill(pri->master, SIGURG);
1464         return 0;
1465 }
1466 #endif  /* defined(HAVE_PRI) */
1467
1468 #if defined(HAVE_SS7)
1469 static inline void ss7_rel(struct dahdi_ss7 *ss7)
1470 {
1471         ast_mutex_unlock(&ss7->lock);
1472 }
1473 #endif  /* defined(HAVE_SS7) */
1474
1475 #if defined(HAVE_SS7)
1476 static inline int ss7_grab(struct dahdi_pvt *pvt, struct dahdi_ss7 *pri)
1477 {
1478         int res;
1479         /* Grab the lock first */
1480         do {
1481                 res = ast_mutex_trylock(&pri->lock);
1482                 if (res) {
1483                         DEADLOCK_AVOIDANCE(&pvt->lock);
1484                 }
1485         } while (res);
1486         /* Then break the poll */
1487         if (pri->master != AST_PTHREADT_NULL)
1488                 pthread_kill(pri->master, SIGURG);
1489         return 0;
1490 }
1491 #endif  /* defined(HAVE_SS7) */
1492 #define NUM_CADENCE_MAX 25
1493 static int num_cadence = 4;
1494 static int user_has_defined_cadences = 0;
1495
1496 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
1497         { { 125, 125, 2000, 4000 } },                   /*!< Quick chirp followed by normal ring */
1498         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
1499         { { 125, 125, 125, 125, 125, 4000 } },  /*!< Three short bursts */
1500         { { 1000, 500, 2500, 5000 } },  /*!< Long ring */
1501 };
1502
1503 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
1504  * is 1, the second pause is 2 and so on.
1505  */
1506
1507 static int cidrings[NUM_CADENCE_MAX] = {
1508         2,                                                                              /*!< Right after first long ring */
1509         4,                                                                              /*!< Right after long part */
1510         3,                                                                              /*!< After third chirp */
1511         2,                                                                              /*!< Second spell */
1512 };
1513
1514 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
1515 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
1516
1517 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
1518                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
1519
1520 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
1521 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
1522
1523 static int dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok)
1524 {
1525         int res;
1526         if (p->subs[SUB_REAL].owner == ast)
1527                 res = 0;
1528         else if (p->subs[SUB_CALLWAIT].owner == ast)
1529                 res = 1;
1530         else if (p->subs[SUB_THREEWAY].owner == ast)
1531                 res = 2;
1532         else {
1533                 res = -1;
1534                 if (!nullok)
1535                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
1536         }
1537         return res;
1538 }
1539
1540 static void wakeup_sub(struct dahdi_pvt *p, int a, struct dahdi_pri *pri)
1541 {
1542 #ifdef HAVE_PRI
1543         if (pri)
1544                 ast_mutex_unlock(&pri->lock);
1545 #endif
1546         for (;;) {
1547                 if (p->subs[a].owner) {
1548                         if (ast_channel_trylock(p->subs[a].owner)) {
1549                                 DEADLOCK_AVOIDANCE(&p->lock);
1550                         } else {
1551                                 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
1552                                 ast_channel_unlock(p->subs[a].owner);
1553                                 break;
1554                         }
1555                 } else
1556                         break;
1557         }
1558 #ifdef HAVE_PRI
1559         if (pri)
1560                 ast_mutex_lock(&pri->lock);
1561 #endif
1562 }
1563
1564 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f, void *data)
1565 {
1566 #ifdef HAVE_PRI
1567         struct dahdi_pri *pri = (struct dahdi_pri*) data;
1568 #endif
1569 #ifdef HAVE_SS7
1570         struct dahdi_ss7 *ss7 = (struct dahdi_ss7*) data;
1571 #endif
1572         /* We must unlock the PRI to avoid the possibility of a deadlock */
1573 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1574         if (data) {
1575                 switch (p->sig) {
1576 #ifdef HAVE_PRI
1577                 case SIG_BRI:
1578                 case SIG_BRI_PTMP:
1579                 case SIG_PRI:
1580                         ast_mutex_unlock(&pri->lock);
1581                         break;
1582 #endif
1583 #ifdef HAVE_SS7
1584                 case SIG_SS7:
1585                         ast_mutex_unlock(&ss7->lock);
1586                         break;
1587 #endif
1588                 default:
1589                         break;
1590                 }
1591         }
1592 #endif
1593         for (;;) {
1594                 if (p->owner) {
1595                         if (ast_channel_trylock(p->owner)) {
1596                                 DEADLOCK_AVOIDANCE(&p->lock);
1597                         } else {
1598                                 ast_queue_frame(p->owner, f);
1599                                 ast_channel_unlock(p->owner);
1600                                 break;
1601                         }
1602                 } else
1603                         break;
1604         }
1605 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1606         if (data) {
1607                 switch (p->sig) {
1608 #ifdef HAVE_PRI
1609                 case SIG_BRI:
1610                 case SIG_BRI_PTMP:
1611                 case SIG_PRI:
1612                         ast_mutex_lock(&pri->lock);
1613                         break;
1614 #endif
1615 #ifdef HAVE_SS7
1616                 case SIG_SS7:
1617                         ast_mutex_lock(&ss7->lock);
1618                         break;
1619 #endif
1620                 default:
1621                         break;
1622                 }
1623         }
1624 #endif
1625 }
1626
1627 static struct ast_channel *dahdi_new(struct dahdi_pvt *, int, int, int, int, int);
1628 #ifdef HAVE_OPENR2
1629
1630 static int dahdi_r2_answer(struct dahdi_pvt *p)
1631 {
1632         int res = 0;
1633         /* openr2 1.1.0 and older does not even define OR2_LIB_INTERFACE
1634         * and does not has support for openr2_chan_answer_call_with_mode
1635         *  */
1636 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
1637         const char *double_answer = pbx_builtin_getvar_helper(p->owner, "MFCR2_DOUBLE_ANSWER");
1638         int wants_double_answer = ast_true(double_answer) ? 1 : 0;
1639         if (!double_answer) {
1640                 /* this still can result in double answer if the channel context
1641                 * was configured that way */
1642                 res = openr2_chan_answer_call(p->r2chan);
1643         } else if (wants_double_answer) {
1644                 res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_DOUBLE);
1645         } else {
1646                 res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_SIMPLE);
1647         }
1648 #else
1649         res = openr2_chan_answer_call(p->r2chan);
1650 #endif
1651         return res;
1652 }
1653
1654
1655
1656 /* should be called with the ast_channel locked */
1657 static openr2_calling_party_category_t dahdi_r2_get_channel_category(struct ast_channel *c)
1658 {
1659         openr2_calling_party_category_t cat;
1660         const char *catstr = pbx_builtin_getvar_helper(c, "MFCR2_CATEGORY");
1661         struct dahdi_pvt *p = c->tech_pvt;
1662         if (ast_strlen_zero(catstr)) {
1663                 ast_debug(1, "No MFC/R2 category specified for chan %s, using default %s\n",
1664                                 c->name, openr2_proto_get_category_string(p->mfcr2_category));
1665                 return p->mfcr2_category;
1666         }
1667         if ((cat = openr2_proto_get_category(catstr)) == OR2_CALLING_PARTY_CATEGORY_UNKNOWN) {
1668                 ast_log(LOG_WARNING, "Invalid category specified '%s' for chan %s, using default %s\n",
1669                                 catstr, c->name, openr2_proto_get_category_string(p->mfcr2_category));
1670                 return p->mfcr2_category;
1671         }
1672         ast_debug(1, "Using category %s\n", catstr);
1673         return cat;
1674 }
1675
1676 static void dahdi_r2_on_call_init(openr2_chan_t *r2chan)
1677 {
1678         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1679         ast_mutex_lock(&p->lock);
1680         if (p->mfcr2call) {
1681                 ast_mutex_unlock(&p->lock);
1682                 /* TODO: This can happen when some other thread just finished dahdi_request requesting this very same
1683                    interface but has not yet seized the line (dahdi_call), and the far end wins and seize the line,
1684                    can we avoid this somehow?, at this point when dahdi_call send the seize, it is likely that since
1685                    the other end will see our seize as a forced release and drop the call, we will see an invalid
1686                    pattern that will be seen and treated as protocol error. */
1687                 ast_log(LOG_ERROR, "Collision of calls on chan %d detected!.\n", openr2_chan_get_number(r2chan));
1688                 return;
1689         }
1690         p->mfcr2call = 1;
1691         /* better safe than sorry ... */
1692         p->cid_name[0] = '\0';
1693         p->cid_num[0] = '\0';
1694         p->rdnis[0] = '\0';
1695         p->exten[0] = '\0';
1696         p->mfcr2_ani_index = '\0';
1697         p->mfcr2_dnis_index = '\0';
1698         p->mfcr2_dnis_matched = 0;
1699         p->mfcr2_answer_pending = 0;
1700         p->mfcr2_call_accepted = 0;
1701         ast_mutex_unlock(&p->lock);
1702         ast_log(LOG_NOTICE, "New MFC/R2 call detected on chan %d.\n", openr2_chan_get_number(r2chan));
1703 }
1704
1705 static int get_alarms(struct dahdi_pvt *p);
1706 static void handle_alarms(struct dahdi_pvt *p, int alms);
1707 static void dahdi_r2_on_hardware_alarm(openr2_chan_t *r2chan, int alarm)
1708 {
1709         int res;
1710         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1711         ast_mutex_lock(&p->lock);
1712         p->inalarm = alarm ? 1 : 0;
1713         if (p->inalarm) {
1714                 res = get_alarms(p);
1715                 handle_alarms(p, res);
1716         } else {
1717                 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
1718                 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear", "Channel: %d\r\n", p->channel);
1719         }
1720         ast_mutex_unlock(&p->lock);
1721 }
1722
1723 static void dahdi_r2_on_os_error(openr2_chan_t *r2chan, int errorcode)
1724 {
1725         ast_log(LOG_ERROR, "OS error on chan %d: %s\n", openr2_chan_get_number(r2chan), strerror(errorcode));
1726 }
1727
1728 static void dahdi_r2_on_protocol_error(openr2_chan_t *r2chan, openr2_protocol_error_t reason)
1729 {
1730         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1731         ast_log(LOG_ERROR, "MFC/R2 protocol error on chan %d: %s\n", openr2_chan_get_number(r2chan), openr2_proto_get_error(reason));
1732         if (p->owner) {
1733                 p->owner->hangupcause = AST_CAUSE_PROTOCOL_ERROR;
1734                 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1735         }
1736         ast_mutex_lock(&p->lock);
1737         p->mfcr2call = 0;
1738         ast_mutex_unlock(&p->lock);
1739 }
1740
1741 static void dahdi_r2_update_monitor_count(struct dahdi_mfcr2 *mfcr2, int increment)
1742 {
1743         ast_mutex_lock(&mfcr2->monitored_count_lock);
1744         if (increment) {
1745                 mfcr2->monitored_count++;
1746                 if (mfcr2->monitored_count == 1) {
1747                         ast_log(LOG_DEBUG, "At least one device needs monitoring, let's wake up the monitor thread.\n");
1748                         ast_cond_signal(&mfcr2->do_monitor);
1749                 }
1750         } else {
1751                 mfcr2->monitored_count--;
1752                 if (mfcr2->monitored_count < 0) {
1753                         ast_log(LOG_ERROR, "we have a bug here!.\n");
1754                 }
1755         }
1756         ast_mutex_unlock(&mfcr2->monitored_count_lock);
1757 }
1758
1759 static void dahdi_r2_on_call_offered(openr2_chan_t *r2chan, const char *ani, const char *dnis, openr2_calling_party_category_t category)
1760 {
1761         struct dahdi_pvt *p;
1762         struct ast_channel *c;
1763         ast_log(LOG_NOTICE, "MFC/R2 call offered on chan %d. ANI = %s, DNIS = %s, Category = %s\n",
1764                         openr2_chan_get_number(r2chan), ani ? ani : "(restricted)", dnis,
1765                         openr2_proto_get_category_string(category));
1766         p = openr2_chan_get_client_data(r2chan);
1767         /* if collect calls are not allowed and this is a collect call, reject it! */
1768         if (!p->mfcr2_allow_collect_calls && category == OR2_CALLING_PARTY_CATEGORY_COLLECT_CALL) {
1769                 ast_log(LOG_NOTICE, "Rejecting MFC/R2 collect call\n");
1770                 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_COLLECT_CALL_REJECTED);
1771                 return;
1772         }
1773         ast_mutex_lock(&p->lock);
1774         p->mfcr2_recvd_category = category;
1775         /* if we're not supposed to use CID, clear whatever we have */
1776         if (!p->use_callerid) {
1777                 ast_log(LOG_DEBUG, "No CID allowed in configuration, CID is being cleared!\n");
1778                 p->cid_num[0] = 0;
1779                 p->cid_name[0] = 0;
1780         }
1781         /* if we're supposed to answer immediately, clear DNIS and set 's' exten */
1782         if (p->immediate || !openr2_context_get_max_dnis(openr2_chan_get_context(r2chan))) {
1783                 ast_log(LOG_DEBUG, "Setting exten => s because of immediate or 0 DNIS configured\n");
1784                 p->exten[0] = 's';
1785                 p->exten[1] = 0;
1786         }
1787         ast_mutex_unlock(&p->lock);
1788         if (!ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
1789                 ast_log(LOG_NOTICE, "MFC/R2 call on channel %d requested non-existent extension '%s' in context '%s'. Rejecting call.\n",
1790                                 p->channel, p->exten, p->context);
1791                 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_UNALLOCATED_NUMBER);
1792                 return;
1793         }
1794         if (!p->mfcr2_accept_on_offer) {
1795                 /* The user wants us to start the PBX thread right away without accepting the call first */
1796                 c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, 0);
1797                 if (c) {
1798                         dahdi_r2_update_monitor_count(p->mfcr2, 0);
1799                         /* Done here, don't disable reading now since we still need to generate MF tones to accept
1800                            the call or reject it and detect the tone off condition of the other end, all of this
1801                            will be done in the PBX thread now */
1802                         return;
1803                 }
1804                 ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
1805                 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_OUT_OF_ORDER);
1806         } else if (p->mfcr2_charge_calls) {
1807                 ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge on chan %d\n", p->channel);
1808                 openr2_chan_accept_call(r2chan, OR2_CALL_WITH_CHARGE);
1809         } else {
1810                 ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge on chan %d\n", p->channel);
1811                 openr2_chan_accept_call(r2chan, OR2_CALL_NO_CHARGE);
1812         }
1813 }
1814
1815 static void dahdi_r2_on_call_end(openr2_chan_t *r2chan)
1816 {
1817         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1818         ast_log(LOG_NOTICE, "MFC/R2 call end on chan %d\n", p->channel);
1819         ast_mutex_lock(&p->lock);
1820         p->mfcr2call = 0;
1821         ast_mutex_unlock(&p->lock);
1822 }
1823
1824 static void dahdi_enable_ec(struct dahdi_pvt *p);
1825 static void dahdi_r2_on_call_accepted(openr2_chan_t *r2chan, openr2_call_mode_t mode)
1826 {
1827         struct dahdi_pvt *p = NULL;
1828         struct ast_channel *c = NULL;
1829         ast_log(LOG_NOTICE, "MFC/R2 call has been accepted on chan %d\n", openr2_chan_get_number(r2chan));
1830         p = openr2_chan_get_client_data(r2chan);
1831         dahdi_enable_ec(p);
1832         p->mfcr2_call_accepted = 1;
1833         /* if it's an incoming call ... */
1834         if (OR2_DIR_BACKWARD == openr2_chan_get_direction(r2chan)) {
1835                 /* If accept on offer is not set, it means at this point the PBX thread is already
1836                    launched (was launched in the 'on call offered' handler) and therefore this callback
1837                    is being executed already in the PBX thread rather than the monitor thread, don't launch
1838                    any other thread, just disable the openr2 reading and answer the call if needed */
1839                 if (!p->mfcr2_accept_on_offer) {
1840                         openr2_chan_disable_read(r2chan);
1841                         if (p->mfcr2_answer_pending) {
1842                                 ast_log(LOG_DEBUG, "Answering MFC/R2 call after accepting it on chan %d\n", openr2_chan_get_number(r2chan));
1843                                 dahdi_r2_answer(p);
1844                         }
1845                         return;
1846                 }
1847                 c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, 0);
1848                 if (c) {
1849                         dahdi_r2_update_monitor_count(p->mfcr2, 0);
1850                         /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
1851                            library to forget about it */
1852                         openr2_chan_disable_read(r2chan);
1853                         return;
1854                 }
1855                 ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
1856                 /* failed to create the channel, bail out and report it as an out of order line */
1857                 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_OUT_OF_ORDER);
1858                 return;
1859         }
1860         /* this is an outgoing call, no need to launch the PBX thread, most likely we're in one already */
1861         ast_log(LOG_NOTICE, "Call accepted on forward channel %d\n", p->channel);
1862         p->subs[SUB_REAL].needringing = 1;
1863         p->dialing = 0;
1864         /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
1865            library to forget about it */
1866         openr2_chan_disable_read(r2chan);
1867 }
1868
1869 static void dahdi_r2_on_call_answered(openr2_chan_t *r2chan)
1870 {
1871         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1872         ast_log(LOG_DEBUG, "MFC/R2 call has been answered on chan %d\n", openr2_chan_get_number(r2chan));
1873         p->subs[SUB_REAL].needanswer = 1;
1874 }
1875
1876 static void dahdi_r2_on_call_read(openr2_chan_t *r2chan, const unsigned char *buf, int buflen)
1877 {
1878         /*ast_log(LOG_DEBUG, "Read data from dahdi channel %d\n", openr2_chan_get_number(r2chan));*/
1879 }
1880
1881 static int dahdi_r2_cause_to_ast_cause(openr2_call_disconnect_cause_t cause)
1882 {
1883         switch (cause) {
1884         case OR2_CAUSE_BUSY_NUMBER:
1885                 return AST_CAUSE_BUSY;
1886         case OR2_CAUSE_NETWORK_CONGESTION:
1887                 return AST_CAUSE_CONGESTION;
1888         case OR2_CAUSE_OUT_OF_ORDER:
1889                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1890         case OR2_CAUSE_UNALLOCATED_NUMBER:
1891                 return AST_CAUSE_UNREGISTERED;
1892         case OR2_CAUSE_NO_ANSWER:
1893                 return AST_CAUSE_NO_ANSWER;
1894         case OR2_CAUSE_NORMAL_CLEARING:
1895                 return AST_CAUSE_NORMAL_CLEARING;
1896         case OR2_CAUSE_UNSPECIFIED:
1897         default:
1898                 return AST_CAUSE_NOTDEFINED;
1899         }
1900 }
1901
1902 static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disconnect_cause_t cause)
1903 {
1904         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1905         ast_verb(3, "MFC/R2 call disconnected on chan %d\n", openr2_chan_get_number(r2chan));
1906         ast_mutex_lock(&p->lock);
1907         if (!p->owner) {
1908                 ast_mutex_unlock(&p->lock);
1909                 /* no owner, therefore we can't use dahdi_hangup to disconnect, do it right now */
1910                 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_NORMAL_CLEARING);
1911                 return;
1912         }
1913         /* when we have an owner we don't call openr2_chan_disconnect_call here, that will
1914            be done in dahdi_hangup */
1915         if (p->owner->_state == AST_STATE_UP) {
1916                 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1917                 ast_mutex_unlock(&p->lock);
1918         } else if (openr2_chan_get_direction(r2chan) == OR2_DIR_FORWARD) {
1919                 /* being the forward side we must report what happened to the call to whoever requested it */
1920                 switch (cause) {
1921                 case OR2_CAUSE_BUSY_NUMBER:
1922                         p->subs[SUB_REAL].needbusy = 1;
1923                         break;
1924                 case OR2_CAUSE_NETWORK_CONGESTION:
1925                 case OR2_CAUSE_OUT_OF_ORDER:
1926                 case OR2_CAUSE_UNALLOCATED_NUMBER:
1927                 case OR2_CAUSE_NO_ANSWER:
1928                 case OR2_CAUSE_UNSPECIFIED:
1929                 case OR2_CAUSE_NORMAL_CLEARING:
1930                         p->subs[SUB_REAL].needcongestion = 1;
1931                         break;
1932                 default:
1933                         p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1934                 }
1935                 ast_mutex_unlock(&p->lock);
1936         } else {
1937                 ast_mutex_unlock(&p->lock);
1938                 /* being the backward side and not UP yet, we only need to request hangup */
1939                 /* TODO: what about doing this same thing when were AST_STATE_UP? */
1940                 ast_queue_hangup_with_cause(p->owner, dahdi_r2_cause_to_ast_cause(cause));
1941         }
1942 }
1943
1944 static void dahdi_r2_write_log(openr2_log_level_t level, char *logmessage)
1945 {
1946         switch (level) {
1947         case OR2_LOG_NOTICE:
1948                 ast_log(LOG_NOTICE, "%s", logmessage);
1949                 break;
1950         case OR2_LOG_WARNING:
1951                 ast_log(LOG_WARNING, "%s", logmessage);
1952                 break;
1953         case OR2_LOG_ERROR:
1954                 ast_log(LOG_ERROR, "%s", logmessage);
1955                 break;
1956         case OR2_LOG_STACK_TRACE:
1957         case OR2_LOG_MF_TRACE:
1958         case OR2_LOG_CAS_TRACE:
1959         case OR2_LOG_DEBUG:
1960         case OR2_LOG_EX_DEBUG:
1961                 ast_log(LOG_DEBUG, "%s", logmessage);
1962                 break;
1963         default:
1964                 ast_log(LOG_WARNING, "We should handle logging level %d here.\n", level);
1965                 ast_log(LOG_DEBUG, "%s", logmessage);
1966                 break;
1967         }
1968 }
1969
1970 static void dahdi_r2_on_line_blocked(openr2_chan_t *r2chan)
1971 {
1972         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1973         ast_mutex_lock(&p->lock);
1974         p->remotelyblocked = 1;
1975         ast_mutex_unlock(&p->lock);
1976         ast_log(LOG_NOTICE, "Far end blocked on chan %d\n", openr2_chan_get_number(r2chan));
1977 }
1978
1979 static void dahdi_r2_on_line_idle(openr2_chan_t *r2chan)
1980 {
1981         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1982         ast_mutex_lock(&p->lock);
1983         p->remotelyblocked = 0;
1984         ast_mutex_unlock(&p->lock);
1985         ast_log(LOG_NOTICE, "Far end unblocked on chan %d\n", openr2_chan_get_number(r2chan));
1986 }
1987
1988 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
1989         __attribute__((format (printf, 3, 0)));
1990 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
1991 {
1992 #define CONTEXT_TAG "Context - "
1993         char logmsg[256];
1994         char completemsg[sizeof(logmsg) + sizeof(CONTEXT_TAG) - 1];
1995         vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
1996         snprintf(completemsg, sizeof(completemsg), CONTEXT_TAG "%s", logmsg);
1997         dahdi_r2_write_log(level, completemsg);
1998 #undef CONTEXT_TAG
1999 }
2000
2001 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
2002         __attribute__((format (printf, 3, 0)));
2003 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
2004 {
2005 #define CHAN_TAG "Chan "
2006         char logmsg[256];
2007         char completemsg[sizeof(logmsg) + sizeof(CHAN_TAG) - 1];
2008         vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
2009         snprintf(completemsg, sizeof(completemsg), CHAN_TAG "%d - %s", openr2_chan_get_number(r2chan), logmsg);
2010         dahdi_r2_write_log(level, completemsg);
2011 }
2012
2013 static int dahdi_r2_on_dnis_digit_received(openr2_chan_t *r2chan, char digit)
2014 {
2015         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
2016         /* if 'immediate' is set, let's stop requesting DNIS */
2017         if (p->immediate) {
2018                 return 0;
2019         }
2020         p->exten[p->mfcr2_dnis_index] = digit;
2021         p->rdnis[p->mfcr2_dnis_index] = digit;
2022         p->mfcr2_dnis_index++;
2023         p->exten[p->mfcr2_dnis_index] = 0;
2024         p->rdnis[p->mfcr2_dnis_index] = 0;
2025         /* if the DNIS is a match and cannot match more, stop requesting DNIS */
2026         if ((p->mfcr2_dnis_matched ||
2027             (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num) && (p->mfcr2_dnis_matched = 1))) &&
2028             !ast_matchmore_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
2029                 return 0;
2030         }
2031         /* otherwise keep going */
2032         return 1;
2033 }
2034
2035 static void dahdi_r2_on_ani_digit_received(openr2_chan_t *r2chan, char digit)
2036 {
2037         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
2038         p->cid_num[p->mfcr2_ani_index] = digit;
2039         p->cid_name[p->mfcr2_ani_index] = digit;
2040         p->mfcr2_ani_index++;
2041         p->cid_num[p->mfcr2_ani_index] = 0;
2042         p->cid_name[p->mfcr2_ani_index] = 0;
2043 }
2044
2045 static openr2_event_interface_t dahdi_r2_event_iface = {
2046         .on_call_init = dahdi_r2_on_call_init,
2047         .on_call_offered = dahdi_r2_on_call_offered,
2048         .on_call_accepted = dahdi_r2_on_call_accepted,
2049         .on_call_answered = dahdi_r2_on_call_answered,
2050         .on_call_disconnect = dahdi_r2_on_call_disconnect,
2051         .on_call_end = dahdi_r2_on_call_end,
2052         .on_call_read = dahdi_r2_on_call_read,
2053         .on_hardware_alarm = dahdi_r2_on_hardware_alarm,
2054         .on_os_error = dahdi_r2_on_os_error,
2055         .on_protocol_error = dahdi_r2_on_protocol_error,
2056         .on_line_blocked = dahdi_r2_on_line_blocked,
2057         .on_line_idle = dahdi_r2_on_line_idle,
2058         /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
2059         .on_context_log = (openr2_handle_context_logging_func)dahdi_r2_on_context_log,
2060         .on_dnis_digit_received = dahdi_r2_on_dnis_digit_received,
2061         .on_ani_digit_received = dahdi_r2_on_ani_digit_received,
2062         /* so far we do nothing with billing pulses */
2063         .on_billing_pulse_received = NULL
2064 };
2065
2066 static inline int16_t dahdi_r2_alaw_to_linear(uint8_t sample)
2067 {
2068         return AST_ALAW(sample);
2069 }
2070
2071 static inline uint8_t dahdi_r2_linear_to_alaw(int sample)
2072 {
2073         return AST_LIN2A(sample);
2074 }
2075
2076 static openr2_transcoder_interface_t dahdi_r2_transcode_iface = {
2077         dahdi_r2_alaw_to_linear,
2078         dahdi_r2_linear_to_alaw
2079 };
2080
2081 #endif /* HAVE_OPENR2 */
2082
2083 static int restore_gains(struct dahdi_pvt *p);
2084
2085 static void swap_subs(struct dahdi_pvt *p, int a, int b)
2086 {
2087         int tchan;
2088         int tinthreeway;
2089         struct ast_channel *towner;
2090
2091         ast_debug(1, "Swapping %d and %d\n", a, b);
2092
2093         tchan = p->subs[a].chan;
2094         towner = p->subs[a].owner;
2095         tinthreeway = p->subs[a].inthreeway;
2096
2097         p->subs[a].chan = p->subs[b].chan;
2098         p->subs[a].owner = p->subs[b].owner;
2099         p->subs[a].inthreeway = p->subs[b].inthreeway;
2100
2101         p->subs[b].chan = tchan;
2102         p->subs[b].owner = towner;
2103         p->subs[b].inthreeway = tinthreeway;
2104
2105         if (p->subs[a].owner)
2106                 ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].dfd);
2107         if (p->subs[b].owner)
2108                 ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].dfd);
2109         wakeup_sub(p, a, NULL);
2110         wakeup_sub(p, b, NULL);
2111 }
2112
2113 static int dahdi_open(char *fn)
2114 {
2115         int fd;
2116         int isnum;
2117         int chan = 0;
2118         int bs;
2119         int x;
2120         isnum = 1;
2121         for (x = 0; x < strlen(fn); x++) {
2122                 if (!isdigit(fn[x])) {
2123                         isnum = 0;
2124                         break;
2125                 }
2126         }
2127         if (isnum) {
2128                 chan = atoi(fn);
2129                 if (chan < 1) {
2130                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
2131                         return -1;
2132                 }
2133                 fn = "/dev/dahdi/channel";
2134         }
2135         fd = open(fn, O_RDWR | O_NONBLOCK);
2136         if (fd < 0) {
2137                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
2138                 return -1;
2139         }
2140         if (chan) {
2141                 if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
2142                         x = errno;
2143                         close(fd);
2144                         errno = x;
2145                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
2146                         return -1;
2147                 }
2148         }
2149         bs = READ_SIZE;
2150         if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
2151                 ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
2152                 x = errno;
2153                 close(fd);
2154                 errno = x;
2155                 return -1;
2156         }
2157         return fd;
2158 }
2159
2160 static void dahdi_close(int fd)
2161 {
2162         if (fd > 0)
2163                 close(fd);
2164 }
2165
2166 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
2167 {
2168         dahdi_close(chan_pvt->subs[sub_num].dfd);
2169         chan_pvt->subs[sub_num].dfd = -1;
2170 }
2171
2172 #if defined(HAVE_PRI)
2173 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
2174 {
2175         dahdi_close(pri->fds[fd_num]);
2176         pri->fds[fd_num] = -1;
2177 }
2178 #endif  /* defined(HAVE_PRI) */
2179
2180 #if defined(HAVE_SS7)
2181 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
2182 {
2183         dahdi_close(ss7->fds[fd_num]);
2184         ss7->fds[fd_num] = -1;
2185 }
2186 #endif  /* defined(HAVE_SS7) */
2187
2188 static int dahdi_setlinear(int dfd, int linear)
2189 {
2190         int res;
2191         res = ioctl(dfd, DAHDI_SETLINEAR, &linear);
2192         if (res)
2193                 return res;
2194         return 0;
2195 }
2196
2197
2198 static int alloc_sub(struct dahdi_pvt *p, int x)
2199 {
2200         struct dahdi_bufferinfo bi;
2201         int res;
2202         if (p->subs[x].dfd >= 0) {
2203                 ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
2204                 return -1;
2205         }
2206
2207         p->subs[x].dfd = dahdi_open("/dev/dahdi/pseudo");
2208         if (p->subs[x].dfd <= -1) {
2209                 ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
2210                 return -1;
2211         }
2212
2213         res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
2214         if (!res) {
2215                 bi.txbufpolicy = p->buf_policy;
2216                 bi.rxbufpolicy = p->buf_policy;
2217                 bi.numbufs = p->buf_no;
2218                 res = ioctl(p->subs[x].dfd, DAHDI_SET_BUFINFO, &bi);
2219                 if (res < 0) {
2220                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
2221                 }
2222         } else
2223                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
2224
2225         if (ioctl(p->subs[x].dfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
2226                 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d: %s\n", p->subs[x].dfd, strerror(errno));
2227                 dahdi_close_sub(p, x);
2228                 p->subs[x].dfd = -1;
2229                 return -1;
2230         }
2231         ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
2232         return 0;
2233 }
2234
2235 static int unalloc_sub(struct dahdi_pvt *p, int x)
2236 {
2237         if (!x) {
2238                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
2239                 return -1;
2240         }
2241         ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
2242         dahdi_close_sub(p, x);
2243         p->subs[x].linear = 0;
2244         p->subs[x].chan = 0;
2245         p->subs[x].owner = NULL;
2246         p->subs[x].inthreeway = 0;
2247         p->polarity = POLARITY_IDLE;
2248         memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
2249         return 0;
2250 }
2251
2252 static int digit_to_dtmfindex(char digit)
2253 {
2254         if (isdigit(digit))
2255                 return DAHDI_TONE_DTMF_BASE + (digit - '0');
2256         else if (digit >= 'A' && digit <= 'D')
2257                 return DAHDI_TONE_DTMF_A + (digit - 'A');
2258         else if (digit >= 'a' && digit <= 'd')
2259                 return DAHDI_TONE_DTMF_A + (digit - 'a');
2260         else if (digit == '*')
2261                 return DAHDI_TONE_DTMF_s;
2262         else if (digit == '#')
2263                 return DAHDI_TONE_DTMF_p;
2264         else
2265                 return -1;
2266 }
2267
2268 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
2269 {
2270         struct dahdi_pvt *pvt;
2271         int idx;
2272         int dtmf = -1;
2273
2274         pvt = chan->tech_pvt;
2275
2276         ast_mutex_lock(&pvt->lock);
2277
2278         idx = dahdi_get_index(chan, pvt, 0);
2279
2280         if ((idx != SUB_REAL) || !pvt->owner)
2281                 goto out;
2282
2283 #ifdef HAVE_PRI
2284         if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
2285                         && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
2286                 if (pvt->setup_ack) {
2287                         if (!pri_grab(pvt, pvt->pri)) {
2288                                 pri_information(pvt->pri->pri, pvt->call, digit);
2289                                 pri_rel(pvt->pri);
2290                         } else
2291                                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
2292                 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
2293                         int res;
2294                         ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n", digit);
2295                         res = strlen(pvt->dialdest);
2296                         pvt->dialdest[res++] = digit;
2297                         pvt->dialdest[res] = '\0';
2298                 }
2299                 goto out;
2300         }
2301 #endif
2302         if ((dtmf = digit_to_dtmfindex(digit)) == -1)
2303                 goto out;
2304
2305         if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
2306                 int res;
2307                 struct dahdi_dialoperation zo = {
2308                         .op = DAHDI_DIAL_OP_APPEND,
2309                 };
2310
2311                 zo.dialstr[0] = 'T';
2312                 zo.dialstr[1] = digit;
2313                 zo.dialstr[2] = '\0';
2314                 if ((res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo)))
2315                         ast_log(LOG_WARNING, "Couldn't dial digit %c: %s\n", digit, strerror(errno));
2316                 else
2317                         pvt->dialing = 1;
2318         } else {
2319                 ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
2320                 pvt->dialing = 1;
2321                 pvt->begindigit = digit;
2322         }
2323
2324 out:
2325         ast_mutex_unlock(&pvt->lock);
2326
2327         return 0;
2328 }
2329
2330 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
2331 {
2332         struct dahdi_pvt *pvt;
2333         int res = 0;
2334         int idx;
2335         int x;
2336
2337         pvt = chan->tech_pvt;
2338
2339         ast_mutex_lock(&pvt->lock);
2340
2341         idx = dahdi_get_index(chan, pvt, 0);
2342
2343         if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
2344                 goto out;
2345
2346 #ifdef HAVE_PRI
2347         /* This means that the digit was already sent via PRI signalling */
2348         if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
2349                         && !pvt->begindigit)
2350                 goto out;
2351 #endif
2352
2353         if (pvt->begindigit) {
2354                 x = -1;
2355                 ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
2356                 res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
2357                 pvt->dialing = 0;
2358                 pvt->begindigit = 0;
2359         }
2360
2361 out:
2362         ast_mutex_unlock(&pvt->lock);
2363
2364         return res;
2365 }
2366
2367 static char *events[] = {
2368         "No event",
2369         "On hook",
2370         "Ring/Answered",
2371         "Wink/Flash",
2372         "Alarm",
2373         "No more alarm",
2374         "HDLC Abort",
2375         "HDLC Overrun",
2376         "HDLC Bad FCS",
2377         "Dial Complete",
2378         "Ringer On",
2379         "Ringer Off",
2380         "Hook Transition Complete",
2381         "Bits Changed",
2382         "Pulse Start",
2383         "Timer Expired",
2384         "Timer Ping",
2385         "Polarity Reversal",
2386         "Ring Begin",
2387 };
2388
2389 static struct {
2390         int alarm;
2391         char *name;
2392 } alarms[] = {
2393         { DAHDI_ALARM_RED, "Red Alarm" },
2394         { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
2395         { DAHDI_ALARM_BLUE, "Blue Alarm" },
2396         { DAHDI_ALARM_RECOVER, "Recovering" },
2397         { DAHDI_ALARM_LOOPBACK, "Loopback" },
2398         { DAHDI_ALARM_NOTOPEN, "Not Open" },
2399         { DAHDI_ALARM_NONE, "None" },
2400 };
2401
2402 static char *alarm2str(int alm)
2403 {
2404         int x;
2405         for (x = 0; x < ARRAY_LEN(alarms); x++) {
2406                 if (alarms[x].alarm & alm)
2407                         return alarms[x].name;
2408         }
2409         return alm ? "Unknown Alarm" : "No Alarm";
2410 }
2411
2412 static char *event2str(int event)
2413 {
2414         static char buf[256];
2415         if ((event < (ARRAY_LEN(events))) && (event > -1))
2416                 return events[event];
2417         sprintf(buf, "Event %d", event); /* safe */
2418         return buf;
2419 }
2420
2421 #ifdef HAVE_PRI
2422 static char *dialplan2str(int dialplan)
2423 {
2424         if (dialplan == -1 || dialplan == -2) {
2425                 return("Dynamically set dialplan in ISDN");
2426         }
2427         return (pri_plan2str(dialplan));
2428 }
2429 #endif
2430
2431 static char *dahdi_sig2str(int sig)
2432 {
2433         static char buf[256];
2434         switch (sig) {
2435         case SIG_EM:
2436                 return "E & M Immediate";
2437         case SIG_EMWINK:
2438                 return "E & M Wink";
2439         case SIG_EM_E1:
2440                 return "E & M E1";
2441         case SIG_FEATD:
2442                 return "Feature Group D (DTMF)";
2443         case SIG_FEATDMF:
2444                 return "Feature Group D (MF)";
2445         case SIG_FEATDMF_TA:
2446                 return "Feature Groud D (MF) Tandem Access";
2447         case SIG_FEATB:
2448                 return "Feature Group B (MF)";
2449         case SIG_E911:
2450                 return "E911 (MF)";
2451         case SIG_FGC_CAMA:
2452                 return "FGC/CAMA (Dialpulse)";
2453         case SIG_FGC_CAMAMF:
2454                 return "FGC/CAMA (MF)";
2455         case SIG_FXSLS:
2456                 return "FXS Loopstart";
2457         case SIG_FXSGS:
2458                 return "FXS Groundstart";
2459         case SIG_FXSKS:
2460                 return "FXS Kewlstart";
2461         case SIG_FXOLS:
2462                 return "FXO Loopstart";
2463         case SIG_FXOGS:
2464                 return "FXO Groundstart";
2465         case SIG_FXOKS:
2466                 return "FXO Kewlstart";
2467         case SIG_PRI:
2468                 return "ISDN PRI";
2469         case SIG_BRI:
2470                 return "ISDN BRI Point to Point";
2471         case SIG_BRI_PTMP:
2472                 return "ISDN BRI Point to MultiPoint";
2473         case SIG_SS7:
2474                 return "SS7";
2475         case SIG_MFCR2:
2476                 return "MFC/R2";
2477         case SIG_SF:
2478                 return "SF (Tone) Immediate";
2479         case SIG_SFWINK:
2480                 return "SF (Tone) Wink";
2481         case SIG_SF_FEATD:
2482                 return "SF (Tone) with Feature Group D (DTMF)";
2483         case SIG_SF_FEATDMF:
2484                 return "SF (Tone) with Feature Group D (MF)";
2485         case SIG_SF_FEATB:
2486                 return "SF (Tone) with Feature Group B (MF)";
2487         case SIG_GR303FXOKS:
2488                 return "GR-303 with FXOKS";
2489         case SIG_GR303FXSKS:
2490                 return "GR-303 with FXSKS";
2491         case 0:
2492                 return "Pseudo";
2493         default:
2494                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
2495                 return buf;
2496         }
2497 }
2498
2499 #define sig2str dahdi_sig2str
2500
2501 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
2502 {
2503         /* If the conference already exists, and we're already in it
2504            don't bother doing anything */
2505         struct dahdi_confinfo zi;
2506
2507         memset(&zi, 0, sizeof(zi));
2508         zi.chan = 0;
2509
2510         if (slavechannel > 0) {
2511                 /* If we have only one slave, do a digital mon */
2512                 zi.confmode = DAHDI_CONF_DIGITALMON;
2513                 zi.confno = slavechannel;
2514         } else {
2515                 if (!idx) {
2516                         /* Real-side and pseudo-side both participate in conference */
2517                         zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
2518                                 DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
2519                 } else
2520                         zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
2521                 zi.confno = p->confno;
2522         }
2523         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
2524                 return 0;
2525         if (c->dfd < 0)
2526                 return 0;
2527         if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
2528                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d: %s\n", c->dfd, zi.confmode, zi.confno, strerror(errno));
2529                 return -1;
2530         }
2531         if (slavechannel < 1) {
2532                 p->confno = zi.confno;
2533         }
2534         memcpy(&c->curconf, &zi, sizeof(c->curconf));
2535         ast_debug(1, "Added %d to conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
2536         return 0;
2537 }
2538
2539 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
2540 {
2541         /* If they're listening to our channel, they're ours */
2542         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
2543                 return 1;
2544         /* If they're a talker on our (allocated) conference, they're ours */
2545         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
2546                 return 1;
2547         return 0;
2548 }
2549
2550 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
2551 {
2552         struct dahdi_confinfo zi;
2553         if (/* Can't delete if there's no dfd */
2554                 (c->dfd < 0) ||
2555                 /* Don't delete from the conference if it's not our conference */
2556                 !isourconf(p, c)
2557                 /* Don't delete if we don't think it's conferenced at all (implied) */
2558                 ) return 0;
2559         memset(&zi, 0, sizeof(zi));
2560         if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
2561                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d: %s\n", c->dfd, c->curconf.confmode, c->curconf.confno, strerror(errno));
2562                 return -1;
2563         }
2564         ast_debug(1, "Removed %d from conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
2565         memcpy(&c->curconf, &zi, sizeof(c->curconf));
2566         return 0;
2567 }
2568
2569 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
2570 {
2571         int x;
2572         int useslavenative;
2573         struct dahdi_pvt *slave = NULL;
2574         /* Start out optimistic */
2575         useslavenative = 1;
2576         /* Update conference state in a stateless fashion */
2577         for (x = 0; x < 3; x++) {
2578                 /* Any three-way calling makes slave native mode *definitely* out
2579                    of the question */
2580                 if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
2581                         useslavenative = 0;
2582         }
2583         /* If we don't have any 3-way calls, check to see if we have
2584            precisely one slave */
2585         if (useslavenative) {
2586                 for (x = 0; x < MAX_SLAVES; x++) {
2587                         if (p->slaves[x]) {
2588                                 if (slave) {
2589                                         /* Whoops already have a slave!  No
2590                                            slave native and stop right away */
2591                                         slave = NULL;
2592                                         useslavenative = 0;
2593                                         break;
2594                                 } else {
2595                                         /* We have one slave so far */
2596                                         slave = p->slaves[x];
2597                                 }
2598                         }
2599                 }
2600         }
2601         /* If no slave, slave native definitely out */
2602         if (!slave)
2603                 useslavenative = 0;
2604         else if (slave->law != p->law) {
2605                 useslavenative = 0;
2606                 slave = NULL;
2607         }
2608         if (out)
2609                 *out = slave;
2610         return useslavenative;
2611 }
2612
2613 static int reset_conf(struct dahdi_pvt *p)
2614 {
2615         p->confno = -1;
2616         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
2617         if (p->subs[SUB_REAL].dfd > -1) {
2618                 struct dahdi_confinfo zi;
2619
2620                 memset(&zi, 0, sizeof(zi));
2621                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &zi))
2622                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d: %s\n", p->channel, strerror(errno));
2623         }
2624         return 0;
2625 }
2626
2627 static int update_conf(struct dahdi_pvt *p)
2628 {
2629         int needconf = 0;
2630         int x;
2631         int useslavenative;
2632         struct dahdi_pvt *slave = NULL;
2633
2634         useslavenative = isslavenative(p, &slave);
2635         /* Start with the obvious, general stuff */
2636         for (x = 0; x < 3; x++) {
2637                 /* Look for three way calls */
2638                 if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway) {
2639                         conf_add(p, &p->subs[x], x, 0);
2640                         needconf++;
2641                 } else {
2642                         conf_del(p, &p->subs[x], x);
2643                 }
2644         }
2645         /* If we have a slave, add him to our conference now. or DAX
2646            if this is slave native */
2647         for (x = 0; x < MAX_SLAVES; x++) {
2648                 if (p->slaves[x]) {
2649                         if (useslavenative)
2650                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
2651                         else {
2652                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
2653                                 needconf++;
2654                         }
2655                 }
2656         }
2657         /* If we're supposed to be in there, do so now */
2658         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
2659                 if (useslavenative)
2660                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
2661                 else {
2662                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
2663                         needconf++;
2664                 }
2665         }
2666         /* If we have a master, add ourselves to his conference */
2667         if (p->master) {
2668                 if (isslavenative(p->master, NULL)) {
2669                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
2670                 } else {
2671                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
2672                 }
2673         }
2674         if (!needconf) {
2675                 /* Nobody is left (or should be left) in our conference.
2676                    Kill it. */
2677                 p->confno = -1;
2678         }
2679         ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
2680         return 0;
2681 }
2682
2683 static void dahdi_enable_ec(struct dahdi_pvt *p)
2684 {
2685         int x;
2686         int res;
2687         if (!p)
2688                 return;
2689         if (p->echocanon) {
2690                 ast_debug(1, "Echo cancellation already on\n");
2691                 return;
2692         }
2693         if (p->digital) {
2694                 ast_debug(1, "Echo cancellation isn't required on digital connection\n");
2695                 return;
2696         }
2697         if (p->echocancel.head.tap_length) {
2698                 if ((p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP) || (p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
2699                         x = 1;
2700                         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
2701                         if (res)
2702                                 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n", p->channel, strerror(errno));
2703                 }
2704                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
2705                 if (res) {
2706                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
2707                 } else {
2708                         p->echocanon = 1;
2709                         ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
2710                 }
2711         } else
2712                 ast_debug(1, "No echo cancellation requested\n");
2713 }
2714
2715 static void dahdi_train_ec(struct dahdi_pvt *p)
2716 {
2717         int x;
2718         int res;
2719
2720         if (p && p->echocanon && p->echotraining) {
2721                 x = p->echotraining;
2722                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
2723                 if (res)
2724                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
2725                 else
2726                         ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
2727         } else {
2728                 ast_debug(1, "No echo training requested\n");
2729         }
2730 }
2731
2732 static void dahdi_disable_ec(struct dahdi_pvt *p)
2733 {
2734         int res;
2735
2736         if (p->echocanon) {
2737                 struct dahdi_echocanparams ecp = { .tap_length = 0 };
2738
2739                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
2740
2741                 if (res)
2742                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
2743                 else
2744                         ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
2745         }
2746
2747         p->echocanon = 0;
2748 }
2749
2750 static void fill_txgain(struct dahdi_gains *g, float gain, int law)
2751 {
2752         int j;
2753         int k;
2754         float linear_gain = pow(10.0, gain / 20.0);
2755
2756         switch (law) {
2757         case DAHDI_LAW_ALAW:
2758                 for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
2759                         if (gain) {
2760                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
2761                                 if (k > 32767) k = 32767;
2762                                 if (k < -32767) k = -32767;
2763                                 g->txgain[j] = AST_LIN2A(k);
2764                         } else {
2765                                 g->txgain[j] = j;
2766                         }
2767                 }
2768                 break;
2769         case DAHDI_LAW_MULAW:
2770                 for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
2771                         if (gain) {
2772                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
2773                                 if (k > 32767) k = 32767;
2774                                 if (k < -32767) k = -32767;
2775                                 g->txgain[j] = AST_LIN2MU(k);
2776                         } else {
2777                                 g->txgain[j] = j;
2778                         }
2779                 }
2780                 break;
2781         }
2782 }
2783
2784 static void fill_rxgain(struct dahdi_gains *g, float gain, int law)
2785 {
2786         int j;
2787         int k;
2788         float linear_gain = pow(10.0, gain / 20.0);
2789
2790         switch (law) {
2791         case DAHDI_LAW_ALAW:
2792                 for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
2793                         if (gain) {
2794                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
2795                                 if (k > 32767) k = 32767;
2796                                 if (k < -32767) k = -32767;
2797                                 g->rxgain[j] = AST_LIN2A(k);
2798                         } else {
2799                                 g->rxgain[j] = j;
2800                         }
2801                 }
2802                 break;
2803         case DAHDI_LAW_MULAW:
2804                 for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
2805                         if (gain) {
2806                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
2807                                 if (k > 32767) k = 32767;
2808                                 if (k < -32767) k = -32767;
2809                                 g->rxgain[j] = AST_LIN2MU(k);
2810                         } else {
2811                                 g->rxgain[j] = j;
2812                         }
2813                 }
2814                 break;
2815         }
2816 }
2817
2818 static int set_actual_txgain(int fd, int chan, float gain, int law)
2819 {
2820         struct dahdi_gains g;
2821         int res;
2822
2823         memset(&g, 0, sizeof(g));
2824         g.chan = chan;
2825         res = ioctl(fd, DAHDI_GETGAINS, &g);
2826         if (res) {
2827                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
2828                 return res;
2829         }
2830
2831         fill_txgain(&g, gain, law);
2832
2833         return ioctl(fd, DAHDI_SETGAINS, &g);
2834 }
2835
2836 static int set_actual_rxgain(int fd, int chan, float gain, int law)
2837 {
2838         struct dahdi_gains g;
2839         int res;
2840
2841         memset(&g, 0, sizeof(g));
2842         g.chan = chan;
2843         res = ioctl(fd, DAHDI_GETGAINS, &g);
2844         if (res) {
2845                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
2846                 return res;
2847         }
2848
2849         fill_rxgain(&g, gain, law);
2850
2851         return ioctl(fd, DAHDI_SETGAINS, &g);
2852 }
2853
2854 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
2855 {
2856         return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
2857 }
2858
2859 static int bump_gains(struct dahdi_pvt *p)
2860 {
2861         int res;
2862
2863         /* Bump receive gain by value stored in cid_rxgain */
2864         res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain + p->cid_rxgain, p->txgain, p->law);
2865         if (res) {
2866                 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
2867                 return -1;
2868         }
2869
2870         return 0;
2871 }
2872
2873 static int restore_gains(struct dahdi_pvt *p)
2874 {
2875         int res;
2876
2877         res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
2878         if (res) {
2879                 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
2880                 return -1;
2881         }
2882
2883         return 0;
2884 }
2885
2886 static inline int dahdi_set_hook(int fd, int hs)
2887 {
2888         int x, res;
2889
2890         x = hs;
2891         res = ioctl(fd, DAHDI_HOOK, &x);
2892
2893         if (res < 0) {
2894                 if (errno == EINPROGRESS)
2895                         return 0;
2896                 ast_log(LOG_WARNING, "DAHDI hook failed returned %d (trying %d): %s\n", res, hs, strerror(errno));
2897                 /* will expectedly fail if phone is off hook during operation, such as during a restart */
2898         }
2899
2900         return res;
2901 }
2902
2903 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
2904 {
2905         int x, y, res;
2906         x = muted;
2907         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
2908                 y = 1;
2909                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
2910                 if (res)
2911                         ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n", p->channel, strerror(errno));
2912         }
2913         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
2914         if (res < 0)
2915                 ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
2916         return res;
2917 }
2918
2919 static int save_conference(struct dahdi_pvt *p)
2920 {
2921         struct dahdi_confinfo c;
2922         int res;
2923         if (p->saveconf.confmode) {
2924                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
2925                 return -1;
2926         }
2927         p->saveconf.chan = 0;
2928         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
2929         if (res) {
2930                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
2931                 p->saveconf.confmode = 0;
2932                 return -1;
2933         }
2934         memset(&c, 0, sizeof(c));
2935         c.confmode = DAHDI_CONF_NORMAL;
2936         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
2937         if (res) {
2938                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
2939                 return -1;
2940         }
2941         ast_debug(1, "Disabled conferencing\n");
2942         return 0;
2943 }
2944
2945 /*!
2946  * \brief Send MWI state change
2947  *
2948  * \arg mailbox_full This is the mailbox associated with the FXO line that the
2949  *      MWI state has changed on.
2950  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
2951  *      whether there are messages waiting or not.
2952  *
2953  *  \return nothing
2954  *
2955  * This function does two things:
2956  *
2957  * 1) It generates an internal Asterisk event notifying any other module that
2958  *    cares about MWI that the state of a mailbox has changed.
2959  *
2960  * 2) It runs the script specified by the mwimonitornotify option to allow
2961  *    some custom handling of the state change.
2962  */
2963 static void notify_message(char *mailbox_full, int thereornot)
2964 {
2965         char s[sizeof(mwimonitornotify) + 80];
2966         struct ast_event *event;
2967         char *mailbox, *context;
2968
2969         /* Strip off @default */
2970         context = mailbox = ast_strdupa(mailbox_full);
2971         strsep(&context, "@");
2972         if (ast_strlen_zero(context))
2973                 context = "default";
2974
2975         if (!(event = ast_event_new(AST_EVENT_MWI,
2976                         AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
2977                         AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
2978                         AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
2979                         AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
2980                         AST_EVENT_IE_END))) {
2981                 return;
2982         }
2983
2984         ast_event_queue_and_cache(event);
2985
2986         if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
2987                 snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
2988                 ast_safe_system(s);
2989         }
2990 }
2991
2992 static int restore_conference(struct dahdi_pvt *p)
2993 {
2994         int res;
2995         if (p->saveconf.confmode) {
2996                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
2997                 p->saveconf.confmode = 0;
2998                 if (res) {
2999                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
3000                         return -1;
3001                 }
3002         }
3003         ast_debug(1, "Restored conferencing\n");
3004         return 0;
3005 }
3006
3007 static int send_callerid(struct dahdi_pvt *p);
3008
3009 static int send_cwcidspill(struct dahdi_pvt *p)
3010 {
3011         p->callwaitcas = 0;
3012         p->cidcwexpire = 0;
3013         if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
3014                 return -1;
3015         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
3016         /* Make sure we account for the end */
3017         p->cidlen += READ_SIZE * 4;
3018         p->cidpos = 0;
3019         send_callerid(p);
3020         ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
3021         return 0;
3022 }
3023
3024 static int has_voicemail(struct dahdi_pvt *p)
3025 {
3026         int new_msgs;
3027         struct ast_event *event;
3028         char *mailbox, *context;
3029
3030         mailbox = context = ast_strdupa(p->mailbox);
3031         strsep(&context, "@");
3032         if (ast_strlen_zero(context))
3033                 context = "default";
3034
3035         event = ast_event_get_cached(AST_EVENT_MWI,
3036                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
3037                 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
3038                 AST_EVENT_IE_END);
3039
3040         if (event) {
3041                 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
3042                 ast_event_destroy(event);
3043         } else
3044                 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
3045
3046         return new_msgs;
3047 }
3048
3049 static int send_callerid(struct dahdi_pvt *p)
3050 {
3051         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
3052         int res;
3053         /* Take out of linear mode if necessary */
3054         if (p->subs[SUB_REAL].linear) {
3055                 p->subs[SUB_REAL].linear = 0;
3056                 dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
3057         }
3058         while (p->cidpos < p->cidlen) {
3059                 res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
3060                 if (res < 0) {
3061                         if (errno == EAGAIN)
3062                                 return 0;
3063                         else {
3064                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
3065                                 return -1;
3066                         }
3067                 }
3068                 if (!res)
3069                         return 0;
3070                 p->cidpos += res;
3071         }
3072         ast_free(p->cidspill);
3073         p->cidspill = NULL;
3074         if (p->callwaitcas) {
3075                 /* Wait for CID/CW to expire */
3076                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
3077         } else
3078                 restore_conference(p);
3079         return 0;
3080 }
3081
3082 static int dahdi_callwait(struct ast_channel *ast)
3083 {
3084         struct dahdi_pvt *p = ast->tech_pvt;
3085         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
3086         if (p->cidspill) {
3087                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
3088                 ast_free(p->cidspill);
3089         }
3090         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
3091                 return -1;
3092         save_conference(p);
3093         /* Silence */
3094         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
3095         if (!p->callwaitrings && p->callwaitingcallerid) {
3096                 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
3097                 p->callwaitcas = 1;
3098                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
3099         } else {
3100                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
3101                 p->callwaitcas = 0;
3102                 p->cidlen = 2400 + READ_SIZE * 4;
3103         }
3104         p->cidpos = 0;
3105         send_callerid(p);
3106
3107         return 0;
3108 }
3109
3110 #if defined(HAVE_SS7)
3111 static unsigned char cid_pres2ss7pres(int cid_pres)
3112 {
3113          return (cid_pres >> 5) & 0x03;
3114 }
3115 #endif  /* defined(HAVE_SS7) */
3116
3117 #if defined(HAVE_SS7)
3118 static unsigned char cid_pres2ss7screen(int cid_pres)
3119 {
3120         return cid_pres & 0x03;
3121 }
3122 #endif  /* defined(HAVE_SS7) */
3123
3124 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
3125 {
3126         struct dahdi_pvt *p = ast->tech_pvt;
3127         int x, res, idx,mysig;
3128         char *c, *n, *l;
3129 #ifdef HAVE_PRI
3130         char *s = NULL;
3131 #endif
3132         char dest[256]; /* must be same length as p->dialdest */
3133         ast_mutex_lock(&p->lock);
3134         ast_copy_string(dest, rdest, sizeof(dest));
3135         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
3136         if ((ast->_state == AST_STATE_BUSY)) {
3137                 p->subs[SUB_REAL].needbusy = 1;
3138                 ast_mutex_unlock(&p->lock);
3139                 return 0;
3140         }
3141         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
3142                 ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
3143                 ast_mutex_unlock(&p->lock);
3144                 return -1;
3145         }
3146         p->waitingfordt.tv_sec = 0;
3147         p->dialednone = 0;
3148         if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
3149         {
3150                 /* Special pseudo -- automatically up */
3151                 ast_setstate(ast, AST_STATE_UP);
3152                 ast_mutex_unlock(&p->lock);
3153                 return 0;
3154         }
3155         x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
3156         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
3157         if (res)
3158                 ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
3159         p->outgoing = 1;
3160
3161         set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
3162
3163         mysig = p->sig;
3164         if (p->outsigmod > -1)
3165                 mysig = p->outsigmod;
3166
3167         switch (mysig) {
3168         case SIG_FXOLS:
3169         case SIG_FXOGS:
3170         case SIG_FXOKS:
3171                 if (p->owner == ast) {
3172                         /* Normal ring, on hook */
3173
3174                         /* Don't send audio while on hook, until the call is answered */
3175                         p->dialing = 1;
3176                         if (p->use_callerid) {
3177                                 /* Generate the Caller-ID spill if desired */
3178                                 if (p->cidspill) {
3179                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
3180                                         ast_free(p->cidspill);
3181                                 }
3182                                 p->callwaitcas&