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