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