Sat Mar 26 11:07:08 2011

Asterisk developer's documentation


chan_misdn.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2004 - 2006, Christian Richter
00005  *
00006  * Christian Richter <crich@beronet.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  *
00018  */
00019 
00020 /*!
00021  * \file
00022  *
00023  * \brief the chan_misdn channel driver for Asterisk
00024  *
00025  * \author Christian Richter <crich@beronet.com>
00026  *
00027  * \extref MISDN http://www.misdn.org/
00028  *
00029  * \ingroup channel_drivers
00030  */
00031 
00032 /*!
00033  * \note
00034  * To use the CCBS/CCNR supplementary service feature and other
00035  * supplementary services using FACILITY messages requires a
00036  * modified version of mISDN.
00037  *
00038  * \note
00039  * The latest modified mISDN v1.1.x based version is available at:
00040  * http://svn.digium.com/svn/thirdparty/mISDN/trunk
00041  * http://svn.digium.com/svn/thirdparty/mISDNuser/trunk
00042  *
00043  * \note
00044  * Taged versions of the modified mISDN code are available under:
00045  * http://svn.digium.com/svn/thirdparty/mISDN/tags
00046  * http://svn.digium.com/svn/thirdparty/mISDNuser/tags
00047  */
00048 
00049 /* Define to enable cli commands to generate canned CCBS messages. */
00050 // #define CCBS_TEST_MESSAGES 1
00051 
00052 /*** MODULEINFO
00053    <depend>isdnnet</depend>
00054    <depend>misdn</depend>
00055    <depend>suppserv</depend>
00056    <defaultenabled>no</defaultenabled>
00057  ***/
00058 #include "asterisk.h"
00059 
00060 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 291507 $")
00061 
00062 #include <pthread.h>
00063 #include <sys/socket.h>
00064 #include <sys/time.h>
00065 #include <arpa/inet.h>
00066 #include <fcntl.h>
00067 #include <sys/ioctl.h>
00068 #include <signal.h>
00069 #include <sys/file.h>
00070 #include <semaphore.h>
00071 #include <ctype.h>
00072 #include <time.h>
00073 
00074 #include "asterisk/channel.h"
00075 #include "asterisk/config.h"
00076 #include "asterisk/module.h"
00077 #include "asterisk/pbx.h"
00078 #include "asterisk/io.h"
00079 #include "asterisk/frame.h"
00080 #include "asterisk/translate.h"
00081 #include "asterisk/cli.h"
00082 #include "asterisk/musiconhold.h"
00083 #include "asterisk/dsp.h"
00084 #include "asterisk/file.h"
00085 #include "asterisk/callerid.h"
00086 #include "asterisk/indications.h"
00087 #include "asterisk/app.h"
00088 #include "asterisk/features.h"
00089 #include "asterisk/term.h"
00090 #include "asterisk/sched.h"
00091 #include "asterisk/stringfields.h"
00092 #include "asterisk/abstract_jb.h"
00093 #include "asterisk/causes.h"
00094 
00095 #include "chan_misdn_config.h"
00096 #include "isdn_lib.h"
00097 
00098 static char global_tracefile[BUFFERSIZE + 1];
00099 
00100 static int g_config_initialized = 0;
00101 
00102 struct misdn_jb{
00103    int size;
00104    int upper_threshold;
00105    char *samples, *ok;
00106    int wp,rp;
00107    int state_empty;
00108    int state_full;
00109    int state_buffer;
00110    int bytes_wrote;
00111    ast_mutex_t mutexjb;
00112 };
00113 
00114 /*! \brief allocates the jb-structure and initialize the elements */
00115 struct misdn_jb *misdn_jb_init(int size, int upper_threshold);
00116 
00117 /*! \brief frees the data and destroys the given jitterbuffer struct */
00118 void misdn_jb_destroy(struct misdn_jb *jb);
00119 
00120 /*! \brief fills the jitterbuffer with len data returns < 0 if there was an
00121 error (buffer overrun). */
00122 int misdn_jb_fill(struct misdn_jb *jb, const char *data, int len);
00123 
00124 /*! \brief gets len bytes out of the jitterbuffer if available, else only the
00125 available data is returned and the return value indicates the number
00126 of data. */
00127 int misdn_jb_empty(struct misdn_jb *jb, char *data, int len);
00128 
00129 static char *complete_ch(struct ast_cli_args *a);
00130 static char *complete_debug_port(struct ast_cli_args *a);
00131 static char *complete_show_config(struct ast_cli_args *a);
00132 
00133 /* BEGIN: chan_misdn.h */
00134 
00135 #if defined(AST_MISDN_ENHANCEMENTS)
00136 /*
00137  * This timeout duration is to clean up any call completion records that
00138  * are forgotten about by the switch.
00139  */
00140 #define MISDN_CC_RECORD_AGE_MAX     (6UL * 60 * 60)   /* seconds */
00141 
00142 #define MISDN_CC_REQUEST_WAIT_MAX   5  /* seconds */
00143 
00144 /*!
00145  * \brief Caller that initialized call completion services
00146  *
00147  * \details
00148  * This data is the payload for a datastore that is put on the channel that
00149  * initializes call completion services.  This datastore is set to be inherited
00150  * by the outbound mISDN channel.  When one of these channels hangs up, the
00151  * channel pointer will be set to NULL.  That way, we can ensure that we do not
00152  * touch this channel after it gets destroyed.
00153  */
00154 struct misdn_cc_caller {
00155    /*! \brief The channel that initialized call completion services */
00156    struct ast_channel *chan;
00157 };
00158 
00159 struct misdn_cc_notify {
00160    /*! \brief Dialplan: Notify extension priority */
00161    int priority;
00162 
00163    /*! \brief Dialplan: Notify extension context */
00164    char context[AST_MAX_CONTEXT];
00165 
00166    /*! \brief Dialplan: Notify extension number (User-A) */
00167    char exten[AST_MAX_EXTENSION];
00168 };
00169 
00170 /*! \brief mISDN call completion record */
00171 struct misdn_cc_record {
00172    /*! \brief Call completion record linked list */
00173    AST_LIST_ENTRY(misdn_cc_record) list;
00174 
00175    /*! \brief Time the record was created. */
00176    time_t time_created;
00177 
00178    /*! \brief MISDN_CC_RECORD_ID value */
00179    long record_id;
00180 
00181    /*!
00182     * \brief Logical Layer 1 port associated with this
00183     * call completion record
00184     */
00185    int port;
00186 
00187    /*! \brief TRUE if point-to-point mode (CCBS-T/CCNR-T mode) */
00188    int ptp;
00189 
00190    /*! \brief Mode specific parameters */
00191    union {
00192       /*! \brief point-to-point specific parameters. */
00193       struct {
00194          /*!
00195           * \brief Call-completion signaling link.
00196           * NULL if signaling link not established.
00197           */
00198          struct misdn_bchannel *bc;
00199 
00200          /*!
00201           * \brief TRUE if we requested the request retention option
00202           * to be enabled.
00203           */
00204          int requested_retention;
00205 
00206          /*!
00207           * \brief TRUE if the request retention option is enabled.
00208           */
00209          int retention_enabled;
00210       } ptp;
00211 
00212       /*! \brief point-to-multi-point specific parameters. */
00213       struct {
00214          /*! \brief CallLinkageID (valid when port determined) */
00215          int linkage_id;
00216 
00217          /*! \breif CCBSReference (valid when activated is TRUE) */
00218          int reference_id;
00219 
00220          /*! \brief globalRecall(0),   specificRecall(1) */
00221          int recall_mode;
00222       } ptmp;
00223    } mode;
00224 
00225    /*! \brief TRUE if call completion activated */
00226    int activated;
00227 
00228    /*! \brief Outstanding message ID (valid when outstanding_message) */
00229    int invoke_id;
00230 
00231    /*! \brief TRUE if waiting for a response from a message (invoke_id is valid) */
00232    int outstanding_message;
00233 
00234    /*! \brief TRUE if activation has been requested */
00235    int activation_requested;
00236 
00237    /*!
00238     * \brief TRUE if User-A is free
00239     * \note PTMP - Used to answer CCBSStatusRequest.
00240     * PTP - Determines how to respond to CCBS_T_RemoteUserFree.
00241     */
00242    int party_a_free;
00243 
00244    /*! \brief Error code received from last outstanding message. */
00245    enum FacErrorCode error_code;
00246 
00247    /*! \brief Reject code received from last outstanding message. */
00248    enum FacRejectCode reject_code;
00249 
00250    /*!
00251     * \brief Saved struct misdn_bchannel call information when
00252     * attempted to call User-B
00253     */
00254    struct {
00255       /*! \brief User-A caller id information */
00256       struct misdn_party_id caller;
00257 
00258       /*! \brief User-B number information */
00259       struct misdn_party_dialing dialed;
00260 
00261       /*! \brief The BC, HLC (optional) and LLC (optional) contents from the SETUP message. */
00262       struct Q931_Bc_Hlc_Llc setup_bc_hlc_llc;
00263 
00264       /*! \brief SETUP message bearer capability field code value */
00265       int capability;
00266 
00267       /*! \brief TRUE if call made in digital HDLC mode */
00268       int hdlc;
00269    } redial;
00270 
00271    /*! \brief Dialplan location to indicate User-B free and User-A is free */
00272    struct misdn_cc_notify remote_user_free;
00273 
00274    /*! \brief Dialplan location to indicate User-B free and User-A is busy */
00275    struct misdn_cc_notify b_free;
00276 };
00277 
00278 /*! \brief mISDN call completion record database */
00279 static AST_LIST_HEAD_STATIC(misdn_cc_records_db, misdn_cc_record);
00280 /*! \brief Next call completion record ID to use */
00281 static __u16 misdn_cc_record_id;
00282 /*! \brief Next invoke ID to use */
00283 static __s16 misdn_invoke_id;
00284 
00285 static const char misdn_no_response_from_network[] = "No response from network";
00286 static const char misdn_cc_record_not_found[] = "Call completion record not found";
00287 
00288 /* mISDN channel variable names */
00289 #define MISDN_CC_RECORD_ID "MISDN_CC_RECORD_ID"
00290 #define MISDN_CC_STATUS    "MISDN_CC_STATUS"
00291 #define MISDN_ERROR_MSG    "MISDN_ERROR_MSG"
00292 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00293 
00294 static ast_mutex_t release_lock;
00295 
00296 enum misdn_chan_state {
00297    MISDN_NOTHING = 0,         /*!< at beginning */
00298    MISDN_WAITING4DIGS,        /*!< when waiting for info */
00299    MISDN_EXTCANTMATCH,        /*!< when asterisk couldn't match our ext */
00300    MISDN_INCOMING_SETUP,      /*!< for incoming setup */
00301    MISDN_DIALING,             /*!< when pbx_start */
00302    MISDN_PROGRESS,            /*!< we have progress */
00303    MISDN_PROCEEDING,          /*!< we have progress */
00304    MISDN_CALLING,             /*!< when misdn_call is called */
00305    MISDN_CALLING_ACKNOWLEDGE, /*!< when we get SETUP_ACK */
00306    MISDN_ALERTING,            /*!< when Alerting */
00307    MISDN_BUSY,                /*!< when BUSY */
00308    MISDN_CONNECTED,           /*!< when connected */
00309    MISDN_DISCONNECTED,        /*!< when connected */
00310    MISDN_CLEANING,            /*!< when hangup from * but we were connected before */
00311 };
00312 
00313 /*! Asterisk created the channel (outgoing call) */
00314 #define ORG_AST 1
00315 /*! mISDN created the channel (incoming call) */
00316 #define ORG_MISDN 2
00317 
00318 enum misdn_hold_state {
00319    MISDN_HOLD_IDLE,     /*!< HOLD not active */
00320    MISDN_HOLD_ACTIVE,      /*!< Call is held */
00321    MISDN_HOLD_TRANSFER, /*!< Held call is being transferred */
00322    MISDN_HOLD_DISCONNECT,  /*!< Held call is being disconnected */
00323 };
00324 struct hold_info {
00325    /*!
00326     * \brief Call HOLD state.
00327     */
00328    enum misdn_hold_state state;
00329    /*!
00330     * \brief Logical port the channel call record is HELD on
00331     * because the B channel is no longer associated.
00332     */
00333    int port;
00334 
00335    /*!
00336     * \brief Original B channel number the HELD call was using.
00337     * \note Used only for debug display messages.
00338     */
00339    int channel;
00340 };
00341 
00342 /*!
00343  * \brief Channel call record structure
00344  */
00345 struct chan_list {
00346    /*!
00347     * \brief The "allowed_bearers" string read in from /etc/asterisk/misdn.conf
00348     */
00349    char allowed_bearers[BUFFERSIZE + 1];
00350 
00351    /*!
00352     * \brief State of the channel
00353     */
00354    enum misdn_chan_state state;
00355 
00356    /*!
00357     * \brief TRUE if a hangup needs to be queued
00358     * \note This is a debug flag only used to catch calls to hangup_chan() that are already hungup.
00359     */
00360    int need_queue_hangup;
00361 
00362    /*!
00363     * \brief TRUE if a channel can be hung up by calling asterisk directly when done.
00364     */
00365    int need_hangup;
00366 
00367    /*!
00368     * \brief TRUE if we could send an AST_CONTROL_BUSY if needed.
00369     */
00370    int need_busy;
00371 
00372    /*!
00373     * \brief Who originally created this channel. ORG_AST or ORG_MISDN
00374     */
00375    int originator;
00376 
00377    /*!
00378     * \brief TRUE of we are not to respond immediately to a SETUP message.  Check the dialplan first.
00379     * \note The "noautorespond_on_setup" boolean read in from /etc/asterisk/misdn.conf
00380     */
00381    int noautorespond_on_setup;
00382 
00383    int norxtone;  /*!< Boolean assigned values but the value is not used. */
00384 
00385    /*!
00386     * \brief TRUE if we are not to generate tones (Playtones)
00387     */
00388    int notxtone;
00389 
00390    /*!
00391     * \brief TRUE if echo canceller is enabled.  Value is toggled.
00392     */
00393    int toggle_ec;
00394 
00395    /*!
00396     * \brief TRUE if you want to send Tone Indications to an incoming
00397     * ISDN channel on a TE Port.
00398     * \note The "incoming_early_audio" boolean read in from /etc/asterisk/misdn.conf
00399     */
00400    int incoming_early_audio;
00401 
00402    /*!
00403     * \brief TRUE if DTMF digits are to be passed inband only.
00404     * \note It is settable by the misdn_set_opt() application.
00405     */
00406    int ignore_dtmf;
00407 
00408    /*!
00409     * \brief Pipe file descriptor handles array.
00410     * Read from pipe[0], write to pipe[1]
00411     */
00412    int pipe[2];
00413 
00414    /*!
00415     * \brief Read buffer for inbound audio from pipe[0]
00416     */
00417    char ast_rd_buf[4096];
00418 
00419    /*!
00420     * \brief Inbound audio frame returned by misdn_read().
00421     */
00422    struct ast_frame frame;
00423 
00424    /*!
00425     * \brief Fax detection option. (0:no 1:yes 2:yes+nojump)
00426     * \note The "faxdetect" option string read in from /etc/asterisk/misdn.conf
00427     * \note It is settable by the misdn_set_opt() application.
00428     */
00429    int faxdetect;
00430 
00431    /*!
00432     * \brief Number of seconds to detect a Fax machine when detection enabled.
00433     * \note 0 disables the timeout.
00434     * \note The "faxdetect_timeout" value read in from /etc/asterisk/misdn.conf
00435     */
00436    int faxdetect_timeout;
00437 
00438    /*!
00439     * \brief Starting time of fax detection with timeout when nonzero.
00440     */
00441    struct timeval faxdetect_tv;
00442 
00443    /*!
00444     * \brief TRUE if a fax has been detected.
00445     */
00446    int faxhandled;
00447 
00448    /*!
00449     * \brief TRUE if we will use the Asterisk DSP to detect DTMF/Fax
00450     * \note The "astdtmf" boolean read in from /etc/asterisk/misdn.conf
00451     */
00452    int ast_dsp;
00453 
00454    /*!
00455     * \brief Jitterbuffer length
00456     * \note The "jitterbuffer" value read in from /etc/asterisk/misdn.conf
00457     */
00458    int jb_len;
00459 
00460    /*!
00461     * \brief Jitterbuffer upper threshold
00462     * \note The "jitterbuffer_upper_threshold" value read in from /etc/asterisk/misdn.conf
00463     */
00464    int jb_upper_threshold;
00465 
00466    /*!
00467     * \brief Allocated jitterbuffer controller
00468     * \note misdn_jb_init() creates the jitterbuffer.
00469     * \note Must use misdn_jb_destroy() to clean up.
00470     */
00471    struct misdn_jb *jb;
00472 
00473    /*!
00474     * \brief Allocated DSP controller
00475     * \note ast_dsp_new() creates the DSP controller.
00476     * \note Must use ast_dsp_free() to clean up.
00477     */
00478    struct ast_dsp *dsp;
00479 
00480    /*!
00481     * \brief Associated Asterisk channel structure.
00482     */
00483    struct ast_channel * ast;
00484 
00485    /*!
00486     * \brief Associated B channel structure.
00487     */
00488    struct misdn_bchannel *bc;
00489 
00490 #if defined(AST_MISDN_ENHANCEMENTS)
00491    /*!
00492     * \brief Peer channel for which call completion was initialized.
00493     */
00494    struct misdn_cc_caller *peer;
00495 
00496    /*! \brief Associated call completion record ID (-1 if not associated) */
00497    long record_id;
00498 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00499 
00500    /*!
00501     * \brief HELD channel call information
00502     */
00503    struct hold_info hold;
00504 
00505    /*!
00506     * \brief From associated B channel: Layer 3 process ID
00507     * \note Used to find the HELD channel call record when retrieving a call.
00508     */
00509    unsigned int l3id;
00510 
00511    /*!
00512     * \brief From associated B channel: B Channel mISDN driver layer ID from mISDN_get_layerid()
00513     * \note Used only for debug display messages.
00514     */
00515    int addr;
00516 
00517    /*!
00518     * \brief Incoming call dialplan context identifier.
00519     * \note The "context" string read in from /etc/asterisk/misdn.conf
00520     */
00521    char context[AST_MAX_CONTEXT];
00522 
00523    /*!
00524     * \brief The configured music-on-hold class to use for this call.
00525     * \note The "musicclass" string read in from /etc/asterisk/misdn.conf
00526     */
00527    char mohinterpret[MAX_MUSICCLASS];
00528 
00529    /*!
00530     * \brief Number of outgoing audio frames dropped since last debug gripe message.
00531     */
00532    int dropped_frame_cnt;
00533 
00534    /*!
00535     * \brief TRUE if we must do the ringback tones.
00536     * \note The "far_alerting" boolean read in from /etc/asterisk/misdn.conf
00537     */
00538    int far_alerting;
00539 
00540    /*!
00541     * \brief TRUE if NT should disconnect an overlap dialing call when a timeout occurs.
00542     * \note The "nttimeout" boolean read in from /etc/asterisk/misdn.conf
00543     */
00544    int nttimeout;
00545 
00546    /*!
00547     * \brief Other channel call record PID
00548     * \note Value imported from Asterisk environment variable MISDN_PID
00549     */
00550    int other_pid;
00551 
00552    /*!
00553     * \brief Bridged other channel call record
00554     * \note Pointer set when other_pid imported from Asterisk environment
00555     * variable MISDN_PID by either side.
00556     */
00557    struct chan_list *other_ch;
00558 
00559    /*!
00560     * \brief Tone zone sound used for dialtone generation.
00561     * \note Used as a boolean.  Non-NULL to prod generation if enabled.
00562     */
00563    struct ast_tone_zone_sound *ts;
00564 
00565    /*!
00566     * \brief Enables overlap dialing for the set amount of seconds.  (0 = Disabled)
00567     * \note The "overlapdial" value read in from /etc/asterisk/misdn.conf
00568     */
00569    int overlap_dial;
00570 
00571    /*!
00572     * \brief Overlap dialing timeout Task ID.  -1 if not running.
00573     */
00574    int overlap_dial_task;
00575 
00576    /*!
00577     * \brief overlap_tv access lock.
00578     */
00579    ast_mutex_t overlap_tv_lock;
00580 
00581    /*!
00582     * \brief Overlap timer start time.  Timer restarted for every digit received.
00583     */
00584    struct timeval overlap_tv;
00585 
00586    /*!
00587     * \brief Next channel call record in the list.
00588     */
00589    struct chan_list *next;
00590 };
00591 
00592 
00593 int MAXTICS = 8;
00594 
00595 
00596 void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch);
00597 void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch);
00598 static struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame);
00599 
00600 struct robin_list {
00601    char *group;
00602    int port;
00603    int channel;
00604    struct robin_list *next;
00605    struct robin_list *prev;
00606 };
00607 static struct robin_list *robin = NULL;
00608 
00609 
00610 static void free_robin_list(void)
00611 {
00612    struct robin_list *r;
00613    struct robin_list *next;
00614 
00615    for (r = robin, robin = NULL; r; r = next) {
00616       next = r->next;
00617       ast_free(r->group);
00618       ast_free(r);
00619    }
00620 }
00621 
00622 static struct robin_list *get_robin_position(char *group)
00623 {
00624    struct robin_list *new;
00625    struct robin_list *iter = robin;
00626    for (; iter; iter = iter->next) {
00627       if (!strcasecmp(iter->group, group)) {
00628          return iter;
00629       }
00630    }
00631    new = ast_calloc(1, sizeof(*new));
00632    if (!new) {
00633       return NULL;
00634    }
00635    new->group = ast_strdup(group);
00636    if (!new->group) {
00637       ast_free(new);
00638       return NULL;
00639    }
00640    new->channel = 1;
00641    if (robin) {
00642       new->next = robin;
00643       robin->prev = new;
00644    }
00645    robin = new;
00646    return robin;
00647 }
00648 
00649 
00650 /*! \brief the main schedule context for stuff like l1 watcher, overlap dial, ... */
00651 static struct sched_context *misdn_tasks = NULL;
00652 static pthread_t misdn_tasks_thread;
00653 
00654 static int *misdn_ports;
00655 
00656 static void chan_misdn_log(int level, int port, char *tmpl, ...)
00657    __attribute__((format(printf, 3, 4)));
00658 
00659 static struct ast_channel *misdn_new(struct chan_list *cl, int state,  char *exten, char *callerid, int format, const char *linkedid, int port, int c);
00660 static void send_digit_to_chan(struct chan_list *cl, char digit);
00661 
00662 static int pbx_start_chan(struct chan_list *ch);
00663 
00664 #define MISDN_ASTERISK_TECH_PVT(ast) ast->tech_pvt
00665 
00666 #include "asterisk/strings.h"
00667 
00668 /* #define MISDN_DEBUG 1 */
00669 
00670 static const char misdn_type[] = "mISDN";
00671 
00672 static int tracing = 0;
00673 
00674 /*! \brief Only alaw and mulaw is allowed for now */
00675 static int prefformat =  AST_FORMAT_ALAW ; /*  AST_FORMAT_SLINEAR ;  AST_FORMAT_ULAW | */
00676 
00677 static int *misdn_debug;
00678 static int *misdn_debug_only;
00679 static int max_ports;
00680 
00681 static int *misdn_in_calls;
00682 static int *misdn_out_calls;
00683 
00684 /*!
00685  * \brief Global channel call record list head.
00686  */
00687 static struct chan_list *cl_te=NULL;
00688 static ast_mutex_t cl_te_lock;
00689 
00690 static enum event_response_e
00691 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data);
00692 
00693 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc, struct chan_list *ch);
00694 
00695 static void cl_queue_chan(struct chan_list *chan);
00696 
00697 static int dialtone_indicate(struct chan_list *cl);
00698 static void hanguptone_indicate(struct chan_list *cl);
00699 static int stop_indicate(struct chan_list *cl);
00700 
00701 static int start_bc_tones(struct chan_list *cl);
00702 static int stop_bc_tones(struct chan_list *cl);
00703 static void release_chan_early(struct chan_list *ch);
00704 static void release_chan(struct chan_list *ch, struct misdn_bchannel *bc);
00705 
00706 #if defined(AST_MISDN_ENHANCEMENTS)
00707 static const char misdn_command_name[] = "misdn_command";
00708 static int misdn_command_exec(struct ast_channel *chan, const char *data);
00709 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00710 static int misdn_check_l2l1(struct ast_channel *chan, const char *data);
00711 static int misdn_set_opt_exec(struct ast_channel *chan, const char *data);
00712 static int misdn_facility_exec(struct ast_channel *chan, const char *data);
00713 
00714 int chan_misdn_jb_empty(struct misdn_bchannel *bc, char *buf, int len);
00715 
00716 void debug_numtype(int port, int numtype, char *type);
00717 
00718 int add_out_calls(int port);
00719 int add_in_calls(int port);
00720 
00721 
00722 #ifdef MISDN_1_2
00723 static int update_pipeline_config(struct misdn_bchannel *bc);
00724 #else
00725 static int update_ec_config(struct misdn_bchannel *bc);
00726 #endif
00727 
00728 
00729 
00730 /*************** Helpers *****************/
00731 
00732 static int misdn_chan_is_valid(struct chan_list *ch)
00733 {
00734    struct chan_list *list;
00735 
00736    ast_mutex_lock(&cl_te_lock);
00737    for (list = cl_te; list; list = list->next) {
00738       if (list == ch) {
00739          ast_mutex_unlock(&cl_te_lock);
00740          return 1;
00741       }
00742    }
00743    ast_mutex_unlock(&cl_te_lock);
00744 
00745    return 0;
00746 }
00747 
00748 static struct chan_list *get_chan_by_ast(struct ast_channel *ast)
00749 {
00750    struct chan_list *tmp;
00751 
00752    ast_mutex_lock(&cl_te_lock);
00753    for (tmp = cl_te; tmp; tmp = tmp->next) {
00754       if (tmp->ast == ast) {
00755          ast_mutex_unlock(&cl_te_lock);
00756          return tmp;
00757       }
00758    }
00759    ast_mutex_unlock(&cl_te_lock);
00760 
00761    return NULL;
00762 }
00763 
00764 static struct chan_list *get_chan_by_ast_name(const char *name)
00765 {
00766    struct chan_list *tmp;
00767 
00768    ast_mutex_lock(&cl_te_lock);
00769    for (tmp = cl_te; tmp; tmp = tmp->next) {
00770       if (tmp->ast && strcmp(tmp->ast->name, name) == 0) {
00771          ast_mutex_unlock(&cl_te_lock);
00772          return tmp;
00773       }
00774    }
00775    ast_mutex_unlock(&cl_te_lock);
00776 
00777    return NULL;
00778 }
00779 
00780 #if defined(AST_MISDN_ENHANCEMENTS)
00781 /*!
00782  * \internal
00783  * \brief Destroy the misdn_cc_ds_info datastore payload
00784  *
00785  * \param[in] data the datastore payload, a reference to an misdn_cc_caller
00786  *
00787  * \details
00788  * Since the payload is a reference to an astobj2 object, we just decrement its
00789  * reference count.  Before doing so, we NULL out the channel pointer inside of
00790  * the misdn_cc_caller instance.  This function will be called in one of two
00791  * cases.  In both cases, we no longer need the channel pointer:
00792  *
00793  *  - The original channel that initialized call completion services, the same
00794  *    channel that is stored here, has been destroyed early.  This could happen
00795  *    if it transferred the mISDN channel, for example.
00796  *
00797  *  - The mISDN channel that had this datastore inherited on to it is now being
00798  *    destroyed.  If this is the case, then the call completion events have
00799  *    already occurred and the appropriate channel variables have already been
00800  *    set on the original channel that requested call completion services.
00801  *
00802  * \return Nothing
00803  */
00804 static void misdn_cc_ds_destroy(void *data)
00805 {
00806    struct misdn_cc_caller *cc_caller = data;
00807 
00808    ao2_lock(cc_caller);
00809    cc_caller->chan = NULL;
00810    ao2_unlock(cc_caller);
00811 
00812    ao2_ref(cc_caller, -1);
00813 }
00814 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00815 
00816 #if defined(AST_MISDN_ENHANCEMENTS)
00817 /*!
00818  * \internal
00819  * \brief Duplicate the misdn_cc_ds_info datastore payload
00820  *
00821  * \param[in] data the datastore payload, a reference to an misdn_cc_caller
00822  *
00823  * \details
00824  * All we need to do is bump the reference count and return the same instance.
00825  *
00826  * \return A reference to an instance of a misdn_cc_caller
00827  */
00828 static void *misdn_cc_ds_duplicate(void *data)
00829 {
00830    struct misdn_cc_caller *cc_caller = data;
00831 
00832    ao2_ref(cc_caller, +1);
00833 
00834    return cc_caller;
00835 }
00836 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00837 
00838 #if defined(AST_MISDN_ENHANCEMENTS)
00839 static const struct ast_datastore_info misdn_cc_ds_info = {
00840    .type      = "misdn_cc",
00841    .destroy   = misdn_cc_ds_destroy,
00842    .duplicate = misdn_cc_ds_duplicate,
00843 };
00844 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00845 
00846 #if defined(AST_MISDN_ENHANCEMENTS)
00847 /*!
00848  * \internal
00849  * \brief Set a channel var on the peer channel for call completion services
00850  *
00851  * \param[in] peer The peer that initialized call completion services
00852  * \param[in] var The variable name to set
00853  * \param[in] value The variable value to set
00854  *
00855  * This function may be called from outside of the channel thread.  It handles
00856  * the fact that the peer channel may be hung up and destroyed at any time.
00857  *
00858  * \return nothing
00859  */
00860 static void misdn_cc_set_peer_var(struct misdn_cc_caller *peer, const char *var,
00861    const char *value)
00862 {
00863    ao2_lock(peer);
00864 
00865    /*! \todo XXX This nastiness can go away once ast_channel is ref counted! */
00866    while (peer->chan && ast_channel_trylock(peer->chan)) {
00867       ao2_unlock(peer);
00868       sched_yield();
00869       ao2_lock(peer);
00870    }
00871 
00872    if (peer->chan) {
00873       pbx_builtin_setvar_helper(peer->chan, var, value);
00874       ast_channel_unlock(peer->chan);
00875    }
00876 
00877    ao2_unlock(peer);
00878 }
00879 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00880 
00881 #if defined(AST_MISDN_ENHANCEMENTS)
00882 /*!
00883  * \internal
00884  * \brief Get a reference to the CC caller if it exists
00885  */
00886 static struct misdn_cc_caller *misdn_cc_caller_get(struct ast_channel *chan)
00887 {
00888    struct ast_datastore *datastore;
00889    struct misdn_cc_caller *cc_caller;
00890 
00891    ast_channel_lock(chan);
00892 
00893    if (!(datastore = ast_channel_datastore_find(chan, &misdn_cc_ds_info, NULL))) {
00894       ast_channel_unlock(chan);
00895       return NULL;
00896    }
00897 
00898    ao2_ref(datastore->data, +1);
00899    cc_caller = datastore->data;
00900 
00901    ast_channel_unlock(chan);
00902 
00903    return cc_caller;
00904 }
00905 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00906 
00907 #if defined(AST_MISDN_ENHANCEMENTS)
00908 /*!
00909  * \internal
00910  * \brief Find the call completion record given the record id.
00911  *
00912  * \param record_id
00913  *
00914  * \retval pointer to found call completion record
00915  * \retval NULL if not found
00916  *
00917  * \note Assumes the misdn_cc_records_db lock is already obtained.
00918  */
00919 static struct misdn_cc_record *misdn_cc_find_by_id(long record_id)
00920 {
00921    struct misdn_cc_record *current;
00922 
00923    AST_LIST_TRAVERSE(&misdn_cc_records_db, current, list) {
00924       if (current->record_id == record_id) {
00925          /* Found the record */
00926          break;
00927       }
00928    }
00929 
00930    return current;
00931 }
00932 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00933 
00934 #if defined(AST_MISDN_ENHANCEMENTS)
00935 /*!
00936  * \internal
00937  * \brief Find the call completion record given the port and call linkage id.
00938  *
00939  * \param port Logical port number
00940  * \param linkage_id Call linkage ID number from switch.
00941  *
00942  * \retval pointer to found call completion record
00943  * \retval NULL if not found
00944  *
00945  * \note Assumes the misdn_cc_records_db lock is already obtained.
00946  */
00947 static struct misdn_cc_record *misdn_cc_find_by_linkage(int port, int linkage_id)
00948 {
00949    struct misdn_cc_record *current;
00950 
00951    AST_LIST_TRAVERSE(&misdn_cc_records_db, current, list) {
00952       if (current->port == port
00953          && !current->ptp
00954          && current->mode.ptmp.linkage_id == linkage_id) {
00955          /* Found the record */
00956          break;
00957       }
00958    }
00959 
00960    return current;
00961 }
00962 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00963 
00964 #if defined(AST_MISDN_ENHANCEMENTS)
00965 /*!
00966  * \internal
00967  * \brief Find the call completion record given the port and outstanding invocation id.
00968  *
00969  * \param port Logical port number
00970  * \param invoke_id Outstanding message invocation ID number.
00971  *
00972  * \retval pointer to found call completion record
00973  * \retval NULL if not found
00974  *
00975  * \note Assumes the misdn_cc_records_db lock is already obtained.
00976  */
00977 static struct misdn_cc_record *misdn_cc_find_by_invoke(int port, int invoke_id)
00978 {
00979    struct misdn_cc_record *current;
00980 
00981    AST_LIST_TRAVERSE(&misdn_cc_records_db, current, list) {
00982       if (current->outstanding_message
00983          && current->invoke_id == invoke_id
00984          && current->port == port) {
00985          /* Found the record */
00986          break;
00987       }
00988    }
00989 
00990    return current;
00991 }
00992 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
00993 
00994 #if defined(AST_MISDN_ENHANCEMENTS)
00995 /*!
00996  * \internal
00997  * \brief Find the call completion record given the port and CCBS reference id.
00998  *
00999  * \param port Logical port number
01000  * \param reference_id CCBS reference ID number from switch.
01001  *
01002  * \retval pointer to found call completion record
01003  * \retval NULL if not found
01004  *
01005  * \note Assumes the misdn_cc_records_db lock is already obtained.
01006  */
01007 static struct misdn_cc_record *misdn_cc_find_by_reference(int port, int reference_id)
01008 {
01009    struct misdn_cc_record *current;
01010 
01011    AST_LIST_TRAVERSE(&misdn_cc_records_db, current, list) {
01012       if (current->activated
01013          && current->port == port
01014          && !current->ptp
01015          && current->mode.ptmp.reference_id == reference_id) {
01016          /* Found the record */
01017          break;
01018       }
01019    }
01020 
01021    return current;
01022 }
01023 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01024 
01025 #if defined(AST_MISDN_ENHANCEMENTS)
01026 /*!
01027  * \internal
01028  * \brief Find the call completion record given the B channel pointer
01029  *
01030  * \param bc B channel control structure pointer.
01031  *
01032  * \retval pointer to found call completion record
01033  * \retval NULL if not found
01034  *
01035  * \note Assumes the misdn_cc_records_db lock is already obtained.
01036  */
01037 static struct misdn_cc_record *misdn_cc_find_by_bc(const struct misdn_bchannel *bc)
01038 {
01039    struct misdn_cc_record *current;
01040 
01041    if (bc) {
01042       AST_LIST_TRAVERSE(&misdn_cc_records_db, current, list) {
01043          if (current->ptp
01044             && current->mode.ptp.bc == bc) {
01045             /* Found the record */
01046             break;
01047          }
01048       }
01049    } else {
01050       current = NULL;
01051    }
01052 
01053    return current;
01054 }
01055 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01056 
01057 #if defined(AST_MISDN_ENHANCEMENTS)
01058 /*!
01059  * \internal
01060  * \brief Delete the given call completion record
01061  *
01062  * \param doomed Call completion record to destroy
01063  *
01064  * \return Nothing
01065  *
01066  * \note Assumes the misdn_cc_records_db lock is already obtained.
01067  */
01068 static void misdn_cc_delete(struct misdn_cc_record *doomed)
01069 {
01070    struct misdn_cc_record *current;
01071 
01072    AST_LIST_TRAVERSE_SAFE_BEGIN(&misdn_cc_records_db, current, list) {
01073       if (current == doomed) {
01074          AST_LIST_REMOVE_CURRENT(list);
01075          ast_free(current);
01076          return;
01077       }
01078    }
01079    AST_LIST_TRAVERSE_SAFE_END;
01080 
01081    /* The doomed node is not in the call completion database */
01082 }
01083 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01084 
01085 #if defined(AST_MISDN_ENHANCEMENTS)
01086 /*!
01087  * \internal
01088  * \brief Delete all old call completion records
01089  *
01090  * \return Nothing
01091  *
01092  * \note Assumes the misdn_cc_records_db lock is already obtained.
01093  */
01094 static void misdn_cc_remove_old(void)
01095 {
01096    struct misdn_cc_record *current;
01097    time_t now;
01098 
01099    now = time(NULL);
01100    AST_LIST_TRAVERSE_SAFE_BEGIN(&misdn_cc_records_db, current, list) {
01101       if (MISDN_CC_RECORD_AGE_MAX < now - current->time_created) {
01102          if (current->ptp && current->mode.ptp.bc) {
01103             /* Close the old call-completion signaling link */
01104             current->mode.ptp.bc->fac_out.Function = Fac_None;
01105             current->mode.ptp.bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
01106             misdn_lib_send_event(current->mode.ptp.bc, EVENT_RELEASE_COMPLETE);
01107          }
01108 
01109          /* Remove the old call completion record */
01110          AST_LIST_REMOVE_CURRENT(list);
01111          ast_free(current);
01112       }
01113    }
01114    AST_LIST_TRAVERSE_SAFE_END;
01115 }
01116 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01117 
01118 #if defined(AST_MISDN_ENHANCEMENTS)
01119 /*!
01120  * \internal
01121  * \brief Allocate the next record id.
01122  *
01123  * \retval New record id on success.
01124  * \retval -1 on error.
01125  *
01126  * \note Assumes the misdn_cc_records_db lock is already obtained.
01127  */
01128 static long misdn_cc_record_id_new(void)
01129 {
01130    long record_id;
01131    long first_id;
01132 
01133    record_id = ++misdn_cc_record_id;
01134    first_id = record_id;
01135    while (misdn_cc_find_by_id(record_id)) {
01136       record_id = ++misdn_cc_record_id;
01137       if (record_id == first_id) {
01138          /*
01139           * We have a resource leak.
01140           * We should never need to allocate 64k records.
01141           */
01142          chan_misdn_log(0, 0, " --> ERROR Too many call completion records!\n");
01143          record_id = -1;
01144          break;
01145       }
01146    }
01147 
01148    return record_id;
01149 }
01150 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01151 
01152 #if defined(AST_MISDN_ENHANCEMENTS)
01153 /*!
01154  * \internal
01155  * \brief Create a new call completion record
01156  *
01157  * \retval pointer to new call completion record
01158  * \retval NULL if failed
01159  *
01160  * \note Assumes the misdn_cc_records_db lock is already obtained.
01161  */
01162 static struct misdn_cc_record *misdn_cc_new(void)
01163 {
01164    struct misdn_cc_record *cc_record;
01165    long record_id;
01166 
01167    misdn_cc_remove_old();
01168 
01169    cc_record = ast_calloc(1, sizeof(*cc_record));
01170    if (cc_record) {
01171       record_id = misdn_cc_record_id_new();
01172       if (record_id < 0) {
01173          ast_free(cc_record);
01174          return NULL;
01175       }
01176 
01177       /* Initialize the new record */
01178       cc_record->record_id = record_id;
01179       cc_record->port = -1;/* Invalid port so it will never be found this way */
01180       cc_record->invoke_id = ++misdn_invoke_id;
01181       cc_record->party_a_free = 1;/* Default User-A as free */
01182       cc_record->error_code = FacError_None;
01183       cc_record->reject_code = FacReject_None;
01184       cc_record->time_created = time(NULL);
01185 
01186       /* Insert the new record into the database */
01187       AST_LIST_INSERT_HEAD(&misdn_cc_records_db, cc_record, list);
01188    }
01189    return cc_record;
01190 }
01191 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01192 
01193 #if defined(AST_MISDN_ENHANCEMENTS)
01194 /*!
01195  * \internal
01196  * \brief Destroy the call completion record database
01197  *
01198  * \return Nothing
01199  */
01200 static void misdn_cc_destroy(void)
01201 {
01202    struct misdn_cc_record *current;
01203 
01204    while ((current = AST_LIST_REMOVE_HEAD(&misdn_cc_records_db, list))) {
01205       /* Do a misdn_cc_delete(current) inline */
01206       ast_free(current);
01207    }
01208 }
01209 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01210 
01211 #if defined(AST_MISDN_ENHANCEMENTS)
01212 /*!
01213  * \internal
01214  * \brief Initialize the call completion record database
01215  *
01216  * \return Nothing
01217  */
01218 static void misdn_cc_init(void)
01219 {
01220    misdn_cc_record_id = 0;
01221 }
01222 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01223 
01224 #if defined(AST_MISDN_ENHANCEMENTS)
01225 /*!
01226  * \internal
01227  * \brief Check the status of an outstanding invocation request.
01228  *
01229  * \param data Points to an integer containing the call completion record id.
01230  *
01231  * \retval 0 if got a response.
01232  * \retval -1 if no response yet.
01233  */
01234 static int misdn_cc_response_check(void *data)
01235 {
01236    int not_responded;
01237    struct misdn_cc_record *cc_record;
01238 
01239    AST_LIST_LOCK(&misdn_cc_records_db);
01240    cc_record = misdn_cc_find_by_id(*(long *) data);
01241    if (cc_record) {
01242       if (cc_record->outstanding_message) {
01243          not_responded = -1;
01244       } else {
01245          not_responded = 0;
01246       }
01247    } else {
01248       /* No record so there is no response to check. */
01249       not_responded = 0;
01250    }
01251    AST_LIST_UNLOCK(&misdn_cc_records_db);
01252 
01253    return not_responded;
01254 }
01255 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01256 
01257 #if defined(AST_MISDN_ENHANCEMENTS)
01258 /*!
01259  * \internal
01260  * \brief Wait for a response from the switch for an outstanding
01261  * invocation request.
01262  *
01263  * \param chan Asterisk channel to operate upon.
01264  * \param wait_seconds Number of seconds to wait
01265  * \param record_id Call completion record ID.
01266  *
01267  * \return Nothing
01268  */
01269 static void misdn_cc_response_wait(struct ast_channel *chan, int wait_seconds, long record_id)
01270 {
01271    unsigned count;
01272 
01273    for (count = 2 * MISDN_CC_REQUEST_WAIT_MAX; count--;) {
01274       /* Sleep in 500 ms increments */
01275       if (ast_safe_sleep_conditional(chan, 500, misdn_cc_response_check, &record_id) != 0) {
01276          /* We got hung up or our response came in. */
01277          break;
01278       }
01279    }
01280 }
01281 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01282 
01283 #if defined(AST_MISDN_ENHANCEMENTS)
01284 /*!
01285  * \internal
01286  * \brief Convert the mISDN reject code to a string
01287  *
01288  * \param code mISDN reject code.
01289  *
01290  * \return The mISDN reject code as a string
01291  */
01292 static const char *misdn_to_str_reject_code(enum FacRejectCode code)
01293 {
01294    static const struct {
01295       enum FacRejectCode code;
01296       char *name;
01297    } arr[] = {
01298 /* *INDENT-OFF* */
01299       { FacReject_None,                           "No reject occurred" },
01300       { FacReject_Unknown,                        "Unknown reject code" },
01301 
01302       { FacReject_Gen_UnrecognizedComponent,      "General: Unrecognized Component" },
01303       { FacReject_Gen_MistypedComponent,          "General: Mistyped Component" },
01304       { FacReject_Gen_BadlyStructuredComponent,   "General: Badly Structured Component" },
01305 
01306       { FacReject_Inv_DuplicateInvocation,        "Invoke: Duplicate Invocation" },
01307       { FacReject_Inv_UnrecognizedOperation,      "Invoke: Unrecognized Operation" },
01308       { FacReject_Inv_MistypedArgument,           "Invoke: Mistyped Argument" },
01309       { FacReject_Inv_ResourceLimitation,         "Invoke: Resource Limitation" },
01310       { FacReject_Inv_InitiatorReleasing,         "Invoke: Initiator Releasing" },
01311       { FacReject_Inv_UnrecognizedLinkedID,       "Invoke: Unrecognized Linked ID" },
01312       { FacReject_Inv_LinkedResponseUnexpected,   "Invoke: Linked Response Unexpected" },
01313       { FacReject_Inv_UnexpectedChildOperation,   "Invoke: Unexpected Child Operation" },
01314 
01315       { FacReject_Res_UnrecognizedInvocation,     "Result: Unrecognized Invocation" },
01316       { FacReject_Res_ResultResponseUnexpected,   "Result: Result Response Unexpected" },
01317       { FacReject_Res_MistypedResult,             "Result: Mistyped Result" },
01318 
01319       { FacReject_Err_UnrecognizedInvocation,     "Error: Unrecognized Invocation" },
01320       { FacReject_Err_ErrorResponseUnexpected,    "Error: Error Response Unexpected" },
01321       { FacReject_Err_UnrecognizedError,          "Error: Unrecognized Error" },
01322       { FacReject_Err_UnexpectedError,            "Error: Unexpected Error" },
01323       { FacReject_Err_MistypedParameter,          "Error: Mistyped Parameter" },
01324 /* *INDENT-ON* */
01325    };
01326 
01327    unsigned index;
01328 
01329    for (index = 0; index < ARRAY_LEN(arr); ++index) {
01330       if (arr[index].code == code) {
01331          return arr[index].name;
01332       }
01333    }
01334 
01335    return "unknown";
01336 }
01337 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01338 
01339 #if defined(AST_MISDN_ENHANCEMENTS)
01340 /*!
01341  * \internal
01342  * \brief Convert the mISDN error code to a string
01343  *
01344  * \param code mISDN error code.
01345  *
01346  * \return The mISDN error code as a string
01347  */
01348 static const char *misdn_to_str_error_code(enum FacErrorCode code)
01349 {
01350    static const struct {
01351       enum FacErrorCode code;
01352       char *name;
01353    } arr[] = {
01354 /* *INDENT-OFF* */
01355       { FacError_None,                            "No error occurred" },
01356       { FacError_Unknown,                         "Unknown OID error code" },
01357 
01358       { FacError_Gen_NotSubscribed,               "General: Not Subscribed" },
01359       { FacError_Gen_NotAvailable,                "General: Not Available" },
01360       { FacError_Gen_NotImplemented,              "General: Not Implemented" },
01361       { FacError_Gen_InvalidServedUserNr,         "General: Invalid Served User Number" },
01362       { FacError_Gen_InvalidCallState,            "General: Invalid Call State" },
01363       { FacError_Gen_BasicServiceNotProvided,     "General: Basic Service Not Provided" },
01364       { FacError_Gen_NotIncomingCall,             "General: Not Incoming Call" },
01365       { FacError_Gen_SupplementaryServiceInteractionNotAllowed,"General: Supplementary Service Interaction Not Allowed" },
01366       { FacError_Gen_ResourceUnavailable,         "General: Resource Unavailable" },
01367 
01368       { FacError_Div_InvalidDivertedToNr,         "Diversion: Invalid Diverted To Number" },
01369       { FacError_Div_SpecialServiceNr,            "Diversion: Special Service Number" },
01370       { FacError_Div_DiversionToServedUserNr,     "Diversion: Diversion To Served User Number" },
01371       { FacError_Div_IncomingCallAccepted,        "Diversion: Incoming Call Accepted" },
01372       { FacError_Div_NumberOfDiversionsExceeded,  "Diversion: Number Of Diversions Exceeded" },
01373       { FacError_Div_NotActivated,                "Diversion: Not Activated" },
01374       { FacError_Div_RequestAlreadyAccepted,      "Diversion: Request Already Accepted" },
01375 
01376       { FacError_AOC_NoChargingInfoAvailable,     "AOC: No Charging Info Available" },
01377 
01378       { FacError_CCBS_InvalidCallLinkageID,       "CCBS: Invalid Call Linkage ID" },
01379       { FacError_CCBS_InvalidCCBSReference,       "CCBS: Invalid CCBS Reference" },
01380       { FacError_CCBS_LongTermDenial,             "CCBS: Long Term Denial" },
01381       { FacError_CCBS_ShortTermDenial,            "CCBS: Short Term Denial" },
01382       { FacError_CCBS_IsAlreadyActivated,         "CCBS: Is Already Activated" },
01383       { FacError_CCBS_AlreadyAccepted,            "CCBS: Already Accepted" },
01384       { FacError_CCBS_OutgoingCCBSQueueFull,      "CCBS: Outgoing CCBS Queue Full" },
01385       { FacError_CCBS_CallFailureReasonNotBusy,   "CCBS: Call Failure Reason Not Busy" },
01386       { FacError_CCBS_NotReadyForCall,            "CCBS: Not Ready For Call" },
01387 
01388       { FacError_CCBS_T_LongTermDenial,           "CCBS-T: Long Term Denial" },
01389       { FacError_CCBS_T_ShortTermDenial,          "CCBS-T: Short Term Denial" },
01390 
01391       { FacError_ECT_LinkIdNotAssignedByNetwork,  "ECT: Link ID Not Assigned By Network" },
01392 /* *INDENT-ON* */
01393    };
01394 
01395    unsigned index;
01396 
01397    for (index = 0; index < ARRAY_LEN(arr); ++index) {
01398       if (arr[index].code == code) {
01399          return arr[index].name;
01400       }
01401    }
01402 
01403    return "unknown";
01404 }
01405 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01406 
01407 #if defined(AST_MISDN_ENHANCEMENTS)
01408 /*!
01409  * \internal
01410  * \brief Convert mISDN redirecting reason to diversion reason.
01411  *
01412  * \param reason mISDN redirecting reason code.
01413  *
01414  * \return Supported diversion reason code.
01415  */
01416 static unsigned misdn_to_diversion_reason(enum mISDN_REDIRECTING_REASON reason)
01417 {
01418    unsigned diversion_reason;
01419 
01420    switch (reason) {
01421    case mISDN_REDIRECTING_REASON_CALL_FWD:
01422       diversion_reason = 1;/* cfu */
01423       break;
01424    case mISDN_REDIRECTING_REASON_CALL_FWD_BUSY:
01425       diversion_reason = 2;/* cfb */
01426       break;
01427    case mISDN_REDIRECTING_REASON_NO_REPLY:
01428       diversion_reason = 3;/* cfnr */
01429       break;
01430    default:
01431       diversion_reason = 0;/* unknown */
01432       break;
01433    }
01434 
01435    return diversion_reason;
01436 }
01437 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01438 
01439 #if defined(AST_MISDN_ENHANCEMENTS)
01440 /*!
01441  * \internal
01442  * \brief Convert diversion reason to mISDN redirecting reason
01443  *
01444  * \param diversion_reason Diversion reason to convert
01445  *
01446  * \return Supported redirecting reason code.
01447  */
01448 static enum mISDN_REDIRECTING_REASON diversion_reason_to_misdn(unsigned diversion_reason)
01449 {
01450    enum mISDN_REDIRECTING_REASON reason;
01451 
01452    switch (diversion_reason) {
01453    case 1:/* cfu */
01454       reason = mISDN_REDIRECTING_REASON_CALL_FWD;
01455       break;
01456    case 2:/* cfb */
01457       reason = mISDN_REDIRECTING_REASON_CALL_FWD_BUSY;
01458       break;
01459    case 3:/* cfnr */
01460       reason = mISDN_REDIRECTING_REASON_NO_REPLY;
01461       break;
01462    default:
01463       reason = mISDN_REDIRECTING_REASON_UNKNOWN;
01464       break;
01465    }
01466 
01467    return reason;
01468 }
01469 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01470 
01471 #if defined(AST_MISDN_ENHANCEMENTS)
01472 /*!
01473  * \internal
01474  * \brief Convert the mISDN presentation to PresentedNumberUnscreened type
01475  *
01476  * \param presentation mISDN presentation to convert
01477  * \param number_present TRUE if the number is present
01478  *
01479  * \return PresentedNumberUnscreened type
01480  */
01481 static unsigned misdn_to_PresentedNumberUnscreened_type(int presentation, int number_present)
01482 {
01483    unsigned type;
01484 
01485    switch (presentation) {
01486    case 0:/* allowed */
01487       if (number_present) {
01488          type = 0;/* presentationAllowedNumber */
01489       } else {
01490          type = 2;/* numberNotAvailableDueToInterworking */
01491       }
01492       break;
01493    case 1:/* restricted */
01494       if (number_present) {
01495          type = 3;/* presentationRestrictedNumber */
01496       } else {
01497          type = 1;/* presentationRestricted */
01498       }
01499       break;
01500    default:
01501       type = 2;/* numberNotAvailableDueToInterworking */
01502       break;
01503    }
01504 
01505    return type;
01506 }
01507 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01508 
01509 #if defined(AST_MISDN_ENHANCEMENTS)
01510 /*!
01511  * \internal
01512  * \brief Convert the PresentedNumberUnscreened type to mISDN presentation
01513  *
01514  * \param type PresentedNumberUnscreened type
01515  *
01516  * \return mISDN presentation
01517  */
01518 static int PresentedNumberUnscreened_to_misdn_pres(unsigned type)
01519 {
01520    int presentation;
01521 
01522    switch (type) {
01523    default:
01524    case 0:/* presentationAllowedNumber */
01525       presentation = 0;/* allowed */
01526       break;
01527 
01528    case 1:/* presentationRestricted */
01529    case 3:/* presentationRestrictedNumber */
01530       presentation = 1;/* restricted */
01531       break;
01532 
01533    case 2:/* numberNotAvailableDueToInterworking */
01534       presentation = 2;/* unavailable */
01535       break;
01536    }
01537 
01538    return presentation;
01539 }
01540 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01541 
01542 #if defined(AST_MISDN_ENHANCEMENTS)
01543 /*!
01544  * \internal
01545  * \brief Convert the mISDN numbering plan to PartyNumber numbering plan
01546  *
01547  * \param number_plan mISDN numbering plan
01548  *
01549  * \return PartyNumber numbering plan
01550  */
01551 static unsigned misdn_to_PartyNumber_plan(enum mISDN_NUMBER_PLAN number_plan)
01552 {
01553    unsigned party_plan;
01554 
01555    switch (number_plan) {
01556    default:
01557    case NUMPLAN_UNKNOWN:
01558       party_plan = 0;/* unknown */
01559       break;
01560 
01561    case NUMPLAN_ISDN:
01562       party_plan = 1;/* public */
01563       break;
01564 
01565    case NUMPLAN_DATA:
01566       party_plan = 3;/* data */
01567       break;
01568 
01569    case NUMPLAN_TELEX:
01570       party_plan = 4;/* telex */
01571       break;
01572 
01573    case NUMPLAN_NATIONAL:
01574       party_plan = 8;/* nationalStandard */
01575       break;
01576 
01577    case NUMPLAN_PRIVATE:
01578       party_plan = 5;/* private */
01579       break;
01580    }
01581 
01582    return party_plan;
01583 }
01584 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01585 
01586 #if defined(AST_MISDN_ENHANCEMENTS)
01587 /*!
01588  * \internal
01589  * \brief Convert PartyNumber numbering plan to mISDN numbering plan
01590  *
01591  * \param party_plan PartyNumber numbering plan
01592  *
01593  * \return mISDN numbering plan
01594  */
01595 static enum mISDN_NUMBER_PLAN PartyNumber_to_misdn_plan(unsigned party_plan)
01596 {
01597    enum mISDN_NUMBER_PLAN number_plan;
01598 
01599    switch (party_plan) {
01600    default:
01601    case 0:/* unknown */
01602       number_plan = NUMPLAN_UNKNOWN;
01603       break;
01604    case 1:/* public */
01605       number_plan = NUMPLAN_ISDN;
01606       break;
01607    case 3:/* data */
01608       number_plan = NUMPLAN_DATA;
01609       break;
01610    case 4:/* telex */
01611       number_plan = NUMPLAN_TELEX;
01612       break;
01613    case 8:/* nationalStandard */
01614       number_plan = NUMPLAN_NATIONAL;
01615       break;
01616    case 5:/* private */
01617       number_plan = NUMPLAN_PRIVATE;
01618       break;
01619    }
01620 
01621    return number_plan;
01622 }
01623 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01624 
01625 #if defined(AST_MISDN_ENHANCEMENTS)
01626 /*!
01627  * \internal
01628  * \brief Convert mISDN type-of-number to PartyNumber public type-of-number
01629  *
01630  * \param ton mISDN type-of-number
01631  *
01632  * \return PartyNumber public type-of-number
01633  */
01634 static unsigned misdn_to_PartyNumber_ton_public(enum mISDN_NUMBER_TYPE ton)
01635 {
01636    unsigned party_ton;
01637 
01638    switch (ton) {
01639    default:
01640    case NUMTYPE_UNKNOWN:
01641       party_ton = 0;/* unknown */
01642       break;
01643 
01644    case NUMTYPE_INTERNATIONAL:
01645       party_ton = 1;/* internationalNumber */
01646       break;
01647 
01648    case NUMTYPE_NATIONAL:
01649       party_ton = 2;/* nationalNumber */
01650       break;
01651 
01652    case NUMTYPE_NETWORK_SPECIFIC:
01653       party_ton = 3;/* networkSpecificNumber */
01654       break;
01655 
01656    case NUMTYPE_SUBSCRIBER:
01657       party_ton = 4;/* subscriberNumber */
01658       break;
01659 
01660    case NUMTYPE_ABBREVIATED:
01661       party_ton = 6;/* abbreviatedNumber */
01662       break;
01663    }
01664 
01665    return party_ton;
01666 }
01667 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01668 
01669 #if defined(AST_MISDN_ENHANCEMENTS)
01670 /*!
01671  * \internal
01672  * \brief Convert the PartyNumber public type-of-number to mISDN type-of-number
01673  *
01674  * \param party_ton PartyNumber public type-of-number
01675  *
01676  * \return mISDN type-of-number
01677  */
01678 static enum mISDN_NUMBER_TYPE PartyNumber_to_misdn_ton_public(unsigned party_ton)
01679 {
01680    enum mISDN_NUMBER_TYPE ton;
01681 
01682    switch (party_ton) {
01683    default:
01684    case 0:/* unknown */
01685       ton = NUMTYPE_UNKNOWN;
01686       break;
01687 
01688    case 1:/* internationalNumber */
01689       ton = NUMTYPE_INTERNATIONAL;
01690       break;
01691 
01692    case 2:/* nationalNumber */
01693       ton = NUMTYPE_NATIONAL;
01694       break;
01695 
01696    case 3:/* networkSpecificNumber */
01697       ton = NUMTYPE_NETWORK_SPECIFIC;
01698       break;
01699 
01700    case 4:/* subscriberNumber */
01701       ton = NUMTYPE_SUBSCRIBER;
01702       break;
01703 
01704    case 6:/* abbreviatedNumber */
01705       ton = NUMTYPE_ABBREVIATED;
01706       break;
01707    }
01708 
01709    return ton;
01710 }
01711 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01712 
01713 #if defined(AST_MISDN_ENHANCEMENTS)
01714 /*!
01715  * \internal
01716  * \brief Convert mISDN type-of-number to PartyNumber private type-of-number
01717  *
01718  * \param ton mISDN type-of-number
01719  *
01720  * \return PartyNumber private type-of-number
01721  */
01722 static unsigned misdn_to_PartyNumber_ton_private(enum mISDN_NUMBER_TYPE ton)
01723 {
01724    unsigned party_ton;
01725 
01726    switch (ton) {
01727    default:
01728    case NUMTYPE_UNKNOWN:
01729       party_ton = 0;/* unknown */
01730       break;
01731 
01732    case NUMTYPE_INTERNATIONAL:
01733       party_ton = 1;/* level2RegionalNumber */
01734       break;
01735 
01736    case NUMTYPE_NATIONAL:
01737       party_ton = 2;/* level1RegionalNumber */
01738       break;
01739 
01740    case NUMTYPE_NETWORK_SPECIFIC:
01741       party_ton = 3;/* pTNSpecificNumber */
01742       break;
01743 
01744    case NUMTYPE_SUBSCRIBER:
01745       party_ton = 4;/* localNumber */
01746       break;
01747 
01748    case NUMTYPE_ABBREVIATED:
01749       party_ton = 6;/* abbreviatedNumber */
01750       break;
01751    }
01752 
01753    return party_ton;
01754 }
01755 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01756 
01757 #if defined(AST_MISDN_ENHANCEMENTS)
01758 /*!
01759  * \internal
01760  * \brief Convert the PartyNumber private type-of-number to mISDN type-of-number
01761  *
01762  * \param party_ton PartyNumber private type-of-number
01763  *
01764  * \return mISDN type-of-number
01765  */
01766 static enum mISDN_NUMBER_TYPE PartyNumber_to_misdn_ton_private(unsigned party_ton)
01767 {
01768    enum mISDN_NUMBER_TYPE ton;
01769 
01770    switch (party_ton) {
01771    default:
01772    case 0:/* unknown */
01773       ton = NUMTYPE_UNKNOWN;
01774       break;
01775 
01776    case 1:/* level2RegionalNumber */
01777       ton = NUMTYPE_INTERNATIONAL;
01778       break;
01779 
01780    case 2:/* level1RegionalNumber */
01781       ton = NUMTYPE_NATIONAL;
01782       break;
01783 
01784    case 3:/* pTNSpecificNumber */
01785       ton = NUMTYPE_NETWORK_SPECIFIC;
01786       break;
01787 
01788    case 4:/* localNumber */
01789       ton = NUMTYPE_SUBSCRIBER;
01790       break;
01791 
01792    case 6:/* abbreviatedNumber */
01793       ton = NUMTYPE_ABBREVIATED;
01794       break;
01795    }
01796 
01797    return ton;
01798 }
01799 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
01800 
01801 /*!
01802  * \internal
01803  * \brief Convert the mISDN type of number code to a string
01804  *
01805  * \param number_type mISDN type of number code.
01806  *
01807  * \return The mISDN type of number code as a string
01808  */
01809 static const char *misdn_to_str_ton(enum mISDN_NUMBER_TYPE number_type)
01810 {
01811    const char *str;
01812 
01813    switch (number_type) {
01814    default:
01815    case NUMTYPE_UNKNOWN:
01816       str = "Unknown";
01817       break;
01818 
01819    case NUMTYPE_INTERNATIONAL:
01820       str = "International";
01821       break;
01822 
01823    case NUMTYPE_NATIONAL:
01824       str = "National";
01825       break;
01826 
01827    case NUMTYPE_NETWORK_SPECIFIC:
01828       str = "Network Specific";
01829       break;
01830 
01831    case NUMTYPE_SUBSCRIBER:
01832       str = "Subscriber";
01833       break;
01834 
01835    case NUMTYPE_ABBREVIATED:
01836       str = "Abbreviated";
01837       break;
01838    }
01839 
01840    return str;
01841 }
01842 
01843 /*!
01844  * \internal
01845  * \brief Convert the mISDN type of number code to Asterisk type of number code
01846  *
01847  * \param number_type mISDN type of number code.
01848  *
01849  * \return Asterisk type of number code
01850  */
01851 static int misdn_to_ast_ton(enum mISDN_NUMBER_TYPE number_type)
01852 {
01853    int ast_number_type;
01854 
01855    switch (number_type) {
01856    default:
01857    case NUMTYPE_UNKNOWN:
01858       ast_number_type = NUMTYPE_UNKNOWN << 4;
01859       break;
01860 
01861    case NUMTYPE_INTERNATIONAL:
01862       ast_number_type = NUMTYPE_INTERNATIONAL << 4;
01863       break;
01864 
01865    case NUMTYPE_NATIONAL:
01866       ast_number_type = NUMTYPE_NATIONAL << 4;
01867       break;
01868 
01869    case NUMTYPE_NETWORK_SPECIFIC:
01870       ast_number_type = NUMTYPE_NETWORK_SPECIFIC << 4;
01871       break;
01872 
01873    case NUMTYPE_SUBSCRIBER:
01874       ast_number_type = NUMTYPE_SUBSCRIBER << 4;
01875       break;
01876 
01877    case NUMTYPE_ABBREVIATED:
01878       ast_number_type = NUMTYPE_ABBREVIATED << 4;
01879       break;
01880    }
01881 
01882    return ast_number_type;
01883 }
01884 
01885 /*!
01886  * \internal
01887  * \brief Convert the Asterisk type of number code to mISDN type of number code
01888  *
01889  * \param ast_number_type Asterisk type of number code.
01890  *
01891  * \return mISDN type of number code
01892  */
01893 static enum mISDN_NUMBER_TYPE ast_to_misdn_ton(unsigned ast_number_type)
01894 {
01895    enum mISDN_NUMBER_TYPE number_type;
01896 
01897    switch ((ast_number_type >> 4) & 0x07) {
01898    default:
01899    case NUMTYPE_UNKNOWN:
01900       number_type = NUMTYPE_UNKNOWN;
01901       break;
01902 
01903    case NUMTYPE_INTERNATIONAL:
01904       number_type = NUMTYPE_INTERNATIONAL;
01905       break;
01906 
01907    case NUMTYPE_NATIONAL:
01908       number_type = NUMTYPE_NATIONAL;
01909       break;
01910 
01911    case NUMTYPE_NETWORK_SPECIFIC:
01912       number_type = NUMTYPE_NETWORK_SPECIFIC;
01913       break;
01914 
01915    case NUMTYPE_SUBSCRIBER:
01916       number_type = NUMTYPE_SUBSCRIBER;
01917       break;
01918 
01919    case NUMTYPE_ABBREVIATED:
01920       number_type = NUMTYPE_ABBREVIATED;
01921       break;
01922    }
01923 
01924    return number_type;
01925 }
01926 
01927 /*!
01928  * \internal
01929  * \brief Convert the mISDN numbering plan code to a string
01930  *
01931  * \param number_plan mISDN numbering plan code.
01932  *
01933  * \return The mISDN numbering plan code as a string
01934  */
01935 static const char *misdn_to_str_plan(enum mISDN_NUMBER_PLAN number_plan)
01936 {
01937    const char *str;
01938 
01939    switch (number_plan) {
01940    default:
01941    case NUMPLAN_UNKNOWN:
01942       str = "Unknown";
01943       break;
01944 
01945    case NUMPLAN_ISDN:
01946       str = "ISDN";
01947       break;
01948 
01949    case NUMPLAN_DATA:
01950       str = "Data";
01951       break;
01952 
01953    case NUMPLAN_TELEX:
01954       str = "Telex";
01955       break;
01956 
01957    case NUMPLAN_NATIONAL:
01958       str = "National";
01959       break;
01960 
01961    case NUMPLAN_PRIVATE:
01962       str = "Private";
01963       break;
01964    }
01965 
01966    return str;
01967 }
01968 
01969 /*!
01970  * \internal
01971  * \brief Convert the mISDN numbering plan code to Asterisk numbering plan code
01972  *
01973  * \param number_plan mISDN numbering plan code.
01974  *
01975  * \return Asterisk numbering plan code
01976  */
01977 static int misdn_to_ast_plan(enum mISDN_NUMBER_PLAN number_plan)
01978 {
01979    int ast_number_plan;
01980 
01981    switch (number_plan) {
01982    default:
01983    case NUMPLAN_UNKNOWN:
01984       ast_number_plan = NUMPLAN_UNKNOWN;
01985       break;
01986 
01987    case NUMPLAN_ISDN:
01988       ast_number_plan = NUMPLAN_ISDN;
01989       break;
01990 
01991    case NUMPLAN_DATA:
01992       ast_number_plan = NUMPLAN_DATA;
01993       break;
01994 
01995    case NUMPLAN_TELEX:
01996       ast_number_plan = NUMPLAN_TELEX;
01997       break;
01998 
01999    case NUMPLAN_NATIONAL:
02000       ast_number_plan = NUMPLAN_NATIONAL;
02001       break;
02002 
02003    case NUMPLAN_PRIVATE:
02004       ast_number_plan = NUMPLAN_PRIVATE;
02005       break;
02006    }
02007 
02008    return ast_number_plan;
02009 }
02010 
02011 /*!
02012  * \internal
02013  * \brief Convert the Asterisk numbering plan code to mISDN numbering plan code
02014  *
02015  * \param ast_number_plan Asterisk numbering plan code.
02016  *
02017  * \return mISDN numbering plan code
02018  */
02019 static enum mISDN_NUMBER_PLAN ast_to_misdn_plan(unsigned ast_number_plan)
02020 {
02021    enum mISDN_NUMBER_PLAN number_plan;
02022 
02023    switch (ast_number_plan & 0x0F) {
02024    default:
02025    case NUMPLAN_UNKNOWN:
02026       number_plan = NUMPLAN_UNKNOWN;
02027       break;
02028 
02029    case NUMPLAN_ISDN:
02030       number_plan = NUMPLAN_ISDN;
02031       break;
02032 
02033    case NUMPLAN_DATA:
02034       number_plan = NUMPLAN_DATA;
02035       break;
02036 
02037    case NUMPLAN_TELEX:
02038       number_plan = NUMPLAN_TELEX;
02039       break;
02040 
02041    case NUMPLAN_NATIONAL:
02042       number_plan = NUMPLAN_NATIONAL;
02043       break;
02044 
02045    case NUMPLAN_PRIVATE:
02046       number_plan = NUMPLAN_PRIVATE;
02047       break;
02048    }
02049 
02050    return number_plan;
02051 }
02052 
02053 /*!
02054  * \internal
02055  * \brief Convert the mISDN presentation code to a string
02056  *
02057  * \param presentation mISDN number presentation restriction code.
02058  *
02059  * \return The mISDN presentation code as a string
02060  */
02061 static const char *misdn_to_str_pres(int presentation)
02062 {
02063    const char *str;
02064 
02065    switch (presentation) {
02066    case 0:
02067       str = "Allowed";
02068       break;
02069 
02070    case 1:
02071       str = "Restricted";
02072       break;
02073 
02074    case 2:
02075       str = "Unavailable";
02076       break;
02077 
02078    default:
02079       str = "Unknown";
02080       break;
02081    }
02082 
02083    return str;
02084 }
02085 
02086 /*!
02087  * \internal
02088  * \brief Convert the mISDN presentation code to Asterisk presentation code
02089  *
02090  * \param presentation mISDN number presentation restriction code.
02091  *
02092  * \return Asterisk presentation code
02093  */
02094 static int misdn_to_ast_pres(int presentation)
02095 {
02096    switch (presentation) {
02097    default:
02098    case 0:
02099       presentation = AST_PRES_ALLOWED;
02100       break;
02101 
02102    case 1:
02103       presentation = AST_PRES_RESTRICTED;
02104       break;
02105 
02106    case 2:
02107       presentation = AST_PRES_UNAVAILABLE;
02108       break;
02109    }
02110 
02111    return presentation;
02112 }
02113 
02114 /*!
02115  * \internal
02116  * \brief Convert the Asterisk presentation code to mISDN presentation code
02117  *
02118  * \param presentation Asterisk number presentation restriction code.
02119  *
02120  * \return mISDN presentation code
02121  */
02122 static int ast_to_misdn_pres(int presentation)
02123 {
02124    switch (presentation & AST_PRES_RESTRICTION) {
02125    default:
02126    case AST_PRES_ALLOWED:
02127       presentation = 0;
02128       break;
02129 
02130    case AST_PRES_RESTRICTED:
02131       presentation = 1;
02132       break;
02133 
02134    case AST_PRES_UNAVAILABLE:
02135       presentation = 2;
02136       break;
02137    }
02138 
02139    return presentation;
02140 }
02141 
02142 /*!
02143  * \internal
02144  * \brief Convert the mISDN screening code to a string
02145  *
02146  * \param screening mISDN number screening code.
02147  *
02148  * \return The mISDN screening code as a string
02149  */
02150 static const char *misdn_to_str_screen(int screening)
02151 {
02152    const char *str;
02153 
02154    switch (screening) {
02155    case 0:
02156       str = "Unscreened";
02157       break;
02158 
02159    case 1:
02160       str = "Passed Screen";
02161       break;
02162 
02163    case 2:
02164       str = "Failed Screen";
02165       break;
02166 
02167    case 3:
02168       str = "Network Number";
02169       break;
02170 
02171    default:
02172       str = "Unknown";
02173       break;
02174    }
02175 
02176    return str;
02177 }
02178 
02179 /*!
02180  * \internal
02181  * \brief Convert the mISDN screening code to Asterisk screening code
02182  *
02183  * \param screening mISDN number screening code.
02184  *
02185  * \return Asterisk screening code
02186  */
02187 static int misdn_to_ast_screen(int screening)
02188 {
02189    switch (screening) {
02190    default:
02191    case 0:
02192       screening = AST_PRES_USER_NUMBER_UNSCREENED;
02193       break;
02194 
02195    case 1:
02196       screening = AST_PRES_USER_NUMBER_PASSED_SCREEN;
02197       break;
02198 
02199    case 2:
02200       screening = AST_PRES_USER_NUMBER_FAILED_SCREEN;
02201       break;
02202 
02203    case 3:
02204       screening = AST_PRES_NETWORK_NUMBER;
02205       break;
02206    }
02207 
02208    return screening;
02209 }
02210 
02211 /*!
02212  * \internal
02213  * \brief Convert the Asterisk screening code to mISDN screening code
02214  *
02215  * \param screening Asterisk number screening code.
02216  *
02217  * \return mISDN screening code
02218  */
02219 static int ast_to_misdn_screen(int screening)
02220 {
02221    switch (screening & AST_PRES_NUMBER_TYPE) {
02222    default:
02223    case AST_PRES_USER_NUMBER_UNSCREENED:
02224       screening = 0;
02225       break;
02226 
02227    case AST_PRES_USER_NUMBER_PASSED_SCREEN:
02228       screening = 1;
02229       break;
02230 
02231    case AST_PRES_USER_NUMBER_FAILED_SCREEN:
02232       screening = 2;
02233       break;
02234 
02235    case AST_PRES_NETWORK_NUMBER:
02236       screening = 3;
02237       break;
02238    }
02239 
02240    return screening;
02241 }
02242 
02243 /*!
02244  * \internal
02245  * \brief Convert Asterisk redirecting reason to mISDN redirecting reason code.
02246  *
02247  * \param ast Asterisk redirecting reason code.
02248  *
02249  * \return mISDN reason code
02250  */
02251 static enum mISDN_REDIRECTING_REASON ast_to_misdn_reason(const enum AST_REDIRECTING_REASON ast)
02252 {
02253    unsigned index;
02254 
02255    static const struct misdn_reasons {
02256       enum AST_REDIRECTING_REASON ast;
02257       enum mISDN_REDIRECTING_REASON q931;
02258    } misdn_reason_table[] = {
02259    /* *INDENT-OFF* */
02260       { AST_REDIRECTING_REASON_UNKNOWN,        mISDN_REDIRECTING_REASON_UNKNOWN },
02261       { AST_REDIRECTING_REASON_USER_BUSY,      mISDN_REDIRECTING_REASON_CALL_FWD_BUSY },
02262       { AST_REDIRECTING_REASON_NO_ANSWER,      mISDN_REDIRECTING_REASON_NO_REPLY },
02263       { AST_REDIRECTING_REASON_UNAVAILABLE,    mISDN_REDIRECTING_REASON_NO_REPLY },
02264       { AST_REDIRECTING_REASON_UNCONDITIONAL,  mISDN_REDIRECTING_REASON_CALL_FWD },
02265       { AST_REDIRECTING_REASON_TIME_OF_DAY,    mISDN_REDIRECTING_REASON_UNKNOWN },
02266       { AST_REDIRECTING_REASON_DO_NOT_DISTURB, mISDN_REDIRECTING_REASON_UNKNOWN },
02267       { AST_REDIRECTING_REASON_DEFLECTION,     mISDN_REDIRECTING_REASON_DEFLECTION },
02268       { AST_REDIRECTING_REASON_FOLLOW_ME,      mISDN_REDIRECTING_REASON_UNKNOWN },
02269       { AST_REDIRECTING_REASON_OUT_OF_ORDER,   mISDN_REDIRECTING_REASON_OUT_OF_ORDER },
02270       { AST_REDIRECTING_REASON_AWAY,           mISDN_REDIRECTING_REASON_UNKNOWN },
02271       { AST_REDIRECTING_REASON_CALL_FWD_DTE,   mISDN_REDIRECTING_REASON_CALL_FWD_DTE }
02272    /* *INDENT-ON* */
02273    };
02274 
02275    for (index = 0; index < ARRAY_LEN(misdn_reason_table); ++index) {
02276       if (misdn_reason_table[index].ast == ast) {
02277          return misdn_reason_table[index].q931;
02278       }
02279    }
02280    return mISDN_REDIRECTING_REASON_UNKNOWN;
02281 }
02282 
02283 /*!
02284  * \internal
02285  * \brief Convert the mISDN redirecting reason to Asterisk redirecting reason code
02286  *
02287  * \param q931 mISDN redirecting reason code.
02288  *
02289  * \return Asterisk redirecting reason code
02290  */
02291 static enum AST_REDIRECTING_REASON misdn_to_ast_reason(const enum mISDN_REDIRECTING_REASON q931)
02292 {
02293    enum AST_REDIRECTING_REASON ast;
02294 
02295    switch (q931) {
02296    default:
02297    case mISDN_REDIRECTING_REASON_UNKNOWN:
02298       ast = AST_REDIRECTING_REASON_UNKNOWN;
02299       break;
02300 
02301    case mISDN_REDIRECTING_REASON_CALL_FWD_BUSY:
02302       ast = AST_REDIRECTING_REASON_USER_BUSY;
02303       break;
02304 
02305    case mISDN_REDIRECTING_REASON_NO_REPLY:
02306       ast = AST_REDIRECTING_REASON_NO_ANSWER;
02307       break;
02308 
02309    case mISDN_REDIRECTING_REASON_DEFLECTION:
02310       ast = AST_REDIRECTING_REASON_DEFLECTION;
02311       break;
02312 
02313    case mISDN_REDIRECTING_REASON_OUT_OF_ORDER:
02314       ast = AST_REDIRECTING_REASON_OUT_OF_ORDER;
02315       break;
02316 
02317    case mISDN_REDIRECTING_REASON_CALL_FWD_DTE:
02318       ast = AST_REDIRECTING_REASON_CALL_FWD_DTE;
02319       break;
02320 
02321    case mISDN_REDIRECTING_REASON_CALL_FWD:
02322       ast = AST_REDIRECTING_REASON_UNCONDITIONAL;
02323       break;
02324    }
02325 
02326    return ast;
02327 }
02328 
02329 
02330 
02331 struct allowed_bearers {
02332    char *name;         /*!< Bearer capability name string used in /etc/misdn.conf allowed_bearers */
02333    char *display;      /*!< Bearer capability displayable name */
02334    int cap;            /*!< SETUP message bearer capability field code value */
02335    int deprecated;     /*!< TRUE if this entry is deprecated. (Misspelled or bad name to use) */
02336 };
02337 
02338 /* *INDENT-OFF* */
02339 static const struct allowed_bearers allowed_bearers_array[] = {
02340    /* Name,                      Displayable Name       Bearer Capability,                    Deprecated */
02341    { "speech",                  "Speech",               INFO_CAPABILITY_SPEECH,               0 },
02342    { "3_1khz",                  "3.1KHz Audio",         INFO_CAPABILITY_AUDIO_3_1K,           0 },
02343    { "digital_unrestricted",    "Unrestricted Digital", INFO_CAPABILITY_DIGITAL_UNRESTRICTED, 0 },
02344    { "digital_restricted",      "Restricted Digital",   INFO_CAPABILITY_DIGITAL_RESTRICTED,   0 },
02345    { "digital_restriced",       "Restricted Digital",   INFO_CAPABILITY_DIGITAL_RESTRICTED,   1 }, /* Allow misspelling for backwards compatibility */
02346    { "video",                   "Video",                INFO_CAPABILITY_VIDEO,                0 }
02347 };
02348 /* *INDENT-ON* */
02349 
02350 static const char *bearer2str(int cap)
02351 {
02352    unsigned index;
02353 
02354    for (index = 0; index < ARRAY_LEN(allowed_bearers_array); ++index) {
02355       if (allowed_bearers_array[index].cap == cap) {
02356          return allowed_bearers_array[index].display;
02357       }
02358    }
02359 
02360    return "Unknown Bearer";
02361 }
02362 
02363 #if defined(AST_MISDN_ENHANCEMENTS)
02364 /*!
02365  * \internal
02366  * \brief Fill in facility PartyNumber information
02367  *
02368  * \param party PartyNumber structure to fill in.
02369  * \param id Information to put in PartyNumber structure.
02370  *
02371  * \return Nothing
02372  */
02373 static void misdn_PartyNumber_fill(struct FacPartyNumber *party, const struct misdn_party_id *id)
02374 {
02375    ast_copy_string((char *) party->Number, id->number, sizeof(party->Number));
02376    party->LengthOfNumber = strlen((char *) party->Number);
02377    party->Type = misdn_to_PartyNumber_plan(id->number_plan);
02378    switch (party->Type) {
02379    case 1:/* public */
02380       party->TypeOfNumber = misdn_to_PartyNumber_ton_public(id->number_type);
02381       break;
02382    case 5:/* private */
02383       party->TypeOfNumber = misdn_to_PartyNumber_ton_private(id->number_type);
02384       break;
02385    default:
02386       party->TypeOfNumber = 0;/* Don't care */
02387       break;
02388    }
02389 }
02390 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02391 
02392 #if defined(AST_MISDN_ENHANCEMENTS)
02393 /*!
02394  * \internal
02395  * \brief Extract the information from PartyNumber
02396  *
02397  * \param id Where to put extracted PartyNumber information
02398  * \param party PartyNumber information to extract
02399  *
02400  * \return Nothing
02401  */
02402 static void misdn_PartyNumber_extract(struct misdn_party_id *id, const struct FacPartyNumber *party)
02403 {
02404    if (party->LengthOfNumber) {
02405       ast_copy_string(id->number, (char *) party->Number, sizeof(id->number));
02406       id->number_plan = PartyNumber_to_misdn_plan(party->Type);
02407       switch (party->Type) {
02408       case 1:/* public */
02409          id->number_type = PartyNumber_to_misdn_ton_public(party->TypeOfNumber);
02410          break;
02411       case 5:/* private */
02412          id->number_type = PartyNumber_to_misdn_ton_private(party->TypeOfNumber);
02413          break;
02414       default:
02415          id->number_type = NUMTYPE_UNKNOWN;
02416          break;
02417       }
02418    } else {
02419       /* Number not present */
02420       id->number_type = NUMTYPE_UNKNOWN;
02421       id->number_plan = NUMPLAN_ISDN;
02422       id->number[0] = 0;
02423    }
02424 }
02425 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02426 
02427 #if defined(AST_MISDN_ENHANCEMENTS)
02428 /*!
02429  * \internal
02430  * \brief Fill in facility Address information
02431  *
02432  * \param Address Address structure to fill in.
02433  * \param id Information to put in Address structure.
02434  *
02435  * \return Nothing
02436  */
02437 static void misdn_Address_fill(struct FacAddress *Address, const struct misdn_party_id *id)
02438 {
02439    misdn_PartyNumber_fill(&Address->Party, id);
02440 
02441    /* Subaddresses are not supported yet */
02442    Address->Subaddress.Length = 0;
02443 }
02444 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02445 
02446 #if defined(AST_MISDN_ENHANCEMENTS)
02447 /*!
02448  * \internal
02449  * \brief Fill in facility PresentedNumberUnscreened information
02450  *
02451  * \param presented PresentedNumberUnscreened structure to fill in.
02452  * \param id Information to put in PresentedNumberUnscreened structure.
02453  *
02454  * \return Nothing
02455  */
02456 static void misdn_PresentedNumberUnscreened_fill(struct FacPresentedNumberUnscreened *presented, const struct misdn_party_id *id)
02457 {
02458    presented->Type = misdn_to_PresentedNumberUnscreened_type(id->presentation, id->number[0] ? 1 : 0);
02459    misdn_PartyNumber_fill(&presented->Unscreened, id);
02460 }
02461 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02462 
02463 #if defined(AST_MISDN_ENHANCEMENTS)
02464 /*!
02465  * \internal
02466  * \brief Extract the information from PartyNumber
02467  *
02468  * \param id Where to put extracted PresentedNumberUnscreened information
02469  * \param presented PresentedNumberUnscreened information to extract
02470  *
02471  * \return Nothing
02472  */
02473 static void misdn_PresentedNumberUnscreened_extract(struct misdn_party_id *id, const struct FacPresentedNumberUnscreened *presented)
02474 {
02475    id->presentation = PresentedNumberUnscreened_to_misdn_pres(presented->Type);
02476    id->screening = 0;/* unscreened */
02477    switch (presented->Type) {
02478    case 0:/* presentationAllowedNumber */
02479    case 3:/* presentationRestrictedNumber */
02480       misdn_PartyNumber_extract(id, &presented->Unscreened);
02481       break;
02482    case 1:/* presentationRestricted */
02483    case 2:/* numberNotAvailableDueToInterworking */
02484    default:
02485       /* Number not present (And uninitialized so do not even look at it!) */
02486       id->number_type = NUMTYPE_UNKNOWN;
02487       id->number_plan = NUMPLAN_ISDN;
02488       id->number[0] = 0;
02489       break;
02490    }
02491 }
02492 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02493 
02494 #if defined(AST_MISDN_ENHANCEMENTS)
02495 static const char Level_Spacing[] = "          ";/* Work for up to 10 levels */
02496 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02497 
02498 #if defined(AST_MISDN_ENHANCEMENTS)
02499 static void print_facility_PartyNumber(unsigned Level, const struct FacPartyNumber *Party, const struct misdn_bchannel *bc)
02500 {
02501    if (Party->LengthOfNumber) {
02502       const char *Spacing;
02503 
02504       Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02505       chan_misdn_log(1, bc->port, " -->%s PartyNumber: Type:%d\n",
02506          Spacing, Party->Type);
02507       switch (Party->Type) {
02508       case 0: /* Unknown PartyNumber */
02509          chan_misdn_log(1, bc->port, " -->%s  Unknown: %s\n",
02510             Spacing, Party->Number);
02511          break;
02512       case 1: /* Public PartyNumber */
02513          chan_misdn_log(1, bc->port, " -->%s  Public TON:%d %s\n",
02514             Spacing, Party->TypeOfNumber, Party->Number);
02515          break;
02516       case 2: /* NSAP encoded PartyNumber */
02517          chan_misdn_log(1, bc->port, " -->%s  NSAP: %s\n",
02518             Spacing, Party->Number);
02519          break;
02520       case 3: /* Data PartyNumber (Not used) */
02521          chan_misdn_log(1, bc->port, " -->%s  Data: %s\n",
02522             Spacing, Party->Number);
02523          break;
02524       case 4: /* Telex PartyNumber (Not used) */
02525          chan_misdn_log(1, bc->port, " -->%s  Telex: %s\n",
02526             Spacing, Party->Number);
02527          break;
02528       case 5: /* Private PartyNumber */
02529          chan_misdn_log(1, bc->port, " -->%s  Private TON:%d %s\n",
02530             Spacing, Party->TypeOfNumber, Party->Number);
02531          break;
02532       case 8: /* National Standard PartyNumber (Not used) */
02533          chan_misdn_log(1, bc->port, " -->%s  National: %s\n",
02534             Spacing, Party->Number);
02535          break;
02536       default:
02537          break;
02538       }
02539    }
02540 }
02541 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02542 
02543 #if defined(AST_MISDN_ENHANCEMENTS)
02544 static void print_facility_Subaddress(unsigned Level, const struct FacPartySubaddress *Subaddress, const struct misdn_bchannel *bc)
02545 {
02546    if (Subaddress->Length) {
02547       const char *Spacing;
02548 
02549       Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02550       chan_misdn_log(1, bc->port, " -->%s Subaddress: Type:%d\n",
02551          Spacing, Subaddress->Type);
02552       switch (Subaddress->Type) {
02553       case 0: /* UserSpecified */
02554          if (Subaddress->u.UserSpecified.OddCountPresent) {
02555             chan_misdn_log(1, bc->port, " -->%s  User BCD OddCount:%d NumOctets:%d\n",
02556                Spacing, Subaddress->u.UserSpecified.OddCount, Subaddress->Length);
02557          } else {
02558             chan_misdn_log(1, bc->port, " -->%s  User: %s\n",
02559                Spacing, Subaddress->u.UserSpecified.Information);
02560          }
02561          break;
02562       case 1: /* NSAP */
02563          chan_misdn_log(1, bc->port, " -->%s  NSAP: %s\n",
02564             Spacing, Subaddress->u.Nsap);
02565          break;
02566       default:
02567          break;
02568       }
02569    }
02570 }
02571 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02572 
02573 #if defined(AST_MISDN_ENHANCEMENTS)
02574 static void print_facility_Address(unsigned Level, const struct FacAddress *Address, const struct misdn_bchannel *bc)
02575 {
02576    print_facility_PartyNumber(Level, &Address->Party, bc);
02577    print_facility_Subaddress(Level, &Address->Subaddress, bc);
02578 }
02579 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02580 
02581 #if defined(AST_MISDN_ENHANCEMENTS)
02582 static void print_facility_PresentedNumberUnscreened(unsigned Level, const struct FacPresentedNumberUnscreened *Presented, const struct misdn_bchannel *bc)
02583 {
02584    const char *Spacing;
02585 
02586    Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02587    chan_misdn_log(1, bc->port, " -->%s Unscreened Type:%d\n", Spacing, Presented->Type);
02588    switch (Presented->Type) {
02589    case 0: /* presentationAllowedNumber */
02590       chan_misdn_log(1, bc->port, " -->%s  Allowed:\n", Spacing);
02591       print_facility_PartyNumber(Level + 2, &Presented->Unscreened, bc);
02592       break;
02593    case 1: /* presentationRestricted */
02594       chan_misdn_log(1, bc->port, " -->%s  Restricted\n", Spacing);
02595       break;
02596    case 2: /* numberNotAvailableDueToInterworking */
02597       chan_misdn_log(1, bc->port, " -->%s  Not Available\n", Spacing);
02598       break;
02599    case 3: /* presentationRestrictedNumber */
02600       chan_misdn_log(1, bc->port, " -->%s  Restricted:\n", Spacing);
02601       print_facility_PartyNumber(Level + 2, &Presented->Unscreened, bc);
02602       break;
02603    default:
02604       break;
02605    }
02606 }
02607 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02608 
02609 #if defined(AST_MISDN_ENHANCEMENTS)
02610 static void print_facility_AddressScreened(unsigned Level, const struct FacAddressScreened *Address, const struct misdn_bchannel *bc)
02611 {
02612    const char *Spacing;
02613 
02614    Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02615    chan_misdn_log(1, bc->port, " -->%s ScreeningIndicator:%d\n", Spacing, Address->ScreeningIndicator);
02616    print_facility_PartyNumber(Level, &Address->Party, bc);
02617    print_facility_Subaddress(Level, &Address->Subaddress, bc);
02618 }
02619 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02620 
02621 #if defined(AST_MISDN_ENHANCEMENTS)
02622 static void print_facility_PresentedAddressScreened(unsigned Level, const struct FacPresentedAddressScreened *Presented, const struct misdn_bchannel *bc)
02623 {
02624    const char *Spacing;
02625 
02626    Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02627    chan_misdn_log(1, bc->port, " -->%s Screened Type:%d\n", Spacing, Presented->Type);
02628    switch (Presented->Type) {
02629    case 0: /* presentationAllowedAddress */
02630       chan_misdn_log(1, bc->port, " -->%s  Allowed:\n", Spacing);
02631       print_facility_AddressScreened(Level + 2, &Presented->Address, bc);
02632       break;
02633    case 1: /* presentationRestricted */
02634       chan_misdn_log(1, bc->port, " -->%s  Restricted\n", Spacing);
02635       break;
02636    case 2: /* numberNotAvailableDueToInterworking */
02637       chan_misdn_log(1, bc->port, " -->%s  Not Available\n", Spacing);
02638       break;
02639    case 3: /* presentationRestrictedAddress */
02640       chan_misdn_log(1, bc->port, " -->%s  Restricted:\n", Spacing);
02641       print_facility_AddressScreened(Level + 2, &Presented->Address, bc);
02642       break;
02643    default:
02644       break;
02645    }
02646 }
02647 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02648 
02649 #if defined(AST_MISDN_ENHANCEMENTS)
02650 static void print_facility_Q931_Bc_Hlc_Llc(unsigned Level, const struct Q931_Bc_Hlc_Llc *Q931ie, const struct misdn_bchannel *bc)
02651 {
02652    const char *Spacing;
02653 
02654    Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02655    chan_misdn_log(1, bc->port, " -->%s Q931ie:\n", Spacing);
02656    if (Q931ie->Bc.Length) {
02657       chan_misdn_log(1, bc->port, " -->%s  Bc Len:%d\n", Spacing, Q931ie->Bc.Length);
02658    }
02659    if (Q931ie->Hlc.Length) {
02660       chan_misdn_log(1, bc->port, " -->%s  Hlc Len:%d\n", Spacing, Q931ie->Hlc.Length);
02661    }
02662    if (Q931ie->Llc.Length) {
02663       chan_misdn_log(1, bc->port, " -->%s  Llc Len:%d\n", Spacing, Q931ie->Llc.Length);
02664    }
02665 }
02666 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02667 
02668 #if defined(AST_MISDN_ENHANCEMENTS)
02669 static void print_facility_Q931_Bc_Hlc_Llc_Uu(unsigned Level, const struct Q931_Bc_Hlc_Llc_Uu *Q931ie, const struct misdn_bchannel *bc)
02670 {
02671    const char *Spacing;
02672 
02673    Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02674    chan_misdn_log(1, bc->port, " -->%s Q931ie:\n", Spacing);
02675    if (Q931ie->Bc.Length) {
02676       chan_misdn_log(1, bc->port, " -->%s  Bc Len:%d\n", Spacing, Q931ie->Bc.Length);
02677    }
02678    if (Q931ie->Hlc.Length) {
02679       chan_misdn_log(1, bc->port, " -->%s  Hlc Len:%d\n", Spacing, Q931ie->Hlc.Length);
02680    }
02681    if (Q931ie->Llc.Length) {
02682       chan_misdn_log(1, bc->port, " -->%s  Llc Len:%d\n", Spacing, Q931ie->Llc.Length);
02683    }
02684    if (Q931ie->UserInfo.Length) {
02685       chan_misdn_log(1, bc->port, " -->%s  UserInfo Len:%d\n", Spacing, Q931ie->UserInfo.Length);
02686    }
02687 }
02688 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02689 
02690 #if defined(AST_MISDN_ENHANCEMENTS)
02691 static void print_facility_CallInformation(unsigned Level, const struct FacCallInformation *CallInfo, const struct misdn_bchannel *bc)
02692 {
02693    const char *Spacing;
02694 
02695    Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02696    chan_misdn_log(1, bc->port, " -->%s CCBSReference:%d\n",
02697       Spacing, CallInfo->CCBSReference);
02698    chan_misdn_log(1, bc->port, " -->%s AddressOfB:\n", Spacing);
02699    print_facility_Address(Level + 1, &CallInfo->AddressOfB, bc);
02700    print_facility_Q931_Bc_Hlc_Llc(Level, &CallInfo->Q931ie, bc);
02701    if (CallInfo->SubaddressOfA.Length) {
02702       chan_misdn_log(1, bc->port, " -->%s SubaddressOfA:\n", Spacing);
02703       print_facility_Subaddress(Level + 1, &CallInfo->SubaddressOfA, bc);
02704    }
02705 }
02706 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02707 
02708 #if defined(AST_MISDN_ENHANCEMENTS)
02709 static void print_facility_ServedUserNr(unsigned Level, const struct FacPartyNumber *Party, const struct misdn_bchannel *bc)
02710 {
02711    const char *Spacing;
02712 
02713    Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02714    if (Party->LengthOfNumber) {
02715       print_facility_PartyNumber(Level, Party, bc);
02716    } else {
02717       chan_misdn_log(1, bc->port, " -->%s All Numbers\n", Spacing);
02718    }
02719 }
02720 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02721 
02722 #if defined(AST_MISDN_ENHANCEMENTS)
02723 static void print_facility_IntResult(unsigned Level, const struct FacForwardingRecord *ForwardingRecord, const struct misdn_bchannel *bc)
02724 {
02725    const char *Spacing;
02726 
02727    Spacing = &Level_Spacing[sizeof(Level_Spacing) - 1 - Level];
02728    chan_misdn_log(1, bc->port, " -->%s Procedure:%d BasicService:%d\n",
02729       Spacing,
02730       ForwardingRecord->Procedure,
02731       ForwardingRecord->BasicService);
02732    chan_misdn_log(1, bc->port, " -->%s ForwardedTo:\n", Spacing);
02733    print_facility_Address(Level + 1, &ForwardingRecord->ForwardedTo, bc);
02734    chan_misdn_log(1, bc->port, " -->%s ServedUserNr:\n", Spacing);
02735    print_facility_ServedUserNr(Level + 1, &ForwardingRecord->ServedUser, bc);
02736 }
02737 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02738 
02739 static void print_facility(const struct FacParm *fac, const const struct misdn_bchannel *bc)
02740 {
02741 #if defined(AST_MISDN_ENHANCEMENTS)
02742    unsigned Index;
02743 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
02744 
02745    switch (fac->Function) {
02746 #if defined(AST_MISDN_ENHANCEMENTS)
02747    case Fac_ActivationDiversion:
02748       chan_misdn_log(1, bc->port, " --> ActivationDiversion: InvokeID:%d\n",
02749          fac->u.ActivationDiversion.InvokeID);
02750       switch (fac->u.ActivationDiversion.ComponentType) {
02751       case FacComponent_Invoke:
02752          chan_misdn_log(1, bc->port, " -->  Invoke: Procedure:%d BasicService:%d\n",
02753             fac->u.ActivationDiversion.Component.Invoke.Procedure,
02754             fac->u.ActivationDiversion.Component.Invoke.BasicService);
02755          chan_misdn_log(1, bc->port, " -->   ForwardedTo:\n");
02756          print_facility_Address(3, &fac->u.ActivationDiversion.Component.Invoke.ForwardedTo, bc);
02757          chan_misdn_log(1, bc->port, " -->   ServedUserNr:\n");
02758          print_facility_ServedUserNr(3, &fac->u.ActivationDiversion.Component.Invoke.ServedUser, bc);
02759          break;
02760       case FacComponent_Result:
02761          chan_misdn_log(1, bc->port, " -->  Result\n");
02762          break;
02763       default:
02764          break;
02765       }
02766       break;
02767    case Fac_DeactivationDiversion:
02768       chan_misdn_log(1, bc->port, " --> DeactivationDiversion: InvokeID:%d\n",
02769          fac->u.DeactivationDiversion.InvokeID);
02770       switch (fac->u.DeactivationDiversion.ComponentType) {
02771       case FacComponent_Invoke:
02772          chan_misdn_log(1, bc->port, " -->  Invoke: Procedure:%d BasicService:%d\n",
02773             fac->u.DeactivationDiversion.Component.Invoke.Procedure,
02774             fac->u.DeactivationDiversion.Component.Invoke.BasicService);
02775          chan_misdn_log(1, bc->port, " -->   ServedUserNr:\n");
02776          print_facility_ServedUserNr(3, &fac->u.DeactivationDiversion.Component.Invoke.ServedUser, bc);
02777          break;
02778       case FacComponent_Result:
02779          chan_misdn_log(1, bc->port, " -->  Result\n");
02780          break;
02781       default:
02782          break;
02783       }
02784       break;
02785    case Fac_ActivationStatusNotificationDiv:
02786       chan_misdn_log(1, bc->port, " --> ActivationStatusNotificationDiv: InvokeID:%d Procedure:%d BasicService:%d\n",
02787          fac->u.ActivationStatusNotificationDiv.InvokeID,
02788          fac->u.ActivationStatusNotificationDiv.Procedure,
02789          fac->u.ActivationStatusNotificationDiv.BasicService);
02790       chan_misdn_log(1, bc->port, " -->  ForwardedTo:\n");
02791       print_facility_Address(2, &fac->u.ActivationStatusNotificationDiv.ForwardedTo, bc);
02792       chan_misdn_log(1, bc->port, " -->  ServedUserNr:\n");
02793       print_facility_ServedUserNr(2, &fac->u.ActivationStatusNotificationDiv.ServedUser, bc);
02794       break;
02795    case Fac_DeactivationStatusNotificationDiv:
02796       chan_misdn_log(1, bc->port, " --> DeactivationStatusNotificationDiv: InvokeID:%d Procedure:%d BasicService:%d\n",
02797          fac->u.DeactivationStatusNotificationDiv.InvokeID,
02798          fac->u.DeactivationStatusNotificationDiv.Procedure,
02799          fac->u.DeactivationStatusNotificationDiv.BasicService);
02800       chan_misdn_log(1, bc->port, " -->  ServedUserNr:\n");
02801       print_facility_ServedUserNr(2, &fac->u.DeactivationStatusNotificationDiv.ServedUser, bc);
02802       break;
02803    case Fac_InterrogationDiversion:
02804       chan_misdn_log(1, bc->port, " --> InterrogationDiversion: InvokeID:%d\n",
02805          fac->u.InterrogationDiversion.InvokeID);
02806       switch (fac->u.InterrogationDiversion.ComponentType) {
02807       case FacComponent_Invoke:
02808          chan_misdn_log(1, bc->port, " -->  Invoke: Procedure:%d BasicService:%d\n",
02809             fac->u.InterrogationDiversion.Component.Invoke.Procedure,
02810             fac->u.InterrogationDiversion.Component.Invoke.BasicService);
02811          chan_misdn_log(1, bc->port, " -->   ServedUserNr:\n");
02812          print_facility_ServedUserNr(3, &fac->u.InterrogationDiversion.Component.Invoke.ServedUser, bc);
02813          break;
02814       case FacComponent_Result:
02815          chan_misdn_log(1, bc->port, " -->  Result:\n");
02816          if (fac->u.InterrogationDiversion.Component.Result.NumRecords) {
02817             for (Index = 0; Index < fac->u.InterrogationDiversion.Component.Result.NumRecords; ++Index) {
02818                chan_misdn_log(1, bc->port, " -->   IntResult[%d]:\n", Index);
02819                print_facility_IntResult(3, &fac->u.InterrogationDiversion.Component.Result.List[Index], bc);
02820             }
02821          }
02822          break;
02823       default:
02824          break;
02825       }
02826       break;
02827    case Fac_DiversionInformation:
02828       chan_misdn_log(1, bc->port, " --> DiversionInformation: InvokeID:%d Reason:%d BasicService:%d\n",
02829          fac->u.DiversionInformation.InvokeID,
02830          fac->u.DiversionInformation.DiversionReason,
02831          fac->u.DiversionInformation.BasicService);
02832       if (fac->u.DiversionInformation.ServedUserSubaddress.Length) {
02833          chan_misdn_log(1, bc->port, " -->  ServedUserSubaddress:\n");
02834          print_facility_Subaddress(2, &fac->u.DiversionInformation.ServedUserSubaddress, bc);
02835       }
02836       if (fac->u.DiversionInformation.CallingAddressPresent) {
02837          chan_misdn_log(1, bc->port, " -->  CallingAddress:\n");
02838          print_facility_PresentedAddressScreened(2, &fac->u.DiversionInformation.CallingAddress, bc);
02839       }
02840       if (fac->u.DiversionInformation.OriginalCalledPresent) {
02841          chan_misdn_log(1, bc->port, " -->  OriginalCalledNr:\n");
02842          print_facility_PresentedNumberUnscreened(2, &fac->u.DiversionInformation.OriginalCalled, bc);
02843       }
02844       if (fac->u.DiversionInformation.LastDivertingPresent) {
02845          chan_misdn_log(1, bc->port, " -->  LastDivertingNr:\n");
02846          print_facility_PresentedNumberUnscreened(2, &fac->u.DiversionInformation.LastDiverting, bc);
02847       }
02848       if (fac->u.DiversionInformation.LastDivertingReasonPresent) {
02849          chan_misdn_log(1, bc->port, " -->  LastDivertingReason:%d\n", fac->u.DiversionInformation.LastDivertingReason);
02850       }
02851       if (fac->u.DiversionInformation.UserInfo.Length) {
02852          chan_misdn_log(1, bc->port, " -->  UserInfo Length:%d\n", fac->u.DiversionInformation.UserInfo.Length);
02853       }
02854       break;
02855    case Fac_CallDeflection:
02856       chan_misdn_log(1, bc->port, " --> CallDeflection: InvokeID:%d\n",
02857          fac->u.CallDeflection.InvokeID);
02858       switch (fac->u.CallDeflection.ComponentType) {
02859       case FacComponent_Invoke:
02860          chan_misdn_log(1, bc->port, " -->  Invoke:\n");
02861          if (fac->u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUserPresent) {
02862             chan_misdn_log(1, bc->port, " -->   PresentationAllowed:%d\n",
02863                fac->u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUser);
02864          }
02865          chan_misdn_log(1, bc->port, " -->   DeflectionAddress:\n");
02866          print_facility_Address(3, &fac->u.CallDeflection.Component.Invoke.Deflection, bc);
02867          break;
02868       case FacComponent_Result:
02869          chan_misdn_log(1, bc->port, " -->  Result\n");
02870          break;
02871       default:
02872          break;
02873       }
02874       break;
02875    case Fac_CallRerouteing:
02876       chan_misdn_log(1, bc->port, " --> CallRerouteing: InvokeID:%d\n",
02877          fac->u.CallRerouteing.InvokeID);
02878       switch (fac->u.CallRerouteing.ComponentType) {
02879       case FacComponent_Invoke:
02880          chan_misdn_log(1, bc->port, " -->  Invoke: Reason:%d Counter:%d\n",
02881             fac->u.CallRerouteing.Component.Invoke.ReroutingReason,
02882             fac->u.CallRerouteing.Component.Invoke.ReroutingCounter);
02883          chan_misdn_log(1, bc->port, " -->   CalledAddress:\n");
02884          print_facility_Address(3, &fac->u.CallRerouteing.Component.Invoke.CalledAddress, bc);
02885          print_facility_Q931_Bc_Hlc_Llc_Uu(2, &fac->u.CallRerouteing.Component.Invoke.Q931ie, bc);
02886          chan_misdn_log(1, bc->port, " -->   LastReroutingNr:\n");
02887          print_facility_PresentedNumberUnscreened(3, &fac->u.CallRerouteing.Component.Invoke.LastRerouting, bc);
02888          chan_misdn_log(1, bc->port, " -->   SubscriptionOption:%d\n",
02889             fac->u.CallRerouteing.Component.Invoke.SubscriptionOption);
02890          if (fac->u.CallRerouteing.Component.Invoke.CallingPartySubaddress.Length) {
02891             chan_misdn_log(1, bc->port, " -->   CallingParty:\n");
02892             print_facility_Subaddress(3, &fac->u.CallRerouteing.Component.Invoke.CallingPartySubaddress, bc);
02893          }
02894          break;
02895       case FacComponent_Result:
02896          chan_misdn_log(1, bc->port, " -->  Result\n");
02897          break;
02898       default:
02899          break;
02900       }
02901       break;
02902    case Fac_InterrogateServedUserNumbers:
02903       chan_misdn_log(1, bc->port, " --> InterrogateServedUserNumbers: InvokeID:%d\n",
02904          fac->u.InterrogateServedUserNumbers.InvokeID);
02905       switch (fac->u.InterrogateServedUserNumbers.ComponentType) {
02906       case FacComponent_Invoke:
02907          chan_misdn_log(1, bc->port, " -->  Invoke\n");
02908          break;
02909       case FacComponent_Result:
02910          chan_misdn_log(1, bc->port, " -->  Result:\n");
02911          if (fac->u.InterrogateServedUserNumbers.Component.Result.NumRecords) {
02912             for (Index = 0; Index < fac->u.InterrogateServedUserNumbers.Component.Result.NumRecords; ++Index) {
02913                chan_misdn_log(1, bc->port, " -->   ServedUserNr[%d]:\n", Index);
02914                print_facility_PartyNumber(3, &fac->u.InterrogateServedUserNumbers.Component.Result.List[Index], bc);
02915             }
02916          }
02917          break;
02918       default:
02919          break;
02920       }
02921       break;
02922    case Fac_DivertingLegInformation1:
02923       chan_misdn_log(1, bc->port, " --> DivertingLegInformation1: InvokeID:%d Reason:%d SubscriptionOption:%d\n",
02924          fac->u.DivertingLegInformation1.InvokeID,
02925          fac->u.DivertingLegInformation1.DiversionReason,
02926          fac->u.DivertingLegInformation1.SubscriptionOption);
02927       if (fac->u.DivertingLegInformation1.DivertedToPresent) {
02928          chan_misdn_log(1, bc->port, " -->  DivertedToNr:\n");
02929          print_facility_PresentedNumberUnscreened(2, &fac->u.DivertingLegInformation1.DivertedTo, bc);
02930       }
02931       break;
02932    case Fac_DivertingLegInformation2:
02933       chan_misdn_log(1, bc->port, " --> DivertingLegInformation2: InvokeID:%d Reason:%d Count:%d\n",
02934          fac->u.DivertingLegInformation2.InvokeID,
02935          fac->u.DivertingLegInformation2.DiversionReason,
02936          fac->u.DivertingLegInformation2.DiversionCounter);
02937       if (fac->u.DivertingLegInformation2.DivertingPresent) {
02938          chan_misdn_log(1, bc->port, " -->  DivertingNr:\n");
02939          print_facility_PresentedNumberUnscreened(2, &fac->u.DivertingLegInformation2.Diverting, bc);
02940       }
02941       if (fac->u.DivertingLegInformation2.OriginalCalledPresent) {
02942          chan_misdn_log(1, bc->port, " -->  OriginalCalledNr:\n");
02943          print_facility_PresentedNumberUnscreened(2, &fac->u.DivertingLegInformation2.OriginalCalled, bc);
02944       }
02945       break;
02946    case Fac_DivertingLegInformation3:
02947       chan_misdn_log(1, bc->port, " --> DivertingLegInformation3: InvokeID:%d PresentationAllowed:%d\n",
02948          fac->u.DivertingLegInformation3.InvokeID,
02949          fac->u.DivertingLegInformation3.PresentationAllowedIndicator);
02950       break;
02951 
02952 #else /* !defined(AST_MISDN_ENHANCEMENTS) */
02953 
02954    case Fac_CD:
02955       chan_misdn_log(1, bc->port, " --> calldeflect to: %s, presentable: %s\n", fac->u.CDeflection.DeflectedToNumber,
02956          fac->u.CDeflection.PresentationAllowed ? "yes" : "no");
02957       break;
02958 #endif   /* !defined(AST_MISDN_ENHANCEMENTS) */
02959    case Fac_AOCDCurrency:
02960       if (fac->u.AOCDcur.chargeNotAvailable) {
02961          chan_misdn_log(1, bc->port, " --> AOCD currency: charge not available\n");
02962       } else if (fac->u.AOCDcur.freeOfCharge) {
02963          chan_misdn_log(1, bc->port, " --> AOCD currency: free of charge\n");
02964       } else if (fac->u.AOCDchu.billingId >= 0) {
02965          chan_misdn_log(1, bc->port, " --> AOCD currency: currency:%s amount:%d multiplier:%d typeOfChargingInfo:%s billingId:%d\n",
02966             fac->u.AOCDcur.currency, fac->u.AOCDcur.currencyAmount, fac->u.AOCDcur.multiplier,
02967             (fac->u.AOCDcur.typeOfChargingInfo == 0) ? "subTotal" : "total", fac->u.AOCDcur.billingId);
02968       } else {
02969          chan_misdn_log(1, bc->port, " --> AOCD currency: currency:%s amount:%d multiplier:%d typeOfChargingInfo:%s\n",
02970             fac->u.AOCDcur.currency, fac->u.AOCDcur.currencyAmount, fac->u.AOCDcur.multiplier,
02971             (fac->u.AOCDcur.typeOfChargingInfo == 0) ? "subTotal" : "total");
02972       }
02973       break;
02974    case Fac_AOCDChargingUnit:
02975       if (fac->u.AOCDchu.chargeNotAvailable) {
02976          chan_misdn_log(1, bc->port, " --> AOCD charging unit: charge not available\n");
02977       } else if (fac->u.AOCDchu.freeOfCharge) {
02978          chan_misdn_log(1, bc->port, " --> AOCD charging unit: free of charge\n");
02979       } else if (fac->u.AOCDchu.billingId >= 0) {
02980          chan_misdn_log(1, bc->port, " --> AOCD charging unit: recordedUnits:%d typeOfChargingInfo:%s billingId:%d\n",
02981             fac->u.AOCDchu.recordedUnits, (fac->u.AOCDchu.typeOfChargingInfo == 0) ? "subTotal" : "total", fac->u.AOCDchu.billingId);
02982       } else {
02983          chan_misdn_log(1, bc->port, " --> AOCD charging unit: recordedUnits:%d typeOfChargingInfo:%s\n",
02984             fac->u.AOCDchu.recordedUnits, (fac->u.AOCDchu.typeOfChargingInfo == 0) ? "subTotal" : "total");
02985       }
02986       break;
02987 #if defined(AST_MISDN_ENHANCEMENTS)
02988    case Fac_ERROR:
02989       chan_misdn_log(1, bc->port, " --> ERROR: InvokeID:%d, Code:0x%02x\n",
02990          fac->u.ERROR.invokeId, fac->u.ERROR.errorValue);
02991       break;
02992    case Fac_RESULT:
02993       chan_misdn_log(1, bc->port, " --> RESULT: InvokeID:%d\n",
02994          fac->u.RESULT.InvokeID);
02995       break;
02996    case Fac_REJECT:
02997       if (fac->u.REJECT.InvokeIDPresent) {
02998          chan_misdn_log(1, bc->port, " --> REJECT: InvokeID:%d, Code:0x%02x\n",
02999             fac->u.REJECT.InvokeID, fac->u.REJECT.Code);
03000       } else {
03001          chan_misdn_log(1, bc->port, " --> REJECT: Code:0x%02x\n",
03002             fac->u.REJECT.Code);
03003       }
03004       break;
03005    case Fac_EctExecute:
03006       chan_misdn_log(1, bc->port, " --> EctExecute: InvokeID:%d\n",
03007          fac->u.EctExecute.InvokeID);
03008       break;
03009    case Fac_ExplicitEctExecute:
03010       chan_misdn_log(1, bc->port, " --> ExplicitEctExecute: InvokeID:%d LinkID:%d\n",
03011          fac->u.ExplicitEctExecute.InvokeID,
03012          fac->u.ExplicitEctExecute.LinkID);
03013       break;
03014    case Fac_RequestSubaddress:
03015       chan_misdn_log(1, bc->port, " --> RequestSubaddress: InvokeID:%d\n",
03016          fac->u.RequestSubaddress.InvokeID);
03017       break;
03018    case Fac_SubaddressTransfer:
03019       chan_misdn_log(1, bc->port, " --> SubaddressTransfer: InvokeID:%d\n",
03020          fac->u.SubaddressTransfer.InvokeID);
03021       print_facility_Subaddress(1, &fac->u.SubaddressTransfer.Subaddress, bc);
03022       break;
03023    case Fac_EctLinkIdRequest:
03024       chan_misdn_log(1, bc->port, " --> EctLinkIdRequest: InvokeID:%d\n",
03025          fac->u.EctLinkIdRequest.InvokeID);
03026       switch (fac->u.EctLinkIdRequest.ComponentType) {
03027       case FacComponent_Invoke:
03028          chan_misdn_log(1, bc->port, " -->  Invoke\n");
03029          break;
03030       case FacComponent_Result:
03031          chan_misdn_log(1, bc->port, " -->  Result: LinkID:%d\n",
03032             fac->u.EctLinkIdRequest.Component.Result.LinkID);
03033          break;
03034       default:
03035          break;
03036       }
03037       break;
03038    case Fac_EctInform:
03039       chan_misdn_log(1, bc->port, " --> EctInform: InvokeID:%d Status:%d\n",
03040          fac->u.EctInform.InvokeID,
03041          fac->u.EctInform.Status);
03042       if (fac->u.EctInform.RedirectionPresent) {
03043          chan_misdn_log(1, bc->port, " -->  Redirection Number\n");
03044          print_facility_PresentedNumberUnscreened(2, &fac->u.EctInform.Redirection, bc);
03045       }
03046       break;
03047    case Fac_EctLoopTest:
03048       chan_misdn_log(1, bc->port, " --> EctLoopTest: InvokeID:%d\n",
03049          fac->u.EctLoopTest.InvokeID);
03050       switch (fac->u.EctLoopTest.ComponentType) {
03051       case FacComponent_Invoke:
03052          chan_misdn_log(1, bc->port, " -->  Invoke: CallTransferID:%d\n",
03053             fac->u.EctLoopTest.Component.Invoke.CallTransferID);
03054          break;
03055       case FacComponent_Result:
03056          chan_misdn_log(1, bc->port, " -->  Result: LoopResult:%d\n",
03057             fac->u.EctLoopTest.Component.Result.LoopResult);
03058          break;
03059       default:
03060          break;
03061       }
03062       break;
03063    case Fac_StatusRequest:
03064       chan_misdn_log(1, bc->port, " --> StatusRequest: InvokeID:%d\n",
03065          fac->u.StatusRequest.InvokeID);
03066       switch (fac->u.StatusRequest.ComponentType) {
03067       case FacComponent_Invoke:
03068          chan_misdn_log(1, bc->port, " -->  Invoke: Compatibility:%d\n",
03069             fac->u.StatusRequest.Component.Invoke.CompatibilityMode);
03070          break;
03071       case FacComponent_Result:
03072          chan_misdn_log(1, bc->port, " -->  Result: Status:%d\n",
03073             fac->u.StatusRequest.Component.Result.Status);
03074          break;
03075       default:
03076          break;
03077       }
03078       break;
03079    case Fac_CallInfoRetain:
03080       chan_misdn_log(1, bc->port, " --> CallInfoRetain: InvokeID:%d, LinkageID:%d\n",
03081          fac->u.CallInfoRetain.InvokeID, fac->u.CallInfoRetain.CallLinkageID);
03082       break;
03083    case Fac_CCBSDeactivate:
03084       chan_misdn_log(1, bc->port, " --> CCBSDeactivate: InvokeID:%d\n",
03085          fac->u.CCBSDeactivate.InvokeID);
03086       switch (fac->u.CCBSDeactivate.ComponentType) {
03087       case FacComponent_Invoke:
03088          chan_misdn_log(1, bc->port, " -->  Invoke: CCBSReference:%d\n",
03089             fac->u.CCBSDeactivate.Component.Invoke.CCBSReference);
03090          break;
03091       case FacComponent_Result:
03092          chan_misdn_log(1, bc->port, " -->  Result\n");
03093          break;
03094       default:
03095          break;
03096       }
03097       break;
03098    case Fac_CCBSErase:
03099       chan_misdn_log(1, bc->port, " --> CCBSErase: InvokeID:%d, CCBSReference:%d RecallMode:%d, Reason:%d\n",
03100          fac->u.CCBSErase.InvokeID, fac->u.CCBSErase.CCBSReference,
03101          fac->u.CCBSErase.RecallMode, fac->u.CCBSErase.Reason);
03102       chan_misdn_log(1, bc->port, " -->  AddressOfB\n");
03103       print_facility_Address(2, &fac->u.CCBSErase.AddressOfB, bc);
03104       print_facility_Q931_Bc_Hlc_Llc(1, &fac->u.CCBSErase.Q931ie, bc);
03105       break;
03106    case Fac_CCBSRemoteUserFree:
03107       chan_misdn_log(1, bc->port, " --> CCBSRemoteUserFree: InvokeID:%d, CCBSReference:%d RecallMode:%d\n",
03108          fac->u.CCBSRemoteUserFree.InvokeID, fac->u.CCBSRemoteUserFree.CCBSReference,
03109          fac->u.CCBSRemoteUserFree.RecallMode);
03110       chan_misdn_log(1, bc->port, " -->  AddressOfB\n");
03111       print_facility_Address(2, &fac->u.CCBSRemoteUserFree.AddressOfB, bc);
03112       print_facility_Q931_Bc_Hlc_Llc(1, &fac->u.CCBSRemoteUserFree.Q931ie, bc);
03113       break;
03114    case Fac_CCBSCall:
03115       chan_misdn_log(1, bc->port, " --> CCBSCall: InvokeID:%d, CCBSReference:%d\n",
03116          fac->u.CCBSCall.InvokeID, fac->u.CCBSCall.CCBSReference);
03117       break;
03118    case Fac_CCBSStatusRequest:
03119       chan_misdn_log(1, bc->port, " --> CCBSStatusRequest: InvokeID:%d\n",
03120          fac->u.CCBSStatusRequest.InvokeID);
03121       switch (fac->u.CCBSStatusRequest.ComponentType) {
03122       case FacComponent_Invoke:
03123          chan_misdn_log(1, bc->port, " -->  Invoke: CCBSReference:%d RecallMode:%d\n",
03124             fac->u.CCBSStatusRequest.Component.Invoke.CCBSReference,
03125             fac->u.CCBSStatusRequest.Component.Invoke.RecallMode);
03126          print_facility_Q931_Bc_Hlc_Llc(2, &fac->u.CCBSStatusRequest.Component.Invoke.Q931ie, bc);
03127          break;
03128       case FacComponent_Result:
03129          chan_misdn_log(1, bc->port, " -->  Result: Free:%d\n",
03130             fac->u.CCBSStatusRequest.Component.Result.Free);
03131          break;
03132       default:
03133          break;
03134       }
03135       break;
03136    case Fac_CCBSBFree:
03137       chan_misdn_log(1, bc->port, " --> CCBSBFree: InvokeID:%d, CCBSReference:%d RecallMode:%d\n",
03138          fac->u.CCBSBFree.InvokeID, fac->u.CCBSBFree.CCBSReference,
03139          fac->u.CCBSBFree.RecallMode);
03140       chan_misdn_log(1, bc->port, " -->  AddressOfB\n");
03141       print_facility_Address(2, &fac->u.CCBSBFree.AddressOfB, bc);
03142       print_facility_Q931_Bc_Hlc_Llc(1, &fac->u.CCBSBFree.Q931ie, bc);
03143       break;
03144    case Fac_EraseCallLinkageID:
03145       chan_misdn_log(1, bc->port, " --> EraseCallLinkageID: InvokeID:%d, LinkageID:%d\n",
03146          fac->u.EraseCallLinkageID.InvokeID, fac->u.EraseCallLinkageID.CallLinkageID);
03147       break;
03148    case Fac_CCBSStopAlerting:
03149       chan_misdn_log(1, bc->port, " --> CCBSStopAlerting: InvokeID:%d, CCBSReference:%d\n",
03150          fac->u.CCBSStopAlerting.InvokeID, fac->u.CCBSStopAlerting.CCBSReference);
03151       break;
03152    case Fac_CCBSRequest:
03153       chan_misdn_log(1, bc->port, " --> CCBSRequest: InvokeID:%d\n",
03154          fac->u.CCBSRequest.InvokeID);
03155       switch (fac->u.CCBSRequest.ComponentType) {
03156       case FacComponent_Invoke:
03157          chan_misdn_log(1, bc->port, " -->  Invoke: LinkageID:%d\n",
03158             fac->u.CCBSRequest.Component.Invoke.CallLinkageID);
03159          break;
03160       case FacComponent_Result:
03161          chan_misdn_log(1, bc->port, " -->  Result: CCBSReference:%d RecallMode:%d\n",
03162             fac->u.CCBSRequest.Component.Result.CCBSReference,
03163             fac->u.CCBSRequest.Component.Result.RecallMode);
03164          break;
03165       default:
03166          break;
03167       }
03168       break;
03169    case Fac_CCBSInterrogate:
03170       chan_misdn_log(1, bc->port, " --> CCBSInterrogate: InvokeID:%d\n",
03171          fac->u.CCBSInterrogate.InvokeID);
03172       switch (fac->u.CCBSInterrogate.ComponentType) {
03173       case FacComponent_Invoke:
03174          chan_misdn_log(1, bc->port, " -->  Invoke\n");
03175          if (fac->u.CCBSInterrogate.Component.Invoke.CCBSReferencePresent) {
03176             chan_misdn_log(1, bc->port, " -->   CCBSReference:%d\n",
03177                fac->u.CCBSInterrogate.Component.Invoke.CCBSReference);
03178          }
03179          if (fac->u.CCBSInterrogate.Component.Invoke.AParty.LengthOfNumber) {
03180             chan_misdn_log(1, bc->port, " -->   AParty\n");
03181             print_facility_PartyNumber(3, &fac->u.CCBSInterrogate.Component.Invoke.AParty, bc);
03182          }
03183          break;
03184       case FacComponent_Result:
03185          chan_misdn_log(1, bc->port, " -->  Result: RecallMode:%d\n",
03186             fac->u.CCBSInterrogate.Component.Result.RecallMode);
03187          if (fac->u.CCBSInterrogate.Component.Result.NumRecords) {
03188             for (Index = 0; Index < fac->u.CCBSInterrogate.Component.Result.NumRecords; ++Index) {
03189                chan_misdn_log(1, bc->port, " -->   CallDetails[%d]:\n", Index);
03190                print_facility_CallInformation(3, &fac->u.CCBSInterrogate.Component.Result.CallDetails[Index], bc);
03191             }
03192          }
03193          break;
03194       default:
03195          break;
03196       }
03197       break;
03198    case Fac_CCNRRequest:
03199       chan_misdn_log(1, bc->port, " --> CCNRRequest: InvokeID:%d\n",
03200          fac->u.CCNRRequest.InvokeID);
03201       switch (fac->u.CCNRRequest.ComponentType) {
03202       case FacComponent_Invoke:
03203          chan_misdn_log(1, bc->port, " -->  Invoke: LinkageID:%d\n",
03204             fac->u.CCNRRequest.Component.Invoke.CallLinkageID);
03205          break;
03206       case FacComponent_Result:
03207          chan_misdn_log(1, bc->port, " -->  Result: CCBSReference:%d RecallMode:%d\n",
03208             fac->u.CCNRRequest.Component.Result.CCBSReference,
03209             fac->u.CCNRRequest.Component.Result.RecallMode);
03210          break;
03211       default:
03212          break;
03213       }
03214       break;
03215    case Fac_CCNRInterrogate:
03216       chan_misdn_log(1, bc->port, " --> CCNRInterrogate: InvokeID:%d\n",
03217          fac->u.CCNRInterrogate.InvokeID);
03218       switch (fac->u.CCNRInterrogate.ComponentType) {
03219       case FacComponent_Invoke:
03220          chan_misdn_log(1, bc->port, " -->  Invoke\n");
03221          if (fac->u.CCNRInterrogate.Component.Invoke.CCBSReferencePresent) {
03222             chan_misdn_log(1, bc->port, " -->   CCBSReference:%d\n",
03223                fac->u.CCNRInterrogate.Component.Invoke.CCBSReference);
03224          }
03225          if (fac->u.CCNRInterrogate.Component.Invoke.AParty.LengthOfNumber) {
03226             chan_misdn_log(1, bc->port, " -->   AParty\n");
03227             print_facility_PartyNumber(3, &fac->u.CCNRInterrogate.Component.Invoke.AParty, bc);
03228          }
03229          break;
03230       case FacComponent_Result:
03231          chan_misdn_log(1, bc->port, " -->  Result: RecallMode:%d\n",
03232             fac->u.CCNRInterrogate.Component.Result.RecallMode);
03233          if (fac->u.CCNRInterrogate.Component.Result.NumRecords) {
03234             for (Index = 0; Index < fac->u.CCNRInterrogate.Component.Result.NumRecords; ++Index) {
03235                chan_misdn_log(1, bc->port, " -->   CallDetails[%d]:\n", Index);
03236                print_facility_CallInformation(3, &fac->u.CCNRInterrogate.Component.Result.CallDetails[Index], bc);
03237             }
03238          }
03239          break;
03240       default:
03241          break;
03242       }
03243       break;
03244    case Fac_CCBS_T_Call:
03245       chan_misdn_log(1, bc->port, " --> CCBS_T_Call: InvokeID:%d\n",
03246          fac->u.CCBS_T_Call.InvokeID);
03247       break;
03248    case Fac_CCBS_T_Suspend:
03249       chan_misdn_log(1, bc->port, " --> CCBS_T_Suspend: InvokeID:%d\n",
03250          fac->u.CCBS_T_Suspend.InvokeID);
03251       break;
03252    case Fac_CCBS_T_Resume:
03253       chan_misdn_log(1, bc->port, " --> CCBS_T_Resume: InvokeID:%d\n",
03254          fac->u.CCBS_T_Resume.InvokeID);
03255       break;
03256    case Fac_CCBS_T_RemoteUserFree:
03257       chan_misdn_log(1, bc->port, " --> CCBS_T_RemoteUserFree: InvokeID:%d\n",
03258          fac->u.CCBS_T_RemoteUserFree.InvokeID);
03259       break;
03260    case Fac_CCBS_T_Available:
03261       chan_misdn_log(1, bc->port, " --> CCBS_T_Available: InvokeID:%d\n",
03262          fac->u.CCBS_T_Available.InvokeID);
03263       break;
03264    case Fac_CCBS_T_Request:
03265       chan_misdn_log(1, bc->port, " --> CCBS_T_Request: InvokeID:%d\n",
03266          fac->u.CCBS_T_Request.InvokeID);
03267       switch (fac->u.CCBS_T_Request.ComponentType) {
03268       case FacComponent_Invoke:
03269          chan_misdn_log(1, bc->port, " -->  Invoke\n");
03270          chan_misdn_log(1, bc->port, " -->   DestinationAddress:\n");
03271          print_facility_Address(3, &fac->u.CCBS_T_Request.Component.Invoke.Destination, bc);
03272          print_facility_Q931_Bc_Hlc_Llc(2, &fac->u.CCBS_T_Request.Component.Invoke.Q931ie, bc);
03273          if (fac->u.CCBS_T_Request.Component.Invoke.RetentionSupported) {
03274             chan_misdn_log(1, bc->port, " -->   RetentionSupported:1\n");
03275          }
03276          if (fac->u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicatorPresent) {
03277             chan_misdn_log(1, bc->port, " -->   PresentationAllowed:%d\n",
03278                fac->u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicator);
03279          }
03280          if (fac->u.CCBS_T_Request.Component.Invoke.Originating.Party.LengthOfNumber) {
03281             chan_misdn_log(1, bc->port, " -->   OriginatingAddress:\n");
03282             print_facility_Address(3, &fac->u.CCBS_T_Request.Component.Invoke.Originating, bc);
03283          }
03284          break;
03285       case FacComponent_Result:
03286          chan_misdn_log(1, bc->port, " -->  Result: RetentionSupported:%d\n",
03287             fac->u.CCBS_T_Request.Component.Result.RetentionSupported);
03288          break;
03289       default:
03290          break;
03291       }
03292       break;
03293    case Fac_CCNR_T_Request:
03294       chan_misdn_log(1, bc->port, " --> CCNR_T_Request: InvokeID:%d\n",
03295          fac->u.CCNR_T_Request.InvokeID);
03296       switch (fac->u.CCNR_T_Request.ComponentType) {
03297       case FacComponent_Invoke:
03298          chan_misdn_log(1, bc->port, " -->  Invoke\n");
03299          chan_misdn_log(1, bc->port, " -->   DestinationAddress:\n");
03300          print_facility_Address(3, &fac->u.CCNR_T_Request.Component.Invoke.Destination, bc);
03301          print_facility_Q931_Bc_Hlc_Llc(2, &fac->u.CCNR_T_Request.Component.Invoke.Q931ie, bc);
03302          if (fac->u.CCNR_T_Request.Component.Invoke.RetentionSupported) {
03303             chan_misdn_log(1, bc->port, " -->   RetentionSupported:1\n");
03304          }
03305          if (fac->u.CCNR_T_Request.Component.Invoke.PresentationAllowedIndicatorPresent) {
03306             chan_misdn_log(1, bc->port, " -->   PresentationAllowed:%d\n",
03307                fac->u.CCNR_T_Request.Component.Invoke.PresentationAllowedIndicator);
03308          }
03309          if (fac->u.CCNR_T_Request.Component.Invoke.Originating.Party.LengthOfNumber) {
03310             chan_misdn_log(1, bc->port, " -->   OriginatingAddress:\n");
03311             print_facility_Address(3, &fac->u.CCNR_T_Request.Component.Invoke.Originating, bc);
03312          }
03313          break;
03314       case FacComponent_Result:
03315          chan_misdn_log(1, bc->port, " -->  Result: RetentionSupported:%d\n",
03316             fac->u.CCNR_T_Request.Component.Result.RetentionSupported);
03317          break;
03318       default:
03319          break;
03320       }
03321       break;
03322 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
03323    case Fac_None:
03324       /* No facility so print nothing */
03325       break;
03326    default:
03327       chan_misdn_log(1, bc->port, " --> unknown facility\n");
03328       break;
03329    }
03330 }
03331 
03332 static void print_bearer(struct misdn_bchannel *bc)
03333 {
03334    chan_misdn_log(2, bc->port, " --> Bearer: %s\n", bearer2str(bc->capability));
03335 
03336    switch(bc->law) {
03337    case INFO_CODEC_ALAW:
03338       chan_misdn_log(2, bc->port, " --> Codec: Alaw\n");
03339       break;
03340    case INFO_CODEC_ULAW:
03341       chan_misdn_log(2, bc->port, " --> Codec: Ulaw\n");
03342       break;
03343    }
03344 }
03345 
03346 /*!
03347  * \internal
03348  * \brief Prefix a string to another string in place.
03349  *
03350  * \param str_prefix String to prefix to the main string.
03351  * \param str_main String to get the prefix added to it.
03352  * \param size Buffer size of the main string (Includes null terminator).
03353  *
03354  * \note The str_main buffer size must be greater than one.
03355  *
03356  * \return Nothing
03357  */
03358 static void misdn_prefix_string(const char *str_prefix, char *str_main, size_t size)
03359 {
03360    size_t len_over;
03361    size_t len_total;
03362    size_t len_main;
03363    size_t len_prefix;
03364 
03365    len_prefix = strlen(str_prefix);
03366    if (!len_prefix) {
03367       /* There is no prefix to prepend. */
03368       return;
03369    }
03370    len_main = strlen(str_main);
03371    len_total = len_prefix + len_main;
03372    if (size <= len_total) {
03373       /* We need to truncate since the buffer is too small. */
03374       len_over = len_total + 1 - size;
03375       if (len_over <= len_main) {
03376          len_main -= len_over;
03377       } else {
03378          len_over -= len_main;
03379          len_main = 0;
03380          len_prefix -= len_over;
03381       }
03382    }
03383    if (len_main) {
03384       memmove(str_main + len_prefix, str_main, len_main);
03385    }
03386    memcpy(str_main, str_prefix, len_prefix);
03387    str_main[len_prefix + len_main] = '\0';
03388 }
03389 
03390 /*!
03391  * \internal
03392  * \brief Add a configured prefix to the given number.
03393  *
03394  * \param port Logical port number
03395  * \param number_type Type-of-number passed in.
03396  * \param number Given number string to add prefix
03397  * \param size Buffer size number string occupies.
03398  *
03399  * \return Nothing
03400  */
03401 static void misdn_add_number_prefix(int port, enum mISDN_NUMBER_TYPE number_type, char *number, size_t size)
03402 {
03403    enum misdn_cfg_elements type_prefix;
03404    char num_prefix[MISDN_MAX_NUMBER_LEN];
03405 
03406    /* Get prefix string. */
03407    switch (number_type) {
03408    case NUMTYPE_UNKNOWN:
03409       type_prefix = MISDN_CFG_TON_PREFIX_UNKNOWN;
03410       break;
03411    case NUMTYPE_INTERNATIONAL:
03412       type_prefix = MISDN_CFG_TON_PREFIX_INTERNATIONAL;
03413       break;
03414    case NUMTYPE_NATIONAL:
03415       type_prefix = MISDN_CFG_TON_PREFIX_NATIONAL;
03416       break;
03417    case NUMTYPE_NETWORK_SPECIFIC:
03418       type_prefix = MISDN_CFG_TON_PREFIX_NETWORK_SPECIFIC;
03419       break;
03420    case NUMTYPE_SUBSCRIBER:
03421       type_prefix = MISDN_CFG_TON_PREFIX_SUBSCRIBER;
03422       break;
03423    case NUMTYPE_ABBREVIATED:
03424       type_prefix = MISDN_CFG_TON_PREFIX_ABBREVIATED;
03425       break;
03426    default:
03427       /* Type-of-number does not have a prefix that can be added. */
03428       return;
03429    }
03430    misdn_cfg_get(port, type_prefix, num_prefix, sizeof(num_prefix));
03431 
03432    misdn_prefix_string(num_prefix, number, size);
03433 }
03434 
03435 static void export_aoc_vars(int originator, struct ast_channel *ast, struct misdn_bchannel *bc)
03436 {
03437    char buf[128];
03438 
03439    if (!bc->AOCD_need_export || !ast) {
03440       return;
03441    }
03442 
03443    if (originator == ORG_AST) {
03444       ast = ast_bridged_channel(ast);
03445       if (!ast) {
03446          return;
03447       }
03448    }
03449 
03450    switch (bc->AOCDtype) {
03451    case Fac_AOCDCurrency:
03452       pbx_builtin_setvar_helper(ast, "AOCD_Type", "currency");
03453       if (bc->AOCD.currency.chargeNotAvailable) {
03454          pbx_builtin_setvar_helper(ast, "AOCD_ChargeAvailable", "no");
03455       } else {
03456          pbx_builtin_setvar_helper(ast, "AOCD_ChargeAvailable", "yes");
03457          if (bc->AOCD.currency.freeOfCharge) {
03458             pbx_builtin_setvar_helper(ast, "AOCD_FreeOfCharge", "yes");
03459          } else {
03460             pbx_builtin_setvar_helper(ast, "AOCD_FreeOfCharge", "no");
03461             if (snprintf(buf, sizeof(buf), "%d %s", bc->AOCD.currency.currencyAmount * bc->AOCD.currency.multiplier, bc->AOCD.currency.currency) < sizeof(buf)) {
03462                pbx_builtin_setvar_helper(ast, "AOCD_Amount", buf);
03463                if (bc->AOCD.currency.billingId >= 0 && snprintf(buf, sizeof(buf), "%d", bc->AOCD.currency.billingId) < sizeof(buf)) {
03464                   pbx_builtin_setvar_helper(ast, "AOCD_BillingId", buf);
03465                }
03466             }
03467          }
03468       }
03469       break;
03470    case Fac_AOCDChargingUnit:
03471       pbx_builtin_setvar_helper(ast, "AOCD_Type", "charging_unit");
03472       if (bc->AOCD.chargingUnit.chargeNotAvailable) {
03473          pbx_builtin_setvar_helper(ast, "AOCD_ChargeAvailable", "no");
03474       } else {
03475          pbx_builtin_setvar_helper(ast, "AOCD_ChargeAvailable", "yes");
03476          if (bc->AOCD.chargingUnit.freeOfCharge) {
03477             pbx_builtin_setvar_helper(ast, "AOCD_FreeOfCharge", "yes");
03478          } else {
03479             pbx_builtin_setvar_helper(ast, "AOCD_FreeOfCharge", "no");
03480             if (snprintf(buf, sizeof(buf), "%d", bc->AOCD.chargingUnit.recordedUnits) < sizeof(buf)) {
03481                pbx_builtin_setvar_helper(ast, "AOCD_RecordedUnits", buf);
03482                if (bc->AOCD.chargingUnit.billingId >= 0 && snprintf(buf, sizeof(buf), "%d", bc->AOCD.chargingUnit.billingId) < sizeof(buf)) {
03483                   pbx_builtin_setvar_helper(ast, "AOCD_BillingId", buf);
03484                }
03485             }
03486          }
03487       }
03488       break;
03489    default:
03490       break;
03491    }
03492 
03493    bc->AOCD_need_export = 0;
03494 }
03495 
03496 /*************** Helpers END *************/
03497 
03498 static void sighandler(int sig)
03499 {
03500 }
03501 
03502 static void *misdn_tasks_thread_func(void *data)
03503 {
03504    int wait;
03505    struct sigaction sa;
03506 
03507    sa.sa_handler = sighandler;
03508    sa.sa_flags = SA_NODEFER;
03509    sigemptyset(&sa.sa_mask);
03510    sigaddset(&sa.sa_mask, SIGUSR1);
03511    sigaction(SIGUSR1, &sa, NULL);
03512 
03513    sem_post((sem_t *)data);
03514 
03515    while (1) {
03516       wait = ast_sched_wait(misdn_tasks);
03517       if (wait < 0) {
03518          wait = 8000;
03519       }
03520       if (poll(NULL, 0, wait) < 0) {
03521          chan_misdn_log(4, 0, "Waking up misdn_tasks thread\n");
03522       }
03523       ast_sched_runq(misdn_tasks);
03524    }
03525    return NULL;
03526 }
03527 
03528 static void misdn_tasks_init(void)
03529 {
03530    sem_t blocker;
03531    int i = 5;
03532 
03533    if (sem_init(&blocker, 0, 0)) {
03534       perror("chan_misdn: Failed to initialize semaphore!");
03535       exit(1);
03536    }
03537 
03538    chan_misdn_log(4, 0, "Starting misdn_tasks thread\n");
03539 
03540    misdn_tasks = sched_context_create();
03541    pthread_create(&misdn_tasks_thread, NULL, misdn_tasks_thread_func, &blocker);
03542 
03543    while (sem_wait(&blocker) && --i) {
03544    }
03545    sem_destroy(&blocker);
03546 }
03547 
03548 static void misdn_tasks_destroy(void)
03549 {
03550    if (misdn_tasks) {
03551       chan_misdn_log(4, 0, "Killing misdn_tasks thread\n");
03552       if (pthread_cancel(misdn_tasks_thread) == 0) {
03553          cb_log(4, 0, "Joining misdn_tasks thread\n");
03554          pthread_join(misdn_tasks_thread, NULL);
03555       }
03556       sched_context_destroy(misdn_tasks);
03557    }
03558 }
03559 
03560 static inline void misdn_tasks_wakeup(void)
03561 {
03562    pthread_kill(misdn_tasks_thread, SIGUSR1);
03563 }
03564 
03565 static inline int _misdn_tasks_add_variable(int timeout, ast_sched_cb callback, const void *data, int variable)
03566 {
03567    int task_id;
03568 
03569    if (!misdn_tasks) {
03570       misdn_tasks_init();
03571    }
03572    task_id = ast_sched_add_variable(misdn_tasks, timeout, callback, data, variable);
03573    misdn_tasks_wakeup();
03574 
03575    return task_id;
03576 }
03577 
03578 static int misdn_tasks_add(int timeout, ast_sched_cb callback, const void *data)
03579 {
03580    return _misdn_tasks_add_variable(timeout, callback, data, 0);
03581 }
03582 
03583 static int misdn_tasks_add_variable(int timeout, ast_sched_cb callback, const void *data)
03584 {
03585    return _misdn_tasks_add_variable(timeout, callback, data, 1);
03586 }
03587 
03588 static void misdn_tasks_remove(int task_id)
03589 {
03590    AST_SCHED_DEL(misdn_tasks, task_id);
03591 }
03592 
03593 static int misdn_l1_task(const void *vdata)
03594 {
03595    const int *data = vdata;
03596 
03597    misdn_lib_isdn_l1watcher(*data);
03598    chan_misdn_log(5, *data, "L1watcher timeout\n");
03599    return 1;
03600 }
03601 
03602 static int misdn_overlap_dial_task(const void *data)
03603 {
03604    struct timeval tv_end, tv_now;
03605    int diff;
03606    struct chan_list *ch = (struct chan_list *) data;
03607    char *dad;
03608 
03609    chan_misdn_log(4, ch->bc->port, "overlap dial task, chan_state: %d\n", ch->state);
03610 
03611    if (ch->state != MISDN_WAITING4DIGS) {
03612       ch->overlap_dial_task = -1;
03613       return 0;
03614    }
03615 
03616    ast_mutex_lock(&ch->overlap_tv_lock);
03617    tv_end = ch->overlap_tv;
03618    ast_mutex_unlock(&ch->overlap_tv_lock);
03619 
03620    tv_end.tv_sec += ch->overlap_dial;
03621    tv_now = ast_tvnow();
03622 
03623    diff = ast_tvdiff_ms(tv_end, tv_now);
03624    if (100 < diff) {
03625       return diff;
03626    }
03627 
03628    /* if we are 100ms near the timeout, we are satisfied.. */
03629    stop_indicate(ch);
03630 
03631    if (ast_strlen_zero(ch->bc->dialed.number)) {
03632       dad = "s";
03633       strcpy(ch->ast->exten, dad);
03634    } else {
03635       dad = ch->bc->dialed.number;
03636    }
03637 
03638    if (ast_exists_extension(ch->ast, ch->context, dad, 1, ch->bc->caller.number)) {
03639       ch->state = MISDN_DIALING;
03640       if (pbx_start_chan(ch) < 0) {
03641          chan_misdn_log(-1, ch->bc->port, "ast_pbx_start returned < 0 in misdn_overlap_dial_task\n");
03642          goto misdn_overlap_dial_task_disconnect;
03643       }
03644    } else {
03645 misdn_overlap_dial_task_disconnect:
03646       hanguptone_indicate(ch);
03647       ch->bc->out_cause = AST_CAUSE_UNALLOCATED;
03648       ch->state = MISDN_CLEANING;
03649       misdn_lib_send_event(ch->bc, EVENT_DISCONNECT);
03650    }
03651    ch->overlap_dial_task = -1;
03652    return 0;
03653 }
03654 
03655 static void send_digit_to_chan(struct chan_list *cl, char digit)
03656 {
03657    static const char * const dtmf_tones[] = {
03658 /* *INDENT-OFF* */
03659       "!941+1336/100,!0/100", /* 0 */
03660       "!697+1209/100,!0/100", /* 1 */
03661       "!697+1336/100,!0/100", /* 2 */
03662       "!697+1477/100,!0/100", /* 3 */
03663       "!770+1209/100,!0/100", /* 4 */
03664       "!770+1336/100,!0/100", /* 5 */
03665       "!770+1477/100,!0/100", /* 6 */
03666       "!852+1209/100,!0/100", /* 7 */
03667       "!852+1336/100,!0/100", /* 8 */
03668       "!852+1477/100,!0/100", /* 9 */
03669       "!697+1633/100,!0/100", /* A */
03670       "!770+1633/100,!0/100", /* B */
03671       "!852+1633/100,!0/100", /* C */
03672       "!941+1633/100,!0/100", /* D */
03673       "!941+1209/100,!0/100", /* * */
03674       "!941+1477/100,!0/100", /* # */
03675 /* *INDENT-ON* */
03676    };
03677    struct ast_channel *chan = cl->ast;
03678 
03679    if (digit >= '0' && digit <='9') {
03680       ast_playtones_start(chan, 0, dtmf_tones[digit - '0'], 0);
03681    } else if (digit >= 'A' && digit <= 'D') {
03682       ast_playtones_start(chan, 0, dtmf_tones[digit - 'A' + 10], 0);
03683    } else if (digit == '*') {
03684       ast_playtones_start(chan, 0, dtmf_tones[14], 0);
03685    } else if (digit == '#') {
03686       ast_playtones_start(chan, 0, dtmf_tones[15], 0);
03687    } else {
03688       /* not handled */
03689       ast_debug(1, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
03690    }
03691 }
03692 
03693 /*** CLI HANDLING ***/
03694 static char *handle_cli_misdn_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03695 {
03696    int level;
03697 
03698    switch (cmd) {
03699    case CLI_INIT:
03700       e->command = "misdn set debug [on|off]";
03701       e->usage =
03702          "Usage: misdn set debug {on|off|<level>} [only] | [port <port> [only]]\n"
03703          "       Set the debug level of the mISDN channel.\n";
03704       return NULL;
03705    case CLI_GENERATE:
03706       return complete_debug_port(a);
03707    }
03708 
03709    if (a->argc < 4 || a->argc > 7) {
03710       return CLI_SHOWUSAGE;
03711    }
03712 
03713    if (!strcasecmp(a->argv[3], "on")) {
03714       level = 1;
03715    } else if (!strcasecmp(a->argv[3], "off")) {
03716       level = 0;
03717    } else if (isdigit(a->argv[3][0])) {
03718       level = atoi(a->argv[3]);
03719    } else {
03720       return CLI_SHOWUSAGE;
03721    }
03722 
03723    switch (a->argc) {
03724    case 4:
03725    case 5:
03726       {
03727          int i;
03728          int only = 0;
03729          if (a->argc == 5) {
03730             if (strncasecmp(a->argv[4], "only", strlen(a->argv[4]))) {
03731                return CLI_SHOWUSAGE;
03732             } else {
03733                only = 1;
03734             }
03735          }
03736 
03737          for (i = 0; i <= max_ports; i++) {
03738             misdn_debug[i] = level;
03739             misdn_debug_only[i] = only;
03740          }
03741          ast_cli(a->fd, "changing debug level for all ports to %d%s\n", misdn_debug[0], only ? " (only)" : "");
03742       }
03743       break;
03744    case 6:
03745    case 7:
03746       {
03747          int port;
03748          if (strncasecmp(a->argv[4], "port", strlen(a->argv[4])))
03749             return CLI_SHOWUSAGE;
03750          port = atoi(a->argv[5]);
03751          if (port <= 0 || port > max_ports) {
03752             switch (max_ports) {
03753             case 0:
03754                ast_cli(a->fd, "port number not valid! no ports available so you won't get lucky with any number here...\n");
03755                break;
03756             case 1:
03757                ast_cli(a->fd, "port number not valid! only port 1 is available.\n");
03758                break;
03759             default:
03760                ast_cli(a->fd, "port number not valid! only ports 1 to %d are available.\n", max_ports);
03761             }
03762             return 0;
03763          }
03764          if (a->argc == 7) {
03765             if (strncasecmp(a->argv[6], "only", strlen(a->argv[6]))) {
03766                return CLI_SHOWUSAGE;
03767             } else {
03768                misdn_debug_only[port] = 1;
03769             }
03770          } else {
03771             misdn_debug_only[port] = 0;
03772          }
03773          misdn_debug[port] = level;
03774          ast_cli(a->fd, "changing debug level to %d%s for port %d\n", misdn_debug[port], misdn_debug_only[port] ? " (only)" : "", port);
03775       }
03776    }
03777 
03778    return CLI_SUCCESS;
03779 }
03780 
03781 static char *handle_cli_misdn_set_crypt_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03782 {
03783    switch (cmd) {
03784    case CLI_INIT:
03785       e->command = "misdn set crypt debug";
03786       e->usage =
03787          "Usage: misdn set crypt debug <level>\n"
03788          "       Set the crypt debug level of the mISDN channel. Level\n"
03789          "       must be 1 or 2.\n";
03790       return NULL;
03791    case CLI_GENERATE:
03792       return NULL;
03793    }
03794 
03795    if (a->argc != 5) {
03796       return CLI_SHOWUSAGE;
03797    }
03798 
03799    /* XXX Is this supposed to not do anything? XXX */
03800 
03801    return CLI_SUCCESS;
03802 }
03803 
03804 static char *handle_cli_misdn_port_block(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03805 {
03806    switch (cmd) {
03807    case CLI_INIT:
03808       e->command = "misdn port block";
03809       e->usage =
03810          "Usage: misdn port block <port>\n"
03811          "       Block the specified port by <port>.\n";
03812       return NULL;
03813    case CLI_GENERATE:
03814       return NULL;
03815    }
03816 
03817    if (a->argc != 4) {
03818       return CLI_SHOWUSAGE;
03819    }
03820 
03821    misdn_lib_port_block(atoi(a->argv[3]));
03822 
03823    return CLI_SUCCESS;
03824 }
03825 
03826 static char *handle_cli_misdn_port_unblock(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03827 {
03828    switch (cmd) {
03829    case CLI_INIT:
03830       e->command = "misdn port unblock";
03831       e->usage =
03832          "Usage: misdn port unblock <port>\n"
03833          "       Unblock the port specified by <port>.\n";
03834       return NULL;
03835    case CLI_GENERATE:
03836       return NULL;
03837    }
03838 
03839    if (a->argc != 4) {
03840       return CLI_SHOWUSAGE;
03841    }
03842 
03843    misdn_lib_port_unblock(atoi(a->argv[3]));
03844 
03845    return CLI_SUCCESS;
03846 }
03847 
03848 static char *handle_cli_misdn_restart_port(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03849 {
03850    switch (cmd) {
03851    case CLI_INIT:
03852       e->command = "misdn restart port";
03853       e->usage =
03854          "Usage: misdn restart port <port>\n"
03855          "       Restart the given port.\n";
03856       return NULL;
03857    case CLI_GENERATE:
03858       return NULL;
03859    }
03860 
03861    if (a->argc != 4) {
03862       return CLI_SHOWUSAGE;
03863    }
03864 
03865    misdn_lib_port_restart(atoi(a->argv[3]));
03866 
03867    return CLI_SUCCESS;
03868 }
03869 
03870 static char *handle_cli_misdn_restart_pid(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03871 {
03872    switch (cmd) {
03873    case CLI_INIT:
03874       e->command = "misdn restart pid";
03875       e->usage =
03876          "Usage: misdn restart pid <pid>\n"
03877          "       Restart the given pid\n";
03878       return NULL;
03879    case CLI_GENERATE:
03880       return NULL;
03881    }
03882 
03883    if (a->argc != 4) {
03884       return CLI_SHOWUSAGE;
03885    }
03886 
03887    misdn_lib_pid_restart(atoi(a->argv[3]));
03888 
03889    return CLI_SUCCESS;
03890 }
03891 
03892 static char *handle_cli_misdn_port_up(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03893 {
03894    switch (cmd) {
03895    case CLI_INIT:
03896       e->command = "misdn port up";
03897       e->usage =
03898          "Usage: misdn port up <port>\n"
03899          "       Try to establish L1 on the given port.\n";
03900       return NULL;
03901    case CLI_GENERATE:
03902       return NULL;
03903    }
03904 
03905    if (a->argc != 4) {
03906       return CLI_SHOWUSAGE;
03907    }
03908 
03909    misdn_lib_get_port_up(atoi(a->argv[3]));
03910 
03911    return CLI_SUCCESS;
03912 }
03913 
03914 static char *handle_cli_misdn_port_down(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03915 {
03916    switch (cmd) {
03917    case CLI_INIT:
03918       e->command = "misdn port down";
03919       e->usage =
03920          "Usage: misdn port down <port>\n"
03921          "       Try to deactivate the L1 on the given port.\n";
03922       return NULL;
03923    case CLI_GENERATE:
03924       return NULL;
03925    }
03926 
03927    if (a->argc != 4) {
03928       return CLI_SHOWUSAGE;
03929    }
03930 
03931    misdn_lib_get_port_down(atoi(a->argv[3]));
03932 
03933    return CLI_SUCCESS;
03934 }
03935 
03936 static inline void show_config_description(int fd, enum misdn_cfg_elements elem)
03937 {
03938    char section[BUFFERSIZE];
03939    char name[BUFFERSIZE];
03940    char desc[BUFFERSIZE];
03941    char def[BUFFERSIZE];
03942    char tmp[BUFFERSIZE];
03943 
03944    misdn_cfg_get_name(elem, tmp, sizeof(tmp));
03945    term_color(name, tmp, COLOR_BRWHITE, 0, sizeof(tmp));
03946    misdn_cfg_get_desc(elem, desc, sizeof(desc), def, sizeof(def));
03947 
03948    if (elem < MISDN_CFG_LAST) {
03949       term_color(section, "PORTS SECTION", COLOR_YELLOW, 0, sizeof(section));
03950    } else {
03951       term_color(section, "GENERAL SECTION", COLOR_YELLOW, 0, sizeof(section));
03952    }
03953 
03954    if (*def) {
03955       ast_cli(fd, "[%s] %s   (Default: %s)\n\t%s\n", section, name, def, desc);
03956    } else {
03957       ast_cli(fd, "[%s] %s\n\t%s\n", section, name, desc);
03958    }
03959 }
03960 
03961 static char *handle_cli_misdn_show_config(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03962 {
03963    char buffer[BUFFERSIZE];
03964    enum misdn_cfg_elements elem;
03965    int linebreak;
03966    int onlyport = -1;
03967    int ok = 0;
03968 
03969    switch (cmd) {
03970    case CLI_INIT:
03971       e->command = "misdn show config";
03972       e->usage =
03973          "Usage: misdn show config [<port> | description <config element> | descriptions [general|ports]]\n"
03974          "       Use 0 for <port> to only print the general config.\n";
03975       return NULL;
03976    case CLI_GENERATE:
03977       return complete_show_config(a);
03978    }
03979 
03980    if (a->argc >= 4) {
03981       if (!strcmp(a->argv[3], "description")) {
03982          if (a->argc == 5) {
03983             enum misdn_cfg_elements elem = misdn_cfg_get_elem(a->argv[4]);
03984             if (elem == MISDN_CFG_FIRST) {
03985                ast_cli(a->fd, "Unknown element: %s\n", a->argv[4]);
03986             } else {
03987                show_config_description(a->fd, elem);
03988             }
03989             return CLI_SUCCESS;
03990          }
03991          return CLI_SHOWUSAGE;
03992       } else if (!strcmp(a->argv[3], "descriptions")) {
03993          if ((a->argc == 4) || ((a->argc == 5) && !strcmp(a->argv[4], "general"))) {
03994             for (elem = MISDN_GEN_FIRST + 1; elem < MISDN_GEN_LAST; ++elem) {
03995                show_config_description(a->fd, elem);
03996                ast_cli(a->fd, "\n");
03997             }
03998             ok = 1;
03999          }
04000          if ((a->argc == 4) || ((a->argc == 5) && !strcmp(a->argv[4], "ports"))) {
04001             for (elem = MISDN_CFG_FIRST + 1; elem < MISDN_CFG_LAST - 1 /* the ptp hack, remove the -1 when ptp is gone */; ++elem) {
04002                show_config_description(a->fd, elem);
04003                ast_cli(a->fd, "\n");
04004             }
04005             ok = 1;
04006          }
04007          return ok ? CLI_SUCCESS : CLI_SHOWUSAGE;
04008       } else if (!sscanf(a->argv[3], "%5d", &onlyport) || onlyport < 0) {
04009          ast_cli(a->fd, "Unknown option: %s\n", a->argv[3]);
04010          return CLI_SHOWUSAGE;
04011       }
04012    }
04013 
04014    if (a->argc == 3 || onlyport == 0) {
04015       ast_cli(a->fd, "mISDN General-Config:\n");
04016       for (elem = MISDN_GEN_FIRST + 1, linebreak = 1; elem < MISDN_GEN_LAST; elem++, linebreak++) {
04017          misdn_cfg_get_config_string(0, elem, buffer, sizeof(buffer));
04018          ast_cli(a->fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
04019       }
04020       ast_cli(a->fd, "\n");
04021    }
04022 
04023    if (onlyport < 0) {
04024       int port = misdn_cfg_get_next_port(0);
04025 
04026       for (; port > 0; port = misdn_cfg_get_next_port(port)) {
04027          ast_cli(a->fd, "\n[PORT %d]\n", port);
04028          for (elem = MISDN_CFG_FIRST + 1, linebreak = 1; elem < MISDN_CFG_LAST; elem++, linebreak++) {
04029             misdn_cfg_get_config_string(port, elem, buffer, sizeof(buffer));
04030             ast_cli(a->fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
04031          }
04032          ast_cli(a->fd, "\n");
04033       }
04034    }
04035 
04036    if (onlyport > 0) {
04037       if (misdn_cfg_is_port_valid(onlyport)) {
04038          ast_cli(a->fd, "[PORT %d]\n", onlyport);
04039          for (elem = MISDN_CFG_FIRST + 1, linebreak = 1; elem < MISDN_CFG_LAST; elem++, linebreak++) {
04040             misdn_cfg_get_config_string(onlyport, elem, buffer, sizeof(buffer));
04041             ast_cli(a->fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
04042          }
04043          ast_cli(a->fd, "\n");
04044       } else {
04045          ast_cli(a->fd, "Port %d is not active!\n", onlyport);
04046       }
04047    }
04048 
04049    return CLI_SUCCESS;
04050 }
04051 
04052 struct state_struct {
04053    enum misdn_chan_state state;
04054    char txt[255];
04055 };
04056 
04057 static const struct state_struct state_array[] = {
04058 /* *INDENT-OFF* */
04059    { MISDN_NOTHING,             "NOTHING" },             /* at beginning */
04060    { MISDN_WAITING4DIGS,        "WAITING4DIGS" },        /* when waiting for infos */
04061    { MISDN_EXTCANTMATCH,        "EXTCANTMATCH" },        /* when asterisk couldn't match our ext */
04062    { MISDN_INCOMING_SETUP,      "INCOMING SETUP" },      /* when pbx_start */
04063    { MISDN_DIALING,             "DIALING" },             /* when pbx_start */
04064    { MISDN_PROGRESS,            "PROGRESS" },            /* when pbx_start */
04065    { MISDN_PROCEEDING,          "PROCEEDING" },          /* when pbx_start */
04066    { MISDN_CALLING,             "CALLING" },             /* when misdn_call is called */
04067    { MISDN_CALLING_ACKNOWLEDGE, "CALLING_ACKNOWLEDGE" }, /* when misdn_call is called */
04068    { MISDN_ALERTING,            "ALERTING" },            /* when Alerting */
04069    { MISDN_BUSY,                "BUSY" },                /* when BUSY */
04070    { MISDN_CONNECTED,           "CONNECTED" },           /* when connected */
04071    { MISDN_DISCONNECTED,        "DISCONNECTED" },        /* when connected */
04072    { MISDN_CLEANING,            "CLEANING" },            /* when hangup from * but we were connected before */
04073 /* *INDENT-ON* */
04074 };
04075 
04076 static const char *misdn_get_ch_state(struct chan_list *p)
04077 {
04078    int i;
04079    static char state[8];
04080 
04081    if (!p) {
04082       return NULL;
04083    }
04084 
04085    for (i = 0; i < ARRAY_LEN(state_array); i++) {
04086       if (state_array[i].state == p->state) {
04087          return state_array[i].txt;
04088       }
04089    }
04090 
04091    snprintf(state, sizeof(state), "%d", p->state) ;
04092 
04093    return state;
04094 }
04095 
04096 
04097 static void reload_config(void)
04098 {
04099    int i, cfg_debug;
04100 
04101    if (!g_config_initialized) {
04102       ast_log(LOG_WARNING, "chan_misdn is not initialized properly, still reloading ?\n");
04103       return ;
04104    }
04105 
04106    free_robin_list();
04107    misdn_cfg_reload();
04108    misdn_cfg_update_ptp();
04109    misdn_cfg_get(0, MISDN_GEN_TRACEFILE, global_tracefile, sizeof(global_tracefile));
04110    misdn_cfg_get(0, MISDN_GEN_DEBUG, &cfg_debug, sizeof(cfg_debug));
04111 
04112    for (i = 0;  i <= max_ports; i++) {
04113       misdn_debug[i] = cfg_debug;
04114       misdn_debug_only[i] = 0;
04115    }
04116 }
04117 
04118 static char *handle_cli_misdn_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04119 {
04120    switch (cmd) {
04121    case CLI_INIT:
04122       e->command = "misdn reload";
04123       e->usage =
04124          "Usage: misdn reload\n"
04125          "       Reload internal mISDN config, read from the config\n"
04126          "       file.\n";
04127       return NULL;
04128    case CLI_GENERATE:
04129       return NULL;
04130    }
04131 
04132    if (a->argc != 2) {
04133       return CLI_SHOWUSAGE;
04134    }
04135 
04136    ast_cli(a->fd, "Reloading mISDN configuration\n");
04137    reload_config();
04138    return CLI_SUCCESS;
04139 }
04140 
04141 static void print_bc_info(int fd, struct chan_list *help, struct misdn_bchannel *bc)
04142 {
04143    struct ast_channel *ast = help->ast;
04144 
04145    ast_cli(fd,
04146       "* Pid:%d Port:%d Ch:%d Mode:%s Orig:%s dialed:%s\n"
04147       "  --> caller:\"%s\" <%s>\n"
04148       "  --> redirecting-from:\"%s\" <%s>\n"
04149       "  --> redirecting-to:\"%s\" <%s>\n"
04150       "  --> context:%s state:%s\n",
04151       bc->pid,
04152       bc->port,
04153       bc->channel,
04154       bc->nt ? "NT" : "TE",
04155       help->originator == ORG_AST ? "*" : "I",
04156       ast ? ast->exten : "",
04157       (ast && ast->caller.id.name.valid && ast->caller.id.name.str)
04158          ? ast->caller.id.name.str : "",
04159       (ast && ast->caller.id.number.valid && ast->caller.id.number.str)
04160          ? ast->caller.id.number.str : "",
04161       bc->redirecting.from.name,
04162       bc->redirecting.from.number,
04163       bc->redirecting.to.name,
04164       bc->redirecting.to.number,
04165       ast ? ast->context : "",
04166       misdn_get_ch_state(help));
04167    if (misdn_debug[bc->port] > 0) {
04168       ast_cli(fd,
04169          "  --> astname: %s\n"
04170          "  --> ch_l3id: %x\n"
04171          "  --> ch_addr: %x\n"
04172          "  --> bc_addr: %x\n"
04173          "  --> bc_l3id: %x\n"
04174          "  --> display: %s\n"
04175          "  --> activated: %d\n"
04176          "  --> state: %s\n"
04177          "  --> capability: %s\n"
04178 #ifdef MISDN_1_2
04179          "  --> pipeline: %s\n"
04180 #else
04181          "  --> echo_cancel: %d\n"
04182 #endif
04183          "  --> notone : rx %d tx:%d\n"
04184          "  --> bc_hold: %d\n",
04185          help->ast->name,
04186          help->l3id,
04187          help->addr,
04188          bc->addr,
04189          bc->l3_id,
04190          bc->display,
04191          bc->active,
04192          bc_state2str(bc->bc_state),
04193          bearer2str(bc->capability),
04194 #ifdef MISDN_1_2
04195          bc->pipeline,
04196 #else
04197          bc->ec_enable,
04198 #endif
04199          help->norxtone, help->notxtone,
04200          bc->holded);
04201    }
04202 }
04203 
04204 static char *handle_cli_misdn_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04205 {
04206    struct chan_list *help;
04207 
04208    switch (cmd) {
04209    case CLI_INIT:
04210       e->command = "misdn show channels";
04211       e->usage =
04212          "Usage: misdn show channels\n"
04213          "       Show the internal mISDN channel list\n";
04214       return NULL;
04215    case CLI_GENERATE:
04216       return NULL;
04217    }
04218 
04219    if (a->argc != 3) {
04220       return CLI_SHOWUSAGE;
04221    }
04222 
04223    ast_cli(a->fd, "Channel List: %p\n", cl_te);
04224 
04225    /*
04226     * Walking the list and dumping the channel information could
04227     * take awhile.  With the list locked for the duration, the
04228     * channel driver cannot process signaling messages.  However,
04229     * since this is a CLI command it should not be run very often.
04230     */
04231    ast_mutex_lock(&cl_te_lock);
04232    for (help = cl_te; help; help = help->next) {
04233       struct misdn_bchannel *bc = help->bc;
04234       struct ast_channel *ast = help->ast;
04235       if (!ast) {
04236          if (!bc) {
04237             ast_cli(a->fd, "chan_list obj. with l3id:%x has no bc and no ast Leg\n", help->l3id);
04238             continue;
04239          }
04240          ast_cli(a->fd, "bc with pid:%d has no Ast Leg\n", bc->pid);
04241          continue;
04242       }
04243 
04244       if (misdn_debug[0] > 2) {
04245          ast_cli(a->fd, "Bc:%p Ast:%p\n", bc, ast);
04246       }
04247       if (bc) {
04248          print_bc_info(a->fd, help, bc);
04249       } else {
04250          if (help->hold.state != MISDN_HOLD_IDLE) {
04251             ast_cli(a->fd, "ITS A HELD CALL BC:\n");
04252             ast_cli(a->fd, " --> l3_id: %x\n"
04253                " --> dialed:%s\n"
04254                " --> caller:\"%s\" <%s>\n"
04255                " --> hold_port: %d\n"
04256                " --> hold_channel: %d\n",
04257                help->l3id,
04258                ast->exten,
04259                S_COR(ast->caller.id.name.valid, ast->caller.id.name.str, ""),
04260                S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, ""),
04261                help->hold.port,
04262                help->hold.channel
04263                );
04264          } else {
04265             ast_cli(a->fd, "* Channel in unknown STATE !!! Exten:%s, Callerid:%s\n",
04266                ast->exten,
04267                S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, ""));
04268          }
04269       }
04270    }
04271    ast_mutex_unlock(&cl_te_lock);
04272 
04273    misdn_dump_chanlist();
04274 
04275    return CLI_SUCCESS;
04276 }
04277 
04278 static char *handle_cli_misdn_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04279 {
04280    struct chan_list *help;
04281 
04282    switch (cmd) {
04283    case CLI_INIT:
04284       e->command = "misdn show channel";
04285       e->usage =
04286          "Usage: misdn show channel <channel>\n"
04287          "       Show an internal mISDN channel\n.";
04288       return NULL;
04289    case CLI_GENERATE:
04290       return complete_ch(a);
04291    }
04292 
04293    if (a->argc != 4) {
04294       return CLI_SHOWUSAGE;
04295    }
04296 
04297    ast_mutex_lock(&cl_te_lock);
04298    for (help = cl_te; help; help = help->next) {
04299       struct misdn_bchannel *bc = help->bc;
04300       struct ast_channel *ast = help->ast;
04301 
04302       if (bc && ast) {
04303          if (!strcasecmp(ast->name, a->argv[3])) {
04304             print_bc_info(a->fd, help, bc);
04305             break;
04306          }
04307       }
04308    }
04309    ast_mutex_unlock(&cl_te_lock);
04310 
04311    return CLI_SUCCESS;
04312 }
04313 
04314 static char *handle_cli_misdn_set_tics(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04315 {
04316    switch (cmd) {
04317    case CLI_INIT:
04318       e->command = "misdn set tics";
04319       e->usage =
04320          "Usage: misdn set tics <value>\n";
04321       return NULL;
04322    case CLI_GENERATE:
04323       return NULL;
04324    }
04325 
04326    if (a->argc != 4) {
04327       return CLI_SHOWUSAGE;
04328    }
04329 
04330    /* XXX Wow, this does... a whole lot of nothing... XXX */
04331    MAXTICS = atoi(a->argv[3]);
04332 
04333    return CLI_SUCCESS;
04334 }
04335 
04336 static char *handle_cli_misdn_show_stacks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04337 {
04338    int port;
04339 
04340    switch (cmd) {
04341    case CLI_INIT:
04342       e->command = "misdn show stacks";
04343       e->usage =
04344          "Usage: misdn show stacks\n"
04345          "       Show internal mISDN stack_list.\n";
04346       return NULL;
04347    case CLI_GENERATE:
04348       return NULL;
04349    }
04350 
04351    if (a->argc != 3) {
04352       return CLI_SHOWUSAGE;
04353    }
04354 
04355    ast_cli(a->fd, "BEGIN STACK_LIST:\n");
04356    for (port = misdn_cfg_get_next_port(0); port > 0;
04357       port = misdn_cfg_get_next_port(port)) {
04358       char buf[128];
04359 
04360       get_show_stack_details(port, buf);
04361       ast_cli(a->fd, "  %s  Debug:%d%s\n", buf, misdn_debug[port], misdn_debug_only[port] ? "(only)" : "");
04362    }
04363 
04364    return CLI_SUCCESS;
04365 }
04366 
04367 static char *handle_cli_misdn_show_ports_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04368 {
04369    int port;
04370 
04371    switch (cmd) {
04372    case CLI_INIT:
04373       e->command = "misdn show ports stats";
04374       e->usage =
04375          "Usage: misdn show ports stats\n"
04376          "       Show mISDNs channel's call statistics per port.\n";
04377       return NULL;
04378    case CLI_GENERATE:
04379       return NULL;
04380    }
04381 
04382    if (a->argc != 4) {
04383       return CLI_SHOWUSAGE;
04384    }
04385 
04386    ast_cli(a->fd, "Port\tin_calls\tout_calls\n");
04387    for (port = misdn_cfg_get_next_port(0); port > 0;
04388       port = misdn_cfg_get_next_port(port)) {
04389       ast_cli(a->fd, "%d\t%d\t\t%d\n", port, misdn_in_calls[port], misdn_out_calls[port]);
04390    }
04391    ast_cli(a->fd, "\n");
04392 
04393    return CLI_SUCCESS;
04394 }
04395 
04396 static char *handle_cli_misdn_show_port(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04397 {
04398    int port;
04399    char buf[128];
04400 
04401    switch (cmd) {
04402    case CLI_INIT:
04403       e->command = "misdn show port";
04404       e->usage =
04405          "Usage: misdn show port <port>\n"
04406          "       Show detailed information for given port.\n";
04407       return NULL;
04408    case CLI_GENERATE:
04409       return NULL;
04410    }
04411 
04412    if (a->argc != 4) {
04413       return CLI_SHOWUSAGE;
04414    }
04415 
04416    port = atoi(a->argv[3]);
04417 
04418    ast_cli(a->fd, "BEGIN STACK_LIST:\n");
04419    get_show_stack_details(port, buf);
04420    ast_cli(a->fd, "  %s  Debug:%d%s\n", buf, misdn_debug[port], misdn_debug_only[port] ? "(only)" : "");
04421 
04422    return CLI_SUCCESS;
04423 }
04424 
04425 #if defined(AST_MISDN_ENHANCEMENTS) && defined(CCBS_TEST_MESSAGES)
04426 static const struct FacParm Fac_Msgs[] = {
04427 /* *INDENT-OFF* */
04428    [0].Function = Fac_ERROR,
04429    [0].u.ERROR.invokeId = 8,
04430    [0].u.ERROR.errorValue = FacError_CCBS_AlreadyAccepted,
04431 
04432    [1].Function = Fac_RESULT,
04433    [1].u.RESULT.InvokeID = 9,
04434 
04435    [2].Function = Fac_REJECT,
04436    [2].u.REJECT.Code = FacReject_Gen_BadlyStructuredComponent,
04437 
04438    [3].Function = Fac_REJECT,
04439    [3].u.REJECT.InvokeIDPresent = 1,
04440    [3].u.REJECT.InvokeID = 10,
04441    [3].u.REJECT.Code = FacReject_Inv_InitiatorReleasing,
04442 
04443    [4].Function = Fac_REJECT,
04444    [4].u.REJECT.InvokeIDPresent = 1,
04445    [4].u.REJECT.InvokeID = 11,
04446    [4].u.REJECT.Code = FacReject_Res_MistypedResult,
04447 
04448    [5].Function = Fac_REJECT,
04449    [5].u.REJECT.InvokeIDPresent = 1,
04450    [5].u.REJECT.InvokeID = 12,
04451    [5].u.REJECT.Code = FacReject_Err_ErrorResponseUnexpected,
04452 
04453    [6].Function = Fac_StatusRequest,
04454    [6].u.StatusRequest.InvokeID = 13,
04455    [6].u.StatusRequest.ComponentType = FacComponent_Invoke,
04456    [6].u.StatusRequest.Component.Invoke.Q931ie.Bc.Length = 2,
04457    [6].u.StatusRequest.Component.Invoke.Q931ie.Bc.Contents = "AB",
04458    [6].u.StatusRequest.Component.Invoke.Q931ie.Llc.Length = 3,
04459    [6].u.StatusRequest.Component.Invoke.Q931ie.Llc.Contents = "CDE",
04460    [6].u.StatusRequest.Component.Invoke.Q931ie.Hlc.Length = 4,
04461    [6].u.StatusRequest.Component.Invoke.Q931ie.Hlc.Contents = "FGHI",
04462    [6].u.StatusRequest.Component.Invoke.CompatibilityMode = 1,
04463 
04464    [7].Function = Fac_StatusRequest,
04465    [7].u.StatusRequest.InvokeID = 14,
04466    [7].u.StatusRequest.ComponentType = FacComponent_Result,
04467    [7].u.StatusRequest.Component.Result.Status = 2,
04468 
04469    [8].Function = Fac_CallInfoRetain,
04470    [8].u.CallInfoRetain.InvokeID = 15,
04471    [8].u.CallInfoRetain.CallLinkageID = 115,
04472 
04473    [9].Function = Fac_EraseCallLinkageID,
04474    [9].u.EraseCallLinkageID.InvokeID = 16,
04475    [9].u.EraseCallLinkageID.CallLinkageID = 105,
04476 
04477    [10].Function = Fac_CCBSDeactivate,
04478    [10].u.CCBSDeactivate.InvokeID = 17,
04479    [10].u.CCBSDeactivate.ComponentType = FacComponent_Invoke,
04480    [10].u.CCBSDeactivate.Component.Invoke.CCBSReference = 2,
04481 
04482    [11].Function = Fac_CCBSDeactivate,
04483    [11].u.CCBSDeactivate.InvokeID = 18,
04484    [11].u.CCBSDeactivate.ComponentType = FacComponent_Result,
04485 
04486    [12].Function = Fac_CCBSErase,
04487    [12].u.CCBSErase.InvokeID = 19,
04488    [12].u.CCBSErase.Q931ie.Bc.Length = 2,
04489    [12].u.CCBSErase.Q931ie.Bc.Contents = "JK",
04490    [12].u.CCBSErase.AddressOfB.Party.Type = 0,
04491    [12].u.CCBSErase.AddressOfB.Party.LengthOfNumber = 5,
04492    [12].u.CCBSErase.AddressOfB.Party.Number = "33403",
04493    [12].u.CCBSErase.AddressOfB.Subaddress.Type = 0,
04494    [12].u.CCBSErase.AddressOfB.Subaddress.Length = 4,
04495    [12].u.CCBSErase.AddressOfB.Subaddress.u.UserSpecified.Information = "3748",
04496    [12].u.CCBSErase.RecallMode = 1,
04497    [12].u.CCBSErase.CCBSReference = 102,
04498    [12].u.CCBSErase.Reason = 3,
04499 
04500    [13].Function = Fac_CCBSErase,
04501    [13].u.CCBSErase.InvokeID = 20,
04502    [13].u.CCBSErase.Q931ie.Bc.Length = 2,
04503    [13].u.CCBSErase.Q931ie.Bc.Contents = "JK",
04504    [13].u.CCBSErase.AddressOfB.Party.Type = 1,
04505    [13].u.CCBSErase.AddressOfB.Party.LengthOfNumber = 11,
04506    [13].u.CCBSErase.AddressOfB.Party.TypeOfNumber = 1,
04507    [13].u.CCBSErase.AddressOfB.Party.Number = "18003020102",
04508    [13].u.CCBSErase.AddressOfB.Subaddress.Type = 0,
04509    [13].u.CCBSErase.AddressOfB.Subaddress.Length = 4,
04510    [13].u.CCBSErase.AddressOfB.Subaddress.u.UserSpecified.OddCountPresent = 1,
04511    [13].u.CCBSErase.AddressOfB.Subaddress.u.UserSpecified.OddCount = 1,
04512    [13].u.CCBSErase.AddressOfB.Subaddress.u.UserSpecified.Information = "3748",
04513    [13].u.CCBSErase.RecallMode = 1,
04514    [13].u.CCBSErase.CCBSReference = 102,
04515    [13].u.CCBSErase.Reason = 3,
04516 
04517    [14].Function = Fac_CCBSErase,
04518    [14].u.CCBSErase.InvokeID = 21,
04519    [14].u.CCBSErase.Q931ie.Bc.Length = 2,
04520    [14].u.CCBSErase.Q931ie.Bc.Contents = "JK",
04521    [14].u.CCBSErase.AddressOfB.Party.Type = 2,
04522    [14].u.CCBSErase.AddressOfB.Party.LengthOfNumber = 4,
04523    [14].u.CCBSErase.AddressOfB.Party.Number = "1803",
04524    [14].u.CCBSErase.AddressOfB.Subaddress.Type = 1,
04525    [14].u.CCBSErase.AddressOfB.Subaddress.Length = 4,
04526    [14].u.CCBSErase.AddressOfB.Subaddress.u.Nsap = "6492",
04527    [14].u.CCBSErase.RecallMode = 1,
04528    [14].u.CCBSErase.CCBSReference = 102,
04529    [14].u.CCBSErase.Reason = 3,
04530 
04531    [15].Function = Fac_CCBSErase,
04532    [15].u.CCBSErase.InvokeID = 22,
04533    [15].u.CCBSErase.Q931ie.Bc.Length = 2,
04534    [15].u.CCBSErase.Q931ie.Bc.Contents = "JK",
04535    [15].u.CCBSErase.AddressOfB.Party.Type = 3,
04536    [15].u.CCBSErase.AddressOfB.Party.LengthOfNumber = 4,
04537    [15].u.CCBSErase.AddressOfB.Party.Number = "1803",
04538    [15].u.CCBSErase.RecallMode = 1,
04539    [15].u.CCBSErase.CCBSReference = 102,
04540    [15].u.CCBSErase.Reason = 3,
04541 
04542    [16].Function = Fac_CCBSErase,
04543    [16].u.CCBSErase.InvokeID = 23,
04544    [16].u.CCBSErase.Q931ie.Bc.Length = 2,
04545    [16].u.CCBSErase.Q931ie.Bc.Contents = "JK",
04546    [16].u.CCBSErase.AddressOfB.Party.Type = 4,
04547    [16].u.CCBSErase.AddressOfB.Party.LengthOfNumber = 4,
04548    [16].u.CCBSErase.AddressOfB.Party.Number = "1803",
04549    [16].u.CCBSErase.RecallMode = 1,
04550    [16].u.CCBSErase.CCBSReference = 102,
04551    [16].u.CCBSErase.Reason = 3,
04552 
04553    [17].Function = Fac_CCBSErase,
04554    [17].u.CCBSErase.InvokeID = 24,
04555    [17].u.CCBSErase.Q931ie.Bc.Length = 2,
04556    [17].u.CCBSErase.Q931ie.Bc.Contents = "JK",
04557    [17].u.CCBSErase.AddressOfB.Party.Type = 5,
04558    [17].u.CCBSErase.AddressOfB.Party.LengthOfNumber = 11,
04559    [17].u.CCBSErase.AddressOfB.Party.TypeOfNumber = 4,
04560    [17].u.CCBSErase.AddressOfB.Party.Number = "18003020102",
04561    [17].u.CCBSErase.RecallMode = 1,
04562    [17].u.CCBSErase.CCBSReference = 102,
04563    [17].u.CCBSErase.Reason = 3,
04564 
04565    [18].Function = Fac_CCBSErase,
04566    [18].u.CCBSErase.InvokeID = 25,
04567    [18].u.CCBSErase.Q931ie.Bc.Length = 2,
04568    [18].u.CCBSErase.Q931ie.Bc.Contents = "JK",
04569    [18].u.CCBSErase.AddressOfB.Party.Type = 8,
04570    [18].u.CCBSErase.AddressOfB.Party.LengthOfNumber = 4,
04571    [18].u.CCBSErase.AddressOfB.Party.Number = "1803",
04572    [18].u.CCBSErase.RecallMode = 1,
04573    [18].u.CCBSErase.CCBSReference = 102,
04574    [18].u.CCBSErase.Reason = 3,
04575 
04576    [19].Function = Fac_CCBSRemoteUserFree,
04577    [19].u.CCBSRemoteUserFree.InvokeID = 26,
04578    [19].u.CCBSRemoteUserFree.Q931ie.Bc.Length = 2,
04579    [19].u.CCBSRemoteUserFree.Q931ie.Bc.Contents = "JK",
04580    [19].u.CCBSRemoteUserFree.AddressOfB.Party.Type = 8,
04581    [19].u.CCBSRemoteUserFree.AddressOfB.Party.LengthOfNumber = 4,
04582    [19].u.CCBSRemoteUserFree.AddressOfB.Party.Number = "1803",
04583    [19].u.CCBSRemoteUserFree.RecallMode = 1,
04584    [19].u.CCBSRemoteUserFree.CCBSReference = 102,
04585 
04586    [20].Function = Fac_CCBSCall,
04587    [20].u.CCBSCall.InvokeID = 27,
04588    [20].u.CCBSCall.CCBSReference = 115,
04589 
04590    [21].Function = Fac_CCBSStatusRequest,
04591    [21].u.CCBSStatusRequest.InvokeID = 28,
04592    [21].u.CCBSStatusRequest.ComponentType = FacComponent_Invoke,
04593    [21].u.CCBSStatusRequest.Component.Invoke.Q931ie.Bc.Length = 2,
04594    [21].u.CCBSStatusRequest.Component.Invoke.Q931ie.Bc.Contents = "JK",
04595    [21].u.CCBSStatusRequest.Component.Invoke.RecallMode = 1,
04596    [21].u.CCBSStatusRequest.Component.Invoke.CCBSReference = 102,
04597 
04598    [22].Function = Fac_CCBSStatusRequest,
04599    [22].u.CCBSStatusRequest.InvokeID = 29,
04600    [22].u.CCBSStatusRequest.ComponentType = FacComponent_Result,
04601    [22].u.CCBSStatusRequest.Component.Result.Free = 1,
04602 
04603    [23].Function = Fac_CCBSBFree,
04604    [23].u.CCBSBFree.InvokeID = 30,
04605    [23].u.CCBSBFree.Q931ie.Bc.Length = 2,
04606    [23].u.CCBSBFree.Q931ie.Bc.Contents = "JK",
04607    [23].u.CCBSBFree.AddressOfB.Party.Type = 8,
04608    [23].u.CCBSBFree.AddressOfB.Party.LengthOfNumber = 4,
04609    [23].u.CCBSBFree.AddressOfB.Party.Number = "1803",
04610    [23].u.CCBSBFree.RecallMode = 1,
04611    [23].u.CCBSBFree.CCBSReference = 14,
04612 
04613    [24].Function = Fac_CCBSStopAlerting,
04614    [24].u.CCBSStopAlerting.InvokeID = 31,
04615    [24].u.CCBSStopAlerting.CCBSReference = 37,
04616 
04617    [25].Function = Fac_CCBSRequest,
04618    [25].u.CCBSRequest.InvokeID = 32,
04619    [25].u.CCBSRequest.ComponentType = FacComponent_Invoke,
04620    [25].u.CCBSRequest.Component.Invoke.CallLinkageID = 57,
04621 
04622    [26].Function = Fac_CCBSRequest,
04623    [26].u.CCBSRequest.InvokeID = 33,
04624    [26].u.CCBSRequest.ComponentType = FacComponent_Result,
04625    [26].u.CCBSRequest.Component.Result.RecallMode = 1,
04626    [26].u.CCBSRequest.Component.Result.CCBSReference = 102,
04627 
04628    [27].Function = Fac_CCBSInterrogate,
04629    [27].u.CCBSInterrogate.InvokeID = 34,
04630    [27].u.CCBSInterrogate.ComponentType = FacComponent_Invoke,
04631    [27].u.CCBSInterrogate.Component.Invoke.AParty.Type = 8,
04632    [27].u.CCBSInterrogate.Component.Invoke.AParty.LengthOfNumber = 4,
04633    [27].u.CCBSInterrogate.Component.Invoke.AParty.Number = "1803",
04634    [27].u.CCBSInterrogate.Component.Invoke.CCBSReferencePresent = 1,
04635    [27].u.CCBSInterrogate.Component.Invoke.CCBSReference = 76,
04636 
04637    [28].Function = Fac_CCBSInterrogate,
04638    [28].u.CCBSInterrogate.InvokeID = 35,
04639    [28].u.CCBSInterrogate.ComponentType = FacComponent_Invoke,
04640    [28].u.CCBSInterrogate.Component.Invoke.AParty.Type = 8,
04641    [28].u.CCBSInterrogate.Component.Invoke.AParty.LengthOfNumber = 4,
04642    [28].u.CCBSInterrogate.Component.Invoke.AParty.Number = "1803",
04643 
04644    [29].Function = Fac_CCBSInterrogate,
04645    [29].u.CCBSInterrogate.InvokeID = 36,
04646    [29].u.CCBSInterrogate.ComponentType = FacComponent_Invoke,
04647    [29].u.CCBSInterrogate.Component.Invoke.CCBSReferencePresent = 1,
04648    [29].u.CCBSInterrogate.Component.Invoke.CCBSReference = 76,
04649 
04650    [30].Function = Fac_CCBSInterrogate,
04651    [30].u.CCBSInterrogate.InvokeID = 37,
04652    [30].u.CCBSInterrogate.ComponentType = FacComponent_Invoke,
04653 
04654    [31].Function = Fac_CCBSInterrogate,
04655    [31].u.CCBSInterrogate.InvokeID = 38,
04656    [31].u.CCBSInterrogate.ComponentType = FacComponent_Result,
04657    [31].u.CCBSInterrogate.Component.Result.RecallMode = 1,
04658 
04659    [32].Function = Fac_CCBSInterrogate,
04660    [32].u.CCBSInterrogate.InvokeID = 39,
04661    [32].u.CCBSInterrogate.ComponentType = FacComponent_Result,
04662    [32].u.CCBSInterrogate.Component.Result.RecallMode = 1,
04663    [32].u.CCBSInterrogate.Component.Result.NumRecords = 1,
04664    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].CCBSReference = 12,
04665    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].Q931ie.Bc.Length = 2,
04666    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].Q931ie.Bc.Contents = "JK",
04667    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].AddressOfB.Party.Type = 8,
04668    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].AddressOfB.Party.LengthOfNumber = 4,
04669    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].AddressOfB.Party.Number = "1803",
04670    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].SubaddressOfA.Type = 1,
04671    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].SubaddressOfA.Length = 4,
04672    [32].u.CCBSInterrogate.Component.Result.CallDetails[0].SubaddressOfA.u.Nsap = "6492",
04673 
04674    [33].Function = Fac_CCBSInterrogate,
04675    [33].u.CCBSInterrogate.InvokeID = 40,
04676    [33].u.CCBSInterrogate.ComponentType = FacComponent_Result,
04677    [33].u.CCBSInterrogate.Component.Result.RecallMode = 1,
04678    [33].u.CCBSInterrogate.Component.Result.NumRecords = 2,
04679    [33].u.CCBSInterrogate.Component.Result.CallDetails[0].CCBSReference = 12,
04680    [33].u.CCBSInterrogate.Component.Result.CallDetails[0].Q931ie.Bc.Length = 2,
04681    [33].u.CCBSInterrogate.Component.Result.CallDetails[0].Q931ie.Bc.Contents = "JK",
04682    [33].u.CCBSInterrogate.Component.Result.CallDetails[0].AddressOfB.Party.Type = 8,
04683    [33].u.CCBSInterrogate.Component.Result.CallDetails[0].AddressOfB.Party.LengthOfNumber = 4,
04684    [33].u.CCBSInterrogate.Component.Result.CallDetails[0].AddressOfB.Party.Number = "1803",
04685    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].CCBSReference = 102,
04686    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].Q931ie.Bc.Length = 2,
04687    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].Q931ie.Bc.Contents = "LM",
04688    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].AddressOfB.Party.Type = 8,
04689    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].AddressOfB.Party.LengthOfNumber = 4,
04690    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].AddressOfB.Party.Number = "6229",
04691    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].AddressOfB.Subaddress.Type = 1,
04692    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].AddressOfB.Subaddress.Length = 4,
04693    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].AddressOfB.Subaddress.u.Nsap = "8592",
04694    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].SubaddressOfA.Type = 1,
04695    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].SubaddressOfA.Length = 4,
04696    [33].u.CCBSInterrogate.Component.Result.CallDetails[1].SubaddressOfA.u.Nsap = "6492",
04697 
04698    [34].Function = Fac_CCNRRequest,
04699    [34].u.CCNRRequest.InvokeID = 512,
04700    [34].u.CCNRRequest.ComponentType = FacComponent_Invoke,
04701    [34].u.CCNRRequest.Component.Invoke.CallLinkageID = 57,
04702 
04703    [35].Function = Fac_CCNRRequest,
04704    [35].u.CCNRRequest.InvokeID = 150,
04705    [35].u.CCNRRequest.ComponentType = FacComponent_Result,
04706    [35].u.CCNRRequest.Component.Result.RecallMode = 1,
04707    [35].u.CCNRRequest.Component.Result.CCBSReference = 102,
04708 
04709    [36].Function = Fac_CCNRInterrogate,
04710    [36].u.CCNRInterrogate.InvokeID = -129,
04711    [36].u.CCNRInterrogate.ComponentType = FacComponent_Invoke,
04712 
04713    [37].Function = Fac_CCNRInterrogate,
04714    [37].u.CCNRInterrogate.InvokeID = -3,
04715    [37].u.CCNRInterrogate.ComponentType = FacComponent_Result,
04716    [37].u.CCNRInterrogate.Component.Result.RecallMode = 1,
04717 
04718    [38].Function = Fac_CCBS_T_Call,
04719    [38].u.EctExecute.InvokeID = 41,
04720 
04721    [39].Function = Fac_CCBS_T_Suspend,
04722    [39].u.EctExecute.InvokeID = 42,
04723 
04724    [40].Function = Fac_CCBS_T_Resume,
04725    [40].u.EctExecute.InvokeID = 43,
04726 
04727    [41].Function = Fac_CCBS_T_RemoteUserFree,
04728    [41].u.EctExecute.InvokeID = 44,
04729 
04730    [42].Function = Fac_CCBS_T_Available,
04731    [42].u.EctExecute.InvokeID = 45,
04732 
04733    [43].Function = Fac_CCBS_T_Request,
04734    [43].u.CCBS_T_Request.InvokeID = 46,
04735    [43].u.CCBS_T_Request.ComponentType = FacComponent_Invoke,
04736    [43].u.CCBS_T_Request.Component.Invoke.Destination.Party.Type = 8,
04737    [43].u.CCBS_T_Request.Component.Invoke.Destination.Party.LengthOfNumber = 4,
04738    [43].u.CCBS_T_Request.Component.Invoke.Destination.Party.Number = "6229",
04739    [43].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Length = 2,
04740    [43].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Contents = "LM",
04741    [43].u.CCBS_T_Request.Component.Invoke.RetentionSupported = 1,
04742    [43].u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicatorPresent = 1,
04743    [43].u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicator = 1,
04744    [43].u.CCBS_T_Request.Component.Invoke.Originating.Party.Type = 8,
04745    [43].u.CCBS_T_Request.Component.Invoke.Originating.Party.LengthOfNumber = 4,
04746    [43].u.CCBS_T_Request.Component.Invoke.Originating.Party.Number = "9864",
04747 
04748    [44].Function = Fac_CCBS_T_Request,
04749    [44].u.CCBS_T_Request.InvokeID = 47,
04750    [44].u.CCBS_T_Request.ComponentType = FacComponent_Invoke,
04751    [44].u.CCBS_T_Request.Component.Invoke.Destination.Party.Type = 8,
04752    [44].u.CCBS_T_Request.Component.Invoke.Destination.Party.LengthOfNumber = 4,
04753    [44].u.CCBS_T_Request.Component.Invoke.Destination.Party.Number = "6229",
04754    [44].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Length = 2,
04755    [44].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Contents = "LM",
04756    [44].u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicatorPresent = 1,
04757    [44].u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicator = 1,
04758    [44].u.CCBS_T_Request.Component.Invoke.Originating.Party.Type = 8,
04759    [44].u.CCBS_T_Request.Component.Invoke.Originating.Party.LengthOfNumber = 4,
04760    [44].u.CCBS_T_Request.Component.Invoke.Originating.Party.Number = "9864",
04761 
04762    [45].Function = Fac_CCBS_T_Request,
04763    [45].u.CCBS_T_Request.InvokeID = 48,
04764    [45].u.CCBS_T_Request.ComponentType = FacComponent_Invoke,
04765    [45].u.CCBS_T_Request.Component.Invoke.Destination.Party.Type = 8,
04766    [45].u.CCBS_T_Request.Component.Invoke.Destination.Party.LengthOfNumber = 4,
04767    [45].u.CCBS_T_Request.Component.Invoke.Destination.Party.Number = "6229",
04768    [45].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Length = 2,
04769    [45].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Contents = "LM",
04770    [45].u.CCBS_T_Request.Component.Invoke.Originating.Party.Type = 8,
04771    [45].u.CCBS_T_Request.Component.Invoke.Originating.Party.LengthOfNumber = 4,
04772    [45].u.CCBS_T_Request.Component.Invoke.Originating.Party.Number = "9864",
04773 
04774    [46].Function = Fac_CCBS_T_Request,
04775    [46].u.CCBS_T_Request.InvokeID = 49,
04776    [46].u.CCBS_T_Request.ComponentType = FacComponent_Invoke,
04777    [46].u.CCBS_T_Request.Component.Invoke.Destination.Party.Type = 8,
04778    [46].u.CCBS_T_Request.Component.Invoke.Destination.Party.LengthOfNumber = 4,
04779    [46].u.CCBS_T_Request.Component.Invoke.Destination.Party.Number = "6229",
04780    [46].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Length = 2,
04781    [46].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Contents = "LM",
04782    [46].u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicatorPresent = 1,
04783    [46].u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicator = 1,
04784 
04785    [47].Function = Fac_CCBS_T_Request,
04786    [47].u.CCBS_T_Request.InvokeID = 50,
04787    [47].u.CCBS_T_Request.ComponentType = FacComponent_Invoke,
04788    [47].u.CCBS_T_Request.Component.Invoke.Destination.Party.Type = 8,
04789    [47].u.CCBS_T_Request.Component.Invoke.Destination.Party.LengthOfNumber = 4,
04790    [47].u.CCBS_T_Request.Component.Invoke.Destination.Party.Number = "6229",
04791    [47].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Length = 2,
04792    [47].u.CCBS_T_Request.Component.Invoke.Q931ie.Bc.Contents = "LM",
04793 
04794    [48].Function = Fac_CCBS_T_Request,
04795    [48].u.CCBS_T_Request.InvokeID = 51,
04796    [48].u.CCBS_T_Request.ComponentType = FacComponent_Result,
04797    [48].u.CCBS_T_Request.Component.Result.RetentionSupported = 1,
04798 
04799    [49].Function = Fac_CCNR_T_Request,
04800    [49].u.CCNR_T_Request.InvokeID = 52,
04801    [49].u.CCNR_T_Request.ComponentType = FacComponent_Invoke,
04802    [49].u.CCNR_T_Request.Component.Invoke.Destination.Party.Type = 8,
04803    [49].u.CCNR_T_Request.Component.Invoke.Destination.Party.LengthOfNumber = 4,
04804    [49].u.CCNR_T_Request.Component.Invoke.Destination.Party.Number = "6229",
04805    [49].u.CCNR_T_Request.Component.Invoke.Q931ie.Bc.Length = 2,
04806    [49].u.CCNR_T_Request.Component.Invoke.Q931ie.Bc.Contents = "LM",
04807 
04808    [50].Function = Fac_CCNR_T_Request,
04809    [50].u.CCNR_T_Request.InvokeID = 53,
04810    [50].u.CCNR_T_Request.ComponentType = FacComponent_Result,
04811    [50].u.CCNR_T_Request.Component.Result.RetentionSupported = 1,
04812 
04813    [51].Function = Fac_EctExecute,
04814    [51].u.EctExecute.InvokeID = 54,
04815 
04816    [52].Function = Fac_ExplicitEctExecute,
04817    [52].u.ExplicitEctExecute.InvokeID = 55,
04818    [52].u.ExplicitEctExecute.LinkID = 23,
04819 
04820    [53].Function = Fac_RequestSubaddress,
04821    [53].u.RequestSubaddress.InvokeID = 56,
04822 
04823    [54].Function = Fac_SubaddressTransfer,
04824    [54].u.SubaddressTransfer.InvokeID = 57,
04825    [54].u.SubaddressTransfer.Subaddress.Type = 1,
04826    [54].u.SubaddressTransfer.Subaddress.Length = 4,
04827    [54].u.SubaddressTransfer.Subaddress.u.Nsap = "6492",
04828 
04829    [55].Function = Fac_EctLinkIdRequest,
04830    [55].u.EctLinkIdRequest.InvokeID = 58,
04831    [55].u.EctLinkIdRequest.ComponentType = FacComponent_Invoke,
04832 
04833    [56].Function = Fac_EctLinkIdRequest,
04834    [56].u.EctLinkIdRequest.InvokeID = 59,
04835    [56].u.EctLinkIdRequest.ComponentType = FacComponent_Result,
04836    [56].u.EctLinkIdRequest.Component.Result.LinkID = 76,
04837 
04838    [57].Function = Fac_EctInform,
04839    [57].u.EctInform.InvokeID = 60,
04840    [57].u.EctInform.Status = 1,
04841    [57].u.EctInform.RedirectionPresent = 1,
04842    [57].u.EctInform.Redirection.Type = 0,
04843    [57].u.EctInform.Redirection.Unscreened.Type = 8,
04844    [57].u.EctInform.Redirection.Unscreened.LengthOfNumber = 4,
04845    [57].u.EctInform.Redirection.Unscreened.Number = "6229",
04846 
04847    [58].Function = Fac_EctInform,
04848    [58].u.EctInform.InvokeID = 61,
04849    [58].u.EctInform.Status = 1,
04850    [58].u.EctInform.RedirectionPresent = 1,
04851    [58].u.EctInform.Redirection.Type = 1,
04852 
04853    [59].Function = Fac_EctInform,
04854    [59].u.EctInform.InvokeID = 62,
04855    [59].u.EctInform.Status = 1,
04856    [59].u.EctInform.RedirectionPresent = 1,
04857    [59].u.EctInform.Redirection.Type = 2,
04858 
04859    [60].Function = Fac_EctInform,
04860    [60].u.EctInform.InvokeID = 63,
04861    [60].u.EctInform.Status = 1,
04862    [60].u.EctInform.RedirectionPresent = 1,
04863    [60].u.EctInform.Redirection.Type = 3,
04864    [60].u.EctInform.Redirection.Unscreened.Type = 8,
04865    [60].u.EctInform.Redirection.Unscreened.LengthOfNumber = 4,
04866    [60].u.EctInform.Redirection.Unscreened.Number = "3340",
04867 
04868    [61].Function = Fac_EctInform,
04869    [61].u.EctInform.InvokeID = 64,
04870    [61].u.EctInform.Status = 1,
04871    [61].u.EctInform.RedirectionPresent = 0,
04872 
04873    [62].Function = Fac_EctLoopTest,
04874    [62].u.EctLoopTest.InvokeID = 65,
04875    [62].u.EctLoopTest.ComponentType = FacComponent_Invoke,
04876    [62].u.EctLoopTest.Component.Invoke.CallTransferID = 7,
04877 
04878    [63].Function = Fac_EctLoopTest,
04879    [63].u.EctLoopTest.InvokeID = 66,
04880    [63].u.EctLoopTest.ComponentType = FacComponent_Result,
04881    [63].u.EctLoopTest.Component.Result.LoopResult = 2,
04882 
04883    [64].Function = Fac_ActivationDiversion,
04884    [64].u.ActivationDiversion.InvokeID = 67,
04885    [64].u.ActivationDiversion.ComponentType = FacComponent_Invoke,
04886    [64].u.ActivationDiversion.Component.Invoke.Procedure = 2,
04887    [64].u.ActivationDiversion.Component.Invoke.BasicService = 3,
04888    [64].u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.Type = 4,
04889    [64].u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.LengthOfNumber = 4,
04890    [64].u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.Number = "1803",
04891    [64].u.ActivationDiversion.Component.Invoke.ServedUser.Type = 4,
04892    [64].u.ActivationDiversion.Component.Invoke.ServedUser.LengthOfNumber = 4,
04893    [64].u.ActivationDiversion.Component.Invoke.ServedUser.Number = "5398",
04894 
04895    [65].Function = Fac_ActivationDiversion,
04896    [65].u.ActivationDiversion.InvokeID = 68,
04897    [65].u.ActivationDiversion.ComponentType = FacComponent_Invoke,
04898    [65].u.ActivationDiversion.Component.Invoke.Procedure = 1,
04899    [65].u.ActivationDiversion.Component.Invoke.BasicService = 5,
04900    [65].u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.Type = 4,
04901    [65].u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.LengthOfNumber = 4,
04902    [65].u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.Number = "1803",
04903 
04904    [66].Function = Fac_ActivationDiversion,
04905    [66].u.ActivationDiversion.InvokeID = 69,
04906    [66].u.ActivationDiversion.ComponentType = FacComponent_Result,
04907 
04908    [67].Function = Fac_DeactivationDiversion,
04909    [67].u.DeactivationDiversion.InvokeID = 70,
04910    [67].u.DeactivationDiversion.ComponentType = FacComponent_Invoke,
04911    [67].u.DeactivationDiversion.Component.Invoke.Procedure = 1,
04912    [67].u.DeactivationDiversion.Component.Invoke.BasicService = 5,
04913 
04914    [68].Function = Fac_DeactivationDiversion,
04915    [68].u.DeactivationDiversion.InvokeID = 71,
04916    [68].u.DeactivationDiversion.ComponentType = FacComponent_Result,
04917 
04918    [69].Function = Fac_ActivationStatusNotificationDiv,
04919    [69].u.ActivationStatusNotificationDiv.InvokeID = 72,
04920    [69].u.ActivationStatusNotificationDiv.Procedure = 1,
04921    [69].u.ActivationStatusNotificationDiv.BasicService = 5,
04922    [69].u.ActivationStatusNotificationDiv.ForwardedTo.Party.Type = 4,
04923    [69].u.ActivationStatusNotificationDiv.ForwardedTo.Party.LengthOfNumber = 4,
04924    [69].u.ActivationStatusNotificationDiv.ForwardedTo.Party.Number = "1803",
04925 
04926    [70].Function = Fac_DeactivationStatusNotificationDiv,
04927    [70].u.DeactivationStatusNotificationDiv.InvokeID = 73,
04928    [70].u.DeactivationStatusNotificationDiv.Procedure = 1,
04929    [70].u.DeactivationStatusNotificationDiv.BasicService = 5,
04930 
04931    [71].Function = Fac_InterrogationDiversion,
04932    [71].u.InterrogationDiversion.InvokeID = 74,
04933    [71].u.InterrogationDiversion.ComponentType = FacComponent_Invoke,
04934    [71].u.InterrogationDiversion.Component.Invoke.Procedure = 1,
04935    [71].u.InterrogationDiversion.Component.Invoke.BasicService = 5,
04936 
04937    [72].Function = Fac_InterrogationDiversion,
04938    [72].u.InterrogationDiversion.InvokeID = 75,
04939    [72].u.InterrogationDiversion.ComponentType = FacComponent_Invoke,
04940    [72].u.InterrogationDiversion.Component.Invoke.Procedure = 1,
04941 
04942    [73].Function = Fac_InterrogationDiversion,
04943    [73].u.InterrogationDiversion.InvokeID = 76,
04944    [73].u.InterrogationDiversion.ComponentType = FacComponent_Result,
04945    [73].u.InterrogationDiversion.Component.Result.NumRecords = 2,
04946    [73].u.InterrogationDiversion.Component.Result.List[0].Procedure = 2,
04947    [73].u.InterrogationDiversion.Component.Result.List[0].BasicService = 5,
04948    [73].u.InterrogationDiversion.Component.Result.List[0].ForwardedTo.Party.Type = 4,
04949    [73].u.InterrogationDiversion.Component.Result.List[0].ForwardedTo.Party.LengthOfNumber = 4,
04950    [73].u.InterrogationDiversion.Component.Result.List[0].ForwardedTo.Party.Number = "1803",
04951    [73].u.InterrogationDiversion.Component.Result.List[1].Procedure = 1,
04952    [73].u.InterrogationDiversion.Component.Result.List[1].BasicService = 3,
04953    [73].u.InterrogationDiversion.Component.Result.List[1].ForwardedTo.Party.Type = 4,
04954    [73].u.InterrogationDiversion.Component.Result.List[1].ForwardedTo.Party.LengthOfNumber = 4,
04955    [73].u.InterrogationDiversion.Component.Result.List[1].ForwardedTo.Party.Number = "1903",
04956    [73].u.InterrogationDiversion.Component.Result.List[1].ServedUser.Type = 4,
04957    [73].u.InterrogationDiversion.Component.Result.List[1].ServedUser.LengthOfNumber = 4,
04958    [73].u.InterrogationDiversion.Component.Result.List[1].ServedUser.Number = "5398",
04959 
04960    [74].Function = Fac_DiversionInformation,
04961    [74].u.DiversionInformation.InvokeID = 77,
04962    [74].u.DiversionInformation.DiversionReason = 3,
04963    [74].u.DiversionInformation.BasicService = 5,
04964    [74].u.DiversionInformation.ServedUserSubaddress.Type = 1,
04965    [74].u.DiversionInformation.ServedUserSubaddress.Length = 4,
04966    [74].u.DiversionInformation.ServedUserSubaddress.u.Nsap = "6492",
04967    [74].u.DiversionInformation.CallingAddressPresent = 1,
04968    [74].u.DiversionInformation.CallingAddress.Type = 0,
04969    [74].u.DiversionInformation.CallingAddress.Address.ScreeningIndicator = 3,
04970    [74].u.DiversionInformation.CallingAddress.Address.Party.Type = 4,
04971    [74].u.DiversionInformation.CallingAddress.Address.Party.LengthOfNumber = 4,
04972    [74].u.DiversionInformation.CallingAddress.Address.Party.Number = "1803",
04973    [74].u.DiversionInformation.OriginalCalledPresent = 1,
04974    [74].u.DiversionInformation.OriginalCalled.Type = 1,
04975    [74].u.DiversionInformation.LastDivertingPresent = 1,
04976    [74].u.DiversionInformation.LastDiverting.Type = 2,
04977    [74].u.DiversionInformation.LastDivertingReasonPresent = 1,
04978    [74].u.DiversionInformation.LastDivertingReason = 3,
04979    [74].u.DiversionInformation.UserInfo.Length = 5,
04980    [74].u.DiversionInformation.UserInfo.Contents = "79828",
04981 
04982    [75].Function = Fac_DiversionInformation,
04983    [75].u.DiversionInformation.InvokeID = 78,
04984    [75].u.DiversionInformation.DiversionReason = 3,
04985    [75].u.DiversionInformation.BasicService = 5,
04986    [75].u.DiversionInformation.CallingAddressPresent = 1,
04987    [75].u.DiversionInformation.CallingAddress.Type = 1,
04988    [75].u.DiversionInformation.OriginalCalledPresent = 1,
04989    [75].u.DiversionInformation.OriginalCalled.Type = 2,
04990    [75].u.DiversionInformation.LastDivertingPresent = 1,
04991    [75].u.DiversionInformation.LastDiverting.Type = 1,
04992 
04993    [76].Function = Fac_DiversionInformation,
04994    [76].u.DiversionInformation.InvokeID = 79,
04995    [76].u.DiversionInformation.DiversionReason = 2,
04996    [76].u.DiversionInformation.BasicService = 3,
04997    [76].u.DiversionInformation.CallingAddressPresent = 1,
04998    [76].u.DiversionInformation.CallingAddress.Type = 2,
04999 
05000    [77].Function = Fac_DiversionInformation,
05001    [77].u.DiversionInformation.InvokeID = 80,
05002    [77].u.DiversionInformation.DiversionReason = 3,
05003    [77].u.DiversionInformation.BasicService = 5,
05004    [77].u.DiversionInformation.CallingAddressPresent = 1,
05005    [77].u.DiversionInformation.CallingAddress.Type = 3,
05006    [77].u.DiversionInformation.CallingAddress.Address.ScreeningIndicator = 2,
05007    [77].u.DiversionInformation.CallingAddress.Address.Party.Type = 4,
05008    [77].u.DiversionInformation.CallingAddress.Address.Party.LengthOfNumber = 4,
05009    [77].u.DiversionInformation.CallingAddress.Address.Party.Number = "1803",
05010 
05011    [78].Function = Fac_DiversionInformation,
05012    [78].u.DiversionInformation.InvokeID = 81,
05013    [78].u.DiversionInformation.DiversionReason = 2,
05014    [78].u.DiversionInformation.BasicService = 4,
05015    [78].u.DiversionInformation.UserInfo.Length = 5,
05016    [78].u.DiversionInformation.UserInfo.Contents = "79828",
05017 
05018    [79].Function = Fac_DiversionInformation,
05019    [79].u.DiversionInformation.InvokeID = 82,
05020    [79].u.DiversionInformation.DiversionReason = 2,
05021    [79].u.DiversionInformation.BasicService = 4,
05022 
05023    [80].Function = Fac_CallDeflection,
05024    [80].u.CallDeflection.InvokeID = 83,
05025    [80].u.CallDeflection.ComponentType = FacComponent_Invoke,
05026    [80].u.CallDeflection.Component.Invoke.Deflection.Party.Type = 4,
05027    [80].u.CallDeflection.Component.Invoke.Deflection.Party.LengthOfNumber = 4,
05028    [80].u.CallDeflection.Component.Invoke.Deflection.Party.Number = "1803",
05029    [80].u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUserPresent = 1,
05030    [80].u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUser = 1,
05031 
05032    [81].Function = Fac_CallDeflection,
05033    [81].u.CallDeflection.InvokeID = 84,
05034    [81].u.CallDeflection.ComponentType = FacComponent_Invoke,
05035    [81].u.CallDeflection.Component.Invoke.Deflection.Party.Type = 4,
05036    [81].u.CallDeflection.Component.Invoke.Deflection.Party.LengthOfNumber = 4,
05037    [81].u.CallDeflection.Component.Invoke.Deflection.Party.Number = "1803",
05038    [81].u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUserPresent = 1,
05039    [81].u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUser = 0,
05040 
05041    [82].Function = Fac_CallDeflection,
05042    [82].u.CallDeflection.InvokeID = 85,
05043    [82].u.CallDeflection.ComponentType = FacComponent_Invoke,
05044    [82].u.CallDeflection.Component.Invoke.Deflection.Party.Type = 4,
05045    [82].u.CallDeflection.Component.Invoke.Deflection.Party.LengthOfNumber = 4,
05046    [82].u.CallDeflection.Component.Invoke.Deflection.Party.Number = "1803",
05047 
05048    [83].Function = Fac_CallDeflection,
05049    [83].u.CallDeflection.InvokeID = 86,
05050    [83].u.CallDeflection.ComponentType = FacComponent_Result,
05051 
05052    [84].Function = Fac_CallRerouteing,
05053    [84].u.CallRerouteing.InvokeID = 87,
05054    [84].u.CallRerouteing.ComponentType = FacComponent_Invoke,
05055    [84].u.CallRerouteing.Component.Invoke.ReroutingReason = 3,
05056    [84].u.CallRerouteing.Component.Invoke.ReroutingCounter = 2,
05057    [84].u.CallRerouteing.Component.Invoke.CalledAddress.Party.Type = 4,
05058    [84].u.CallRerouteing.Component.Invoke.CalledAddress.Party.LengthOfNumber = 4,
05059    [84].u.CallRerouteing.Component.Invoke.CalledAddress.Party.Number = "1803",
05060    [84].u.CallRerouteing.Component.Invoke.Q931ie.Bc.Length = 2,
05061    [84].u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents = "RT",
05062    [84].u.CallRerouteing.Component.Invoke.Q931ie.Hlc.Length = 3,
05063    [84].u.CallRerouteing.Component.Invoke.Q931ie.Hlc.Contents = "RTG",
05064    [84].u.CallRerouteing.Component.Invoke.Q931ie.Llc.Length = 2,
05065    [84].u.CallRerouteing.Component.Invoke.Q931ie.Llc.Contents = "MY",
05066    [84].u.CallRerouteing.Component.Invoke.Q931ie.UserInfo.Length = 5,
05067    [84].u.CallRerouteing.Component.Invoke.Q931ie.UserInfo.Contents = "YEHAW",
05068    [84].u.CallRerouteing.Component.Invoke.LastRerouting.Type = 1,
05069    [84].u.CallRerouteing.Component.Invoke.SubscriptionOption = 2,
05070    [84].u.CallRerouteing.Component.Invoke.CallingPartySubaddress.Type = 1,
05071    [84].u.CallRerouteing.Component.Invoke.CallingPartySubaddress.Length = 4,
05072    [84].u.CallRerouteing.Component.Invoke.CallingPartySubaddress.u.Nsap = "6492",
05073 
05074    [85].Function = Fac_CallRerouteing,
05075    [85].u.CallRerouteing.InvokeID = 88,
05076    [85].u.CallRerouteing.ComponentType = FacComponent_Invoke,
05077    [85].u.CallRerouteing.Component.Invoke.ReroutingReason = 3,
05078    [85].u.CallRerouteing.Component.Invoke.ReroutingCounter = 2,
05079    [85].u.CallRerouteing.Component.Invoke.CalledAddress.Party.Type = 4,
05080    [85].u.CallRerouteing.Component.Invoke.CalledAddress.Party.LengthOfNumber = 4,
05081    [85].u.CallRerouteing.Component.Invoke.CalledAddress.Party.Number = "1803",
05082    [85].u.CallRerouteing.Component.Invoke.Q931ie.Bc.Length = 2,
05083    [85].u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents = "RT",
05084    [85].u.CallRerouteing.Component.Invoke.LastRerouting.Type = 1,
05085    [85].u.CallRerouteing.Component.Invoke.SubscriptionOption = 2,
05086 
05087    [86].Function = Fac_CallRerouteing,
05088    [86].u.CallRerouteing.InvokeID = 89,
05089    [86].u.CallRerouteing.ComponentType = FacComponent_Invoke,
05090    [86].u.CallRerouteing.Component.Invoke.ReroutingReason = 3,
05091    [86].u.CallRerouteing.Component.Invoke.ReroutingCounter = 2,
05092    [86].u.CallRerouteing.Component.Invoke.CalledAddress.Party.Type = 4,
05093    [86].u.CallRerouteing.Component.Invoke.CalledAddress.Party.LengthOfNumber = 4,
05094    [86].u.CallRerouteing.Component.Invoke.CalledAddress.Party.Number = "1803",
05095    [86].u.CallRerouteing.Component.Invoke.Q931ie.Bc.Length = 2,
05096    [86].u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents = "RT",
05097    [86].u.CallRerouteing.Component.Invoke.LastRerouting.Type = 2,
05098 
05099    [87].Function = Fac_CallRerouteing,
05100    [87].u.CallRerouteing.InvokeID = 90,
05101    [87].u.CallRerouteing.ComponentType = FacComponent_Result,
05102 
05103    [88].Function = Fac_InterrogateServedUserNumbers,
05104    [88].u.InterrogateServedUserNumbers.InvokeID = 91,
05105    [88].u.InterrogateServedUserNumbers.ComponentType = FacComponent_Invoke,
05106 
05107    [89].Function = Fac_InterrogateServedUserNumbers,
05108    [89].u.InterrogateServedUserNumbers.InvokeID = 92,
05109    [89].u.InterrogateServedUserNumbers.ComponentType = FacComponent_Result,
05110    [89].u.InterrogateServedUserNumbers.Component.Result.NumRecords = 2,
05111    [89].u.InterrogateServedUserNumbers.Component.Result.List[0].Type = 4,
05112    [89].u.InterrogateServedUserNumbers.Component.Result.List[0].LengthOfNumber = 4,
05113    [89].u.InterrogateServedUserNumbers.Component.Result.List[0].Number = "1803",
05114    [89].u.InterrogateServedUserNumbers.Component.Result.List[1].Type = 4,
05115    [89].u.InterrogateServedUserNumbers.Component.Result.List[1].LengthOfNumber = 4,
05116    [89].u.InterrogateServedUserNumbers.Component.Result.List[1].Number = "5786",
05117 
05118    [90].Function = Fac_DivertingLegInformation1,
05119    [90].u.DivertingLegInformation1.InvokeID = 93,
05120    [90].u.DivertingLegInformation1.DiversionReason = 4,
05121    [90].u.DivertingLegInformation1.SubscriptionOption = 1,
05122    [90].u.DivertingLegInformation1.DivertedToPresent = 1,
05123    [90].u.DivertingLegInformation1.DivertedTo.Type = 2,
05124 
05125    [91].Function = Fac_DivertingLegInformation1,
05126    [91].u.DivertingLegInformation1.InvokeID = 94,
05127    [91].u.DivertingLegInformation1.DiversionReason = 4,
05128    [91].u.DivertingLegInformation1.SubscriptionOption = 1,
05129 
05130    [92].Function = Fac_DivertingLegInformation2,
05131    [92].u.DivertingLegInformation2.InvokeID = 95,
05132    [92].u.DivertingLegInformation2.DiversionCounter = 3,
05133    [92].u.DivertingLegInformation2.DiversionReason = 2,
05134    [92].u.DivertingLegInformation2.DivertingPresent = 1,
05135    [92].u.DivertingLegInformation2.Diverting.Type = 2,
05136    [92].u.DivertingLegInformation2.OriginalCalledPresent = 1,
05137    [92].u.DivertingLegInformation2.OriginalCalled.Type = 1,
05138 
05139    [93].Function = Fac_DivertingLegInformation2,
05140    [93].u.DivertingLegInformation2.InvokeID = 96,
05141    [93].u.DivertingLegInformation2.DiversionCounter = 3,
05142    [93].u.DivertingLegInformation2.DiversionReason = 2,
05143    [93].u.DivertingLegInformation2.OriginalCalledPresent = 1,
05144    [93].u.DivertingLegInformation2.OriginalCalled.Type = 1,
05145 
05146    [94].Function = Fac_DivertingLegInformation2,
05147    [94].u.DivertingLegInformation2.InvokeID = 97,
05148    [94].u.DivertingLegInformation2.DiversionCounter = 1,
05149    [94].u.DivertingLegInformation2.DiversionReason = 2,
05150 
05151    [95].Function = Fac_DivertingLegInformation3,
05152    [95].u.DivertingLegInformation3.InvokeID = 98,
05153    [95].u.DivertingLegInformation3.PresentationAllowedIndicator = 1,
05154 /* *INDENT-ON* */
05155 };
05156 #endif   /* defined(AST_MISDN_ENHANCEMENTS) && defined(CCBS_TEST_MESSAGES) */
05157 
05158 static char *handle_cli_misdn_send_facility(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05159 {
05160    const char *channame;
05161    const char *nr;
05162    struct chan_list *tmp;
05163    int port;
05164    const char *served_nr;
05165    struct misdn_bchannel dummy, *bc=&dummy;
05166    unsigned max_len;
05167 
05168    switch (cmd) {
05169    case CLI_INIT:
05170       e->command = "misdn send facility";
05171       e->usage = "Usage: misdn send facility <type> <channel|port> \"<args>\" \n"
05172       "\t type is one of:\n"
05173       "\t - calldeflect\n"
05174 #if defined(AST_MISDN_ENHANCEMENTS)
05175       "\t - callrerouting\n"
05176 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
05177       "\t - CFActivate\n"
05178       "\t - CFDeactivate\n";
05179 
05180       return NULL;
05181    case CLI_GENERATE:
05182       return complete_ch(a);
05183    }
05184 
05185    if (a->argc < 5) {
05186       return CLI_SHOWUSAGE;
05187    }
05188 
05189    if (strstr(a->argv[3], "calldeflect")) {
05190       if (a->argc < 6) {
05191          ast_verbose("calldeflect requires 1 arg: ToNumber\n\n");
05192          return 0;
05193       }
05194       channame = a->argv[4];
05195       nr = a->argv[5];
05196 
05197       ast_verbose("Sending Calldeflection (%s) to %s\n", nr, channame);
05198       tmp = get_chan_by_ast_name(channame);
05199       if (!tmp) {
05200          ast_verbose("Sending CD with nr %s to %s failed: Channel does not exist.\n", nr, channame);
05201          return 0;
05202       }
05203 
05204 #if defined(AST_MISDN_ENHANCEMENTS)
05205       max_len = sizeof(tmp->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Party.Number) - 1;
05206       if (max_len < strlen(nr)) {
05207          ast_verbose("Sending CD with nr %s to %s failed: Number too long (up to %u digits are allowed).\n",
05208             nr, channame, max_len);
05209          return 0;
05210       }
05211       tmp->bc->fac_out.Function = Fac_CallDeflection;
05212       tmp->bc->fac_out.u.CallDeflection.InvokeID = ++misdn_invoke_id;
05213       tmp->bc->fac_out.u.CallDeflection.ComponentType = FacComponent_Invoke;
05214       tmp->bc->fac_out.u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUserPresent = 1;
05215       tmp->bc->fac_out.u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUser = 0;
05216       tmp->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Party.Type = 0;/* unknown */
05217       tmp->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Party.LengthOfNumber = strlen(nr);
05218       strcpy((char *) tmp->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Party.Number, nr);
05219       tmp->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Subaddress.Length = 0;
05220 
05221 #else /* !defined(AST_MISDN_ENHANCEMENTS) */
05222 
05223       max_len = sizeof(tmp->bc->fac_out.u.CDeflection.DeflectedToNumber) - 1;
05224       if (max_len < strlen(nr)) {
05225          ast_verbose("Sending CD with nr %s to %s failed: Number too long (up to %u digits are allowed).\n",
05226             nr, channame, max_len);
05227          return 0;
05228       }
05229       tmp->bc->fac_out.Function = Fac_CD;
05230       tmp->bc->fac_out.u.CDeflection.PresentationAllowed = 0;
05231       //tmp->bc->fac_out.u.CDeflection.DeflectedToSubaddress[0] = 0;
05232       strcpy((char *) tmp->bc->fac_out.u.CDeflection.DeflectedToNumber, nr);
05233 #endif   /* !defined(AST_MISDN_ENHANCEMENTS) */
05234 
05235       /* Send message */
05236       print_facility(&tmp->bc->fac_out, tmp->bc);
05237       misdn_lib_send_event(tmp->bc, EVENT_FACILITY);
05238 #if defined(AST_MISDN_ENHANCEMENTS)
05239    } else if (strstr(a->argv[3], "callrerouteing") || strstr(a->argv[3], "callrerouting")) {
05240       if (a->argc < 6) {
05241          ast_verbose("callrerouting requires 1 arg: ToNumber\n\n");
05242          return 0;
05243       }
05244       channame = a->argv[4];
05245       nr = a->argv[5];
05246 
05247       ast_verbose("Sending Callrerouting (%s) to %s\n", nr, channame);
05248       tmp = get_chan_by_ast_name(channame);
05249       if (!tmp) {
05250          ast_verbose("Sending Call Rerouting with nr %s to %s failed: Channel does not exist.\n", nr, channame);
05251          return 0;
05252       }
05253 
05254       max_len = sizeof(tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Party.Number) - 1;
05255       if (max_len < strlen(nr)) {
05256          ast_verbose("Sending Call Rerouting with nr %s to %s failed: Number too long (up to %u digits are allowed).\n",
05257             nr, channame, max_len);
05258          return 0;
05259       }
05260       tmp->bc->fac_out.Function = Fac_CallRerouteing;
05261       tmp->bc->fac_out.u.CallRerouteing.InvokeID = ++misdn_invoke_id;
05262       tmp->bc->fac_out.u.CallRerouteing.ComponentType = FacComponent_Invoke;
05263 
05264       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.ReroutingReason = 0;/* unknown */
05265       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.ReroutingCounter = 1;
05266 
05267       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Party.Type = 0;/* unknown */
05268       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Party.LengthOfNumber = strlen(nr);
05269       strcpy((char *) tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Party.Number, nr);
05270       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Subaddress.Length = 0;
05271 
05272       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.CallingPartySubaddress.Length = 0;
05273 
05274       /* 0x90 0x90 0xa3 3.1 kHz audio, circuit mode, 64kbit/sec, level1/a-Law */
05275       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Bc.Length = 3;
05276       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents[0] = 0x90;
05277       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents[1] = 0x90;
05278       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents[2] = 0xa3;
05279       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Hlc.Length = 0;
05280       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Llc.Length = 0;
05281       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.UserInfo.Length = 0;
05282 
05283       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.LastRerouting.Type = 1;/* presentationRestricted */
05284       tmp->bc->fac_out.u.CallRerouteing.Component.Invoke.SubscriptionOption = 0;/* no notification to caller */
05285 
05286       /* Send message */
05287       print_facility(&tmp->bc->fac_out, tmp->bc);
05288       misdn_lib_send_event(tmp->bc, EVENT_FACILITY);
05289 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
05290       } else if (strstr(a->argv[3], "CFActivate")) {
05291          if (a->argc < 7) {
05292             ast_verbose("CFActivate requires 2 args: 1.FromNumber, 2.ToNumber\n\n");
05293          return 0;
05294       }
05295       port = atoi(a->argv[4]);
05296       served_nr = a->argv[5];
05297       nr = a->argv[6];
05298 
05299       misdn_make_dummy(bc, port, 0, misdn_lib_port_is_nt(port), 0);
05300 
05301       ast_verbose("Sending CFActivate  Port:(%d) FromNr. (%s) to Nr. (%s)\n", port, served_nr, nr);
05302 
05303 #if defined(AST_MISDN_ENHANCEMENTS)
05304       bc->fac_out.Function = Fac_ActivationDiversion;
05305       bc->fac_out.u.ActivationDiversion.InvokeID = ++misdn_invoke_id;
05306       bc->fac_out.u.ActivationDiversion.ComponentType = FacComponent_Invoke;
05307       bc->fac_out.u.ActivationDiversion.Component.Invoke.BasicService = 0;/* allServices */
05308       bc->fac_out.u.ActivationDiversion.Component.Invoke.Procedure = 0;/* cfu (Call Forward Unconditional) */
05309       ast_copy_string((char *) bc->fac_out.u.ActivationDiversion.Component.Invoke.ServedUser.Number,
05310          served_nr, sizeof(bc->fac_out.u.ActivationDiversion.Component.Invoke.ServedUser.Number));
05311       bc->fac_out.u.ActivationDiversion.Component.Invoke.ServedUser.LengthOfNumber =
05312          strlen((char *) bc->fac_out.u.ActivationDiversion.Component.Invoke.ServedUser.Number);
05313       bc->fac_out.u.ActivationDiversion.Component.Invoke.ServedUser.Type = 0;/* unknown */
05314       ast_copy_string((char *) bc->fac_out.u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.Number,
05315          nr, sizeof(bc->fac_out.u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.Number));
05316       bc->fac_out.u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.LengthOfNumber =
05317          strlen((char *) bc->fac_out.u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.Number);
05318       bc->fac_out.u.ActivationDiversion.Component.Invoke.ForwardedTo.Party.Type = 0;/* unknown */
05319       bc->fac_out.u.ActivationDiversion.Component.Invoke.ForwardedTo.Subaddress.Length = 0;
05320 
05321 #else /* !defined(AST_MISDN_ENHANCEMENTS) */
05322 
05323       bc->fac_out.Function = Fac_CFActivate;
05324       bc->fac_out.u.CFActivate.BasicService = 0; /* All Services */
05325       bc->fac_out.u.CFActivate.Procedure = 0; /* Unconditional */
05326       ast_copy_string((char *) bc->fac_out.u.CFActivate.ServedUserNumber, served_nr, sizeof(bc->fac_out.u.CFActivate.ServedUserNumber));
05327       ast_copy_string((char *) bc->fac_out.u.CFActivate.ForwardedToNumber, nr, sizeof(bc->fac_out.u.CFActivate.ForwardedToNumber));
05328 #endif   /* !defined(AST_MISDN_ENHANCEMENTS) */
05329 
05330       /* Send message */
05331       print_facility(&bc->fac_out, bc);
05332       misdn_lib_send_event(bc, EVENT_FACILITY);
05333    } else if (strstr(a->argv[3], "CFDeactivate")) {
05334       if (a->argc < 6) {
05335          ast_verbose("CFDeactivate requires 1 arg: FromNumber\n\n");
05336          return 0;
05337       }
05338       port = atoi(a->argv[4]);
05339       served_nr = a->argv[5];
05340 
05341       misdn_make_dummy(bc, port, 0, misdn_lib_port_is_nt(port), 0);
05342       ast_verbose("Sending CFDeactivate  Port:(%d) FromNr. (%s)\n", port, served_nr);
05343 
05344 #if defined(AST_MISDN_ENHANCEMENTS)
05345       bc->fac_out.Function = Fac_DeactivationDiversion;
05346       bc->fac_out.u.DeactivationDiversion.InvokeID = ++misdn_invoke_id;
05347       bc->fac_out.u.DeactivationDiversion.ComponentType = FacComponent_Invoke;
05348       bc->fac_out.u.DeactivationDiversion.Component.Invoke.BasicService = 0;/* allServices */
05349       bc->fac_out.u.DeactivationDiversion.Component.Invoke.Procedure = 0;/* cfu (Call Forward Unconditional) */
05350       ast_copy_string((char *) bc->fac_out.u.DeactivationDiversion.Component.Invoke.ServedUser.Number,
05351          served_nr, sizeof(bc->fac_out.u.DeactivationDiversion.Component.Invoke.ServedUser.Number));
05352       bc->fac_out.u.DeactivationDiversion.Component.Invoke.ServedUser.LengthOfNumber =
05353          strlen((char *) bc->fac_out.u.DeactivationDiversion.Component.Invoke.ServedUser.Number);
05354       bc->fac_out.u.DeactivationDiversion.Component.Invoke.ServedUser.Type = 0;/* unknown */
05355 
05356 #else /* !defined(AST_MISDN_ENHANCEMENTS) */
05357 
05358       bc->fac_out.Function = Fac_CFDeactivate;
05359       bc->fac_out.u.CFDeactivate.BasicService = 0; /* All Services */
05360       bc->fac_out.u.CFDeactivate.Procedure = 0; /* Unconditional */
05361       ast_copy_string((char *) bc->fac_out.u.CFActivate.ServedUserNumber, served_nr, sizeof(bc->fac_out.u.CFActivate.ServedUserNumber));
05362 #endif   /* !defined(AST_MISDN_ENHANCEMENTS) */
05363 
05364       /* Send message */
05365       print_facility(&bc->fac_out, bc);
05366       misdn_lib_send_event(bc, EVENT_FACILITY);
05367 #if defined(AST_MISDN_ENHANCEMENTS) && defined(CCBS_TEST_MESSAGES)
05368    } else if (strstr(a->argv[3], "test")) {
05369       int msg_number;
05370 
05371       if (a->argc < 5) {
05372          ast_verbose("test (<port> [<msg#>]) | (<channel-name> <msg#>)\n\n");
05373          return 0;
05374       }
05375       port = atoi(a->argv[4]);
05376 
05377       channame = argv[4];
05378       tmp = get_chan_by_ast_name(channame);
05379       if (tmp) {
05380          /* We are going to send this FACILITY message out on an existing connection */
05381          msg_number = atoi(argv[5]);
05382          if (msg_number < ARRAY_LEN(Fac_Msgs)) {
05383             tmp->bc->fac_out = Fac_Msgs[msg_number];
05384 
05385             /* Send message */
05386             print_facility(&tmp->bc->fac_out, tmp->bc);
05387             misdn_lib_send_event(tmp->bc, EVENT_FACILITY);
05388          } else {
05389             ast_verbose("test <channel-name> <msg#>\n\n");
05390          }
05391       } else if (a->argc < 6) {
05392          for (msg_number = 0; msg_number < ARRAY_LEN(Fac_Msgs); ++msg_number) {
05393             misdn_make_dummy(bc, port, 0, misdn_lib_port_is_nt(port), 0);
05394             bc->fac_out = Fac_Msgs[msg_number];
05395 
05396             /* Send message */
05397             print_facility(&bc->fac_out, bc);
05398             misdn_lib_send_event(bc, EVENT_FACILITY);
05399             sleep(1);
05400          }
05401       } else {
05402          msg_number = atoi(a->argv[5]);
05403          if (msg_number < ARRAY_LEN(Fac_Msgs)) {
05404             misdn_make_dummy(bc, port, 0, misdn_lib_port_is_nt(port), 0);
05405             bc->fac_out = Fac_Msgs[msg_number];
05406 
05407             /* Send message */
05408             print_facility(&bc->fac_out, bc);
05409             misdn_lib_send_event(bc, EVENT_FACILITY);
05410          } else {
05411             ast_verbose("test <port> [<msg#>]\n\n");
05412          }
05413       }
05414    } else if (strstr(argv[3], "register")) {
05415       if (argc < 5) {
05416          ast_cli(fd, "register <port>\n\n");
05417          return 0;
05418       }
05419       port = atoi(argv[4]);
05420 
05421       bc = misdn_lib_get_register_bc(port);
05422       if (!bc) {
05423          ast_cli(fd, "Could not allocate REGISTER bc struct\n\n");
05424          return 0;
05425       }
05426       bc->fac_out = Fac_Msgs[45];
05427 
05428       /* Send message */
05429       print_facility(&bc->fac_out, bc);
05430       misdn_lib_send_event(bc, EVENT_REGISTER);
05431 #endif   /* defined(AST_MISDN_ENHANCEMENTS) && defined(CCBS_TEST_MESSAGES) */
05432    }
05433 
05434    return CLI_SUCCESS;
05435 }
05436 
05437 static char *handle_cli_misdn_send_restart(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05438 {
05439    int port;
05440    int channel;
05441 
05442    switch (cmd) {
05443    case CLI_INIT:
05444       e->command = "misdn send restart";
05445       e->usage =
05446          "Usage: misdn send restart [port [channel]]\n"
05447          "       Send a restart for every bchannel on the given port.\n";
05448       return NULL;
05449    case CLI_GENERATE:
05450       return NULL;
05451    }
05452 
05453    if (a->argc < 4 || a->argc > 5) {
05454       return CLI_SHOWUSAGE;
05455    }
05456 
05457    port = atoi(a->argv[3]);
05458 
05459    if (a->argc == 5) {
05460       channel = atoi(a->argv[4]);
05461       misdn_lib_send_restart(port, channel);
05462    } else {
05463       misdn_lib_send_restart(port, -1);
05464    }
05465 
05466    return CLI_SUCCESS;
05467 }
05468 
05469 static char *handle_cli_misdn_send_digit(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05470 {
05471    const char *channame;
05472    const char *msg;
05473    struct chan_list *tmp;
05474    int i, msglen;
05475 
05476    switch (cmd) {
05477    case CLI_INIT:
05478       e->command = "misdn send digit";
05479       e->usage =
05480          "Usage: misdn send digit <channel> \"<msg>\" \n"
05481          "       Send <digit> to <channel> as DTMF Tone\n"
05482          "       when channel is a mISDN channel\n";
05483       return NULL;
05484    case CLI_GENERATE:
05485       return complete_ch(a);
05486    }
05487 
05488    if (a->argc != 5) {
05489       return CLI_SHOWUSAGE;
05490    }
05491 
05492    channame = a->argv[3];
05493    msg = a->argv[4];
05494    msglen = strlen(msg);
05495 
05496    ast_cli(a->fd, "Sending %s to %s\n", msg, channame);
05497 
05498    tmp = get_chan_by_ast_name(channame);
05499    if (!tmp) {
05500       ast_cli(a->fd, "Sending %s to %s failed Channel does not exist\n", msg, channame);
05501       return CLI_SUCCESS;
05502    }
05503 #if 1
05504    for (i = 0; i < msglen; i++) {
05505       ast_cli(a->fd, "Sending: %c\n", msg[i]);
05506       send_digit_to_chan(tmp, msg[i]);
05507       /* res = ast_safe_sleep(tmp->ast, 250); */
05508       usleep(250000);
05509       /* res = ast_waitfor(tmp->ast,100); */
05510    }
05511 #else
05512    ast_dtmf_stream(tmp->ast, NULL, msg, 250);
05513 #endif
05514 
05515    return CLI_SUCCESS;
05516 }
05517 
05518 static char *handle_cli_misdn_toggle_echocancel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05519 {
05520    const char *channame;
05521    struct chan_list *tmp;
05522 
05523    switch (cmd) {
05524    case CLI_INIT:
05525       e->command = "misdn toggle echocancel";
05526       e->usage =
05527          "Usage: misdn toggle echocancel <channel>\n"
05528          "       Toggle EchoCancel on mISDN Channel.\n";
05529       return NULL;
05530    case CLI_GENERATE:
05531       return complete_ch(a);
05532    }
05533 
05534    if (a->argc != 4) {
05535       return CLI_SHOWUSAGE;
05536    }
05537 
05538    channame = a->argv[3];
05539 
05540    ast_cli(a->fd, "Toggling EchoCancel on %s\n", channame);
05541 
05542    tmp = get_chan_by_ast_name(channame);
05543    if (!tmp) {
05544       ast_cli(a->fd, "Toggling EchoCancel %s failed Channel does not exist\n", channame);
05545       return CLI_SUCCESS;
05546    }
05547 
05548    tmp->toggle_ec = tmp->toggle_ec ? 0 : 1;
05549 
05550    if (tmp->toggle_ec) {
05551 #ifdef MISDN_1_2
05552       update_pipeline_config(tmp->bc);
05553 #else
05554       update_ec_config(tmp->bc);
05555 #endif
05556       manager_ec_enable(tmp->bc);
05557    } else {
05558       manager_ec_disable(tmp->bc);
05559    }
05560 
05561    return CLI_SUCCESS;
05562 }
05563 
05564 static char *handle_cli_misdn_send_display(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05565 {
05566    const char *channame;
05567    const char *msg;
05568    struct chan_list *tmp;
05569 
05570    switch (cmd) {
05571    case CLI_INIT:
05572       e->command = "misdn send display";
05573       e->usage =
05574          "Usage: misdn send display <channel> \"<msg>\" \n"
05575          "       Send <msg> to <channel> as Display Message\n"
05576          "       when channel is a mISDN channel\n";
05577       return NULL;
05578    case CLI_GENERATE:
05579       return complete_ch(a);
05580    }
05581 
05582    if (a->argc != 5) {
05583       return CLI_SHOWUSAGE;
05584    }
05585 
05586    channame = a->argv[3];
05587    msg = a->argv[4];
05588 
05589    ast_cli(a->fd, "Sending %s to %s\n", msg, channame);
05590    tmp = get_chan_by_ast_name(channame);
05591 
05592    if (tmp && tmp->bc) {
05593       ast_copy_string(tmp->bc->display, msg, sizeof(tmp->bc->display));
05594       misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
05595    } else {
05596       ast_cli(a->fd, "No such channel %s\n", channame);
05597       return CLI_SUCCESS;
05598    }
05599 
05600    return CLI_SUCCESS;
05601 }
05602 
05603 static char *complete_ch(struct ast_cli_args *a)
05604 {
05605    return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
05606 }
05607 
05608 static char *complete_debug_port(struct ast_cli_args *a)
05609 {
05610    if (a->n) {
05611       return NULL;
05612    }
05613 
05614    switch (a->pos) {
05615    case 4:
05616       if (a->word[0] == 'p') {
05617          return ast_strdup("port");
05618       } else if (a->word[0] == 'o') {
05619          return ast_strdup("only");
05620       }
05621       break;
05622    case 6:
05623       if (a->word[0] == 'o') {
05624          return ast_strdup("only");
05625       }
05626       break;
05627    }
05628    return NULL;
05629 }
05630 
05631 static char *complete_show_config(struct ast_cli_args *a)
05632 {
05633    char buffer[BUFFERSIZE];
05634    enum misdn_cfg_elements elem;
05635    int wordlen = strlen(a->word);
05636    int which = 0;
05637    int port = 0;
05638 
05639    switch (a->pos) {
05640    case 3:
05641       if ((!strncmp(a->word, "description", wordlen)) && (++which > a->n)) {
05642          return ast_strdup("description");
05643       }
05644       if ((!strncmp(a->word, "descriptions", wordlen)) && (++which > a->n)) {
05645          return ast_strdup("descriptions");
05646       }
05647       if ((!strncmp(a->word, "0", wordlen)) && (++which > a->n)) {
05648          return ast_strdup("0");
05649       }
05650       while ((port = misdn_cfg_get_next_port(port)) != -1) {
05651          snprintf(buffer, sizeof(buffer), "%d", port);
05652          if ((!strncmp(a->word, buffer, wordlen)) && (++which > a->n)) {
05653             return ast_strdup(buffer);
05654          }
05655       }
05656       break;
05657    case 4:
05658       if (strstr(a->line, "description ")) {
05659          for (elem = MISDN_CFG_FIRST + 1; elem < MISDN_GEN_LAST; ++elem) {
05660             if ((elem == MISDN_CFG_LAST) || (elem == MISDN_GEN_FIRST)) {
05661                continue;
05662             }
05663             misdn_cfg_get_name(elem, buffer, sizeof(buffer));
05664             if (!wordlen || !strncmp(a->word, buffer, wordlen)) {
05665                if (++which > a->n) {
05666                   return ast_strdup(buffer);
05667                }
05668             }
05669          }
05670       } else if (strstr(a->line, "descriptions ")) {
05671          if ((!wordlen || !strncmp(a->word, "general", wordlen)) && (++which > a->n)) {
05672             return ast_strdup("general");
05673          }
05674          if ((!wordlen || !strncmp(a->word, "ports", wordlen)) && (++which > a->n)) {
05675             return ast_strdup("ports");
05676          }
05677       }
05678       break;
05679    }
05680    return NULL;
05681 }
05682 
05683 static struct ast_cli_entry chan_misdn_clis[] = {
05684 /* *INDENT-OFF* */
05685    AST_CLI_DEFINE(handle_cli_misdn_port_block,        "Block the given port"),
05686    AST_CLI_DEFINE(handle_cli_misdn_port_down,         "Try to deactivate the L1 on the given port"),
05687    AST_CLI_DEFINE(handle_cli_misdn_port_unblock,      "Unblock the given port"),
05688    AST_CLI_DEFINE(handle_cli_misdn_port_up,           "Try to establish L1 on the given port"),
05689    AST_CLI_DEFINE(handle_cli_misdn_reload,            "Reload internal mISDN config, read from the config file"),
05690    AST_CLI_DEFINE(handle_cli_misdn_restart_pid,       "Restart the given pid"),
05691    AST_CLI_DEFINE(handle_cli_misdn_restart_port,      "Restart the given port"),
05692    AST_CLI_DEFINE(handle_cli_misdn_show_channel,      "Show an internal mISDN channel"),
05693    AST_CLI_DEFINE(handle_cli_misdn_show_channels,     "Show the internal mISDN channel list"),
05694    AST_CLI_DEFINE(handle_cli_misdn_show_config,       "Show internal mISDN config, read from the config file"),
05695    AST_CLI_DEFINE(handle_cli_misdn_show_port,         "Show detailed information for given port"),
05696    AST_CLI_DEFINE(handle_cli_misdn_show_ports_stats,  "Show mISDNs channel's call statistics per port"),
05697    AST_CLI_DEFINE(handle_cli_misdn_show_stacks,       "Show internal mISDN stack_list"),
05698    AST_CLI_DEFINE(handle_cli_misdn_send_facility,     "Sends a Facility Message to the mISDN Channel"),
05699    AST_CLI_DEFINE(handle_cli_misdn_send_digit,        "Send DTMF digit to mISDN Channel"),
05700    AST_CLI_DEFINE(handle_cli_misdn_send_display,      "Send Text to mISDN Channel"),
05701    AST_CLI_DEFINE(handle_cli_misdn_send_restart,      "Send a restart for every bchannel on the given port"),
05702    AST_CLI_DEFINE(handle_cli_misdn_set_crypt_debug,   "Set CryptDebuglevel of chan_misdn, at the moment, level={1,2}"),
05703    AST_CLI_DEFINE(handle_cli_misdn_set_debug,         "Set Debuglevel of chan_misdn"),
05704    AST_CLI_DEFINE(handle_cli_misdn_set_tics,          "???"),
05705    AST_CLI_DEFINE(handle_cli_misdn_toggle_echocancel, "Toggle EchoCancel on mISDN Channel"),
05706 /* *INDENT-ON* */
05707 };
05708 
05709 /*! \brief Updates caller ID information from config */
05710 static void update_config(struct chan_list *ch)
05711 {
05712    struct ast_channel *ast;
05713    struct misdn_bchannel *bc;
05714    int port;
05715    int hdlc = 0;
05716    int pres;
05717    int screen;
05718 
05719    if (!ch) {
05720       ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
05721       return;
05722    }
05723 
05724    ast = ch->ast;
05725    bc = ch->bc;
05726    if (! ast || ! bc) {
05727       ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
05728       return;
05729    }
05730 
05731    port = bc->port;
05732 
05733    chan_misdn_log(7, port, "update_config: Getting Config\n");
05734 
05735    misdn_cfg_get(port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
05736    if (hdlc) {
05737       switch (bc->capability) {
05738       case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
05739       case INFO_CAPABILITY_DIGITAL_RESTRICTED:
05740          chan_misdn_log(1, bc->port, " --> CONF HDLC\n");
05741          bc->hdlc = 1;
05742          break;
05743       }
05744    }
05745 
05746 
05747    misdn_cfg_get(port, MISDN_CFG_PRES, &pres, sizeof(pres));
05748    misdn_cfg_get(port, MISDN_CFG_SCREEN, &screen, sizeof(screen));
05749    chan_misdn_log(2, port, " --> pres: %d screen: %d\n", pres, screen);
05750 
05751    if (pres < 0 || screen < 0) {
05752       chan_misdn_log(2, port, " --> pres: %x\n", ast->connected.id.number.presentation);
05753 
05754       bc->caller.presentation = ast_to_misdn_pres(ast->connected.id.number.presentation);
05755       chan_misdn_log(2, port, " --> PRES: %s(%d)\n", misdn_to_str_pres(bc->caller.presentation), bc->caller.presentation);
05756 
05757       bc->caller.screening = ast_to_misdn_screen(ast->connected.id.number.presentation);
05758       chan_misdn_log(2, port, " --> SCREEN: %s(%d)\n", misdn_to_str_screen(bc->caller.screening), bc->caller.screening);
05759    } else {
05760       bc->caller.screening = screen;
05761       bc->caller.presentation = pres;
05762    }
05763 }
05764 
05765 
05766 static void config_jitterbuffer(struct chan_list *ch)
05767 {
05768    struct misdn_bchannel *bc = ch->bc;
05769    int len = ch->jb_len;
05770    int threshold = ch->jb_upper_threshold;
05771 
05772    chan_misdn_log(5, bc->port, "config_jb: Called\n");
05773 
05774    if (!len) {
05775       chan_misdn_log(1, bc->port, "config_jb: Deactivating Jitterbuffer\n");
05776       bc->nojitter = 1;
05777    } else {
05778       if (len <= 100 || len > 8000) {
05779          chan_misdn_log(0, bc->port, "config_jb: Jitterbuffer out of Bounds, setting to 1000\n");
05780          len = 1000;
05781       }
05782 
05783       if (threshold > len) {
05784          chan_misdn_log(0, bc->port, "config_jb: Jitterbuffer Threshold > Jitterbuffer setting to Jitterbuffer -1\n");
05785       }
05786 
05787       if (ch->jb) {
05788          cb_log(0, bc->port, "config_jb: We've got a Jitterbuffer Already on this port.\n");
05789          misdn_jb_destroy(ch->jb);
05790          ch->jb = NULL;
05791       }
05792 
05793       ch->jb = misdn_jb_init(len, threshold);
05794 
05795       if (!ch->jb) {
05796          bc->nojitter = 1;
05797       }
05798    }
05799 }
05800 
05801 
05802 void debug_numtype(int port, int numtype, char *type)
05803 {
05804    switch (numtype) {
05805    case NUMTYPE_UNKNOWN:
05806       chan_misdn_log(2, port, " --> %s: Unknown\n", type);
05807       break;
05808    case NUMTYPE_INTERNATIONAL:
05809       chan_misdn_log(2, port, " --> %s: International\n", type);
05810       break;
05811    case NUMTYPE_NATIONAL:
05812       chan_misdn_log(2, port, " --> %s: National\n", type);
05813       break;
05814    case NUMTYPE_NETWORK_SPECIFIC:
05815       chan_misdn_log(2, port, " --> %s: Network Specific\n", type);
05816       break;
05817    case NUMTYPE_SUBSCRIBER:
05818       chan_misdn_log(2, port, " --> %s: Subscriber\n", type);
05819       break;
05820    case NUMTYPE_ABBREVIATED:
05821       chan_misdn_log(2, port, " --> %s: Abbreviated\n", type);
05822       break;
05823       /* Maybe we should cut off the prefix if present ? */
05824    default:
05825       chan_misdn_log(0, port, " --> !!!! Wrong dialplan setting, please see the misdn.conf sample file\n ");
05826       break;
05827    }
05828 }
05829 
05830 
05831 #ifdef MISDN_1_2
05832 static int update_pipeline_config(struct misdn_bchannel *bc)
05833 {
05834    int ec;
05835 
05836    misdn_cfg_get(bc->port, MISDN_CFG_PIPELINE, bc->pipeline, sizeof(bc->pipeline));
05837 
05838    if (*bc->pipeline) {
05839       return 0;
05840    }
05841 
05842    misdn_cfg_get(bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(ec));
05843    if (ec == 1) {
05844       ast_copy_string(bc->pipeline, "mg2ec", sizeof(bc->pipeline));
05845    } else if (ec > 1) {
05846       snprintf(bc->pipeline, sizeof(bc->pipeline), "mg2ec(deftaps=%d)", ec);
05847    }
05848 
05849    return 0;
05850 }
05851 #else
05852 static int update_ec_config(struct misdn_bchannel *bc)
05853 {
05854    int ec;
05855    int port = bc->port;
05856 
05857    misdn_cfg_get(port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(ec));
05858 
05859    if (ec == 1) {
05860       bc->ec_enable = 1;
05861    } else if (ec > 1) {
05862       bc->ec_enable = 1;
05863       bc->ec_deftaps = ec;
05864    }
05865 
05866    return 0;
05867 }
05868 #endif
05869 
05870 
05871 static int read_config(struct chan_list *ch)
05872 {
05873    struct ast_channel *ast;
05874    struct misdn_bchannel *bc;
05875    int port;
05876    int hdlc = 0;
05877    char lang[BUFFERSIZE + 1];
05878    char faxdetect[BUFFERSIZE + 1];
05879    char buf[256];
05880    char buf2[256];
05881    ast_group_t pg;
05882    ast_group_t cg;
05883 
05884    if (!ch) {
05885       ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
05886       return -1;
05887    }
05888 
05889    ast = ch->ast;
05890    bc = ch->bc;
05891    if (! ast || ! bc) {
05892       ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
05893       return -1;
05894    }
05895 
05896    port = bc->port;
05897    chan_misdn_log(1, port, "read_config: Getting Config\n");
05898 
05899    misdn_cfg_get(port, MISDN_CFG_LANGUAGE, lang, sizeof(lang));
05900    ast_string_field_set(ast, language, lang);
05901 
05902    misdn_cfg_get(port, MISDN_CFG_MUSICCLASS, ch->mohinterpret, sizeof(ch->mohinterpret));
05903 
05904    misdn_cfg_get(port, MISDN_CFG_TXGAIN, &bc->txgain, sizeof(bc->txgain));
05905    misdn_cfg_get(port, MISDN_CFG_RXGAIN, &bc->rxgain, sizeof(bc->rxgain));
05906 
05907    misdn_cfg_get(port, MISDN_CFG_INCOMING_EARLY_AUDIO, &ch->incoming_early_audio, sizeof(ch->incoming_early_audio));
05908 
05909    misdn_cfg_get(port, MISDN_CFG_SENDDTMF, &bc->send_dtmf, sizeof(bc->send_dtmf));
05910 
05911    misdn_cfg_get(port, MISDN_CFG_ASTDTMF, &ch->ast_dsp, sizeof(int));
05912    if (ch->ast_dsp) {
05913       ch->ignore_dtmf = 1;
05914    }
05915 
05916    misdn_cfg_get(port, MISDN_CFG_NEED_MORE_INFOS, &bc->need_more_infos, sizeof(bc->need_more_infos));
05917    misdn_cfg_get(port, MISDN_CFG_NTTIMEOUT, &ch->nttimeout, sizeof(ch->nttimeout));
05918 
05919    misdn_cfg_get(port, MISDN_CFG_NOAUTORESPOND_ON_SETUP, &ch->noautorespond_on_setup, sizeof(ch->noautorespond_on_setup));
05920 
05921    misdn_cfg_get(port, MISDN_CFG_FAR_ALERTING, &ch->far_alerting, sizeof(ch->far_alerting));
05922 
05923    misdn_cfg_get(port, MISDN_CFG_ALLOWED_BEARERS, &ch->allowed_bearers, sizeof(ch->allowed_bearers));
05924 
05925    misdn_cfg_get(port, MISDN_CFG_FAXDETECT, faxdetect, sizeof(faxdetect));
05926 
05927    misdn_cfg_get(port, MISDN_CFG_HDLC, &hdlc, sizeof(hdlc));
05928    if (hdlc) {
05929       switch (bc->capability) {
05930       case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
05931       case INFO_CAPABILITY_DIGITAL_RESTRICTED:
05932          chan_misdn_log(1, bc->port, " --> CONF HDLC\n");
05933          bc->hdlc = 1;
05934          break;
05935       }
05936 
05937    }
05938    /*Initialize new Jitterbuffer*/
05939    misdn_cfg_get(port, MISDN_CFG_JITTERBUFFER, &ch->jb_len, sizeof(ch->jb_len));
05940    misdn_cfg_get(port, MISDN_CFG_JITTERBUFFER_UPPER_THRESHOLD, &ch->jb_upper_threshold, sizeof(ch->jb_upper_threshold));
05941 
05942    config_jitterbuffer(ch);
05943 
05944    misdn_cfg_get(bc->port, MISDN_CFG_CONTEXT, ch->context, sizeof(ch->context));
05945 
05946    ast_copy_string(ast->context, ch->context, sizeof(ast->context));
05947 
05948 #ifdef MISDN_1_2
05949    update_pipeline_config(bc);
05950 #else
05951    update_ec_config(bc);
05952 #endif
05953 
05954    misdn_cfg_get(bc->port, MISDN_CFG_EARLY_BCONNECT, &bc->early_bconnect, sizeof(bc->early_bconnect));
05955 
05956    misdn_cfg_get(port, MISDN_CFG_DISPLAY_CONNECTED, &bc->display_connected, sizeof(bc->display_connected));
05957    misdn_cfg_get(port, MISDN_CFG_DISPLAY_SETUP, &bc->display_setup, sizeof(bc->display_setup));
05958    misdn_cfg_get(port, MISDN_CFG_OUTGOING_COLP, &bc->outgoing_colp, sizeof(bc->outgoing_colp));
05959 
05960    misdn_cfg_get(port, MISDN_CFG_PICKUPGROUP, &pg, sizeof(pg));
05961    misdn_cfg_get(port, MISDN_CFG_CALLGROUP, &cg, sizeof(cg));
05962    chan_misdn_log(5, port, " --> * CallGrp:%s PickupGrp:%s\n", ast_print_group(buf, sizeof(buf), cg), ast_print_group(buf2, sizeof(buf2), pg));
05963    ast->pickupgroup = pg;
05964    ast->callgroup = cg;
05965 
05966    if (ch->originator == ORG_AST) {
05967       char callerid[BUFFERSIZE + 1];
05968 
05969       /* ORIGINATOR Asterisk (outgoing call) */
05970 
05971       misdn_cfg_get(port, MISDN_CFG_TE_CHOOSE_CHANNEL, &(bc->te_choose_channel), sizeof(bc->te_choose_channel));
05972 
05973       if (strstr(faxdetect, "outgoing") || strstr(faxdetect, "both")) {
05974          ch->faxdetect = strstr(faxdetect, "nojump") ? 2 : 1;
05975       }
05976 
05977       misdn_cfg_get(port, MISDN_CFG_CALLERID, callerid, sizeof(callerid));
05978       if (!ast_strlen_zero(callerid)) {
05979          char *cid_name = NULL;
05980          char *cid_num = NULL;
05981 
05982          ast_callerid_parse(callerid, &cid_name, &cid_num);
05983          if (cid_name) {
05984             ast_copy_string(bc->caller.name, cid_name, sizeof(bc->caller.name));
05985          } else {
05986             bc->caller.name[0] = '\0';
05987          }
05988          if (cid_num) {
05989             ast_copy_string(bc->caller.number, cid_num, sizeof(bc->caller.number));
05990          } else {
05991             bc->caller.number[0] = '\0';
05992          }
05993          chan_misdn_log(1, port, " --> * Setting caller to \"%s\" <%s>\n", bc->caller.name, bc->caller.number);
05994       }
05995 
05996       misdn_cfg_get(port, MISDN_CFG_DIALPLAN, &bc->dialed.number_type, sizeof(bc->dialed.number_type));
05997       bc->dialed.number_plan = NUMPLAN_ISDN;
05998       debug_numtype(port, bc->dialed.number_type, "TON");
05999 
06000       ch->overlap_dial = 0;
06001    } else {
06002       /* ORIGINATOR MISDN (incoming call) */
06003 
06004       if (strstr(faxdetect, "incoming") || strstr(faxdetect, "both")) {
06005          ch->faxdetect = (strstr(faxdetect, "nojump")) ? 2 : 1;
06006       }
06007 
06008       /* Add configured prefix to caller.number */
06009       misdn_add_number_prefix(bc->port, bc->caller.number_type, bc->caller.number, sizeof(bc->caller.number));
06010 
06011       if (ast_strlen_zero(bc->dialed.number) && !ast_strlen_zero(bc->keypad)) {
06012          ast_copy_string(bc->dialed.number, bc->keypad, sizeof(bc->dialed.number));
06013       }
06014 
06015       /* Add configured prefix to dialed.number */
06016       misdn_add_number_prefix(bc->port, bc->dialed.number_type, bc->dialed.number, sizeof(bc->dialed.number));
06017 
06018       ast_copy_string(ast->exten, bc->dialed.number, sizeof(ast->exten));
06019 
06020       misdn_cfg_get(bc->port, MISDN_CFG_OVERLAP_DIAL, &ch->overlap_dial, sizeof(ch->overlap_dial));
06021       ast_mutex_init(&ch->overlap_tv_lock);
06022    } /* ORIG MISDN END */
06023 
06024    misdn_cfg_get(port, MISDN_CFG_INCOMING_CALLERID_TAG, bc->incoming_cid_tag, sizeof(bc->incoming_cid_tag));
06025    if (!ast_strlen_zero(bc->incoming_cid_tag)) {
06026       chan_misdn_log(1, port, " --> * Setting incoming caller id tag to \"%s\"\n", bc->incoming_cid_tag);
06027    }
06028    ch->overlap_dial_task = -1;
06029 
06030    if (ch->faxdetect  || ch->ast_dsp) {
06031       misdn_cfg_get(port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
06032       if (!ch->dsp) {
06033          ch->dsp = ast_dsp_new();
06034       }
06035       if (ch->dsp) {
06036          ast_dsp_set_features(ch->dsp, DSP_FEATURE_DIGIT_DETECT | (ch->faxdetect ? DSP_FEATURE_FAX_DETECT : 0));
06037       }
06038    }
06039 
06040    /* AOCD initialization */
06041    bc->AOCDtype = Fac_None;
06042 
06043    return 0;
06044 }
06045 
06046 /*!
06047  * \internal
06048  * \brief Send a connected line update to the other channel
06049  *
06050  * \param ast Current Asterisk channel
06051  * \param id Party id information to send to the other side
06052  * \param source Why are we sending this update
06053  * \param cid_tag User tag to apply to the party id.
06054  *
06055  * \return Nothing
06056  */
06057 static void misdn_queue_connected_line_update(struct ast_channel *ast, const struct misdn_party_id *id, enum AST_CONNECTED_LINE_UPDATE_SOURCE source, char *cid_tag)
06058 {
06059    struct ast_party_connected_line connected;
06060    struct ast_set_party_connected_line update_connected;
06061 
06062    ast_party_connected_line_init(&connected);
06063    memset(&update_connected, 0, sizeof(update_connected));
06064    update_connected.id.number = 1;
06065    connected.id.number.valid = 1;
06066    connected.id.number.str = (char *) id->number;
06067    connected.id.number.plan = misdn_to_ast_ton(id->number_type)
06068       | misdn_to_ast_plan(id->number_plan);
06069    connected.id.number.presentation = misdn_to_ast_pres(id->presentation)
06070       | misdn_to_ast_screen(id->screening);
06071    connected.id.tag = cid_tag;
06072    connected.source = source;
06073    ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
06074 }
06075 
06076 /*!
06077  * \internal
06078  * \brief Update the caller id party on this channel.
06079  *
06080  * \param ast Current Asterisk channel
06081  * \param id Remote party id information to update.
06082  * \param cid_tag User tag to apply to the party id.
06083  *
06084  * \return Nothing
06085  */
06086 static void misdn_update_caller_id(struct ast_channel *ast, const struct misdn_party_id *id, char *cid_tag)
06087 {
06088    struct ast_party_caller caller;
06089    struct ast_set_party_caller update_caller;
06090 
06091    memset(&update_caller, 0, sizeof(update_caller));
06092    update_caller.id.number = 1;
06093    update_caller.ani.number = 1;
06094 
06095    ast_channel_lock(ast);
06096    ast_party_caller_set_init(&caller, &ast->caller);
06097 
06098    caller.id.number.valid = 1;
06099    caller.id.number.str = (char *) id->number;
06100    caller.id.number.plan = misdn_to_ast_ton(id->number_type)
06101       | misdn_to_ast_plan(id->number_plan);
06102    caller.id.number.presentation = misdn_to_ast_pres(id->presentation)
06103       | misdn_to_ast_screen(id->screening);
06104 
06105    caller.ani.number = caller.id.number;
06106 
06107    caller.id.tag = cid_tag;
06108    caller.ani.tag = cid_tag;
06109 
06110    ast_channel_set_caller_event(ast, &caller, &update_caller);
06111    ast_channel_unlock(ast);
06112 }
06113 
06114 /*!
06115  * \internal
06116  * \brief Update the remote party id information.
06117  *
06118  * \param ast Current Asterisk channel
06119  * \param id Remote party id information to update.
06120  * \param source Why are we sending this update
06121  * \param cid_tag User tag to apply to the party id.
06122  *
06123  * \return Nothing
06124  */
06125 static void misdn_update_remote_party(struct ast_channel *ast, const struct misdn_party_id *id, enum AST_CONNECTED_LINE_UPDATE_SOURCE source, char *cid_tag)
06126 {
06127    misdn_update_caller_id(ast, id, cid_tag);
06128    misdn_queue_connected_line_update(ast, id, source, cid_tag);
06129 }
06130 
06131 /*!
06132  * \internal
06133  * \brief Get the connected line information out of the Asterisk channel.
06134  *
06135  * \param ast Current Asterisk channel
06136  * \param bc Associated B channel
06137  * \param originator Who originally created this channel. ORG_AST or ORG_MISDN
06138  *
06139  * \return Nothing
06140  */
06141 static void misdn_get_connected_line(struct ast_channel *ast, struct misdn_bchannel *bc, int originator)
06142 {
06143    int number_type;
06144 
06145    if (originator == ORG_MISDN) {
06146       /* ORIGINATOR MISDN (incoming call) */
06147 
06148       ast_copy_string(bc->connected.name,
06149          S_COR(ast->connected.id.name.valid, ast->connected.id.name.str, ""),
06150          sizeof(bc->connected.name));
06151       if (ast->connected.id.number.valid) {
06152          ast_copy_string(bc->connected.number, S_OR(ast->connected.id.number.str, ""),
06153             sizeof(bc->connected.number));
06154          bc->connected.presentation = ast_to_misdn_pres(ast->connected.id.number.presentation);
06155          bc->connected.screening = ast_to_misdn_screen(ast->connected.id.number.presentation);
06156          bc->connected.number_type = ast_to_misdn_ton(ast->connected.id.number.plan);
06157          bc->connected.number_plan = ast_to_misdn_plan(ast->connected.id.number.plan);
06158       } else {
06159          bc->connected.number[0] = '\0';
06160          bc->connected.presentation = 0;/* Allowed */
06161          bc->connected.screening = 0;/* Unscreened */
06162          bc->connected.number_type = NUMTYPE_UNKNOWN;
06163          bc->connected.number_plan = NUMPLAN_UNKNOWN;
06164       }
06165 
06166       misdn_cfg_get(bc->port, MISDN_CFG_CPNDIALPLAN, &number_type, sizeof(number_type));
06167       if (0 <= number_type) {
06168          /* Force us to send in CONNECT message */
06169          bc->connected.number_type = number_type;
06170          bc->connected.number_plan = NUMPLAN_ISDN;
06171       }
06172       debug_numtype(bc->port, bc->connected.number_type, "CTON");
06173    } else {
06174       /* ORIGINATOR Asterisk (outgoing call) */
06175 
06176       ast_copy_string(bc->caller.name,
06177          S_COR(ast->connected.id.name.valid, ast->connected.id.name.str, ""),
06178          sizeof(bc->caller.name));
06179       if (ast->connected.id.number.valid) {
06180          ast_copy_string(bc->caller.number, S_OR(ast->connected.id.number.str, ""),
06181             sizeof(bc->caller.number));
06182          bc->caller.presentation = ast_to_misdn_pres(ast->connected.id.number.presentation);
06183          bc->caller.screening = ast_to_misdn_screen(ast->connected.id.number.presentation);
06184          bc->caller.number_type = ast_to_misdn_ton(ast->connected.id.number.plan);
06185          bc->caller.number_plan = ast_to_misdn_plan(ast->connected.id.number.plan);
06186       } else {
06187          bc->caller.number[0] = '\0';
06188          bc->caller.presentation = 0;/* Allowed */
06189          bc->caller.screening = 0;/* Unscreened */
06190          bc->caller.number_type = NUMTYPE_UNKNOWN;
06191          bc->caller.number_plan = NUMPLAN_UNKNOWN;
06192       }
06193 
06194       misdn_cfg_get(bc->port, MISDN_CFG_LOCALDIALPLAN, &number_type, sizeof(number_type));
06195       if (0 <= number_type) {
06196          /* Force us to send in SETUP message */
06197          bc->caller.number_type = number_type;
06198          bc->caller.number_plan = NUMPLAN_ISDN;
06199       }
06200       debug_numtype(bc->port, bc->caller.number_type, "LTON");
06201    }
06202 }
06203 
06204 /*!
06205  * \internal
06206  * \brief Notify peer that the connected line has changed.
06207  *
06208  * \param ast Current Asterisk channel
06209  * \param bc Associated B channel
06210  * \param originator Who originally created this channel. ORG_AST or ORG_MISDN
06211  *
06212  * \return Nothing
06213  */
06214 static void misdn_update_connected_line(struct ast_channel *ast, struct misdn_bchannel *bc, int originator)
06215 {
06216    struct chan_list *ch;
06217 
06218    misdn_get_connected_line(ast, bc, originator);
06219    if (originator == ORG_MISDN) {
06220       bc->redirecting.to = bc->connected;
06221    } else {
06222       bc->redirecting.to = bc->caller;
06223    }
06224    switch (bc->outgoing_colp) {
06225    case 1:/* restricted */
06226       bc->redirecting.to.presentation = 1;/* restricted */
06227       break;
06228    case 2:/* blocked */
06229       /* Don't tell the remote party that the call was transferred. */
06230       return;
06231    default:
06232       break;
06233    }
06234 
06235    ch = MISDN_ASTERISK_TECH_PVT(ast);
06236    if (ch->state == MISDN_CONNECTED
06237       || originator != ORG_MISDN) {
06238       int is_ptmp;
06239 
06240       is_ptmp = !misdn_lib_is_ptp(bc->port);
06241       if (is_ptmp) {
06242          /*
06243           * We should not send these messages to the network if we are
06244           * the CPE side since phones do not transfer calls within
06245           * themselves.  Well... If you consider handing the handset to
06246           * someone else a transfer then how is the network to know?
06247           */
06248          if (!misdn_lib_port_is_nt(bc->port)) {
06249             return;
06250          }
06251          if (ch->state != MISDN_CONNECTED) {
06252             /* Send NOTIFY(Nie(transfer-active), RDNie(redirecting.to data)) */
06253             bc->redirecting.to_changed = 1;
06254             bc->notify_description_code = mISDN_NOTIFY_CODE_CALL_TRANSFER_ACTIVE;
06255             misdn_lib_send_event(bc, EVENT_NOTIFY);
06256 #if defined(AST_MISDN_ENHANCEMENTS)
06257          } else {
06258             /* Send FACILITY(Fie(RequestSubaddress), Nie(transfer-active), RDNie(redirecting.to data)) */
06259             bc->redirecting.to_changed = 1;
06260             bc->notify_description_code = mISDN_NOTIFY_CODE_CALL_TRANSFER_ACTIVE;
06261             bc->fac_out.Function = Fac_RequestSubaddress;
06262             bc->fac_out.u.RequestSubaddress.InvokeID = ++misdn_invoke_id;
06263 
06264             /* Send message */
06265             print_facility(&bc->fac_out, bc);
06266             misdn_lib_send_event(bc, EVENT_FACILITY);
06267 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
06268          }
06269 #if defined(AST_MISDN_ENHANCEMENTS)
06270       } else {
06271          /* Send FACILITY(Fie(EctInform(transfer-active, redirecting.to data))) */
06272          bc->fac_out.Function = Fac_EctInform;
06273          bc->fac_out.u.EctInform.InvokeID = ++misdn_invoke_id;
06274          bc->fac_out.u.EctInform.Status = 1;/* active */
06275          bc->fac_out.u.EctInform.RedirectionPresent = 1;/* Must be present when status is active */
06276          misdn_PresentedNumberUnscreened_fill(&bc->fac_out.u.EctInform.Redirection,
06277             &bc->redirecting.to);
06278 
06279          /* Send message */
06280          print_facility(&bc->fac_out, bc);
06281          misdn_lib_send_event(bc, EVENT_FACILITY);
06282 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
06283       }
06284    }
06285 }
06286 
06287 /*!
06288  * \internal
06289  * \brief Copy the redirecting information out of the Asterisk channel
06290  *
06291  * \param bc Associated B channel
06292  * \param ast Current Asterisk channel
06293  *
06294  * \return Nothing
06295  */
06296 static void misdn_copy_redirecting_from_ast(struct misdn_bchannel *bc, struct ast_channel *ast)
06297 {
06298    ast_copy_string(bc->redirecting.from.name,
06299       S_COR(ast->redirecting.from.name.valid, ast->redirecting.from.name.str, ""),
06300       sizeof(bc->redirecting.from.name));
06301    if (ast->redirecting.from.number.valid) {
06302       ast_copy_string(bc->redirecting.from.number, S_OR(ast->redirecting.from.number.str, ""),
06303          sizeof(bc->redirecting.from.number));
06304       bc->redirecting.from.presentation = ast_to_misdn_pres(ast->redirecting.from.number.presentation);
06305       bc->redirecting.from.screening = ast_to_misdn_screen(ast->redirecting.from.number.presentation);
06306       bc->redirecting.from.number_type = ast_to_misdn_ton(ast->redirecting.from.number.plan);
06307       bc->redirecting.from.number_plan = ast_to_misdn_plan(ast->redirecting.from.number.plan);
06308    } else {
06309       bc->redirecting.from.number[0] = '\0';
06310       bc->redirecting.from.presentation = 0;/* Allowed */
06311       bc->redirecting.from.screening = 0;/* Unscreened */
06312       bc->redirecting.from.number_type = NUMTYPE_UNKNOWN;
06313       bc->redirecting.from.number_plan = NUMPLAN_UNKNOWN;
06314    }
06315 
06316    ast_copy_string(bc->redirecting.to.name,
06317       S_COR(ast->redirecting.to.name.valid, ast->redirecting.to.name.str, ""),
06318       sizeof(bc->redirecting.to.name));
06319    if (ast->redirecting.to.number.valid) {
06320       ast_copy_string(bc->redirecting.to.number, S_OR(ast->redirecting.to.number.str, ""),
06321          sizeof(bc->redirecting.to.number));
06322       bc->redirecting.to.presentation = ast_to_misdn_pres(ast->redirecting.to.number.presentation);
06323       bc->redirecting.to.screening = ast_to_misdn_screen(ast->redirecting.to.number.presentation);
06324       bc->redirecting.to.number_type = ast_to_misdn_ton(ast->redirecting.to.number.plan);
06325       bc->redirecting.to.number_plan = ast_to_misdn_plan(ast->redirecting.to.number.plan);
06326    } else {
06327       bc->redirecting.to.number[0] = '\0';
06328       bc->redirecting.to.presentation = 0;/* Allowed */
06329       bc->redirecting.to.screening = 0;/* Unscreened */
06330       bc->redirecting.to.number_type = NUMTYPE_UNKNOWN;
06331       bc->redirecting.to.number_plan = NUMPLAN_UNKNOWN;
06332    }
06333 
06334    bc->redirecting.reason = ast_to_misdn_reason(ast->redirecting.reason);
06335    bc->redirecting.count = ast->redirecting.count;
06336 }
06337 
06338 /*!
06339  * \internal
06340  * \brief Copy the redirecting info into the Asterisk channel
06341  *
06342  * \param ast Current Asterisk channel
06343  * \param redirect Associated B channel redirecting info
06344  * \param tag Caller ID tag to set in the redirecting party fields
06345  *
06346  * \return Nothing
06347  */
06348 static void misdn_copy_redirecting_to_ast(struct ast_channel *ast, const struct misdn_party_redirecting *redirect, char *tag)
06349 {
06350    struct ast_party_redirecting redirecting;
06351    struct ast_set_party_redirecting update_redirecting;
06352 
06353    ast_party_redirecting_set_init(&redirecting, &ast->redirecting);
06354    memset(&update_redirecting, 0, sizeof(update_redirecting));
06355 
06356    update_redirecting.from.number = 1;
06357    redirecting.from.number.valid = 1;
06358    redirecting.from.number.str = (char *) redirect->from.number;
06359    redirecting.from.number.plan =
06360       misdn_to_ast_ton(redirect->from.number_type)
06361       | misdn_to_ast_plan(redirect->from.number_plan);
06362    redirecting.from.number.presentation =
06363       misdn_to_ast_pres(redirect->from.presentation)
06364       | misdn_to_ast_screen(redirect->from.screening);
06365    redirecting.from.tag = tag;
06366 
06367    update_redirecting.to.number = 1;
06368    redirecting.to.number.valid = 1;
06369    redirecting.to.number.str = (char *) redirect->to.number;
06370    redirecting.to.number.plan =
06371       misdn_to_ast_ton(redirect->to.number_type)
06372       | misdn_to_ast_plan(redirect->to.number_plan);
06373    redirecting.to.number.presentation =
06374       misdn_to_ast_pres(redirect->to.presentation)
06375       | misdn_to_ast_screen(redirect->to.screening);
06376    redirecting.to.tag = tag;
06377 
06378    redirecting.reason = misdn_to_ast_reason(redirect->reason);
06379    redirecting.count = redirect->count;
06380 
06381    ast_channel_set_redirecting(ast, &redirecting, &update_redirecting);
06382 }
06383 
06384 /*!
06385  * \internal
06386  * \brief Notify peer that the redirecting information has changed.
06387  *
06388  * \param ast Current Asterisk channel
06389  * \param bc Associated B channel
06390  * \param originator Who originally created this channel. ORG_AST or ORG_MISDN
06391  *
06392  * \return Nothing
06393  */
06394 static void misdn_update_redirecting(struct ast_channel *ast, struct misdn_bchannel *bc, int originator)
06395 {
06396    int is_ptmp;
06397 
06398    misdn_copy_redirecting_from_ast(bc, ast);
06399    switch (bc->outgoing_colp) {
06400    case 1:/* restricted */
06401       bc->redirecting.to.presentation = 1;/* restricted */
06402       break;
06403    case 2:/* blocked */
06404       /* Don't tell the remote party that the call was redirected. */
06405       return;
06406    default:
06407       break;
06408    }
06409 
06410    if (originator != ORG_MISDN) {
06411       return;
06412    }
06413 
06414    is_ptmp = !misdn_lib_is_ptp(bc->port);
06415    if (is_ptmp) {
06416       /* Send NOTIFY(call-is-diverting, redirecting.to data) */
06417       bc->redirecting.to_changed = 1;
06418       bc->notify_description_code = mISDN_NOTIFY_CODE_CALL_IS_DIVERTING;
06419       misdn_lib_send_event(bc, EVENT_NOTIFY);
06420 #if defined(AST_MISDN_ENHANCEMENTS)
06421    } else {
06422       int match;  /* TRUE if the dialed number matches the redirecting to number */
06423 
06424       match = (strcmp(ast->exten, bc->redirecting.to.number) == 0) ? 1 : 0;
06425       if (!bc->div_leg_3_tx_pending
06426          || !match) {
06427          /* Send DivertingLegInformation1 */
06428          bc->fac_out.Function = Fac_DivertingLegInformation1;
06429          bc->fac_out.u.DivertingLegInformation1.InvokeID = ++misdn_invoke_id;
06430          bc->fac_out.u.DivertingLegInformation1.DiversionReason =
06431             misdn_to_diversion_reason(bc->redirecting.reason);
06432          bc->fac_out.u.DivertingLegInformation1.SubscriptionOption = 2;/* notificationWithDivertedToNr */
06433          bc->fac_out.u.DivertingLegInformation1.DivertedToPresent = 1;
06434          misdn_PresentedNumberUnscreened_fill(&bc->fac_out.u.DivertingLegInformation1.DivertedTo, &bc->redirecting.to);
06435          print_facility(&bc->fac_out, bc);
06436          misdn_lib_send_event(bc, EVENT_FACILITY);
06437       }
06438       bc->div_leg_3_tx_pending = 0;
06439 
06440       /* Send DivertingLegInformation3 */
06441       bc->fac_out.Function = Fac_DivertingLegInformation3;
06442       bc->fac_out.u.DivertingLegInformation3.InvokeID = ++misdn_invoke_id;
06443       bc->fac_out.u.DivertingLegInformation3.PresentationAllowedIndicator =
06444          bc->redirecting.to.presentation == 0 ? 1 : 0;
06445       print_facility(&bc->fac_out, bc);
06446       misdn_lib_send_event(bc, EVENT_FACILITY);
06447 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
06448    }
06449 }
06450 
06451 
06452 /*****************************/
06453 /*** AST Indications Start ***/
06454 /*****************************/
06455 
06456 static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
06457 {
06458    int port = 0;
06459    int r;
06460    int exceed;
06461    int bridging;
06462    int number_type;
06463    struct chan_list *ch;
06464    struct misdn_bchannel *newbc;
06465    char *dest_cp;
06466    int append_msn = 0;
06467 
06468    AST_DECLARE_APP_ARGS(args,
06469       AST_APP_ARG(intf);   /* The interface token is discarded. */
06470       AST_APP_ARG(ext); /* extension token */
06471       AST_APP_ARG(opts);   /* options token */
06472    );
06473 
06474    if (!ast) {
06475       ast_log(LOG_WARNING, " --> ! misdn_call called on ast_channel *ast where ast == NULL\n");
06476       return -1;
06477    }
06478 
06479    if (((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) || !dest) {
06480       ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
06481       ast->hangupcause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06482       ast_setstate(ast, AST_STATE_DOWN);
06483       return -1;
06484    }
06485 
06486    ch = MISDN_ASTERISK_TECH_PVT(ast);
06487    if (!ch) {
06488       ast_log(LOG_WARNING, " --> ! misdn_call called on %s, chan_list *ch==NULL\n", ast->name);
06489       ast->hangupcause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06490       ast_setstate(ast, AST_STATE_DOWN);
06491       return -1;
06492    }
06493 
06494    newbc = ch->bc;
06495    if (!newbc) {
06496       ast_log(LOG_WARNING, " --> ! misdn_call called on %s, newbc==NULL\n", ast->name);
06497       ast->hangupcause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06498       ast_setstate(ast, AST_STATE_DOWN);
06499       return -1;
06500    }
06501 
06502    port = newbc->port;
06503 
06504 #if defined(AST_MISDN_ENHANCEMENTS)
06505    if ((ch->peer = misdn_cc_caller_get(ast))) {
06506       chan_misdn_log(3, port, " --> Found CC caller data, peer:%s\n",
06507          ch->peer->chan ? "available" : "NULL");
06508    }
06509 
06510    if (ch->record_id != -1) {
06511       struct misdn_cc_record *cc_record;
06512 
06513       /* This is a call completion retry call */
06514       AST_LIST_LOCK(&misdn_cc_records_db);
06515       cc_record = misdn_cc_find_by_id(ch->record_id);
06516       if (!cc_record) {
06517          AST_LIST_UNLOCK(&misdn_cc_records_db);
06518          ast_log(LOG_WARNING, " --> ! misdn_call called on %s, cc_record==NULL\n", ast->name);
06519          ast->hangupcause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06520          ast_setstate(ast, AST_STATE_DOWN);
06521          return -1;
06522       }
06523 
06524       /* Setup calling parameters to retry the call. */
06525       newbc->dialed = cc_record->redial.dialed;
06526       newbc->caller = cc_record->redial.caller;
06527       memset(&newbc->redirecting, 0, sizeof(newbc->redirecting));
06528       newbc->capability = cc_record->redial.capability;
06529       newbc->hdlc = cc_record->redial.hdlc;
06530       newbc->sending_complete = 1;
06531 
06532       if (cc_record->ptp) {
06533          newbc->fac_out.Function = Fac_CCBS_T_Call;
06534          newbc->fac_out.u.CCBS_T_Call.InvokeID = ++misdn_invoke_id;
06535       } else {
06536          newbc->fac_out.Function = Fac_CCBSCall;
06537          newbc->fac_out.u.CCBSCall.InvokeID = ++misdn_invoke_id;
06538          newbc->fac_out.u.CCBSCall.CCBSReference = cc_record->mode.ptmp.reference_id;
06539       }
06540       AST_LIST_UNLOCK(&misdn_cc_records_db);
06541 
06542       ast_copy_string(ast->exten, newbc->dialed.number, sizeof(ast->exten));
06543 
06544       chan_misdn_log(1, port, "* Call completion to: %s\n", newbc->dialed.number);
06545       chan_misdn_log(2, port, " --> * tech:%s context:%s\n", ast->name, ast->context);
06546    } else
06547 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
06548    {
06549       /*
06550        * dest is ---v
06551        * Dial(mISDN/g:group_name[/extension[/options]])
06552        * Dial(mISDN/port[:preselected_channel][/extension[/options]])
06553        *
06554        * The dial extension could be empty if you are using MISDN_KEYPAD
06555        * to control ISDN provider features.
06556        */
06557       dest_cp = ast_strdupa(dest);
06558       AST_NONSTANDARD_APP_ARGS(args, dest_cp, '/');
06559       if (!args.ext) {
06560          args.ext = "";
06561       }
06562 
06563       chan_misdn_log(1, port, "* CALL: %s\n", dest);
06564       chan_misdn_log(2, port, " --> * dialed:%s tech:%s context:%s\n", args.ext, ast->name, ast->context);
06565 
06566       ast_copy_string(ast->exten, args.ext, sizeof(ast->exten));
06567       ast_copy_string(newbc->dialed.number, args.ext, sizeof(newbc->dialed.number));
06568 
06569       if (ast_strlen_zero(newbc->caller.name)
06570          && ast->connected.id.name.valid
06571          && !ast_strlen_zero(ast->connected.id.name.str)) {
06572          ast_copy_string(newbc->caller.name, ast->connected.id.name.str, sizeof(newbc->caller.name));
06573          chan_misdn_log(3, port, " --> * set caller:\"%s\" <%s>\n", newbc->caller.name, newbc->caller.number);
06574       }
06575       if (ast_strlen_zero(newbc->caller.number)
06576          && ast->connected.id.number.valid
06577          && !ast_strlen_zero(ast->connected.id.number.str)) {
06578          ast_copy_string(newbc->caller.number, ast->connected.id.number.str, sizeof(newbc->caller.number));
06579          chan_misdn_log(3, port, " --> * set caller:\"%s\" <%s>\n", newbc->caller.name, newbc->caller.number);
06580       }
06581 
06582       misdn_cfg_get(port, MISDN_CFG_APPEND_MSN_TO_CALLERID_TAG, &append_msn, sizeof(append_msn));
06583       if (append_msn) {
06584          strncat(newbc->incoming_cid_tag, "_", sizeof(newbc->incoming_cid_tag) - strlen(newbc->incoming_cid_tag) - 1);
06585          strncat(newbc->incoming_cid_tag, newbc->caller.number, sizeof(newbc->incoming_cid_tag) - strlen(newbc->incoming_cid_tag) - 1);
06586       }
06587 
06588       ast->caller.id.tag = ast_strdup(newbc->incoming_cid_tag);
06589 
06590       misdn_cfg_get(port, MISDN_CFG_LOCALDIALPLAN, &number_type, sizeof(number_type));
06591       if (number_type < 0) {
06592          if (ast->connected.id.number.valid) {
06593             newbc->caller.number_type = ast_to_misdn_ton(ast->connected.id.number.plan);
06594             newbc->caller.number_plan = ast_to_misdn_plan(ast->connected.id.number.plan);
06595          } else {
06596             newbc->caller.number_type = NUMTYPE_UNKNOWN;
06597             newbc->caller.number_plan = NUMPLAN_ISDN;
06598          }
06599       } else {
06600          /* Force us to send in SETUP message */
06601          newbc->caller.number_type = number_type;
06602          newbc->caller.number_plan = NUMPLAN_ISDN;
06603       }
06604       debug_numtype(port, newbc->caller.number_type, "LTON");
06605 
06606       newbc->capability = ast->transfercapability;
06607       pbx_builtin_setvar_helper(ast, "TRANSFERCAPABILITY", ast_transfercapability2str(newbc->capability));
06608       if (ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
06609          chan_misdn_log(2, port, " --> * Call with flag Digital\n");
06610       }
06611 
06612       /* update caller screening and presentation */
06613       update_config(ch);
06614 
06615       /* fill in some ies from channel dialplan variables */
06616       import_ch(ast, newbc, ch);
06617 
06618       /* Finally The Options Override Everything */
06619       if (!ast_strlen_zero(args.opts)) {
06620          misdn_set_opt_exec(ast, args.opts);
06621       } else {
06622          chan_misdn_log(2, port, "NO OPTS GIVEN\n");
06623       }
06624       if (newbc->set_presentation) {
06625          newbc->caller.presentation = newbc->presentation;
06626       }
06627 
06628       misdn_copy_redirecting_from_ast(newbc, ast);
06629       switch (newbc->outgoing_colp) {
06630       case 1:/* restricted */
06631       case 2:/* blocked */
06632          newbc->redirecting.from.presentation = 1;/* restricted */
06633          break;
06634       default:
06635          break;
06636       }
06637 #if defined(AST_MISDN_ENHANCEMENTS)
06638       if (newbc->redirecting.from.number[0] && misdn_lib_is_ptp(port)) {
06639          if (newbc->redirecting.count < 1) {
06640             newbc->redirecting.count = 1;
06641          }
06642 
06643          /* Create DivertingLegInformation2 facility */
06644          newbc->fac_out.Function = Fac_DivertingLegInformation2;
06645          newbc->fac_out.u.DivertingLegInformation2.InvokeID = ++misdn_invoke_id;
06646          newbc->fac_out.u.DivertingLegInformation2.DivertingPresent = 1;
06647          misdn_PresentedNumberUnscreened_fill(
06648             &newbc->fac_out.u.DivertingLegInformation2.Diverting,
06649             &newbc->redirecting.from);
06650          switch (newbc->outgoing_colp) {
06651          case 2:/* blocked */
06652             /* Block the number going out */
06653             newbc->fac_out.u.DivertingLegInformation2.Diverting.Type = 1;/* presentationRestricted */
06654 
06655             /* Don't tell about any previous diversions or why for that matter. */
06656             newbc->fac_out.u.DivertingLegInformation2.DiversionCounter = 1;
06657             newbc->fac_out.u.DivertingLegInformation2.DiversionReason = 0;/* unknown */
06658             break;
06659          default:
06660             newbc->fac_out.u.DivertingLegInformation2.DiversionCounter =
06661                newbc->redirecting.count;
06662             newbc->fac_out.u.DivertingLegInformation2.DiversionReason =
06663                misdn_to_diversion_reason(newbc->redirecting.reason);
06664             break;
06665          }
06666          newbc->fac_out.u.DivertingLegInformation2.OriginalCalledPresent = 0;
06667          if (1 < newbc->fac_out.u.DivertingLegInformation2.DiversionCounter) {
06668             newbc->fac_out.u.DivertingLegInformation2.OriginalCalledPresent = 1;
06669             newbc->fac_out.u.DivertingLegInformation2.OriginalCalled.Type = 2;/* numberNotAvailableDueToInterworking */
06670          }
06671 
06672          /*
06673           * Expect a DivertingLegInformation3 to update the COLR of the
06674           * redirecting-to party we are attempting to call now.
06675           */
06676          newbc->div_leg_3_rx_wanted = 1;
06677       }
06678 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
06679 
06680       /*check for bridging*/
06681       misdn_cfg_get(0, MISDN_GEN_BRIDGING, &bridging, sizeof(bridging));
06682       if (bridging && ch->other_ch) {
06683 #ifdef MISDN_1_2
06684          chan_misdn_log(1, port, "Disabling EC (aka Pipeline) on both Sides\n");
06685          *ch->bc->pipeline = 0;
06686          *ch->other_ch->bc->pipeline = 0;
06687 #else
06688          chan_misdn_log(1, port, "Disabling EC on both Sides\n");
06689          ch->bc->ec_enable = 0;
06690          ch->other_ch->bc->ec_enable = 0;
06691 #endif
06692       }
06693    }
06694 
06695    exceed = add_out_calls(port);
06696    if (exceed != 0) {
06697       char tmp[16];
06698 
06699       snprintf(tmp, sizeof(tmp), "%d", exceed);
06700       pbx_builtin_setvar_helper(ast, "MAX_OVERFLOW", tmp);
06701       ast->hangupcause = AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06702       ast_setstate(ast, AST_STATE_DOWN);
06703       return -1;
06704    }
06705 
06706 #if defined(AST_MISDN_ENHANCEMENTS)
06707    if (newbc->fac_out.Function != Fac_None) {
06708       print_facility(&newbc->fac_out, newbc);
06709    }
06710 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
06711    r = misdn_lib_send_event(newbc, EVENT_SETUP);
06712 
06713    /** we should have l3id after sending setup **/
06714    ch->l3id = newbc->l3_id;
06715 
06716    if (r == -ENOCHAN) {
06717       chan_misdn_log(0, port, " --> * Theres no Channel at the moment .. !\n");
06718       chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n", newbc ? newbc->pid : -1);
06719       ast->hangupcause = AST_CAUSE_NORMAL_CIRCUIT_CONGESTION;
06720       ast_setstate(ast, AST_STATE_DOWN);
06721       return -1;
06722    }
06723 
06724    chan_misdn_log(2, port, " --> * SEND: State Dialing pid:%d\n", newbc ? newbc->pid : 1);
06725 
06726    ast_setstate(ast, AST_STATE_DIALING);
06727    ast->hangupcause = AST_CAUSE_NORMAL_CLEARING;
06728 
06729    if (newbc->nt) {
06730       stop_bc_tones(ch);
06731    }
06732 
06733    ch->state = MISDN_CALLING;
06734 
06735    return 0;
06736 }
06737 
06738 
06739 static int misdn_answer(struct ast_channel *ast)
06740 {
06741    struct chan_list *p;
06742    const char *tmp;
06743 
06744    if (!ast || !(p = MISDN_ASTERISK_TECH_PVT(ast))) {
06745       return -1;
06746    }
06747 
06748    chan_misdn_log(1, p ? (p->bc ? p->bc->port : 0) : 0, "* ANSWER:\n");
06749 
06750    if (!p) {
06751       ast_log(LOG_WARNING, " --> Channel not connected ??\n");
06752       ast_queue_hangup_with_cause(ast, AST_CAUSE_NETWORK_OUT_OF_ORDER);
06753    }
06754 
06755    if (!p->bc) {
06756       chan_misdn_log(1, 0, " --> Got Answer, but there is no bc obj ??\n");
06757 
06758       ast_queue_hangup_with_cause(ast, AST_CAUSE_PROTOCOL_ERROR);
06759    }
06760 
06761    ast_channel_lock(ast);
06762    tmp = pbx_builtin_getvar_helper(ast, "CRYPT_KEY");
06763    if (!ast_strlen_zero(tmp)) {
06764       chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
06765       ast_copy_string(p->bc->crypt_key, tmp, sizeof(p->bc->crypt_key));
06766    } else {
06767       chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
06768    }
06769 
06770    tmp = pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
06771    if (!ast_strlen_zero(tmp) && ast_true(tmp)) {
06772       chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
06773       p->bc->nodsp = 1;
06774       p->bc->hdlc = 0;
06775       p->bc->nojitter = 1;
06776    }
06777    ast_channel_unlock(ast);
06778 
06779    p->state = MISDN_CONNECTED;
06780    stop_indicate(p);
06781 
06782    if (ast_strlen_zero(p->bc->connected.number)) {
06783       chan_misdn_log(2,p->bc->port," --> empty connected number using dialed number\n");
06784       ast_copy_string(p->bc->connected.number, p->bc->dialed.number, sizeof(p->bc->connected.number));
06785 
06786       /*
06787        * Use the misdn_set_opt() application to set the presentation
06788        * before we answer or you can use the CONECTEDLINE() function
06789        * to set everything before using the Answer() application.
06790        */
06791       p->bc->connected.presentation = p->bc->presentation;
06792       p->bc->connected.screening = 0;  /* unscreened */
06793       p->bc->connected.number_type = p->bc->dialed.number_type;
06794       p->bc->connected.number_plan = p->bc->dialed.number_plan;
06795    }
06796 
06797    switch (p->bc->outgoing_colp) {
06798    case 1:/* restricted */
06799    case 2:/* blocked */
06800       p->bc->connected.presentation = 1;/* restricted */
06801       break;
06802    default:
06803       break;
06804    }
06805 
06806 #if defined(AST_MISDN_ENHANCEMENTS)
06807    if (p->bc->div_leg_3_tx_pending) {
06808       p->bc->div_leg_3_tx_pending = 0;
06809 
06810       /* Send DivertingLegInformation3 */
06811       p->bc->fac_out.Function = Fac_DivertingLegInformation3;
06812       p->bc->fac_out.u.DivertingLegInformation3.InvokeID = ++misdn_invoke_id;
06813       p->bc->fac_out.u.DivertingLegInformation3.PresentationAllowedIndicator =
06814          (p->bc->connected.presentation == 0) ? 1 : 0;
06815       print_facility(&p->bc->fac_out, p->bc);
06816    }
06817 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
06818    misdn_lib_send_event(p->bc, EVENT_CONNECT);
06819    start_bc_tones(p);
06820 
06821    return 0;
06822 }
06823 
06824 static int misdn_digit_begin(struct ast_channel *chan, char digit)
06825 {
06826    /* XXX Modify this callback to support Asterisk controlling the length of DTMF */
06827    return 0;
06828 }
06829 
06830 static int misdn_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
06831 {
06832    struct chan_list *p;
06833    struct misdn_bchannel *bc;
06834    char buf[2] = { digit, 0 };
06835 
06836    if (!ast || !(p = MISDN_ASTERISK_TECH_PVT(ast))) {
06837       return -1;
06838    }
06839 
06840    bc = p->bc;
06841    chan_misdn_log(1, bc ? bc->port : 0, "* IND : Digit %c\n", digit);
06842 
06843    if (!bc) {
06844       ast_log(LOG_WARNING, " --> !! Got Digit Event without having bchannel Object\n");
06845       return -1;
06846    }
06847 
06848    switch (p->state) {
06849    case MISDN_CALLING:
06850       if (strlen(bc->infos_pending) < sizeof(bc->infos_pending) - 1) {
06851          strncat(bc->infos_pending, buf, sizeof(bc->infos_pending) - strlen(bc->infos_pending) - 1);
06852       }
06853       break;
06854    case MISDN_CALLING_ACKNOWLEDGE:
06855       ast_copy_string(bc->info_dad, buf, sizeof(bc->info_dad));
06856       if (strlen(bc->dialed.number) < sizeof(bc->dialed.number) - 1) {
06857          strncat(bc->dialed.number, buf, sizeof(bc->dialed.number) - strlen(bc->dialed.number) - 1);
06858       }
06859       ast_copy_string(p->ast->exten, bc->dialed.number, sizeof(p->ast->exten));
06860       misdn_lib_send_event(bc, EVENT_INFORMATION);
06861       break;
06862    default:
06863       if (bc->send_dtmf) {
06864          send_digit_to_chan(p, digit);
06865       }
06866       break;
06867    }
06868 
06869    return 0;
06870 }
06871 
06872 
06873 static int misdn_fixup(struct ast_channel *oldast, struct ast_channel *ast)
06874 {
06875    struct chan_list *p;
06876 
06877    if (!ast || !(p = MISDN_ASTERISK_TECH_PVT(ast))) {
06878       return -1;
06879    }
06880 
06881    chan_misdn_log(1, p->bc ? p->bc->port : 0, "* IND: Got Fixup State:%s L3id:%x\n", misdn_get_ch_state(p), p->l3id);
06882 
06883    p->ast = ast;
06884 
06885    return 0;
06886 }
06887 
06888 
06889 
06890 static int misdn_indication(struct ast_channel *ast, int cond, const void *data, size_t datalen)
06891 {
06892    struct chan_list *p;
06893 
06894    if (!ast || !(p = MISDN_ASTERISK_TECH_PVT(ast))) {
06895       ast_log(LOG_WARNING, "Returned -1 in misdn_indication\n");
06896       return -1;
06897    }
06898 
06899    if (!p->bc) {
06900       if (p->hold.state == MISDN_HOLD_IDLE) {
06901          chan_misdn_log(1, 0, "* IND : Indication [%d] ignored on %s\n", cond,
06902             ast->name);
06903          ast_log(LOG_WARNING, "Private Pointer but no bc ?\n");
06904       } else {
06905          chan_misdn_log(1, 0, "* IND : Indication [%d] ignored on hold %s\n",
06906             cond, ast->name);
06907       }
06908       return -1;
06909    }
06910 
06911    chan_misdn_log(5, p->bc->port, "* IND : Indication [%d] on %s\n\n", cond, ast->name);
06912 
06913    switch (cond) {
06914    case AST_CONTROL_BUSY:
06915       chan_misdn_log(1, p->bc->port, "* IND :\tbusy pid:%d\n", p->bc->pid);
06916       ast_setstate(ast, AST_STATE_BUSY);
06917 
06918       p->bc->out_cause = AST_CAUSE_USER_BUSY;
06919       if (p->state != MISDN_CONNECTED) {
06920          start_bc_tones(p);
06921          misdn_lib_send_event(p->bc, EVENT_DISCONNECT);
06922       }
06923       return -1;
06924    case AST_CONTROL_RING:
06925       chan_misdn_log(1, p->bc->port, "* IND :\tring pid:%d\n", p->bc->pid);
06926       return -1;
06927    case AST_CONTROL_RINGING:
06928       chan_misdn_log(1, p->bc->port, "* IND :\tringing pid:%d\n", p->bc->pid);
06929       switch (p->state) {
06930       case MISDN_ALERTING:
06931          chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d but I was Ringing before, so ignoring it\n", p->bc->pid);
06932          break;
06933       case MISDN_CONNECTED:
06934          chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d but Connected, so just send TONE_ALERTING without state changes \n", p->bc->pid);
06935          return -1;
06936       default:
06937          p->state = MISDN_ALERTING;
06938          chan_misdn_log(2, p->bc->port, " --> * IND :\tringing pid:%d\n", p->bc->pid);
06939          misdn_lib_send_event(p->bc, EVENT_ALERTING);
06940 
06941          if (p->other_ch && p->other_ch->bc) {
06942             if (misdn_inband_avail(p->other_ch->bc)) {
06943                chan_misdn_log(2, p->bc->port, " --> other End is mISDN and has inband info available\n");
06944                break;
06945             }
06946 
06947             if (!p->other_ch->bc->nt) {
06948                chan_misdn_log(2, p->bc->port, " --> other End is mISDN TE so it has inband info for sure (?)\n");
06949                break;
06950             }
06951          }
06952 
06953          chan_misdn_log(3, p->bc->port, " --> * SEND: State Ring pid:%d\n", p->bc->pid);
06954          ast_setstate(ast, AST_STATE_RING);
06955 
06956          if (!p->bc->nt && (p->originator == ORG_MISDN) && !p->incoming_early_audio) {
06957             chan_misdn_log(2, p->bc->port, " --> incoming_early_audio off\n");
06958          } else {
06959             return -1;
06960          }
06961       }
06962       break;
06963    case AST_CONTROL_ANSWER:
06964       chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n", p->bc->pid);
06965       start_bc_tones(p);
06966       break;
06967    case AST_CONTROL_TAKEOFFHOOK:
06968       chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n", p->bc->pid);
06969       return -1;
06970    case AST_CONTROL_OFFHOOK:
06971       chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n", p->bc->pid);
06972       return -1;
06973    case AST_CONTROL_FLASH:
06974       chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n", p->bc->pid);
06975       break;
06976    case AST_CONTROL_PROGRESS:
06977       chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n", p->bc->pid);
06978       misdn_lib_send_event(p->bc, EVENT_PROGRESS);
06979       break;
06980    case AST_CONTROL_PROCEEDING:
06981       chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n", p->bc->pid);
06982       misdn_lib_send_event(p->bc, EVENT_PROCEEDING);
06983       break;
06984    case AST_CONTROL_CONGESTION:
06985       chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n", p->bc->pid);
06986 
06987       p->bc->out_cause = AST_CAUSE_SWITCH_CONGESTION;
06988       start_bc_tones(p);
06989       misdn_lib_send_event(p->bc, EVENT_DISCONNECT);
06990 
06991       if (p->bc->nt) {
06992          hanguptone_indicate(p);
06993       }
06994       break;
06995    case -1 :
06996       chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n", p->bc->pid);
06997 
06998       stop_indicate(p);
06999 
07000       if (p->state == MISDN_CONNECTED) {
07001          start_bc_tones(p);
07002       }
07003       break;
07004    case AST_CONTROL_HOLD:
07005       ast_moh_start(ast, data, p->mohinterpret);
07006       chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n", p->bc->pid);
07007       break;
07008    case AST_CONTROL_UNHOLD:
07009       ast_moh_stop(ast);
07010       chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n", p->bc->pid);
07011       break;
07012    case AST_CONTROL_CONNECTED_LINE:
07013       chan_misdn_log(1, p->bc->port, "* IND :\tconnected line update pid:%d\n", p->bc->pid);
07014       misdn_update_connected_line(ast, p->bc, p->originator);
07015       break;
07016    case AST_CONTROL_REDIRECTING:
07017       chan_misdn_log(1, p->bc->port, "* IND :\tredirecting info update pid:%d\n", p->bc->pid);
07018       misdn_update_redirecting(ast, p->bc, p->originator);
07019       break;
07020    default:
07021       chan_misdn_log(1, p->bc->port, " --> * Unknown Indication:%d pid:%d\n", cond, p->bc->pid);
07022       return -1;
07023    }
07024 
07025    return 0;
07026 }
07027 
07028 static int misdn_hangup(struct ast_channel *ast)
07029 {
07030    struct chan_list *p;
07031    struct misdn_bchannel *bc;
07032    const char *var;
07033 
07034    if (!ast) {
07035       return -1;
07036    }
07037 
07038    ast_mutex_lock(&release_lock);
07039    p = MISDN_ASTERISK_TECH_PVT(ast);
07040    if (!p || !misdn_chan_is_valid(p)) {
07041       ast_mutex_unlock(&release_lock);
07042       return -1;
07043    }
07044    MISDN_ASTERISK_TECH_PVT(ast) = NULL;
07045 
07046    ast_debug(1, "misdn_hangup(%s)\n", ast->name);
07047 
07048    if (p->hold.state == MISDN_HOLD_IDLE) {
07049       bc = p->bc;
07050    } else {
07051       p->hold.state = MISDN_HOLD_DISCONNECT;
07052       bc = misdn_lib_find_held_bc(p->hold.port, p->l3id);
07053       if (!bc) {
07054          chan_misdn_log(4, p->hold.port,
07055             "misdn_hangup: Could not find held bc for (%s)\n", ast->name);
07056          release_chan_early(p);
07057          ast_mutex_unlock(&release_lock);
07058          return 0;
07059       }
07060    }
07061 
07062    if (ast->_state == AST_STATE_RESERVED || p->state == MISDN_NOTHING) {
07063       /* between request and call */
07064       ast_debug(1, "State Reserved (or nothing) => chanIsAvail\n");
07065       release_chan_early(p);
07066       if (bc) {
07067          misdn_lib_release(bc);
07068       }
07069       ast_mutex_unlock(&release_lock);
07070       return 0;
07071    }
07072    if (!bc) {
07073       ast_log(LOG_WARNING, "Hangup with private but no bc ? state:%s l3id:%x\n",
07074          misdn_get_ch_state(p), p->l3id);
07075       release_chan_early(p);
07076       ast_mutex_unlock(&release_lock);
07077       return 0;
07078    }
07079 
07080    p->ast = NULL;
07081    p->need_hangup = 0;
07082    p->need_queue_hangup = 0;
07083    p->need_busy = 0;
07084 
07085    if (!bc->nt) {
07086       stop_bc_tones(p);
07087    }
07088 
07089    bc->out_cause = ast->hangupcause ? ast->hangupcause : AST_CAUSE_NORMAL_CLEARING;
07090 
07091    /* Channel lock is already held when we are called. */
07092    //ast_channel_lock(ast);
07093    var = pbx_builtin_getvar_helper(ast, "HANGUPCAUSE");
07094    if (!var) {
07095       var = pbx_builtin_getvar_helper(ast, "PRI_CAUSE");
07096    }
07097    if (var) {
07098       int tmpcause;
07099 
07100       tmpcause = atoi(var);
07101       bc->out_cause = tmpcause ? tmpcause : AST_CAUSE_NORMAL_CLEARING;
07102    }
07103 
07104    var = pbx_builtin_getvar_helper(ast, "MISDN_USERUSER");
07105    if (var) {
07106       ast_log(LOG_NOTICE, "MISDN_USERUSER: %s\n", var);
07107       ast_copy_string(bc->uu, var, sizeof(bc->uu));
07108       bc->uulen = strlen(bc->uu);
07109    }
07110    //ast_channel_unlock(ast);
07111 
07112    chan_misdn_log(1, bc->port,
07113       "* IND : HANGUP\tpid:%d context:%s dialed:%s caller:\"%s\" <%s> State:%s\n",
07114       bc->pid,
07115       ast->context,
07116       ast->exten,
07117       (ast->caller.id.name.valid && ast->caller.id.name.str)
07118          ? ast->caller.id.name.str : "",
07119       (ast->caller.id.number.valid && ast->caller.id.number.str)
07120          ? ast->caller.id.number.str : "",
07121       misdn_get_ch_state(p));
07122    chan_misdn_log(3, bc->port, " --> l3id:%x\n", p->l3id);
07123    chan_misdn_log(3, bc->port, " --> cause:%d\n", bc->cause);
07124    chan_misdn_log(2, bc->port, " --> out_cause:%d\n", bc->out_cause);
07125 
07126    switch (p->state) {
07127    case MISDN_INCOMING_SETUP:
07128       /*
07129        * This is the only place in misdn_hangup, where we
07130        * can call release_chan, else it might create a lot of trouble.
07131        */
07132       ast_log(LOG_NOTICE, "release channel, in INCOMING_SETUP state.. no other events happened\n");
07133       release_chan(p, bc);
07134       misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
07135       ast_mutex_unlock(&release_lock);
07136       return 0;
07137    case MISDN_DIALING:
07138       if (p->hold.state == MISDN_HOLD_IDLE) {
07139          start_bc_tones(p);
07140          hanguptone_indicate(p);
07141       }
07142 
07143       if (bc->need_disconnect) {
07144          misdn_lib_send_event(bc, EVENT_DISCONNECT);
07145       }
07146       break;
07147    case MISDN_CALLING_ACKNOWLEDGE:
07148       if (p->hold.state == MISDN_HOLD_IDLE) {
07149          start_bc_tones(p);
07150          hanguptone_indicate(p);
07151       }
07152 
07153       if (bc->need_disconnect) {
07154          misdn_lib_send_event(bc, EVENT_DISCONNECT);
07155       }
07156       break;
07157 
07158    case MISDN_CALLING:
07159    case MISDN_ALERTING:
07160    case MISDN_PROGRESS:
07161    case MISDN_PROCEEDING:
07162       if (p->originator != ORG_AST && p->hold.state == MISDN_HOLD_IDLE) {
07163          hanguptone_indicate(p);
07164       }
07165 
07166       if (bc->need_disconnect) {
07167          misdn_lib_send_event(bc, EVENT_DISCONNECT);
07168       }
07169       break;
07170    case MISDN_CONNECTED:
07171       /*  Alerting or Disconnect */
07172       if (bc->nt && p->hold.state == MISDN_HOLD_IDLE) {
07173          start_bc_tones(p);
07174          hanguptone_indicate(p);
07175          bc->progress_indicator = INFO_PI_INBAND_AVAILABLE;
07176       }
07177       if (bc->need_disconnect) {
07178          misdn_lib_send_event(bc, EVENT_DISCONNECT);
07179       }
07180       break;
07181    case MISDN_DISCONNECTED:
07182       if (bc->need_release) {
07183          misdn_lib_send_event(bc, EVENT_RELEASE);
07184       }
07185       break;
07186 
07187    case MISDN_CLEANING:
07188       ast_mutex_unlock(&release_lock);
07189       return 0;
07190 
07191    case MISDN_BUSY:
07192       break;
07193    default:
07194       if (bc->nt) {
07195          bc->out_cause = -1;
07196          if (bc->need_release) {
07197             misdn_lib_send_event(bc, EVENT_RELEASE);
07198          }
07199       } else {
07200          if (bc->need_disconnect) {
07201             misdn_lib_send_event(bc, EVENT_DISCONNECT);
07202          }
07203       }
07204       break;
07205    }
07206 
07207    p->state = MISDN_CLEANING;
07208    chan_misdn_log(3, bc->port, " --> Channel: %s hungup new state:%s\n", ast->name,
07209       misdn_get_ch_state(p));
07210 
07211    ast_mutex_unlock(&release_lock);
07212    return 0;
07213 }
07214 
07215 
07216 static struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame)
07217 {
07218    struct ast_frame *f;
07219 
07220    if (tmp->dsp) {
07221       f = ast_dsp_process(tmp->ast, tmp->dsp, frame);
07222    } else {
07223       chan_misdn_log(0, tmp->bc->port, "No DSP-Path found\n");
07224       return NULL;
07225    }
07226 
07227    if (!f || (f->frametype != AST_FRAME_DTMF)) {
07228       return f;
07229    }
07230 
07231    ast_debug(1, "Detected inband DTMF digit: %c\n", f->subclass.integer);
07232 
07233    if (tmp->faxdetect && (f->subclass.integer == 'f')) {
07234       /* Fax tone -- Handle and return NULL */
07235       if (!tmp->faxhandled) {
07236          struct ast_channel *ast = tmp->ast;
07237          tmp->faxhandled++;
07238          chan_misdn_log(0, tmp->bc->port, "Fax detected, preparing %s for fax transfer.\n", ast->name);
07239          tmp->bc->rxgain = 0;
07240          isdn_lib_update_rxgain(tmp->bc);
07241          tmp->bc->txgain = 0;
07242          isdn_lib_update_txgain(tmp->bc);
07243 #ifdef MISDN_1_2
07244          *tmp->bc->pipeline = 0;
07245 #else
07246          tmp->bc->ec_enable = 0;
07247 #endif
07248          isdn_lib_update_ec(tmp->bc);
07249          isdn_lib_stop_dtmf(tmp->bc);
07250          switch (tmp->faxdetect) {
07251          case 1:
07252             if (strcmp(ast->exten, "fax")) {
07253                char *context;
07254                char context_tmp[BUFFERSIZE];
07255                misdn_cfg_get(tmp->bc->port, MISDN_CFG_FAXDETECT_CONTEXT, &context_tmp, sizeof(context_tmp));
07256                context = ast_strlen_zero(context_tmp) ? (ast_strlen_zero(ast->macrocontext) ? ast->context : ast->macrocontext) : context_tmp;
07257                if (ast_exists_extension(ast, context, "fax", 1,
07258                   S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07259                   ast_verb(3, "Redirecting %s to fax extension (context:%s)\n", ast->name, context);
07260                   /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
07261                   pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
07262                   if (ast_async_goto(ast, context, "fax", 1)) {
07263                      ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, context);
07264                   }
07265                } else {
07266                   ast_log(LOG_NOTICE, "Fax detected but no fax extension, context:%s exten:%s\n", context, ast->exten);
07267                }
07268             } else {
07269                ast_debug(1, "Already in a fax extension, not redirecting\n");
07270             }
07271             break;
07272          case 2:
07273             ast_verb(3, "Not redirecting %s to fax extension, nojump is set.\n", ast->name);
07274             break;
07275          default:
07276             break;
07277          }
07278       } else {
07279          ast_debug(1, "Fax already handled\n");
07280       }
07281    }
07282 
07283    if (tmp->ast_dsp && (f->subclass.integer != 'f')) {
07284       chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n", f->subclass.integer);
07285    }
07286 
07287    return f;
07288 }
07289 
07290 
07291 static struct ast_frame *misdn_read(struct ast_channel *ast)
07292 {
07293    struct chan_list *tmp;
07294    int len, t;
07295    struct pollfd pfd = { .fd = -1, .events = POLLIN };
07296 
07297    if (!ast) {
07298       chan_misdn_log(1, 0, "misdn_read called without ast\n");
07299       return NULL;
07300    }
07301    if (!(tmp = MISDN_ASTERISK_TECH_PVT(ast))) {
07302       chan_misdn_log(1, 0, "misdn_read called without ast->pvt\n");
07303       return NULL;
07304    }
07305 
07306    if (!tmp->bc && tmp->hold.state == MISDN_HOLD_IDLE) {
07307       chan_misdn_log(1, 0, "misdn_read called without bc\n");
07308       return NULL;
07309    }
07310 
07311    pfd.fd = tmp->pipe[0];
07312    t = ast_poll(&pfd, 1, 20);
07313 
07314    if (t < 0) {
07315       chan_misdn_log(-1, tmp->bc->port, "poll() error (err=%s)\n", strerror(errno));
07316       return NULL;
07317    }
07318 
07319    if (!t) {
07320       chan_misdn_log(3, tmp->bc->port, "poll() timed out\n");
07321       len = 160;
07322    } else if (pfd.revents & POLLIN) {
07323       len = read(tmp->pipe[0], tmp->ast_rd_buf, sizeof(tmp->ast_rd_buf));
07324 
07325       if (len <= 0) {
07326          /* we hangup here, since our pipe is closed */
07327          chan_misdn_log(2, tmp->bc->port, "misdn_read: Pipe closed, hanging up\n");
07328          return NULL;
07329       }
07330    } else {
07331       return NULL;
07332    }
07333 
07334    tmp->frame.frametype = AST_FRAME_VOICE;
07335    tmp->frame.subclass.codec = AST_FORMAT_ALAW;
07336    tmp->frame.datalen = len;
07337    tmp->frame.samples = len;
07338    tmp->frame.mallocd = 0;
07339    tmp->frame.offset = 0;
07340    tmp->frame.delivery = ast_tv(0, 0);
07341    tmp->frame.src = NULL;
07342    tmp->frame.data.ptr = tmp->ast_rd_buf;
07343 
07344    if (tmp->faxdetect && !tmp->faxhandled) {
07345       if (tmp->faxdetect_timeout) {
07346          if (ast_tvzero(tmp->faxdetect_tv)) {
07347             tmp->faxdetect_tv = ast_tvnow();
07348             chan_misdn_log(2, tmp->bc->port, "faxdetect: starting detection with timeout: %ds ...\n", tmp->faxdetect_timeout);
07349             return process_ast_dsp(tmp, &tmp->frame);
07350          } else {
07351             struct timeval tv_now = ast_tvnow();
07352             int diff = ast_tvdiff_ms(tv_now, tmp->faxdetect_tv);
07353             if (diff <= (tmp->faxdetect_timeout * 1000)) {
07354                chan_misdn_log(5, tmp->bc->port, "faxdetect: detecting ...\n");
07355                return process_ast_dsp(tmp, &tmp->frame);
07356             } else {
07357                chan_misdn_log(2, tmp->bc->port, "faxdetect: stopping detection (time ran out) ...\n");
07358                tmp->faxdetect = 0;
07359                return &tmp->frame;
07360             }
07361          }
07362       } else {
07363          chan_misdn_log(5, tmp->bc->port, "faxdetect: detecting ... (no timeout)\n");
07364          return process_ast_dsp(tmp, &tmp->frame);
07365       }
07366    } else {
07367       if (tmp->ast_dsp) {
07368          return process_ast_dsp(tmp, &tmp->frame);
07369       } else {
07370          return &tmp->frame;
07371       }
07372    }
07373 }
07374 
07375 
07376 static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
07377 {
07378    struct chan_list *ch;
07379    int i  = 0;
07380 
07381    if (!ast || !(ch = MISDN_ASTERISK_TECH_PVT(ast))) {
07382       return -1;
07383    }
07384 
07385    if (ch->hold.state != MISDN_HOLD_IDLE) {
07386       chan_misdn_log(7, 0, "misdn_write: Returning because hold active\n");
07387       return 0;
07388    }
07389 
07390    if (!ch->bc) {
07391       ast_log(LOG_WARNING, "private but no bc\n");
07392       return -1;
07393    }
07394 
07395    if (ch->notxtone) {
07396       chan_misdn_log(7, ch->bc->port, "misdn_write: Returning because notxtone\n");
07397       return 0;
07398    }
07399 
07400 
07401    if (!frame->subclass.codec) {
07402       chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
07403       return 0;
07404    }
07405 
07406    if (!(frame->subclass.codec & prefformat)) {
07407       chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%s\n", ast_getformatname(frame->subclass.codec));
07408       return 0;
07409    }
07410 
07411 
07412    if (!frame->samples) {
07413       chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
07414 
07415       if (!strcmp(frame->src,"ast_prod")) {
07416          chan_misdn_log(1, ch->bc->port, "misdn_write: state (%s) prodded.\n", misdn_get_ch_state(ch));
07417 
07418          if (ch->ts) {
07419             chan_misdn_log(4, ch->bc->port, "Starting Playtones\n");
07420             misdn_lib_tone_generator_start(ch->bc);
07421          }
07422          return 0;
07423       }
07424 
07425       return -1;
07426    }
07427 
07428    if (!ch->bc->addr) {
07429       chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
07430       return 0;
07431    }
07432 
07433 #ifdef MISDN_DEBUG
07434    {
07435       int i;
07436       int max = 5 > frame->samples ? frame->samples : 5;
07437 
07438       ast_debug(1, "write2mISDN %p %d bytes: ", p, frame->samples);
07439 
07440       for (i = 0; i < max; i++) {
07441          ast_debug(1, "%2.2x ", ((char *) frame->data.ptr)[i]);
07442       }
07443    }
07444 #endif
07445 
07446    switch (ch->bc->bc_state) {
07447    case BCHAN_ACTIVATED:
07448    case BCHAN_BRIDGED:
07449       break;
07450    default:
07451       if (!ch->dropped_frame_cnt) {
07452          chan_misdn_log(5, ch->bc->port,
07453             "BC not active (nor bridged) dropping: %d frames addr:%x exten:%s cid:%s ch->state:%s bc_state:%d l3id:%x\n",
07454             frame->samples, ch->bc->addr, ast->exten,
07455             S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, ""),
07456             misdn_get_ch_state(ch), ch->bc->bc_state, ch->bc->l3_id);
07457       }
07458 
07459       if (++ch->dropped_frame_cnt > 100) {
07460          ch->dropped_frame_cnt = 0;
07461          chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) dropping: %d frames addr:%x  dropped > 100 frames!\n", frame->samples, ch->bc->addr);
07462       }
07463 
07464       return 0;
07465    }
07466 
07467    chan_misdn_log(9, ch->bc->port, "Sending :%d bytes to MISDN\n", frame->samples);
07468    if (!ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability)) {
07469       /* Buffered Transmit (triggered by read from isdn side)*/
07470       if (misdn_jb_fill(ch->jb, frame->data.ptr, frame->samples) < 0) {
07471          if (ch->bc->active) {
07472             cb_log(0, ch->bc->port, "Misdn Jitterbuffer Overflow.\n");
07473          }
07474       }
07475 
07476    } else {
07477       /* transmit without jitterbuffer */
07478       i = misdn_lib_tx2misdn_frm(ch->bc, frame->data.ptr, frame->samples);
07479    }
07480 
07481    return 0;
07482 }
07483 
07484 static enum ast_bridge_result misdn_bridge(struct ast_channel *c0,
07485    struct ast_channel *c1, int flags,
07486    struct ast_frame **fo,
07487    struct ast_channel **rc,
07488    int timeoutms)
07489 {
07490    struct chan_list *ch1, *ch2;
07491    struct ast_channel *carr[2], *who;
07492    int to = -1;
07493    struct ast_frame *f;
07494    int p1_b, p2_b;
07495    int bridging;
07496 
07497    ch1 = get_chan_by_ast(c0);
07498    ch2 = get_chan_by_ast(c1);
07499 
07500    carr[0] = c0;
07501    carr[1] = c1;
07502 
07503    if (!(ch1 && ch2)) {
07504       return -1;
07505    }
07506 
07507    misdn_cfg_get(ch1->bc->port, MISDN_CFG_BRIDGING, &p1_b, sizeof(p1_b));
07508    misdn_cfg_get(ch2->bc->port, MISDN_CFG_BRIDGING, &p2_b, sizeof(p2_b));
07509 
07510    if (! p1_b || ! p2_b) {
07511       ast_log(LOG_NOTICE, "Falling back to Asterisk bridging\n");
07512       return AST_BRIDGE_FAILED;
07513    }
07514 
07515    misdn_cfg_get(0, MISDN_GEN_BRIDGING, &bridging, sizeof(bridging));
07516    if (bridging) {
07517       /* trying to make a mISDN_dsp conference */
07518       chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid + 1);
07519       misdn_lib_bridge(ch1->bc, ch2->bc);
07520    }
07521 
07522    ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
07523 
07524    chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between \"%s\" <%s> and \"%s\" <%s>\n",
07525       ch1->bc->caller.name,
07526       ch1->bc->caller.number,
07527       ch2->bc->caller.name,
07528       ch2->bc->caller.number);
07529 
07530    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
07531       ch1->ignore_dtmf = 1;
07532    }
07533 
07534    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
07535       ch2->ignore_dtmf = 1;
07536    }
07537 
07538    for (;/*ever*/;) {
07539       to = -1;
07540       who = ast_waitfor_n(carr, 2, &to);
07541 
07542       if (!who) {
07543          ast_log(LOG_NOTICE, "misdn_bridge: empty read, breaking out\n");
07544          break;
07545       }
07546       f = ast_read(who);
07547 
07548       if (!f || f->frametype == AST_FRAME_CONTROL) {
07549          /* got hangup .. */
07550 
07551          if (!f) {
07552             chan_misdn_log(4, ch1->bc->port, "Read Null Frame\n");
07553          } else {
07554             chan_misdn_log(4, ch1->bc->port, "Read Frame Control class:%d\n", f->subclass.integer);
07555          }
07556 
07557          *fo = f;
07558          *rc = who;
07559          break;
07560       }
07561 
07562       if (f->frametype == AST_FRAME_DTMF) {
07563          chan_misdn_log(1, 0, "Read DTMF %d from %s\n", f->subclass.integer, who->exten);
07564 
07565          *fo = f;
07566          *rc = who;
07567          break;
07568       }
07569 
07570 #if 0
07571       if (f->frametype == AST_FRAME_VOICE) {
07572          chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
07573 
07574          continue;
07575       }
07576 #endif
07577 
07578       ast_write((who == c0) ? c1 : c0, f);
07579    }
07580 
07581    chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid + 1);
07582 
07583    misdn_lib_split_bridge(ch1->bc, ch2->bc);
07584 
07585    return AST_BRIDGE_COMPLETE;
07586 }
07587 
07588 /** AST INDICATIONS END **/
07589 
07590 static int dialtone_indicate(struct chan_list *cl)
07591 {
07592    struct ast_channel *ast = cl->ast;
07593    int nd = 0;
07594 
07595    if (!ast) {
07596       chan_misdn_log(0, cl->bc->port, "No Ast in dialtone_indicate\n");
07597       return -1;
07598    }
07599 
07600    misdn_cfg_get(cl->bc->port, MISDN_CFG_NODIALTONE, &nd, sizeof(nd));
07601 
07602    if (nd) {
07603       chan_misdn_log(1, cl->bc->port, "Not sending Dialtone, because config wants it\n");
07604       return 0;
07605    }
07606 
07607    chan_misdn_log(3, cl->bc->port, " --> Dial\n");
07608 
07609    cl->ts = ast_get_indication_tone(ast->zone, "dial");
07610 
07611    if (cl->ts) {
07612       cl->notxtone = 0;
07613       cl->norxtone = 0;
07614       /* This prods us in misdn_write */
07615       ast_playtones_start(ast, 0, cl->ts->data, 0);
07616    }
07617 
07618    return 0;
07619 }
07620 
07621 static void hanguptone_indicate(struct chan_list *cl)
07622 {
07623    misdn_lib_send_tone(cl->bc, TONE_HANGUP);
07624 }
07625 
07626 static int stop_indicate(struct chan_list *cl)
07627 {
07628    struct ast_channel *ast = cl->ast;
07629 
07630    if (!ast) {
07631       chan_misdn_log(0, cl->bc->port, "No Ast in stop_indicate\n");
07632       return -1;
07633    }
07634 
07635    chan_misdn_log(3, cl->bc->port, " --> None\n");
07636    misdn_lib_tone_generator_stop(cl->bc);
07637    ast_playtones_stop(ast);
07638 
07639    if (cl->ts) {
07640       cl->ts = ast_tone_zone_sound_unref(cl->ts);
07641    }
07642 
07643    return 0;
07644 }
07645 
07646 
07647 static int start_bc_tones(struct chan_list* cl)
07648 {
07649    misdn_lib_tone_generator_stop(cl->bc);
07650    cl->notxtone = 0;
07651    cl->norxtone = 0;
07652    return 0;
07653 }
07654 
07655 static int stop_bc_tones(struct chan_list *cl)
07656 {
07657    if (!cl) {
07658       return -1;
07659    }
07660 
07661    cl->notxtone = 1;
07662    cl->norxtone = 1;
07663 
07664    return 0;
07665 }
07666 
07667 
07668 static struct chan_list *init_chan_list(int orig)
07669 {
07670    struct chan_list *cl;
07671 
07672    cl = ast_calloc(1, sizeof(*cl));
07673    if (!cl) {
07674       chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
07675       return NULL;
07676    }
07677 
07678    cl->originator = orig;
07679    cl->need_queue_hangup = 1;
07680    cl->need_hangup = 1;
07681    cl->need_busy = 1;
07682    cl->overlap_dial_task = -1;
07683 #if defined(AST_MISDN_ENHANCEMENTS)
07684    cl->record_id = -1;
07685 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
07686 
07687    return cl;
07688 }
07689 
07690 static struct ast_channel *misdn_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
07691 {
07692    struct ast_channel *ast;
07693    char group[BUFFERSIZE + 1] = "";
07694    char dial_str[128];
07695    char *dest_cp;
07696    char *p = NULL;
07697    int channel = 0;
07698    int port = 0;
07699    struct misdn_bchannel *newbc = NULL;
07700    int dec = 0;
07701 #if defined(AST_MISDN_ENHANCEMENTS)
07702    int cc_retry_call = 0;  /* TRUE if this is a call completion retry call */
07703    long record_id = -1;
07704    struct misdn_cc_record *cc_record;
07705    const char *err_msg;
07706 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
07707    struct chan_list *cl;
07708 
07709    AST_DECLARE_APP_ARGS(args,
07710       AST_APP_ARG(intf);   /* interface token */
07711       AST_APP_ARG(ext); /* extension token */
07712       AST_APP_ARG(opts);   /* options token */
07713    );
07714 
07715    snprintf(dial_str, sizeof(dial_str), "%s/%s", misdn_type, (char *) data);
07716 
07717    /*
07718     * data is ---v
07719     * Dial(mISDN/g:group_name[/extension[/options]])
07720     * Dial(mISDN/port[:preselected_channel][/extension[/options]])
07721     * Dial(mISDN/cc/cc-record-id)
07722     *
07723     * The dial extension could be empty if you are using MISDN_KEYPAD
07724     * to control ISDN provider features.
07725     */
07726    dest_cp = ast_strdupa(data);
07727    AST_NONSTANDARD_APP_ARGS(args, dest_cp, '/');
07728    if (!args.ext) {
07729       args.ext = "";
07730    }
07731 
07732    if (!ast_strlen_zero(args.intf)) {
07733       if (args.intf[0] == 'g' && args.intf[1] == ':') {
07734          /* We make a group call lets checkout which ports are in my group */
07735          args.intf += 2;
07736          ast_copy_string(group, args.intf, sizeof(group));
07737          chan_misdn_log(2, 0, " --> Group Call group: %s\n", group);
07738 #if defined(AST_MISDN_ENHANCEMENTS)
07739       } else if (strcmp(args.intf, "cc") == 0) {
07740          cc_retry_call = 1;
07741 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
07742       } else if ((p = strchr(args.intf, ':'))) {
07743          /* we have a preselected channel */
07744          *p++ = 0;
07745          channel = atoi(p);
07746          port = atoi(args.intf);
07747          chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
07748       } else {
07749          port = atoi(args.intf);
07750       }
07751    } else {
07752       ast_log(LOG_WARNING, " --> ! IND : Dial(%s) WITHOUT Port or Group, check extensions.conf\n", dial_str);
07753       return NULL;
07754    }
07755 
07756 #if defined(AST_MISDN_ENHANCEMENTS)
07757    if (cc_retry_call) {
07758       if (ast_strlen_zero(args.ext)) {
07759          ast_log(LOG_WARNING, " --> ! IND : Dial(%s) WITHOUT cc-record-id, check extensions.conf\n", dial_str);
07760          return NULL;
07761       }
07762       if (!isdigit(*args.ext)) {
07763          ast_log(LOG_WARNING, " --> ! IND : Dial(%s) cc-record-id must be a number.\n", dial_str);
07764          return NULL;
07765       }
07766       record_id = atol(args.ext);
07767 
07768       AST_LIST_LOCK(&misdn_cc_records_db);
07769       cc_record = misdn_cc_find_by_id(record_id);
07770       if (!cc_record) {
07771          AST_LIST_UNLOCK(&misdn_cc_records_db);
07772          err_msg = misdn_cc_record_not_found;
07773          ast_log(LOG_WARNING, " --> ! IND : Dial(%s) %s.\n", dial_str, err_msg);
07774          return NULL;
07775       }
07776       if (!cc_record->activated) {
07777          AST_LIST_UNLOCK(&misdn_cc_records_db);
07778          err_msg = "Call completion has not been activated";
07779          ast_log(LOG_WARNING, " --> ! IND : Dial(%s) %s.\n", dial_str, err_msg);
07780          return NULL;
07781       }
07782       port = cc_record->port;
07783       AST_LIST_UNLOCK(&misdn_cc_records_db);
07784    }
07785 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
07786 
07787    if (misdn_cfg_is_group_method(group, METHOD_STANDARD_DEC)) {
07788       chan_misdn_log(4, port, " --> STARTING STANDARD DEC...\n");
07789       dec = 1;
07790    }
07791 
07792    if (!ast_strlen_zero(group)) {
07793       char cfg_group[BUFFERSIZE + 1];
07794       struct robin_list *rr = NULL;
07795 
07796       /* Group dial */
07797 
07798       if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
07799          chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...\n");
07800          rr = get_robin_position(group);
07801       }
07802 
07803       if (rr) {
07804          int robin_channel = rr->channel;
07805          int port_start;
07806          int next_chan = 1;
07807 
07808          do {
07809             port_start = 0;
07810             for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
07811                 port = misdn_cfg_get_next_port_spin(port)) {
07812 
07813                if (!port_start) {
07814                   port_start = port;
07815                }
07816 
07817                if (port >= port_start) {
07818                   next_chan = 1;
07819                }
07820 
07821                if (port <= port_start && next_chan) {
07822                   int maxbchans = misdn_lib_get_maxchans(port);
07823 
07824                   if (++robin_channel >= maxbchans) {
07825                      robin_channel = 1;
07826                   }
07827                   next_chan = 0;
07828                }
07829 
07830                misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, sizeof(cfg_group));
07831 
07832                if (!strcasecmp(cfg_group, group)) {
07833                   int port_up;
07834                   int check;
07835 
07836                   misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(check));
07837                   port_up = misdn_lib_port_up(port, check);
07838 
07839                   if (check && !port_up) {
07840                      chan_misdn_log(1, port, "L1 is not Up on this Port\n");
07841                   }
07842 
07843                   if (check && port_up < 0) {
07844                      ast_log(LOG_WARNING, "This port (%d) is blocked\n", port);
07845                   }
07846 
07847                   if (port_up > 0)  {
07848                      newbc = misdn_lib_get_free_bc(port, robin_channel, 0, 0);
07849                      if (newbc) {
07850                         chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
07851                         if (port_up) {
07852                            chan_misdn_log(4, port, "portup:%d\n",  port_up);
07853                         }
07854                         rr->port = newbc->port;
07855                         rr->channel = newbc->channel;
07856                         break;
07857                      }
07858                   }
07859                }
07860             }
07861          } while (!newbc && robin_channel != rr->channel);
07862       } else {
07863          for (port = misdn_cfg_get_next_port(0); port > 0;
07864             port = misdn_cfg_get_next_port(port)) {
07865             misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, sizeof(cfg_group));
07866 
07867             chan_misdn_log(3, port, "Group [%s] Port [%d]\n", group, port);
07868             if (!strcasecmp(cfg_group, group)) {
07869                int port_up;
07870                int check;
07871 
07872                misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(check));
07873                port_up = misdn_lib_port_up(port, check);
07874 
07875                chan_misdn_log(4, port, "portup:%d\n", port_up);
07876 
07877                if (port_up > 0) {
07878                   newbc = misdn_lib_get_free_bc(port, 0, 0, dec);
07879                   if (newbc) {
07880                      break;
07881                   }
07882                }
07883             }
07884          }
07885       }
07886 
07887       /* Group dial failed ?*/
07888       if (!newbc) {
07889          ast_log(LOG_WARNING,
07890             "Could not Dial out on group '%s'.\n"
07891             "\tEither the L2 and L1 on all of these ports where DOWN (see 'show application misdn_check_l2l1')\n"
07892             "\tOr there was no free channel on none of the ports\n\n",
07893             group);
07894          return NULL;
07895       }
07896    } else {
07897       /* 'Normal' Port dial * Port dial */
07898       if (channel) {
07899          chan_misdn_log(1, port, " --> preselected_channel: %d\n", channel);
07900       }
07901       newbc = misdn_lib_get_free_bc(port, channel, 0, dec);
07902       if (!newbc) {
07903          ast_log(LOG_WARNING, "Could not create channel on port:%d for Dial(%s)\n", port, dial_str);
07904          return NULL;
07905       }
07906    }
07907 
07908    /* create ast_channel and link all the objects together */
07909    cl = init_chan_list(ORG_AST);
07910    if (!cl) {
07911       ast_log(LOG_ERROR, "Could not create call record for Dial(%s)\n", dial_str);
07912       return NULL;
07913    }
07914    cl->bc = newbc;
07915 
07916    ast = misdn_new(cl, AST_STATE_RESERVED, args.ext, NULL, format, requestor ? requestor->linkedid : NULL, port, channel);
07917    if (!ast) {
07918       ast_free(cl);
07919       ast_log(LOG_ERROR, "Could not create Asterisk channel for Dial(%s)\n", dial_str);
07920       return NULL;
07921    }
07922    cl->ast = ast;
07923 
07924 #if defined(AST_MISDN_ENHANCEMENTS)
07925    cl->record_id = record_id;
07926 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
07927 
07928    /* register chan in local list */
07929    cl_queue_chan(cl);
07930 
07931    /* fill in the config into the objects */
07932    read_config(cl);
07933 
07934    /* important */
07935    cl->need_hangup = 0;
07936 
07937    return ast;
07938 }
07939 
07940 
07941 static int misdn_send_text(struct ast_channel *chan, const char *text)
07942 {
07943    struct chan_list *tmp = chan->tech_pvt;
07944 
07945    if (tmp && tmp->bc) {
07946       ast_copy_string(tmp->bc->display, text, sizeof(tmp->bc->display));
07947       misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
07948    } else {
07949       ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
07950       return -1;
07951    }
07952 
07953    return 0;
07954 }
07955 
07956 static struct ast_channel_tech misdn_tech = {
07957    .type = misdn_type,
07958    .description = "Channel driver for mISDN Support (Bri/Pri)",
07959    .capabilities = AST_FORMAT_ALAW ,
07960    .requester = misdn_request,
07961    .send_digit_begin = misdn_digit_begin,
07962    .send_digit_end = misdn_digit_end,
07963    .call = misdn_call,
07964    .bridge = misdn_bridge,
07965    .hangup = misdn_hangup,
07966    .answer = misdn_answer,
07967    .read = misdn_read,
07968    .write = misdn_write,
07969    .indicate = misdn_indication,
07970    .fixup = misdn_fixup,
07971    .send_text = misdn_send_text,
07972    .properties = 0,
07973 };
07974 
07975 static struct ast_channel_tech misdn_tech_wo_bridge = {
07976    .type = misdn_type,
07977    .description = "Channel driver for mISDN Support (Bri/Pri)",
07978    .capabilities = AST_FORMAT_ALAW ,
07979    .requester = misdn_request,
07980    .send_digit_begin = misdn_digit_begin,
07981    .send_digit_end = misdn_digit_end,
07982    .call = misdn_call,
07983    .hangup = misdn_hangup,
07984    .answer = misdn_answer,
07985    .read = misdn_read,
07986    .write = misdn_write,
07987    .indicate = misdn_indication,
07988    .fixup = misdn_fixup,
07989    .send_text = misdn_send_text,
07990    .properties = 0,
07991 };
07992 
07993 
07994 static int glob_channel = 0;
07995 
07996 static void update_name(struct ast_channel *tmp, int port, int c)
07997 {
07998    int chan_offset = 0;
07999    int tmp_port = misdn_cfg_get_next_port(0);
08000    char newname[255];
08001 
08002    for (; tmp_port > 0; tmp_port = misdn_cfg_get_next_port(tmp_port)) {
08003       if (tmp_port == port) {
08004          break;
08005       }
08006       chan_offset += misdn_lib_port_is_pri(tmp_port) ? 30 : 2;
08007    }
08008    if (c < 0) {
08009       c = 0;
08010    }
08011 
08012    snprintf(newname, sizeof(newname), "%s/%d-", misdn_type, chan_offset + c);
08013    if (strncmp(tmp->name, newname, strlen(newname))) {
08014       snprintf(newname, sizeof(newname), "%s/%d-u%d", misdn_type, chan_offset + c, glob_channel++);
08015       ast_change_name(tmp, newname);
08016       chan_misdn_log(3, port, " --> updating channel name to [%s]\n", tmp->name);
08017    }
08018 }
08019 
08020 static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, const char *linkedid, int port, int c)
08021 {
08022    struct ast_channel *tmp;
08023    char *cid_name = NULL;
08024    char *cid_num = NULL;
08025    int chan_offset = 0;
08026    int tmp_port = misdn_cfg_get_next_port(0);
08027    int bridging;
08028 
08029    for (; tmp_port > 0; tmp_port = misdn_cfg_get_next_port(tmp_port)) {
08030       if (tmp_port == port) {
08031          break;
08032       }
08033       chan_offset += misdn_lib_port_is_pri(tmp_port) ? 30 : 2;
08034    }
08035    if (c < 0) {
08036       c = 0;
08037    }
08038 
08039    if (callerid) {
08040       ast_callerid_parse(callerid, &cid_name, &cid_num);
08041    }
08042 
08043    tmp = ast_channel_alloc(1, state, cid_num, cid_name, "", exten, "", linkedid, 0, "%s/%s%d-u%d", misdn_type, c ? "" : "tmp", chan_offset + c, glob_channel++);
08044    if (tmp) {
08045       chan_misdn_log(2, 0, " --> * NEW CHANNEL dialed:%s caller:%s\n", exten, callerid);
08046 
08047       tmp->nativeformats = prefformat;
08048 
08049       tmp->readformat = format;
08050       tmp->rawreadformat = format;
08051       tmp->writeformat = format;
08052       tmp->rawwriteformat = format;
08053 
08054       tmp->tech_pvt = chlist;
08055 
08056       misdn_cfg_get(0, MISDN_GEN_BRIDGING, &bridging, sizeof(bridging));
08057       tmp->tech = bridging ? &misdn_tech : &misdn_tech_wo_bridge;
08058 
08059       tmp->writeformat = format;
08060       tmp->readformat = format;
08061       tmp->priority = 1;
08062 
08063       if (exten) {
08064          ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
08065       } else {
08066          chan_misdn_log(1, 0, "misdn_new: no exten given.\n");
08067       }
08068 
08069       if (!ast_strlen_zero(cid_num)) {
08070          /* Don't use ast_set_callerid() here because it will
08071           * generate a needless NewCallerID event */
08072          tmp->caller.ani.number.valid = 1;
08073          tmp->caller.ani.number.str = ast_strdup(cid_num);
08074       }
08075 
08076       if (pipe(chlist->pipe) < 0) {
08077          ast_log(LOG_ERROR, "Pipe failed\n");
08078       }
08079       ast_channel_set_fd(tmp, 0, chlist->pipe[0]);
08080 
08081       tmp->rings = (state == AST_STATE_RING) ? 1 : 0;
08082 
08083       ast_jb_configure(tmp, misdn_get_global_jbconf());
08084    } else {
08085       chan_misdn_log(-1, 0, "Unable to allocate channel structure\n");
08086    }
08087 
08088    return tmp;
08089 }
08090 
08091 static struct chan_list *find_chan_by_bc(struct misdn_bchannel *bc)
08092 {
08093    struct chan_list *help;
08094 
08095    ast_mutex_lock(&cl_te_lock);
08096    for (help = cl_te; help; help = help->next) {
08097       if (help->bc == bc) {
08098          ast_mutex_unlock(&cl_te_lock);
08099          return help;
08100       }
08101    }
08102    ast_mutex_unlock(&cl_te_lock);
08103 
08104    chan_misdn_log(6, bc->port,
08105       "$$$ find_chan_by_bc: No channel found for dialed:%s caller:\"%s\" <%s>\n",
08106       bc->dialed.number,
08107       bc->caller.name,
08108       bc->caller.number);
08109 
08110    return NULL;
08111 }
08112 
08113 static struct chan_list *find_chan_by_pid(int pid)
08114 {
08115    struct chan_list *help;
08116 
08117    ast_mutex_lock(&cl_te_lock);
08118    for (help = cl_te; help; help = help->next) {
08119       if (help->bc && (help->bc->pid == pid)) {
08120          ast_mutex_unlock(&cl_te_lock);
08121          return help;
08122       }
08123    }
08124    ast_mutex_unlock(&cl_te_lock);
08125 
08126    chan_misdn_log(6, 0, "$$$ find_chan_by_pid: No channel found for pid:%d\n", pid);
08127 
08128    return NULL;
08129 }
08130 
08131 static struct chan_list *find_hold_call(struct misdn_bchannel *bc)
08132 {
08133    struct chan_list *help;
08134 
08135    if (bc->pri) {
08136       return NULL;
08137    }
08138 
08139    chan_misdn_log(6, bc->port, "$$$ find_hold_call: channel:%d dialed:%s caller:\"%s\" <%s>\n",
08140       bc->channel,
08141       bc->dialed.number,
08142       bc->caller.name,
08143       bc->caller.number);
08144    ast_mutex_lock(&cl_te_lock);
08145    for (help = cl_te; help; help = help->next) {
08146       chan_misdn_log(4, bc->port, "$$$ find_hold_call: --> hold:%d channel:%d\n", help->hold.state, help->hold.channel);
08147       if (help->hold.state == MISDN_HOLD_ACTIVE && help->hold.port == bc->port) {
08148          ast_mutex_unlock(&cl_te_lock);
08149          return help;
08150       }
08151    }
08152    ast_mutex_unlock(&cl_te_lock);
08153    chan_misdn_log(6, bc->port,
08154       "$$$ find_hold_call: No channel found for dialed:%s caller:\"%s\" <%s>\n",
08155       bc->dialed.number,
08156       bc->caller.name,
08157       bc->caller.number);
08158 
08159    return NULL;
08160 }
08161 
08162 
08163 static struct chan_list *find_hold_call_l3(unsigned long l3_id)
08164 {
08165    struct chan_list *help;
08166 
08167    ast_mutex_lock(&cl_te_lock);
08168    for (help = cl_te; help; help = help->next) {
08169       if (help->hold.state != MISDN_HOLD_IDLE && help->l3id == l3_id) {
08170          ast_mutex_unlock(&cl_te_lock);
08171          return help;
08172       }
08173    }
08174    ast_mutex_unlock(&cl_te_lock);
08175 
08176    return NULL;
08177 }
08178 
08179 #define TRANSFER_ON_HELD_CALL_HANGUP 1
08180 #if defined(TRANSFER_ON_HELD_CALL_HANGUP)
08181 /*!
08182  * \internal
08183  * \brief Find a suitable active call to go with a held call so we could try a transfer.
08184  *
08185  * \param bc B channel record.
08186  *
08187  * \return Found call record or NULL.
08188  *
08189  * \note There could be a possibility where we find the wrong active call to transfer.
08190  * This concern is mitigated by the fact that there could be at most one other call
08191  * on a PTMP BRI link to another device.  Maybe the l3_id could help in locating an
08192  * active call on the same TEI?
08193  */
08194 static struct chan_list *find_hold_active_call(struct misdn_bchannel *bc)
08195 {
08196    struct chan_list *list;
08197 
08198    ast_mutex_lock(&cl_te_lock);
08199    for (list = cl_te; list; list = list->next) {
08200       if (list->hold.state == MISDN_HOLD_IDLE && list->bc && list->bc->port == bc->port
08201          && list->ast) {
08202          switch (list->state) {
08203          case MISDN_PROCEEDING:
08204          case MISDN_PROGRESS:
08205          case MISDN_ALERTING:
08206          case MISDN_CONNECTED:
08207             ast_mutex_unlock(&cl_te_lock);
08208             return list;
08209          default:
08210             break;
08211          }
08212       }
08213    }
08214    ast_mutex_unlock(&cl_te_lock);
08215    return NULL;
08216 }
08217 #endif   /* defined(TRANSFER_ON_HELD_CALL_HANGUP) */
08218 
08219 static void cl_queue_chan(struct chan_list *chan)
08220 {
08221    chan_misdn_log(4, chan->bc ? chan->bc->port : 0, "* Queuing chan %p\n", chan);
08222 
08223    ast_mutex_lock(&cl_te_lock);
08224    chan->next = NULL;
08225    if (!cl_te) {
08226       /* List is empty, make head of list. */
08227       cl_te = chan;
08228    } else {
08229       struct chan_list *help;
08230 
08231       /* Put at end of list. */
08232       for (help = cl_te; help->next; help = help->next) {
08233       }
08234       help->next = chan;
08235    }
08236    ast_mutex_unlock(&cl_te_lock);
08237 }
08238 
08239 static int cl_dequeue_chan(struct chan_list *chan)
08240 {
08241    int found_it;
08242    struct chan_list *help;
08243 
08244    ast_mutex_lock(&cl_te_lock);
08245    if (!cl_te) {
08246       /* List is empty. */
08247       ast_mutex_unlock(&cl_te_lock);
08248       return 0;
08249    }
08250 
08251    if (cl_te == chan) {
08252       /* What we want is the head of the list. */
08253       cl_te = cl_te->next;
08254       ast_mutex_unlock(&cl_te_lock);
08255       return 1;
08256    }
08257 
08258    found_it = 0;
08259    for (help = cl_te; help->next; help = help->next) {
08260       if (help->next == chan) {
08261          /* Found it in the list. */
08262          help->next = help->next->next;
08263          found_it = 1;
08264          break;
08265       }
08266    }
08267 
08268    ast_mutex_unlock(&cl_te_lock);
08269    return found_it;
08270 }
08271 
08272 /** Channel Queue End **/
08273 
08274 
08275 static int pbx_start_chan(struct chan_list *ch)
08276 {
08277    int ret = ast_pbx_start(ch->ast);
08278 
08279    ch->need_hangup = (ret >= 0) ? 0 : 1;
08280 
08281    return ret;
08282 }
08283 
08284 static void hangup_chan(struct chan_list *ch, struct misdn_bchannel *bc)
08285 {
08286    int port;
08287 
08288    if (!ch) {
08289       cb_log(1, 0, "Cannot hangup chan, no ch\n");
08290       return;
08291    }
08292 
08293    port = bc->port;
08294    cb_log(5, port, "hangup_chan called\n");
08295 
08296    if (ch->need_hangup) {
08297       cb_log(2, port, " --> hangup\n");
08298       ch->need_hangup = 0;
08299       ch->need_queue_hangup = 0;
08300       if (ch->ast) {
08301          send_cause2ast(ch->ast, bc, ch);
08302          ast_hangup(ch->ast);
08303       }
08304       return;
08305    }
08306 
08307    if (!ch->need_queue_hangup) {
08308       cb_log(2, port, " --> No need to queue hangup\n");
08309    }
08310 
08311    ch->need_queue_hangup = 0;
08312    if (ch->ast) {
08313       send_cause2ast(ch->ast, bc, ch);
08314       ast_queue_hangup_with_cause(ch->ast, bc->cause);
08315       cb_log(2, port, " --> queue_hangup\n");
08316    } else {
08317       cb_log(1, port, "Cannot hangup chan, no ast\n");
08318    }
08319 }
08320 
08321 /*!
08322  * \internal
08323  * \brief ISDN asked us to release channel, pendant to misdn_hangup.
08324  *
08325  * \param ch Call channel record to release.
08326  * \param bc Current B channel record associated with ch.
08327  *
08328  * \return Nothing
08329  *
08330  * \note ch must not be referenced after calling.
08331  */
08332 static void release_chan(struct chan_list *ch, struct misdn_bchannel *bc)
08333 {
08334    struct ast_channel *ast;
08335 
08336    chan_misdn_log(5, bc->port, "release_chan: bc with pid:%d l3id: %x\n", bc->pid, bc->l3_id);
08337 
08338    ast_mutex_lock(&release_lock);
08339    for (;;) {
08340       ast = ch->ast;
08341       if (!ast || !ast_channel_trylock(ast)) {
08342          break;
08343       }
08344       DEADLOCK_AVOIDANCE(&release_lock);
08345    }
08346    if (!cl_dequeue_chan(ch)) {
08347       /* Someone already released it. */
08348       if (ast) {
08349          ast_channel_unlock(ast);
08350       }
08351       ast_mutex_unlock(&release_lock);
08352       return;
08353    }
08354    ch->state = MISDN_CLEANING;
08355    ch->ast = NULL;
08356    if (ast) {
08357       MISDN_ASTERISK_TECH_PVT(ast) = NULL;
08358       chan_misdn_log(1, bc->port,
08359          "* RELEASING CHANNEL pid:%d context:%s dialed:%s caller:\"%s\" <%s>\n",
08360          bc->pid,
08361          ast->context,
08362          ast->exten,
08363          S_COR(ast->caller.id.name.valid, ast->caller.id.name.str, ""),
08364          S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, ""));
08365 
08366       if (ast->_state != AST_STATE_RESERVED) {
08367          chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
08368          ast_setstate(ast, AST_STATE_DOWN);
08369       }
08370       ast_channel_unlock(ast);
08371    }
08372 
08373 #if defined(AST_MISDN_ENHANCEMENTS)
08374    if (ch->peer) {
08375       ao2_ref(ch->peer, -1);
08376       ch->peer = NULL;
08377    }
08378 #endif /* AST_MISDN_ENHANCEMENTS */
08379 
08380    if (ch->dsp) {
08381       ast_dsp_free(ch->dsp);
08382       ch->dsp = NULL;
08383    }
08384 
08385    /* releasing jitterbuffer */
08386    if (ch->jb) {
08387       misdn_jb_destroy(ch->jb);
08388       ch->jb = NULL;
08389    } else {
08390       if (!bc->nojitter) {
08391          chan_misdn_log(5, bc->port, "Jitterbuffer already destroyed.\n");
08392       }
08393    }
08394 
08395    if (ch->overlap_dial) {
08396       if (ch->overlap_dial_task != -1) {
08397          misdn_tasks_remove(ch->overlap_dial_task);
08398          ch->overlap_dial_task = -1;
08399       }
08400       ast_mutex_destroy(&ch->overlap_tv_lock);
08401    }
08402 
08403    if (ch->originator == ORG_AST) {
08404       --misdn_out_calls[bc->port];
08405    } else {
08406       --misdn_in_calls[bc->port];
08407    }
08408 
08409    close(ch->pipe[0]);
08410    close(ch->pipe[1]);
08411 
08412    ast_free(ch);
08413 
08414    ast_mutex_unlock(&release_lock);
08415 }
08416 
08417 /*!
08418  * \internal
08419  * \brief Do everything in release_chan() that makes sense without a bc.
08420  *
08421  * \param ch Call channel record to release.
08422  *
08423  * \return Nothing
08424  *
08425  * \note ch must not be referenced after calling.
08426  */
08427 static void release_chan_early(struct chan_list *ch)
08428 {
08429    struct ast_channel *ast;
08430 
08431    ast_mutex_lock(&release_lock);
08432    for (;;) {
08433       ast = ch->ast;
08434       if (!ast || !ast_channel_trylock(ast)) {
08435          break;
08436       }
08437       DEADLOCK_AVOIDANCE(&release_lock);
08438    }
08439    if (!cl_dequeue_chan(ch)) {
08440       /* Someone already released it. */
08441       if (ast) {
08442          ast_channel_unlock(ast);
08443       }
08444       ast_mutex_unlock(&release_lock);
08445       return;
08446    }
08447    ch->state = MISDN_CLEANING;
08448    ch->ast = NULL;
08449    if (ast) {
08450       MISDN_ASTERISK_TECH_PVT(ast) = NULL;
08451       if (ast->_state != AST_STATE_RESERVED) {
08452          ast_setstate(ast, AST_STATE_DOWN);
08453       }
08454       ast_channel_unlock(ast);
08455    }
08456 
08457 #if defined(AST_MISDN_ENHANCEMENTS)
08458    if (ch->peer) {
08459       ao2_ref(ch->peer, -1);
08460       ch->peer = NULL;
08461    }
08462 #endif /* AST_MISDN_ENHANCEMENTS */
08463 
08464    if (ch->dsp) {
08465       ast_dsp_free(ch->dsp);
08466       ch->dsp = NULL;
08467    }
08468 
08469    /* releasing jitterbuffer */
08470    if (ch->jb) {
08471       misdn_jb_destroy(ch->jb);
08472       ch->jb = NULL;
08473    }
08474 
08475    if (ch->overlap_dial) {
08476       if (ch->overlap_dial_task != -1) {
08477          misdn_tasks_remove(ch->overlap_dial_task);
08478          ch->overlap_dial_task = -1;
08479       }
08480       ast_mutex_destroy(&ch->overlap_tv_lock);
08481    }
08482 
08483    if (ch->hold.state != MISDN_HOLD_IDLE) {
08484       if (ch->originator == ORG_AST) {
08485          --misdn_out_calls[ch->hold.port];
08486       } else {
08487          --misdn_in_calls[ch->hold.port];
08488       }
08489    }
08490 
08491    close(ch->pipe[0]);
08492    close(ch->pipe[1]);
08493 
08494    ast_free(ch);
08495 
08496    ast_mutex_unlock(&release_lock);
08497 }
08498 
08499 /*!
08500  * \internal
08501  * \brief Attempt to transfer the active channel party to the held channel party.
08502  *
08503  * \param active_ch Channel currently connected.
08504  * \param held_ch Channel currently on hold.
08505  *
08506  * \retval 0 on success.
08507  * \retval -1 on error.
08508  */
08509 static int misdn_attempt_transfer(struct chan_list *active_ch, struct chan_list *held_ch)
08510 {
08511    int retval;
08512    struct ast_channel *bridged;
08513 
08514    switch (active_ch->state) {
08515    case MISDN_PROCEEDING:
08516    case MISDN_PROGRESS:
08517    case MISDN_ALERTING:
08518    case MISDN_CONNECTED:
08519       break;
08520    default:
08521       return -1;
08522    }
08523 
08524    bridged = ast_bridged_channel(held_ch->ast);
08525    if (bridged) {
08526       ast_queue_control(held_ch->ast, AST_CONTROL_UNHOLD);
08527       held_ch->hold.state = MISDN_HOLD_TRANSFER;
08528 
08529       chan_misdn_log(1, held_ch->hold.port, "TRANSFERRING %s to %s\n",
08530          held_ch->ast->name, active_ch->ast->name);
08531       retval = ast_channel_masquerade(active_ch->ast, bridged);
08532    } else {
08533       /*
08534        * Could not transfer.  Held channel is not bridged anymore.
08535        * Held party probably got tired of waiting and hung up.
08536        */
08537       retval = -1;
08538    }
08539 
08540    return retval;
08541 }
08542 
08543 
08544 static void do_immediate_setup(struct misdn_bchannel *bc, struct chan_list *ch, struct ast_channel *ast)
08545 {
08546    char *predial;
08547    struct ast_frame fr;
08548 
08549    predial = ast_strdupa(ast->exten);
08550 
08551    ch->state = MISDN_DIALING;
08552 
08553    if (!ch->noautorespond_on_setup) {
08554       if (bc->nt) {
08555          misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE);
08556       } else {
08557          if (misdn_lib_is_ptp(bc->port)) {
08558             misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE);
08559          } else {
08560             misdn_lib_send_event(bc, EVENT_PROCEEDING);
08561          }
08562       }
08563    } else {
08564       ch->state = MISDN_INCOMING_SETUP;
08565    }
08566 
08567    chan_misdn_log(1, bc->port,
08568       "* Starting Ast context:%s dialed:%s caller:\"%s\" <%s> with 's' extension\n",
08569       ast->context,
08570       ast->exten,
08571       (ast->caller.id.name.valid && ast->caller.id.name.str)
08572          ? ast->caller.id.name.str : "",
08573       (ast->caller.id.number.valid && ast->caller.id.number.str)
08574          ? ast->caller.id.number.str : "");
08575 
08576    strcpy(ast->exten, "s");
08577 
08578    if (!ast_canmatch_extension(ast, ast->context, ast->exten, 1, bc->caller.number) || pbx_start_chan(ch) < 0) {
08579       ast = NULL;
08580       bc->out_cause = AST_CAUSE_UNALLOCATED;
08581       hangup_chan(ch, bc);
08582       hanguptone_indicate(ch);
08583 
08584       misdn_lib_send_event(bc, bc->nt ? EVENT_RELEASE_COMPLETE : EVENT_DISCONNECT);
08585    }
08586 
08587 
08588    while (!ast_strlen_zero(predial)) {
08589       fr.frametype = AST_FRAME_DTMF;
08590       fr.subclass.integer = *predial;
08591       fr.src = NULL;
08592       fr.data.ptr = NULL;
08593       fr.datalen = 0;
08594       fr.samples = 0;
08595       fr.mallocd = 0;
08596       fr.offset = 0;
08597       fr.delivery = ast_tv(0,0);
08598 
08599       if (ch->ast && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
08600          ast_queue_frame(ch->ast, &fr);
08601       }
08602       predial++;
08603    }
08604 }
08605 
08606 
08607 
08608 static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel *bc, struct chan_list *ch) {
08609    if (!ast) {
08610       chan_misdn_log(1, 0, "send_cause2ast: No Ast\n");
08611       return;
08612    }
08613    if (!bc) {
08614       chan_misdn_log(1, 0, "send_cause2ast: No BC\n");
08615       return;
08616    }
08617    if (!ch) {
08618       chan_misdn_log(1, 0, "send_cause2ast: No Ch\n");
08619       return;
08620    }
08621 
08622    ast->hangupcause = bc->cause;
08623 
08624    switch (bc->cause) {
08625 
08626    case AST_CAUSE_UNALLOCATED:
08627    case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
08628    case AST_CAUSE_NO_ROUTE_DESTINATION:
08629    case 4:  /* Send special information tone */
08630    case AST_CAUSE_NUMBER_CHANGED:
08631    case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
08632       /* Congestion Cases */
08633       /*
08634        * Not Queueing the Congestion anymore, since we want to hear
08635        * the inband message
08636        *
08637       chan_misdn_log(1, bc ? bc->port : 0, " --> * SEND: Queue Congestion pid:%d\n", bc ? bc->pid : -1);
08638       ch->state = MISDN_BUSY;
08639 
08640       ast_queue_control(ast, AST_CONTROL_CONGESTION);
08641       */
08642       break;
08643 
08644    case AST_CAUSE_CALL_REJECTED:
08645    case AST_CAUSE_USER_BUSY:
08646       ch->state = MISDN_BUSY;
08647 
08648       if (!ch->need_busy) {
08649          chan_misdn_log(1, bc ? bc->port : 0, "Queued busy already\n");
08650          break;
08651       }
08652 
08653       chan_misdn_log(1, bc ? bc->port : 0, " --> * SEND: Queue Busy pid:%d\n", bc ? bc->pid : -1);
08654 
08655       ast_queue_control(ast, AST_CONTROL_BUSY);
08656 
08657       ch->need_busy = 0;
08658 
08659       break;
08660    }
08661 }
08662 
08663 
08664 /*! \brief Import parameters from the dialplan environment variables */
08665 void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
08666 {
08667    const char *tmp;
08668 
08669    ast_channel_lock(chan);
08670    tmp = pbx_builtin_getvar_helper(chan, "MISDN_PID");
08671    if (tmp) {
08672       ch->other_pid = atoi(tmp);
08673       chan_misdn_log(3, bc->port, " --> IMPORT_PID: importing pid:%s\n", tmp);
08674       if (ch->other_pid > 0) {
08675          ch->other_ch = find_chan_by_pid(ch->other_pid);
08676          if (ch->other_ch) {
08677             ch->other_ch->other_ch = ch;
08678          }
08679       }
08680    }
08681 
08682    tmp = pbx_builtin_getvar_helper(chan, "MISDN_ADDRESS_COMPLETE");
08683    if (tmp && (atoi(tmp) == 1)) {
08684       bc->sending_complete = 1;
08685    }
08686 
08687    tmp = pbx_builtin_getvar_helper(chan, "MISDN_USERUSER");
08688    if (tmp) {
08689       ast_log(LOG_NOTICE, "MISDN_USERUSER: %s\n", tmp);
08690       ast_copy_string(bc->uu, tmp, sizeof(bc->uu));
08691       bc->uulen = strlen(bc->uu);
08692    }
08693 
08694    tmp = pbx_builtin_getvar_helper(chan, "MISDN_KEYPAD");
08695    if (tmp) {
08696       ast_copy_string(bc->keypad, tmp, sizeof(bc->keypad));
08697    }
08698    ast_channel_unlock(chan);
08699 }
08700 
08701 /*! \brief Export parameters to the dialplan environment variables */
08702 void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
08703 {
08704    char tmp[32];
08705 
08706    chan_misdn_log(3, bc->port, " --> EXPORT_PID: pid:%d\n", bc->pid);
08707    snprintf(tmp, sizeof(tmp), "%d", bc->pid);
08708    pbx_builtin_setvar_helper(chan, "_MISDN_PID", tmp);
08709 
08710    if (bc->sending_complete) {
08711       snprintf(tmp, sizeof(tmp), "%d", bc->sending_complete);
08712       pbx_builtin_setvar_helper(chan, "MISDN_ADDRESS_COMPLETE", tmp);
08713    }
08714 
08715    if (bc->urate) {
08716       snprintf(tmp, sizeof(tmp), "%d", bc->urate);
08717       pbx_builtin_setvar_helper(chan, "MISDN_URATE", tmp);
08718    }
08719 
08720    if (bc->uulen) {
08721       pbx_builtin_setvar_helper(chan, "MISDN_USERUSER", bc->uu);
08722    }
08723 
08724    if (!ast_strlen_zero(bc->keypad)) {
08725       pbx_builtin_setvar_helper(chan, "MISDN_KEYPAD", bc->keypad);
08726    }
08727 }
08728 
08729 int add_in_calls(int port)
08730 {
08731    int max_in_calls;
08732 
08733    misdn_cfg_get(port, MISDN_CFG_MAX_IN, &max_in_calls, sizeof(max_in_calls));
08734    misdn_in_calls[port]++;
08735 
08736    if (max_in_calls >= 0 && max_in_calls < misdn_in_calls[port]) {
08737       ast_log(LOG_NOTICE, "Marking Incoming Call on port[%d]\n", port);
08738       return misdn_in_calls[port] - max_in_calls;
08739    }
08740 
08741    return 0;
08742 }
08743 
08744 int add_out_calls(int port)
08745 {
08746    int max_out_calls;
08747 
08748    misdn_cfg_get(port, MISDN_CFG_MAX_OUT, &max_out_calls, sizeof(max_out_calls));
08749 
08750    if (max_out_calls >= 0 && max_out_calls <= misdn_out_calls[port]) {
08751       ast_log(LOG_NOTICE, "Rejecting Outgoing Call on port[%d]\n", port);
08752       return (misdn_out_calls[port] + 1) - max_out_calls;
08753    }
08754 
08755    misdn_out_calls[port]++;
08756 
08757    return 0;
08758 }
08759 
08760 static void start_pbx(struct chan_list *ch, struct misdn_bchannel *bc, struct ast_channel *chan)
08761 {
08762    if (pbx_start_chan(ch) < 0) {
08763       hangup_chan(ch, bc);
08764       chan_misdn_log(-1, bc->port, "ast_pbx_start returned <0 in SETUP\n");
08765       if (bc->nt) {
08766          hanguptone_indicate(ch);
08767          misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
08768       } else {
08769          misdn_lib_send_event(bc, EVENT_RELEASE);
08770       }
08771    }
08772 }
08773 
08774 static void wait_for_digits(struct chan_list *ch, struct misdn_bchannel *bc, struct ast_channel *chan)
08775 {
08776    ch->state = MISDN_WAITING4DIGS;
08777    misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE);
08778    if (bc->nt && !bc->dialed.number[0]) {
08779       dialtone_indicate(ch);
08780    }
08781 }
08782 
08783 #if defined(AST_MISDN_ENHANCEMENTS)
08784 /*!
08785  * \internal
08786  * \brief Handle the FACILITY CCBSStatusRequest message.
08787  *
08788  * \param port Logical port number.
08789  * \param facility Facility ie contents.
08790  *
08791  * \return Nothing
08792  */
08793 static void misdn_cc_handle_ccbs_status_request(int port, const struct FacParm *facility)
08794 {
08795    struct misdn_cc_record *cc_record;
08796    struct misdn_bchannel dummy;
08797 
08798    switch (facility->u.CCBSStatusRequest.ComponentType) {
08799    case FacComponent_Invoke:
08800       /* Build message */
08801       misdn_make_dummy(&dummy, port, 0, misdn_lib_port_is_nt(port), 0);
08802       dummy.fac_out.Function = Fac_CCBSStatusRequest;
08803       dummy.fac_out.u.CCBSStatusRequest.InvokeID = facility->u.CCBSStatusRequest.InvokeID;
08804       dummy.fac_out.u.CCBSStatusRequest.ComponentType = FacComponent_Result;
08805 
08806       /* Answer User-A free question */
08807       AST_LIST_LOCK(&misdn_cc_records_db);
08808       cc_record = misdn_cc_find_by_reference(port, facility->u.CCBSStatusRequest.Component.Invoke.CCBSReference);
08809       if (cc_record) {
08810          dummy.fac_out.u.CCBSStatusRequest.Component.Result.Free = cc_record->party_a_free;
08811       } else {
08812          /* No record so say User-A is free */
08813          dummy.fac_out.u.CCBSStatusRequest.Component.Result.Free = 1;
08814       }
08815       AST_LIST_UNLOCK(&misdn_cc_records_db);
08816 
08817       /* Send message */
08818       print_facility(&dummy.fac_out, &dummy);
08819       misdn_lib_send_event(&dummy, EVENT_FACILITY);
08820       break;
08821 
08822    default:
08823       chan_misdn_log(0, port, " --> not yet handled: facility type:0x%04X\n", facility->Function);
08824       break;
08825    }
08826 }
08827 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
08828 
08829 #if defined(AST_MISDN_ENHANCEMENTS)
08830 /*!
08831  * \internal
08832  * \brief Start a PBX to notify that User-B is available.
08833  *
08834  * \param record_id Call completion record ID
08835  * \param notify Dialplan location to start processing.
08836  *
08837  * \return Nothing
08838  */
08839 static void misdn_cc_pbx_notify(long record_id, const struct misdn_cc_notify *notify)
08840 {
08841    struct ast_channel *chan;
08842    char id_str[32];
08843 
08844    static unsigned short sequence = 0;
08845 
08846    /* Create a channel to notify with */
08847    snprintf(id_str, sizeof(id_str), "%ld", record_id);
08848    chan = ast_channel_alloc(0, AST_STATE_DOWN, id_str, NULL, NULL,
08849       notify->exten, notify->context, NULL, 0,
08850       "mISDN-CC/%ld-%X", record_id, (unsigned) ++sequence);
08851    if (!chan) {
08852       ast_log(LOG_ERROR, "Unable to allocate channel!\n");
08853       return;
08854    }
08855    chan->priority = notify->priority;
08856    ast_free(chan->dialed.number.str);
08857    chan->dialed.number.str = ast_strdup(notify->exten);
08858 
08859    if (ast_pbx_start(chan)) {
08860       ast_log(LOG_WARNING, "Unable to start pbx channel %s!\n", chan->name);
08861       ast_channel_release(chan);
08862    } else {
08863       ast_verb(1, "Started pbx for call completion notify channel %s\n", chan->name);
08864    }
08865 }
08866 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
08867 
08868 #if defined(AST_MISDN_ENHANCEMENTS)
08869 /*!
08870  * \internal
08871  * \brief Handle the FACILITY CCBS_T_RemoteUserFree message.
08872  *
08873  * \param bc B channel control structure message came in on
08874  *
08875  * \return Nothing
08876  */
08877 static void misdn_cc_handle_T_remote_user_free(struct misdn_bchannel *bc)
08878 {
08879    struct misdn_cc_record *cc_record;
08880    struct misdn_cc_notify notify;
08881    long record_id;
08882 
08883    AST_LIST_LOCK(&misdn_cc_records_db);
08884    cc_record = misdn_cc_find_by_bc(bc);
08885    if (cc_record) {
08886       if (cc_record->party_a_free) {
08887          notify = cc_record->remote_user_free;
08888       } else {
08889          /* Send CCBS_T_Suspend message */
08890          bc->fac_out.Function = Fac_CCBS_T_Suspend;
08891          bc->fac_out.u.CCBS_T_Suspend.InvokeID = ++misdn_invoke_id;
08892          print_facility(&bc->fac_out, bc);
08893          misdn_lib_send_event(bc, EVENT_FACILITY);
08894 
08895          notify = cc_record->b_free;
08896       }
08897       record_id = cc_record->record_id;
08898       AST_LIST_UNLOCK(&misdn_cc_records_db);
08899       if (notify.context[0]) {
08900          /* Party A is free or B-Free notify has been setup. */
08901          misdn_cc_pbx_notify(record_id, &notify);
08902       }
08903    } else {
08904       AST_LIST_UNLOCK(&misdn_cc_records_db);
08905    }
08906 }
08907 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
08908 
08909 #if defined(AST_MISDN_ENHANCEMENTS)
08910 /*!
08911  * \internal
08912  * \brief Handle the FACILITY CCBSRemoteUserFree message.
08913  *
08914  * \param port Logical port number.
08915  * \param facility Facility ie contents.
08916  *
08917  * \return Nothing
08918  */
08919 static void misdn_cc_handle_remote_user_free(int port, const struct FacParm *facility)
08920 {
08921    struct misdn_cc_record *cc_record;
08922    struct misdn_cc_notify notify;
08923    long record_id;
08924 
08925    AST_LIST_LOCK(&misdn_cc_records_db);
08926    cc_record = misdn_cc_find_by_reference(port, facility->u.CCBSRemoteUserFree.CCBSReference);
08927    if (cc_record) {
08928       notify = cc_record->remote_user_free;
08929       record_id = cc_record->record_id;
08930       AST_LIST_UNLOCK(&misdn_cc_records_db);
08931       misdn_cc_pbx_notify(record_id, &notify);
08932    } else {
08933       AST_LIST_UNLOCK(&misdn_cc_records_db);
08934    }
08935 }
08936 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
08937 
08938 #if defined(AST_MISDN_ENHANCEMENTS)
08939 /*!
08940  * \internal
08941  * \brief Handle the FACILITY CCBSBFree message.
08942  *
08943  * \param port Logical port number.
08944  * \param facility Facility ie contents.
08945  *
08946  * \return Nothing
08947  */
08948 static void misdn_cc_handle_b_free(int port, const struct FacParm *facility)
08949 {
08950    struct misdn_cc_record *cc_record;
08951    struct misdn_cc_notify notify;
08952    long record_id;
08953 
08954    AST_LIST_LOCK(&misdn_cc_records_db);
08955    cc_record = misdn_cc_find_by_reference(port, facility->u.CCBSBFree.CCBSReference);
08956    if (cc_record && cc_record->b_free.context[0]) {
08957       /* B-Free notify has been setup. */
08958       notify = cc_record->b_free;
08959       record_id = cc_record->record_id;
08960       AST_LIST_UNLOCK(&misdn_cc_records_db);
08961       misdn_cc_pbx_notify(record_id, &notify);
08962    } else {
08963       AST_LIST_UNLOCK(&misdn_cc_records_db);
08964    }
08965 }
08966 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
08967 
08968 /*!
08969  * \internal
08970  * \brief Handle the incoming facility ie contents
08971  *
08972  * \param event Message type facility ie came in on
08973  * \param bc B channel control structure message came in on
08974  * \param ch Associated channel call record
08975  *
08976  * \return Nothing
08977  */
08978 static void misdn_facility_ie_handler(enum event_e event, struct misdn_bchannel *bc, struct chan_list *ch)
08979 {
08980 #if defined(AST_MISDN_ENHANCEMENTS)
08981    const char *diagnostic_msg;
08982    struct misdn_cc_record *cc_record;
08983    char buf[32];
08984    struct misdn_party_id party_id;
08985    long new_record_id;
08986 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
08987 
08988    print_facility(&bc->fac_in, bc);
08989    switch (bc->fac_in.Function) {
08990 #if defined(AST_MISDN_ENHANCEMENTS)
08991    case Fac_ActivationDiversion:
08992       switch (bc->fac_in.u.ActivationDiversion.ComponentType) {
08993       case FacComponent_Result:
08994          /* Positive ACK to activation */
08995          /* We don't handle this yet */
08996          break;
08997       default:
08998          chan_misdn_log(0, bc->port," --> not yet handled: facility type:0x%04X\n",
08999             bc->fac_in.Function);
09000          break;
09001       }
09002       break;
09003    case Fac_DeactivationDiversion:
09004       switch (bc->fac_in.u.DeactivationDiversion.ComponentType) {
09005       case FacComponent_Result:
09006          /* Positive ACK to deactivation */
09007          /* We don't handle this yet */
09008          break;
09009       default:
09010          chan_misdn_log(0, bc->port," --> not yet handled: facility type:0x%04X\n",
09011             bc->fac_in.Function);
09012          break;
09013       }
09014       break;
09015    case Fac_ActivationStatusNotificationDiv:
09016       /* Sent to other MSN numbers on the line when a user activates call forwarding. */
09017       /* Sent in the first call control message of an outgoing call from the served user. */
09018       /* We do not have anything to do for this message. */
09019       break;
09020    case Fac_DeactivationStatusNotificationDiv:
09021       /* Sent to other MSN numbers on the line when a user deactivates call forwarding. */
09022       /* We do not have anything to do for this message. */
09023       break;
09024 #if 0 /* We don't handle this yet */
09025    case Fac_InterrogationDiversion:
09026       /* We don't handle this yet */
09027       break;
09028    case Fac_InterrogateServedUserNumbers:
09029       /* We don't handle this yet */
09030       break;
09031 #endif   /* We don't handle this yet */
09032    case Fac_DiversionInformation:
09033       /* Sent to the served user when a call is forwarded. */
09034       /* We do not have anything to do for this message. */
09035       break;
09036    case Fac_CallDeflection:
09037       if (ch && ch->ast) {
09038          switch (bc->fac_in.u.CallDeflection.ComponentType) {
09039          case FacComponent_Invoke:
09040             ast_copy_string(bc->redirecting.from.number, bc->dialed.number,
09041                sizeof(bc->redirecting.from.number));
09042             bc->redirecting.from.name[0] = 0;
09043             bc->redirecting.from.number_plan = bc->dialed.number_plan;
09044             bc->redirecting.from.number_type = bc->dialed.number_type;
09045             bc->redirecting.from.screening = 0;/* Unscreened */
09046             if (bc->fac_in.u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUserPresent) {
09047                bc->redirecting.from.presentation =
09048                   bc->fac_in.u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUser
09049                   ? 0 /* Allowed */ : 1 /* Restricted */;
09050             } else {
09051                bc->redirecting.from.presentation = 0;/* Allowed */
09052             }
09053 
09054             /* Add configured prefix to the call deflection number */
09055             memset(&party_id, 0, sizeof(party_id));
09056             misdn_PartyNumber_extract(&party_id,
09057                &bc->fac_in.u.CallDeflection.Component.Invoke.Deflection.Party);
09058             misdn_add_number_prefix(bc->port, party_id.number_type,
09059                party_id.number, sizeof(party_id.number));
09060             //party_id.presentation = 0;/* Allowed */
09061             //party_id.screening = 0;/* Unscreened */
09062             bc->redirecting.to = party_id;
09063 
09064             ++bc->redirecting.count;
09065             bc->redirecting.reason = mISDN_REDIRECTING_REASON_DEFLECTION;
09066 
09067             misdn_copy_redirecting_to_ast(ch->ast, &bc->redirecting, bc->incoming_cid_tag);
09068             ast_string_field_set(ch->ast, call_forward, bc->redirecting.to.number);
09069 
09070             /* Send back positive ACK */
09071 #if 1
09072             /*
09073              * Since there are no return result arguments it must be a
09074              * generic result message.  ETSI 300-196
09075              */
09076             bc->fac_out.Function = Fac_RESULT;
09077             bc->fac_out.u.RESULT.InvokeID = bc->fac_in.u.CallDeflection.InvokeID;
09078 #else
09079             bc->fac_out.Function = Fac_CallDeflection;
09080             bc->fac_out.u.CallDeflection.InvokeID = bc->fac_in.u.CallDeflection.InvokeID;
09081             bc->fac_out.u.CallDeflection.ComponentType = FacComponent_Result;
09082 #endif
09083             print_facility(&bc->fac_out, bc);
09084             misdn_lib_send_event(bc, EVENT_DISCONNECT);
09085 
09086             /* This line is BUSY to further attempts by this dialing attempt. */
09087             ast_queue_control(ch->ast, AST_CONTROL_BUSY);
09088             break;
09089 
09090          case FacComponent_Result:
09091             /* Positive ACK to call deflection */
09092             /*
09093              * Sent in DISCONNECT or FACILITY message depending upon network option.
09094              * It is in the FACILITY message if the call is still offered to the user
09095              * while trying to alert the deflected to party.
09096              */
09097             /* Ignore the ACK */
09098             break;
09099 
09100          default:
09101             break;
09102          }
09103       }
09104       break;
09105 #if 0 /* We don't handle this yet */
09106    case Fac_CallRerouteing:
09107       /* Private-Public ISDN interworking message */
09108       /* We don't handle this yet */
09109       break;
09110 #endif   /* We don't handle this yet */
09111    case Fac_DivertingLegInformation1:
09112       /* Private-Public ISDN interworking message */
09113       bc->div_leg_3_rx_wanted = 0;
09114       if (ch && ch->ast) {
09115          bc->redirecting.reason =
09116             diversion_reason_to_misdn(bc->fac_in.u.DivertingLegInformation1.DiversionReason);
09117          if (bc->fac_in.u.DivertingLegInformation1.DivertedToPresent) {
09118             misdn_PresentedNumberUnscreened_extract(&bc->redirecting.to,
09119                &bc->fac_in.u.DivertingLegInformation1.DivertedTo);
09120 
09121             /* Add configured prefix to redirecting.to.number */
09122             misdn_add_number_prefix(bc->port, bc->redirecting.to.number_type,
09123                bc->redirecting.to.number, sizeof(bc->redirecting.to.number));
09124          } else {
09125             bc->redirecting.to.number[0] = '\0';
09126             bc->redirecting.to.number_plan = NUMPLAN_ISDN;
09127             bc->redirecting.to.number_type = NUMTYPE_UNKNOWN;
09128             bc->redirecting.to.presentation = 1;/* restricted */
09129             bc->redirecting.to.screening = 0;/* unscreened */
09130          }
09131          misdn_copy_redirecting_to_ast(ch->ast, &bc->redirecting, bc->incoming_cid_tag);
09132          bc->div_leg_3_rx_wanted = 1;
09133       }
09134       break;
09135    case Fac_DivertingLegInformation2:
09136       /* Private-Public ISDN interworking message */
09137       switch (event) {
09138       case EVENT_SETUP:
09139          /* Comes in on a SETUP with redirecting.from information */
09140          bc->div_leg_3_tx_pending = 1;
09141          if (ch && ch->ast) {
09142             /*
09143              * Setup the redirecting.to informtion so we can identify
09144              * if the user wants to manually supply the COLR for this
09145              * redirected to number if further redirects could happen.
09146              *
09147              * All the user needs to do is set the REDIRECTING(to-pres)
09148              * to the COLR and REDIRECTING(to-num) = ${EXTEN} to be safe
09149              * after determining that the incoming call was redirected by
09150              * checking if there is a REDIRECTING(from-num).
09151              */
09152             ast_copy_string(bc->redirecting.to.number, bc->dialed.number,
09153                sizeof(bc->redirecting.to.number));
09154             bc->redirecting.to.number_plan = bc->dialed.number_plan;
09155             bc->redirecting.to.number_type = bc->dialed.number_type;
09156             bc->redirecting.to.presentation = 1;/* restricted */
09157             bc->redirecting.to.screening = 0;/* unscreened */
09158 
09159             bc->redirecting.reason =
09160                diversion_reason_to_misdn(bc->fac_in.u.DivertingLegInformation2.DiversionReason);
09161             bc->redirecting.count = bc->fac_in.u.DivertingLegInformation2.DiversionCounter;
09162             if (bc->fac_in.u.DivertingLegInformation2.DivertingPresent) {
09163                /* This information is redundant if there was a redirecting ie in the SETUP. */
09164                misdn_PresentedNumberUnscreened_extract(&bc->redirecting.from,
09165                   &bc->fac_in.u.DivertingLegInformation2.Diverting);
09166 
09167                /* Add configured prefix to redirecting.from.number */
09168                misdn_add_number_prefix(bc->port, bc->redirecting.from.number_type,
09169                   bc->redirecting.from.number, sizeof(bc->redirecting.from.number));
09170             }
09171 #if 0
09172             if (bc->fac_in.u.DivertingLegInformation2.OriginalCalledPresent) {
09173                /* We have no place to put the OriginalCalled number */
09174             }
09175 #endif
09176             misdn_copy_redirecting_to_ast(ch->ast, &bc->redirecting, bc->incoming_cid_tag);
09177          }
09178          break;
09179       default:
09180          chan_misdn_log(0, bc->port," --> Expected in a SETUP message: facility type:0x%04X\n",
09181             bc->fac_in.Function);
09182          break;
09183       }
09184       break;
09185    case Fac_DivertingLegInformation3:
09186       /* Private-Public ISDN interworking message */
09187       if (bc->div_leg_3_rx_wanted) {
09188          bc->div_leg_3_rx_wanted = 0;
09189 
09190          if (ch && ch->ast) {
09191             ch->ast->redirecting.to.number.presentation =
09192                bc->fac_in.u.DivertingLegInformation3.PresentationAllowedIndicator
09193                ? AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_UNSCREENED
09194                : AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED;
09195             ast_channel_queue_redirecting_update(ch->ast, &ch->ast->redirecting, NULL);
09196          }
09197       }
09198       break;
09199 
09200 #else /* !defined(AST_MISDN_ENHANCEMENTS) */
09201 
09202    case Fac_CD:
09203       if (ch && ch->ast) {
09204          ast_copy_string(bc->redirecting.from.number, bc->dialed.number,
09205             sizeof(bc->redirecting.from.number));
09206          bc->redirecting.from.name[0] = 0;
09207          bc->redirecting.from.number_plan = bc->dialed.number_plan;
09208          bc->redirecting.from.number_type = bc->dialed.number_type;
09209          bc->redirecting.from.screening = 0;/* Unscreened */
09210          bc->redirecting.from.presentation =
09211             bc->fac_in.u.CDeflection.PresentationAllowed
09212             ? 0 /* Allowed */ : 1 /* Restricted */;
09213 
09214          ast_copy_string(bc->redirecting.to.number,
09215             (char *) bc->fac_in.u.CDeflection.DeflectedToNumber,
09216             sizeof(bc->redirecting.to.number));
09217          bc->redirecting.to.name[0] = 0;
09218          bc->redirecting.to.number_plan = NUMPLAN_UNKNOWN;
09219          bc->redirecting.to.number_type = NUMTYPE_UNKNOWN;
09220          bc->redirecting.to.presentation = 0;/* Allowed */
09221          bc->redirecting.to.screening = 0;/* Unscreened */
09222 
09223          ++bc->redirecting.count;
09224          bc->redirecting.reason = mISDN_REDIRECTING_REASON_DEFLECTION;
09225 
09226          misdn_copy_redirecting_to_ast(ch->ast, &bc->redirecting, bc->incoming_cid_tag);
09227          ast_string_field_set(ch->ast, call_forward, bc->redirecting.to.number);
09228 
09229          misdn_lib_send_event(bc, EVENT_DISCONNECT);
09230 
09231          /* This line is BUSY to further attempts by this dialing attempt. */
09232          ast_queue_control(ch->ast, AST_CONTROL_BUSY);
09233       }
09234       break;
09235 #endif   /* !defined(AST_MISDN_ENHANCEMENTS) */
09236    case Fac_AOCDCurrency:
09237       if (ch && ch->ast) {
09238          bc->AOCDtype = Fac_AOCDCurrency;
09239          memcpy(&bc->AOCD.currency, &bc->fac_in.u.AOCDcur, sizeof(bc->AOCD.currency));
09240          bc->AOCD_need_export = 1;
09241          export_aoc_vars(ch->originator, ch->ast, bc);
09242       }
09243       break;
09244    case Fac_AOCDChargingUnit:
09245       if (ch && ch->ast) {
09246          bc->AOCDtype = Fac_AOCDChargingUnit;
09247          memcpy(&bc->AOCD.chargingUnit, &bc->fac_in.u.AOCDchu, sizeof(bc->AOCD.chargingUnit));
09248          bc->AOCD_need_export = 1;
09249          export_aoc_vars(ch->originator, ch->ast, bc);
09250       }
09251       break;
09252 #if defined(AST_MISDN_ENHANCEMENTS)
09253    case Fac_ERROR:
09254       diagnostic_msg = misdn_to_str_error_code(bc->fac_in.u.ERROR.errorValue);
09255       chan_misdn_log(1, bc->port, " --> Facility error code: %s\n", diagnostic_msg);
09256       switch (event) {
09257       case EVENT_DISCONNECT:
09258       case EVENT_RELEASE:
09259       case EVENT_RELEASE_COMPLETE:
09260          /* Possible call failure as a result of Fac_CCBSCall/Fac_CCBS_T_Call */
09261          if (ch && ch->peer) {
09262             misdn_cc_set_peer_var(ch->peer, MISDN_ERROR_MSG, diagnostic_msg);
09263          }
09264          break;
09265       default:
09266          break;
09267       }
09268       AST_LIST_LOCK(&misdn_cc_records_db);
09269       cc_record = misdn_cc_find_by_invoke(bc->port, bc->fac_in.u.ERROR.invokeId);
09270       if (cc_record) {
09271          cc_record->outstanding_message = 0;
09272          cc_record->error_code = bc->fac_in.u.ERROR.errorValue;
09273       }
09274       AST_LIST_UNLOCK(&misdn_cc_records_db);
09275       break;
09276    case Fac_REJECT:
09277       diagnostic_msg = misdn_to_str_reject_code(bc->fac_in.u.REJECT.Code);
09278       chan_misdn_log(1, bc->port, " --> Facility reject code: %s\n", diagnostic_msg);
09279       switch (event) {
09280       case EVENT_DISCONNECT:
09281       case EVENT_RELEASE:
09282       case EVENT_RELEASE_COMPLETE:
09283          /* Possible call failure as a result of Fac_CCBSCall/Fac_CCBS_T_Call */
09284          if (ch && ch->peer) {
09285             misdn_cc_set_peer_var(ch->peer, MISDN_ERROR_MSG, diagnostic_msg);
09286          }
09287          break;
09288       default:
09289          break;
09290       }
09291       if (bc->fac_in.u.REJECT.InvokeIDPresent) {
09292          AST_LIST_LOCK(&misdn_cc_records_db);
09293          cc_record = misdn_cc_find_by_invoke(bc->port, bc->fac_in.u.REJECT.InvokeID);
09294          if (cc_record) {
09295             cc_record->outstanding_message = 0;
09296             cc_record->reject_code = bc->fac_in.u.REJECT.Code;
09297          }
09298          AST_LIST_UNLOCK(&misdn_cc_records_db);
09299       }
09300       break;
09301    case Fac_RESULT:
09302       AST_LIST_LOCK(&misdn_cc_records_db);
09303       cc_record = misdn_cc_find_by_invoke(bc->port, bc->fac_in.u.RESULT.InvokeID);
09304       if (cc_record) {
09305          cc_record->outstanding_message = 0;
09306       }
09307       AST_LIST_UNLOCK(&misdn_cc_records_db);
09308       break;
09309 #if 0 /* We don't handle this yet */
09310    case Fac_EctExecute:
09311       /* We don't handle this yet */
09312       break;
09313    case Fac_ExplicitEctExecute:
09314       /* We don't handle this yet */
09315       break;
09316    case Fac_EctLinkIdRequest:
09317       /* We don't handle this yet */
09318       break;
09319 #endif   /* We don't handle this yet */
09320    case Fac_SubaddressTransfer:
09321       /* We do not have anything to do for this message since we do not handle subaddreses. */
09322       break;
09323    case Fac_RequestSubaddress:
09324       /*
09325        * We do not have anything to do for this message since we do not handle subaddreses.
09326        * However, we do care about some other ie's that should be present.
09327        */
09328       if (bc->redirecting.to_changed) {
09329          /* Add configured prefix to redirecting.to.number */
09330          misdn_add_number_prefix(bc->port, bc->redirecting.to.number_type,
09331             bc->redirecting.to.number, sizeof(bc->redirecting.to.number));
09332       }
09333       switch (bc->notify_description_code) {
09334       case mISDN_NOTIFY_CODE_INVALID:
09335          /* Notify ie was not present. */
09336          bc->redirecting.to_changed = 0;
09337          break;
09338       case mISDN_NOTIFY_CODE_CALL_TRANSFER_ALERTING:
09339          /*
09340           * It would be preferable to update the connected line information
09341           * only when the message callStatus is active.  However, the
09342           * optional redirection number may not be present in the active
09343           * message if an alerting message were received earlier.
09344           *
09345           * The consequences if we wind up sending two updates is benign.
09346           * The other end will think that it got transferred twice.
09347           */
09348          if (!bc->redirecting.to_changed) {
09349             break;
09350          }
09351          bc->redirecting.to_changed = 0;
09352          if (!ch || !ch->ast) {
09353             break;
09354          }
09355          misdn_update_remote_party(ch->ast, &bc->redirecting.to,
09356             AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER_ALERTING,
09357             bc->incoming_cid_tag);
09358          break;
09359       case mISDN_NOTIFY_CODE_CALL_TRANSFER_ACTIVE:
09360          if (!bc->redirecting.to_changed) {
09361             break;
09362          }
09363          bc->redirecting.to_changed = 0;
09364          if (!ch || !ch->ast) {
09365             break;
09366          }
09367          misdn_update_remote_party(ch->ast, &bc->redirecting.to,
09368             AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER, bc->incoming_cid_tag);
09369          break;
09370       default:
09371          bc->redirecting.to_changed = 0;
09372          chan_misdn_log(0, bc->port," --> not yet handled: notify code:0x%02X\n",
09373             bc->notify_description_code);
09374          break;
09375       }
09376       bc->notify_description_code = mISDN_NOTIFY_CODE_INVALID;
09377       break;
09378    case Fac_EctInform:
09379       /* Private-Public ISDN interworking message */
09380       if (ch && ch->ast && bc->fac_in.u.EctInform.RedirectionPresent) {
09381          /* Add configured prefix to the redirection number */
09382          memset(&party_id, 0, sizeof(party_id));
09383          misdn_PresentedNumberUnscreened_extract(&party_id,
09384             &bc->fac_in.u.EctInform.Redirection);
09385          misdn_add_number_prefix(bc->port, party_id.number_type,
09386             party_id.number, sizeof(party_id.number));
09387 
09388          /*
09389           * It would be preferable to update the connected line information
09390           * only when the message callStatus is active.  However, the
09391           * optional redirection number may not be present in the active
09392           * message if an alerting message were received earlier.
09393           *
09394           * The consequences if we wind up sending two updates is benign.
09395           * The other end will think that it got transferred twice.
09396           */
09397          misdn_update_remote_party(ch->ast, &party_id,
09398             (bc->fac_in.u.EctInform.Status == 0 /* alerting */)
09399                ? AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER_ALERTING
09400                : AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER,
09401                bc->incoming_cid_tag);
09402       }
09403       break;
09404 #if 0 /* We don't handle this yet */
09405    case Fac_EctLoopTest:
09406       /* The use of this message is unclear on how it works to detect loops. */
09407       /* We don't handle this yet */
09408       break;
09409 #endif   /* We don't handle this yet */
09410    case Fac_CallInfoRetain:
09411       switch (event) {
09412       case EVENT_ALERTING:
09413       case EVENT_DISCONNECT:
09414          /* CCBS/CCNR is available */
09415          if (ch && ch->peer) {
09416             AST_LIST_LOCK(&misdn_cc_records_db);
09417             if (ch->record_id == -1) {
09418                cc_record = misdn_cc_new();
09419             } else {
09420                /*
09421                 * We are doing a call-completion attempt
09422                 * or the switch is sending us extra call-completion
09423                 * availability indications (erroneously?).
09424                 *
09425                 * Assume that the network request retention option
09426                 * is not on and that the current call-completion
09427                 * request is disabled.
09428                 */
09429                cc_record = misdn_cc_find_by_id(ch->record_id);
09430                if (cc_record) {
09431                   if (cc_record->ptp && cc_record->mode.ptp.bc) {
09432                      /*
09433                       * What?  We are getting mixed messages from the
09434                       * switch.  We are currently setup for
09435                       * point-to-point.  Now we are switching to
09436                       * point-to-multipoint.
09437                       *
09438                       * Close the call-completion signaling link
09439                       */
09440                      cc_record->mode.ptp.bc->fac_out.Function = Fac_None;
09441                      cc_record->mode.ptp.bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
09442                      misdn_lib_send_event(cc_record->mode.ptp.bc, EVENT_RELEASE_COMPLETE);
09443                   }
09444 
09445                   /*
09446                    * Resetup the existing record for a possible new
09447                    * call-completion request.
09448                    */
09449                   new_record_id = misdn_cc_record_id_new();
09450                   if (new_record_id < 0) {
09451                      /* Looks like we must keep the old id anyway. */
09452                   } else {
09453                      cc_record->record_id = new_record_id;
09454                      ch->record_id = new_record_id;
09455                   }
09456                   cc_record->ptp = 0;
09457                   cc_record->port = bc->port;
09458                   memset(&cc_record->mode, 0, sizeof(cc_record->mode));
09459                   cc_record->mode.ptmp.linkage_id = bc->fac_in.u.CallInfoRetain.CallLinkageID;
09460                   cc_record->invoke_id = ++misdn_invoke_id;
09461                   cc_record->activated = 0;
09462                   cc_record->outstanding_message = 0;
09463                   cc_record->activation_requested = 0;
09464                   cc_record->error_code = FacError_None;
09465                   cc_record->reject_code = FacReject_None;
09466                   memset(&cc_record->remote_user_free, 0, sizeof(cc_record->remote_user_free));
09467                   memset(&cc_record->b_free, 0, sizeof(cc_record->b_free));
09468                   cc_record->time_created = time(NULL);
09469 
09470                   cc_record = NULL;
09471                } else {
09472                   /*
09473                    * Where did the record go?  We will have to recapture
09474                    * the call setup information.  Unfortunately, some
09475                    * setup information may have been changed.
09476                    */
09477                   ch->record_id = -1;
09478                   cc_record = misdn_cc_new();
09479                }
09480             }
09481             if (cc_record) {
09482                ch->record_id = cc_record->record_id;
09483                cc_record->ptp = 0;
09484                cc_record->port = bc->port;
09485                cc_record->mode.ptmp.linkage_id = bc->fac_in.u.CallInfoRetain.CallLinkageID;
09486 
09487                /* Record call information for possible call-completion attempt. */
09488                cc_record->redial.caller = bc->caller;
09489                cc_record->redial.dialed = bc->dialed;
09490                cc_record->redial.setup_bc_hlc_llc = bc->setup_bc_hlc_llc;
09491                cc_record->redial.capability = bc->capability;
09492                cc_record->redial.hdlc = bc->hdlc;
09493             }
09494             AST_LIST_UNLOCK(&misdn_cc_records_db);
09495 
09496             /* Set MISDN_CC_RECORD_ID in original channel */
09497             if (ch->record_id != -1) {
09498                snprintf(buf, sizeof(buf), "%ld", ch->record_id);
09499             } else {
09500                buf[0] = 0;
09501             }
09502             misdn_cc_set_peer_var(ch->peer, MISDN_CC_RECORD_ID, buf);
09503          }
09504          break;
09505       default:
09506          chan_misdn_log(0, bc->port,
09507             " --> Expected in a DISCONNECT or ALERTING message: facility type:0x%04X\n",
09508             bc->fac_in.Function);
09509          break;
09510       }
09511       break;
09512    case Fac_CCBS_T_Call:
09513    case Fac_CCBSCall:
09514       switch (event) {
09515       case EVENT_SETUP:
09516          /*
09517           * This is a call completion retry call.
09518           * If we had anything to do we would do it here.
09519           */
09520          break;
09521       default:
09522          chan_misdn_log(0, bc->port, " --> Expected in a SETUP message: facility type:0x%04X\n",
09523             bc->fac_in.Function);
09524          break;
09525       }
09526       break;
09527    case Fac_CCBSDeactivate:
09528       switch (bc->fac_in.u.CCBSDeactivate.ComponentType) {
09529       case FacComponent_Result:
09530          AST_LIST_LOCK(&misdn_cc_records_db);
09531          cc_record = misdn_cc_find_by_invoke(bc->port, bc->fac_in.u.CCBSDeactivate.InvokeID);
09532          if (cc_record) {
09533             cc_record->outstanding_message = 0;
09534          }
09535          AST_LIST_UNLOCK(&misdn_cc_records_db);
09536          break;
09537 
09538       default:
09539          chan_misdn_log(0, bc->port, " --> not yet handled: facility type:0x%04X\n",
09540             bc->fac_in.Function);
09541          break;
09542       }
09543       break;
09544    case Fac_CCBSErase:
09545       AST_LIST_LOCK(&misdn_cc_records_db);
09546       cc_record = misdn_cc_find_by_reference(bc->port, bc->fac_in.u.CCBSErase.CCBSReference);
09547       if (cc_record) {
09548          misdn_cc_delete(cc_record);
09549       }
09550       AST_LIST_UNLOCK(&misdn_cc_records_db);
09551       break;
09552    case Fac_CCBSRemoteUserFree:
09553       misdn_cc_handle_remote_user_free(bc->port, &bc->fac_in);
09554       break;
09555    case Fac_CCBSBFree:
09556       misdn_cc_handle_b_free(bc->port, &bc->fac_in);
09557       break;
09558    case Fac_CCBSStatusRequest:
09559       misdn_cc_handle_ccbs_status_request(bc->port, &bc->fac_in);
09560       break;
09561    case Fac_EraseCallLinkageID:
09562       AST_LIST_LOCK(&misdn_cc_records_db);
09563       cc_record = misdn_cc_find_by_linkage(bc->port,
09564          bc->fac_in.u.EraseCallLinkageID.CallLinkageID);
09565       if (cc_record && !cc_record->activation_requested) {
09566          /*
09567           * The T-RETENTION timer expired before we requested
09568           * call completion activation.  Call completion is no
09569           * longer available.
09570           */
09571          misdn_cc_delete(cc_record);
09572       }
09573       AST_LIST_UNLOCK(&misdn_cc_records_db);
09574       break;
09575    case Fac_CCBSStopAlerting:
09576       /* We do not have anything to do for this message. */
09577       break;
09578    case Fac_CCBSRequest:
09579    case Fac_CCNRRequest:
09580       switch (bc->fac_in.u.CCBSRequest.ComponentType) {
09581       case FacComponent_Result:
09582          AST_LIST_LOCK(&misdn_cc_records_db);
09583          cc_record = misdn_cc_find_by_invoke(bc->port, bc->fac_in.u.CCBSRequest.InvokeID);
09584          if (cc_record && !cc_record->ptp) {
09585             cc_record->outstanding_message = 0;
09586             cc_record->activated = 1;
09587             cc_record->mode.ptmp.recall_mode = bc->fac_in.u.CCBSRequest.Component.Result.RecallMode;
09588             cc_record->mode.ptmp.reference_id = bc->fac_in.u.CCBSRequest.Component.Result.CCBSReference;
09589          }
09590          AST_LIST_UNLOCK(&misdn_cc_records_db);
09591          break;
09592 
09593       default:
09594          chan_misdn_log(0, bc->port, " --> not yet handled: facility type:0x%04X\n",
09595             bc->fac_in.Function);
09596          break;
09597       }
09598       break;
09599 #if 0 /* We don't handle this yet */
09600    case Fac_CCBSInterrogate:
09601    case Fac_CCNRInterrogate:
09602       /* We don't handle this yet */
09603       break;
09604    case Fac_StatusRequest:
09605       /* We don't handle this yet */
09606       break;
09607 #endif   /* We don't handle this yet */
09608 #if 0 /* We don't handle this yet */
09609    case Fac_CCBS_T_Suspend:
09610    case Fac_CCBS_T_Resume:
09611       /* We don't handle this yet */
09612       break;
09613 #endif   /* We don't handle this yet */
09614    case Fac_CCBS_T_RemoteUserFree:
09615       misdn_cc_handle_T_remote_user_free(bc);
09616       break;
09617    case Fac_CCBS_T_Available:
09618       switch (event) {
09619       case EVENT_ALERTING:
09620       case EVENT_DISCONNECT:
09621          /* CCBS-T/CCNR-T is available */
09622          if (ch && ch->peer) {
09623             int set_id = 1;
09624 
09625             AST_LIST_LOCK(&misdn_cc_records_db);
09626             if (ch->record_id == -1) {
09627                cc_record = misdn_cc_new();
09628             } else {
09629                /*
09630                 * We are doing a call-completion attempt
09631                 * or the switch is sending us extra call-completion
09632                 * availability indications (erroneously?).
09633                 */
09634                cc_record = misdn_cc_find_by_id(ch->record_id);
09635                if (cc_record) {
09636                   if (cc_record->ptp && cc_record->mode.ptp.retention_enabled) {
09637                      /*
09638                       * Call-completion is still activated.
09639                       * The user does not have to request it again.
09640                       */
09641                      chan_misdn_log(1, bc->port, " --> Call-completion request retention option is enabled\n");
09642 
09643                      set_id = 0;
09644                   } else {
09645                      if (cc_record->ptp && cc_record->mode.ptp.bc) {
09646                         /*
09647                          * The network request retention option
09648                          * is not on and the current call-completion
09649                          * request is to be disabled.
09650                          *
09651                          * We should get here only if EVENT_DISCONNECT
09652                          *
09653                          * Close the call-completion signaling link
09654                          */
09655                         cc_record->mode.ptp.bc->fac_out.Function = Fac_None;
09656                         cc_record->mode.ptp.bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
09657                         misdn_lib_send_event(cc_record->mode.ptp.bc, EVENT_RELEASE_COMPLETE);
09658                      }
09659 
09660                      /*
09661                       * Resetup the existing record for a possible new
09662                       * call-completion request.
09663                       */
09664                      new_record_id = misdn_cc_record_id_new();
09665                      if (new_record_id < 0) {
09666                         /* Looks like we must keep the old id anyway. */
09667                      } else {
09668                         cc_record->record_id = new_record_id;
09669                         ch->record_id = new_record_id;
09670                      }
09671                      cc_record->ptp = 1;
09672                      cc_record->port = bc->port;
09673                      memset(&cc_record->mode, 0, sizeof(cc_record->mode));
09674                      cc_record->invoke_id = ++misdn_invoke_id;
09675                      cc_record->activated = 0;
09676                      cc_record->outstanding_message = 0;
09677                      cc_record->activation_requested = 0;
09678                      cc_record->error_code = FacError_None;
09679                      cc_record->reject_code = FacReject_None;
09680                      memset(&cc_record->remote_user_free, 0, sizeof(cc_record->remote_user_free));
09681                      memset(&cc_record->b_free, 0, sizeof(cc_record->b_free));
09682                      cc_record->time_created = time(NULL);
09683                   }
09684                   cc_record = NULL;
09685                } else {
09686                   /*
09687                    * Where did the record go?  We will have to recapture
09688                    * the call setup information.  Unfortunately, some
09689                    * setup information may have been changed.
09690                    */
09691                   ch->record_id = -1;
09692                   cc_record = misdn_cc_new();
09693                }
09694             }
09695             if (cc_record) {
09696                ch->record_id = cc_record->record_id;
09697                cc_record->ptp = 1;
09698                cc_record->port = bc->port;
09699 
09700                /* Record call information for possible call-completion attempt. */
09701                cc_record->redial.caller = bc->caller;
09702                cc_record->redial.dialed = bc->dialed;
09703                cc_record->redial.setup_bc_hlc_llc = bc->setup_bc_hlc_llc;
09704                cc_record->redial.capability = bc->capability;
09705                cc_record->redial.hdlc = bc->hdlc;
09706             }
09707             AST_LIST_UNLOCK(&misdn_cc_records_db);
09708 
09709             /* Set MISDN_CC_RECORD_ID in original channel */
09710             if (ch->record_id != -1 && set_id) {
09711                snprintf(buf, sizeof(buf), "%ld", ch->record_id);
09712             } else {
09713                buf[0] = 0;
09714             }
09715             misdn_cc_set_peer_var(ch->peer, MISDN_CC_RECORD_ID, buf);
09716          }
09717          break;
09718       default:
09719          chan_misdn_log(0, bc->port,
09720             " --> Expected in a DISCONNECT or ALERTING message: facility type:0x%04X\n",
09721             bc->fac_in.Function);
09722          break;
09723       }
09724       break;
09725    case Fac_CCBS_T_Request:
09726    case Fac_CCNR_T_Request:
09727       switch (bc->fac_in.u.CCBS_T_Request.ComponentType) {
09728       case FacComponent_Result:
09729          AST_LIST_LOCK(&misdn_cc_records_db);
09730          cc_record = misdn_cc_find_by_invoke(bc->port, bc->fac_in.u.CCBS_T_Request.InvokeID);
09731          if (cc_record && cc_record->ptp) {
09732             cc_record->outstanding_message = 0;
09733             cc_record->activated = 1;
09734             cc_record->mode.ptp.retention_enabled =
09735                cc_record->mode.ptp.requested_retention
09736                ? bc->fac_in.u.CCBS_T_Request.Component.Result.RetentionSupported
09737                ? 1 : 0
09738                : 0;
09739          }
09740          AST_LIST_UNLOCK(&misdn_cc_records_db);
09741          break;
09742 
09743       case FacComponent_Invoke:
09744          /* We cannot be User-B in ptp mode. */
09745       default:
09746          chan_misdn_log(0, bc->port, " --> not yet handled: facility type:0x%04X\n",
09747             bc->fac_in.Function);
09748          break;
09749       }
09750       break;
09751 
09752 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
09753    case Fac_None:
09754       break;
09755    default:
09756       chan_misdn_log(0, bc->port, " --> not yet handled: facility type:0x%04X\n",
09757          bc->fac_in.Function);
09758       break;
09759    }
09760 }
09761 
09762 /*!
09763  * \internal
09764  * \brief Determine if the given dialed party matches our MSN.
09765  * \since 1.8
09766  *
09767  * \param port ISDN port
09768  * \param dialed Dialed party information of incoming call.
09769  *
09770  * \retval non-zero if MSN is valid.
09771  * \retval 0 if MSN invalid.
09772  */
09773 static int misdn_is_msn_valid(int port, const struct misdn_party_dialing *dialed)
09774 {
09775    char number[sizeof(dialed->number)];
09776 
09777    ast_copy_string(number, dialed->number, sizeof(number));
09778    misdn_add_number_prefix(port, dialed->number_type, number, sizeof(number));
09779    return misdn_cfg_is_msn_valid(port, number);
09780 }
09781 
09782 /************************************************************/
09783 /*  Receive Events from isdn_lib  here                     */
09784 /************************************************************/
09785 static enum event_response_e
09786 cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
09787 {
09788 #if defined(AST_MISDN_ENHANCEMENTS)
09789    struct misdn_cc_record *cc_record;
09790 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
09791    struct chan_list *held_ch;
09792    struct chan_list *ch = find_chan_by_bc(bc);
09793 
09794    if (event != EVENT_BCHAN_DATA && event != EVENT_TONE_GENERATE) {
09795       int debuglevel = 1;
09796 
09797       /*  Debug Only Non-Bchan */
09798       if (event == EVENT_CLEANUP && !user_data) {
09799          debuglevel = 5;
09800       }
09801 
09802       chan_misdn_log(debuglevel, bc->port,
09803          "I IND :%s caller:\"%s\" <%s> dialed:%s pid:%d state:%s\n",
09804          manager_isdn_get_info(event),
09805          bc->caller.name,
09806          bc->caller.number,
09807          bc->dialed.number,
09808          bc->pid,
09809          ch ? misdn_get_ch_state(ch) : "none");
09810       if (debuglevel == 1) {
09811          misdn_lib_log_ies(bc);
09812          chan_misdn_log(4, bc->port, " --> bc_state:%s\n", bc_state2str(bc->bc_state));
09813       }
09814    }
09815 
09816    if (!ch) {
09817       switch(event) {
09818       case EVENT_SETUP:
09819       case EVENT_DISCONNECT:
09820       case EVENT_RELEASE:
09821       case EVENT_RELEASE_COMPLETE:
09822       case EVENT_PORT_ALARM:
09823       case EVENT_RETRIEVE:
09824       case EVENT_NEW_BC:
09825       case EVENT_FACILITY:
09826       case EVENT_REGISTER:
09827          break;
09828       case EVENT_CLEANUP:
09829       case EVENT_TONE_GENERATE:
09830       case EVENT_BCHAN_DATA:
09831          return -1;
09832       default:
09833          chan_misdn_log(1, bc->port, "Chan not existing at the moment bc->l3id:%x bc:%p event:%s port:%d channel:%d\n", bc->l3_id, bc, manager_isdn_get_info(event), bc->port, bc->channel);
09834          return -1;
09835       }
09836    }
09837 
09838    if (ch) {
09839       switch (event) {
09840       case EVENT_TONE_GENERATE:
09841          break;
09842       case EVENT_DISCONNECT:
09843       case EVENT_RELEASE:
09844       case EVENT_RELEASE_COMPLETE:
09845       case EVENT_CLEANUP:
09846       case EVENT_TIMEOUT:
09847          if (!ch->ast) {
09848             chan_misdn_log(3, bc->port, "ast_hangup already called, so we have no ast ptr anymore in event(%s)\n", manager_isdn_get_info(event));
09849          }
09850          break;
09851       default:
09852          if (!ch->ast || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
09853             if (event != EVENT_BCHAN_DATA) {
09854                ast_log(LOG_NOTICE, "No Ast or No private Pointer in Event (%d:%s)\n", event, manager_isdn_get_info(event));
09855             }
09856             return -1;
09857          }
09858          break;
09859       }
09860    }
09861 
09862 
09863    switch (event) {
09864    case EVENT_PORT_ALARM:
09865       {
09866          int boa = 0;
09867          misdn_cfg_get(bc->port, MISDN_CFG_ALARM_BLOCK, &boa, sizeof(boa));
09868          if (boa) {
09869             cb_log(1, bc->port, " --> blocking\n");
09870             misdn_lib_port_block(bc->port);
09871          }
09872       }
09873       break;
09874    case EVENT_BCHAN_ACTIVATED:
09875       break;
09876 
09877    case EVENT_NEW_CHANNEL:
09878       update_name(ch->ast,bc->port,bc->channel);
09879       break;
09880 
09881    case EVENT_NEW_L3ID:
09882       ch->l3id=bc->l3_id;
09883       ch->addr=bc->addr;
09884       break;
09885 
09886    case EVENT_NEW_BC:
09887       if (!ch) {
09888          ch = find_hold_call(bc);
09889       }
09890 
09891       if (!ch) {
09892          ast_log(LOG_WARNING, "NEW_BC without chan_list?\n");
09893          break;
09894       }
09895 
09896       if (bc) {
09897          ch->bc = (struct misdn_bchannel *) user_data;
09898       }
09899       break;
09900 
09901    case EVENT_DTMF_TONE:
09902    {
09903       /*  sending INFOS as DTMF-Frames :) */
09904       struct ast_frame fr;
09905 
09906       memset(&fr, 0, sizeof(fr));
09907       fr.frametype = AST_FRAME_DTMF;
09908       fr.subclass.integer = bc->dtmf ;
09909       fr.src = NULL;
09910       fr.data.ptr = NULL;
09911       fr.datalen = 0;
09912       fr.samples = 0;
09913       fr.mallocd = 0;
09914       fr.offset = 0;
09915       fr.delivery = ast_tv(0,0);
09916 
09917       if (!ch->ignore_dtmf) {
09918          chan_misdn_log(2, bc->port, " --> DTMF:%c\n", bc->dtmf);
09919          ast_queue_frame(ch->ast, &fr);
09920       } else {
09921          chan_misdn_log(2, bc->port, " --> Ignoring DTMF:%c due to bridge flags\n", bc->dtmf);
09922       }
09923       break;
09924    }
09925    case EVENT_STATUS:
09926       break;
09927 
09928    case EVENT_INFORMATION:
09929       if (ch->state != MISDN_CONNECTED) {
09930          stop_indicate(ch);
09931       }
09932 
09933       if (!ch->ast) {
09934          break;
09935       }
09936 
09937       if (ch->state == MISDN_WAITING4DIGS) {
09938          /*  Ok, incomplete Setup, waiting till extension exists */
09939          if (ast_strlen_zero(bc->info_dad) && ! ast_strlen_zero(bc->keypad)) {
09940             chan_misdn_log(1, bc->port, " --> using keypad as info\n");
09941             ast_copy_string(bc->info_dad, bc->keypad, sizeof(bc->info_dad));
09942          }
09943 
09944          strncat(bc->dialed.number, bc->info_dad, sizeof(bc->dialed.number) - strlen(bc->dialed.number) - 1);
09945          ast_copy_string(ch->ast->exten, bc->dialed.number, sizeof(ch->ast->exten));
09946 
09947          /* Check for Pickup Request first */
09948          if (!strcmp(ch->ast->exten, ast_pickup_ext())) {
09949             if (ast_pickup_call(ch->ast)) {
09950                hangup_chan(ch, bc);
09951             } else {
09952                ch->state = MISDN_CALLING_ACKNOWLEDGE;
09953                hangup_chan(ch, bc);
09954                ch->ast = NULL;
09955                break;
09956             }
09957          }
09958 
09959          if (!ast_canmatch_extension(ch->ast, ch->context, bc->dialed.number, 1, bc->caller.number)) {
09960             if (ast_exists_extension(ch->ast, ch->context, "i", 1, bc->caller.number)) {
09961                ast_log(LOG_WARNING,
09962                   "Extension '%s@%s' can never match. Jumping to 'i' extension. port:%d\n",
09963                   bc->dialed.number, ch->context, bc->port);
09964                strcpy(ch->ast->exten, "i");
09965 
09966                ch->state = MISDN_DIALING;
09967                start_pbx(ch, bc, ch->ast);
09968                break;
09969             }
09970 
09971             ast_log(LOG_WARNING,
09972                "Extension '%s@%s' can never match. Disconnecting. port:%d\n"
09973                "\tMaybe you want to add an 'i' extension to catch this case.\n",
09974                bc->dialed.number, ch->context, bc->port);
09975 
09976             if (bc->nt) {
09977                hanguptone_indicate(ch);
09978             }
09979             ch->state = MISDN_EXTCANTMATCH;
09980             bc->out_cause = AST_CAUSE_UNALLOCATED;
09981 
09982             misdn_lib_send_event(bc, EVENT_DISCONNECT);
09983             break;
09984          }
09985 
09986          if (ch->overlap_dial) {
09987             ast_mutex_lock(&ch->overlap_tv_lock);
09988             ch->overlap_tv = ast_tvnow();
09989             ast_mutex_unlock(&ch->overlap_tv_lock);
09990             if (ch->overlap_dial_task == -1) {
09991                ch->overlap_dial_task =
09992                   misdn_tasks_add_variable(ch->overlap_dial, misdn_overlap_dial_task, ch);
09993             }
09994             break;
09995          }
09996 
09997          if (ast_exists_extension(ch->ast, ch->context, bc->dialed.number, 1, bc->caller.number))  {
09998             ch->state = MISDN_DIALING;
09999             start_pbx(ch, bc, ch->ast);
10000          }
10001       } else {
10002          /*  sending INFOS as DTMF-Frames :) */
10003          struct ast_frame fr;
10004          int digits;
10005 
10006          memset(&fr, 0, sizeof(fr));
10007          fr.frametype = AST_FRAME_DTMF;
10008          fr.subclass.integer = bc->info_dad[0] ;
10009          fr.src = NULL;
10010          fr.data.ptr = NULL;
10011          fr.datalen = 0;
10012          fr.samples = 0;
10013          fr.mallocd = 0;
10014          fr.offset = 0;
10015          fr.delivery = ast_tv(0,0);
10016 
10017          misdn_cfg_get(0, MISDN_GEN_APPEND_DIGITS2EXTEN, &digits, sizeof(digits));
10018          if (ch->state != MISDN_CONNECTED) {
10019             if (digits) {
10020                strncat(bc->dialed.number, bc->info_dad, sizeof(bc->dialed.number) - strlen(bc->dialed.number) - 1);
10021                ast_copy_string(ch->ast->exten, bc->dialed.number, sizeof(ch->ast->exten));
10022                ast_cdr_update(ch->ast);
10023             }
10024 
10025             ast_queue_frame(ch->ast, &fr);
10026          }
10027       }
10028       break;
10029    case EVENT_SETUP:
10030    {
10031       struct chan_list *ch = find_chan_by_bc(bc);
10032       struct ast_channel *chan;
10033       int exceed;
10034       int ai;
10035       int im;
10036       int append_msn = 0;
10037 
10038       if (ch) {
10039          switch (ch->state) {
10040          case MISDN_NOTHING:
10041             ch = NULL;
10042             break;
10043          default:
10044             chan_misdn_log(1, bc->port, " --> Ignoring Call we have already one\n");
10045             return RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE; /*  Ignore MSNs which are not in our List */
10046          }
10047       }
10048 
10049       if (!bc->nt && !misdn_is_msn_valid(bc->port, &bc->dialed)) {
10050          chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
10051          return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
10052       }
10053 
10054       if (bc->cw) {
10055          int cause;
10056          chan_misdn_log(0, bc->port, " --> Call Waiting on PMP sending RELEASE_COMPLETE\n");
10057          misdn_cfg_get(bc->port, MISDN_CFG_REJECT_CAUSE, &cause, sizeof(cause));
10058          bc->out_cause = cause ? cause : AST_CAUSE_NORMAL_CLEARING;
10059          return RESPONSE_RELEASE_SETUP;
10060       }
10061 
10062       print_bearer(bc);
10063 
10064       ch = init_chan_list(ORG_MISDN);
10065       if (!ch) {
10066          chan_misdn_log(-1, bc->port, "cb_events: malloc for chan_list failed!\n");
10067          return 0;
10068       }
10069 
10070       ch->bc = bc;
10071       ch->l3id = bc->l3_id;
10072       ch->addr = bc->addr;
10073 
10074       chan = misdn_new(ch, AST_STATE_RESERVED, bc->dialed.number, bc->caller.number, AST_FORMAT_ALAW, NULL, bc->port, bc->channel);
10075       if (!chan) {
10076          ast_free(ch);
10077          misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
10078          ast_log(LOG_ERROR, "cb_events: misdn_new failed !\n");
10079          return 0;
10080       }
10081 
10082       ch->ast = chan;
10083 
10084       if ((exceed = add_in_calls(bc->port))) {
10085          char tmp[16];
10086          snprintf(tmp, sizeof(tmp), "%d", exceed);
10087          pbx_builtin_setvar_helper(chan, "MAX_OVERFLOW", tmp);
10088       }
10089 
10090       read_config(ch);
10091 
10092       export_ch(chan, bc, ch);
10093 
10094       ch->ast->rings = 1;
10095       ast_setstate(ch->ast, AST_STATE_RINGING);
10096 
10097       /* Update asterisk channel caller information */
10098       chan_misdn_log(2, bc->port, " --> TON: %s(%d)\n", misdn_to_str_ton(bc->caller.number_type), bc->caller.number_type);
10099       chan_misdn_log(2, bc->port, " --> PLAN: %s(%d)\n", misdn_to_str_plan(bc->caller.number_plan), bc->caller.number_plan);
10100       chan->caller.id.number.plan = misdn_to_ast_ton(bc->caller.number_type)
10101          | misdn_to_ast_plan(bc->caller.number_plan);
10102 
10103       chan_misdn_log(2, bc->port, " --> PRES: %s(%d)\n", misdn_to_str_pres(bc->caller.presentation), bc->caller.presentation);
10104       chan_misdn_log(2, bc->port, " --> SCREEN: %s(%d)\n", misdn_to_str_screen(bc->caller.screening), bc->caller.screening);
10105       chan->caller.id.number.presentation = misdn_to_ast_pres(bc->caller.presentation)
10106          | misdn_to_ast_screen(bc->caller.screening);
10107 
10108       ast_set_callerid(chan, bc->caller.number, NULL, bc->caller.number);
10109 
10110       misdn_cfg_get(bc->port, MISDN_CFG_APPEND_MSN_TO_CALLERID_TAG, &append_msn, sizeof(append_msn));
10111       if (append_msn) {
10112          strncat(bc->incoming_cid_tag, "_", sizeof(bc->incoming_cid_tag) - strlen(bc->incoming_cid_tag) - 1);
10113          strncat(bc->incoming_cid_tag, bc->dialed.number, sizeof(bc->incoming_cid_tag) - strlen(bc->incoming_cid_tag) - 1);
10114       }
10115 
10116       ast_channel_lock(chan);
10117       chan->caller.id.tag = ast_strdup(bc->incoming_cid_tag);
10118       ast_channel_unlock(chan);
10119 
10120       if (!ast_strlen_zero(bc->redirecting.from.number)) {
10121          /* Add configured prefix to redirecting.from.number */
10122          misdn_add_number_prefix(bc->port, bc->redirecting.from.number_type, bc->redirecting.from.number, sizeof(bc->redirecting.from.number));
10123 
10124          /* Update asterisk channel redirecting information */
10125          misdn_copy_redirecting_to_ast(chan, &bc->redirecting, bc->incoming_cid_tag);
10126       }
10127 
10128       pbx_builtin_setvar_helper(chan, "TRANSFERCAPABILITY", ast_transfercapability2str(bc->capability));
10129       chan->transfercapability = bc->capability;
10130 
10131       switch (bc->capability) {
10132       case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
10133          pbx_builtin_setvar_helper(chan, "CALLTYPE", "DIGITAL");
10134          break;
10135       default:
10136          pbx_builtin_setvar_helper(chan, "CALLTYPE", "SPEECH");
10137          break;
10138       }
10139 
10140       /** queue new chan **/
10141       cl_queue_chan(ch);
10142 
10143       if (!strstr(ch->allowed_bearers, "all")) {
10144          int i;
10145 
10146          for (i = 0; i < ARRAY_LEN(allowed_bearers_array); ++i) {
10147             if (allowed_bearers_array[i].cap == bc->capability) {
10148                if (strstr(ch->allowed_bearers, allowed_bearers_array[i].name)) {
10149                   /* The bearer capability is allowed */
10150                   if (allowed_bearers_array[i].deprecated) {
10151                      chan_misdn_log(0, bc->port, "%s in allowed_bearers list is deprecated\n",
10152                         allowed_bearers_array[i].name);
10153                   }
10154                   break;
10155                }
10156             }
10157          }
10158          if (i == ARRAY_LEN(allowed_bearers_array)) {
10159             /* We did not find the bearer capability */
10160             chan_misdn_log(0, bc->port, "Bearer capability not allowed: %s(%d)\n",
10161                bearer2str(bc->capability), bc->capability);
10162             bc->out_cause = AST_CAUSE_INCOMPATIBLE_DESTINATION;
10163 
10164             ch->state = MISDN_EXTCANTMATCH;
10165             misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
10166             return RESPONSE_OK;
10167          }
10168       }
10169 
10170       if (bc->fac_in.Function != Fac_None) {
10171          misdn_facility_ie_handler(event, bc, ch);
10172       }
10173 
10174       /* Check for Pickup Request first */
10175       if (!strcmp(chan->exten, ast_pickup_ext())) {
10176          if (!ch->noautorespond_on_setup) {
10177             /* Sending SETUP_ACK */
10178             misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE);
10179          } else {
10180             ch->state = MISDN_INCOMING_SETUP;
10181          }
10182          if (ast_pickup_call(chan)) {
10183             hangup_chan(ch, bc);
10184          } else {
10185             ch->state = MISDN_CALLING_ACKNOWLEDGE;
10186             hangup_chan(ch, bc);
10187             ch->ast = NULL;
10188             break;
10189          }
10190       }
10191 
10192       /*
10193        * added support for s extension hope it will help those poor cretains
10194        * which haven't overlap dial.
10195        */
10196       misdn_cfg_get(bc->port, MISDN_CFG_ALWAYS_IMMEDIATE, &ai, sizeof(ai));
10197       if (ai) {
10198          do_immediate_setup(bc, ch, chan);
10199          break;
10200       }
10201 
10202       /* check if we should jump into s when we have no dialed.number */
10203       misdn_cfg_get(bc->port, MISDN_CFG_IMMEDIATE, &im, sizeof(im));
10204       if (im && ast_strlen_zero(bc->dialed.number)) {
10205          do_immediate_setup(bc, ch, chan);
10206          break;
10207       }
10208 
10209       chan_misdn_log(5, bc->port, "CONTEXT:%s\n", ch->context);
10210       if (!ast_canmatch_extension(ch->ast, ch->context, bc->dialed.number, 1, bc->caller.number)) {
10211          if (ast_exists_extension(ch->ast, ch->context, "i", 1, bc->caller.number)) {
10212             ast_log(LOG_WARNING,
10213                "Extension '%s@%s' can never match. Jumping to 'i' extension. port:%d\n",
10214                bc->dialed.number, ch->context, bc->port);
10215             strcpy(ch->ast->exten, "i");
10216             misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE);
10217             ch->state = MISDN_DIALING;
10218             start_pbx(ch, bc, chan);
10219             break;
10220          }
10221 
10222          ast_log(LOG_WARNING,
10223             "Extension '%s@%s' can never match. Disconnecting. port:%d\n"
10224             "\tMaybe you want to add an 'i' extension to catch this case.\n",
10225             bc->dialed.number, ch->context, bc->port);
10226          if (bc->nt) {
10227             hanguptone_indicate(ch);
10228          }
10229 
10230          ch->state = MISDN_EXTCANTMATCH;
10231          bc->out_cause = AST_CAUSE_UNALLOCATED;
10232 
10233          misdn_lib_send_event(bc, bc->nt ? EVENT_RELEASE_COMPLETE : EVENT_RELEASE);
10234          break;
10235       }
10236 
10237       /* Whatever happens, when sending_complete is set or we are PTMP TE, we will definitely
10238        * jump into the dialplan, when the dialed extension does not exist, the 's' extension
10239        * will be used by Asterisk automatically. */
10240       if (bc->sending_complete || (!bc->nt && !misdn_lib_is_ptp(bc->port))) {
10241          if (!ch->noautorespond_on_setup) {
10242             ch->state=MISDN_DIALING;
10243             misdn_lib_send_event(bc, EVENT_PROCEEDING);
10244          } else {
10245             ch->state = MISDN_INCOMING_SETUP;
10246          }
10247          start_pbx(ch, bc, chan);
10248          break;
10249       }
10250 
10251 
10252       /*
10253        * When we are NT and overlapdial is set and if
10254        * the number is empty, we wait for the ISDN timeout
10255        * instead of our own timer.
10256        */
10257       if (ch->overlap_dial && bc->nt && !bc->dialed.number[0]) {
10258          wait_for_digits(ch, bc, chan);
10259          break;
10260       }
10261 
10262       /*
10263        * If overlapdial we will definitely send a SETUP_ACKNOWLEDGE and wait for more
10264        * Infos with a Interdigit Timeout.
10265        * */
10266       if (ch->overlap_dial) {
10267          ast_mutex_lock(&ch->overlap_tv_lock);
10268          ch->overlap_tv = ast_tvnow();
10269          ast_mutex_unlock(&ch->overlap_tv_lock);
10270 
10271          wait_for_digits(ch, bc, chan);
10272          if (ch->overlap_dial_task == -1) {
10273             ch->overlap_dial_task =
10274                misdn_tasks_add_variable(ch->overlap_dial, misdn_overlap_dial_task, ch);
10275          }
10276          break;
10277       }
10278 
10279       /* If the extension does not exist and we're not TE_PTMP we wait for more digits
10280        * without interdigit timeout.
10281        * */
10282       if (!ast_exists_extension(ch->ast, ch->context, bc->dialed.number, 1, bc->caller.number))  {
10283          wait_for_digits(ch, bc, chan);
10284          break;
10285       }
10286 
10287       /*
10288        * If the extension exists let's just jump into it.
10289        * */
10290       if (ast_exists_extension(ch->ast, ch->context, bc->dialed.number, 1, bc->caller.number)) {
10291          misdn_lib_send_event(bc, bc->need_more_infos ? EVENT_SETUP_ACKNOWLEDGE : EVENT_PROCEEDING);
10292          ch->state = MISDN_DIALING;
10293          start_pbx(ch, bc, chan);
10294          break;
10295       }
10296       break;
10297    }
10298 #if defined(AST_MISDN_ENHANCEMENTS)
10299    case EVENT_REGISTER:
10300       if (bc->fac_in.Function != Fac_None) {
10301          misdn_facility_ie_handler(event, bc, ch);
10302       }
10303       /*
10304        * Shut down this connection immediately.
10305        * The current design of chan_misdn data structures
10306        * does not allow the proper handling of inbound call records
10307        * without an assigned B channel.  Therefore, we cannot
10308        * be the CCBS User-B party in a point-to-point setup.
10309        */
10310       bc->fac_out.Function = Fac_None;
10311       bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
10312       misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
10313       break;
10314 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
10315    case EVENT_SETUP_ACKNOWLEDGE:
10316       ch->state = MISDN_CALLING_ACKNOWLEDGE;
10317 
10318       if (bc->channel) {
10319          update_name(ch->ast,bc->port,bc->channel);
10320       }
10321 
10322       if (bc->fac_in.Function != Fac_None) {
10323          misdn_facility_ie_handler(event, bc, ch);
10324       }
10325 
10326       if (!ast_strlen_zero(bc->infos_pending)) {
10327          /* TX Pending Infos */
10328          strncat(bc->dialed.number, bc->infos_pending, sizeof(bc->dialed.number) - strlen(bc->dialed.number) - 1);
10329 
10330          if (!ch->ast) {
10331             break;
10332          }
10333          ast_copy_string(ch->ast->exten, bc->dialed.number, sizeof(ch->ast->exten));
10334          ast_copy_string(bc->info_dad, bc->infos_pending, sizeof(bc->info_dad));
10335          ast_copy_string(bc->infos_pending, "", sizeof(bc->infos_pending));
10336 
10337          misdn_lib_send_event(bc, EVENT_INFORMATION);
10338       }
10339       break;
10340    case EVENT_PROCEEDING:
10341       if (misdn_cap_is_speech(bc->capability) &&
10342          misdn_inband_avail(bc)) {
10343          start_bc_tones(ch);
10344       }
10345 
10346       ch->state = MISDN_PROCEEDING;
10347 
10348       if (bc->fac_in.Function != Fac_None) {
10349          misdn_facility_ie_handler(event, bc, ch);
10350       }
10351 
10352       if (!ch->ast) {
10353          break;
10354       }
10355 
10356       ast_queue_control(ch->ast, AST_CONTROL_PROCEEDING);
10357       break;
10358    case EVENT_PROGRESS:
10359       if (bc->channel) {
10360          update_name(ch->ast, bc->port, bc->channel);
10361       }
10362 
10363       if (bc->fac_in.Function != Fac_None) {
10364          misdn_facility_ie_handler(event, bc, ch);
10365       }
10366 
10367       if (!bc->nt) {
10368          if (misdn_cap_is_speech(bc->capability) &&
10369             misdn_inband_avail(bc)) {
10370             start_bc_tones(ch);
10371          }
10372 
10373          ch->state = MISDN_PROGRESS;
10374 
10375          if (!ch->ast) {
10376             break;
10377          }
10378          ast_queue_control(ch->ast, AST_CONTROL_PROGRESS);
10379       }
10380       break;
10381    case EVENT_ALERTING:
10382       ch->state = MISDN_ALERTING;
10383 
10384       if (!ch->ast) {
10385          break;
10386       }
10387 
10388       if (bc->fac_in.Function != Fac_None) {
10389          misdn_facility_ie_handler(event, bc, ch);
10390       }
10391 
10392       ast_queue_control(ch->ast, AST_CONTROL_RINGING);
10393       ast_setstate(ch->ast, AST_STATE_RINGING);
10394 
10395       cb_log(7, bc->port, " --> Set State Ringing\n");
10396 
10397       if (misdn_cap_is_speech(bc->capability) && misdn_inband_avail(bc)) {
10398          cb_log(1, bc->port, "Starting Tones, we have inband Data\n");
10399          start_bc_tones(ch);
10400       } else {
10401          cb_log(3, bc->port, " --> We have no inband Data, the other end must create ringing\n");
10402          if (ch->far_alerting) {
10403             cb_log(1, bc->port, " --> The other end can not do ringing eh ?.. we must do all ourself..");
10404             start_bc_tones(ch);
10405             /*tone_indicate(ch, TONE_FAR_ALERTING);*/
10406          }
10407       }
10408       break;
10409    case EVENT_CONNECT:
10410       if (bc->fac_in.Function != Fac_None) {
10411          misdn_facility_ie_handler(event, bc, ch);
10412       }
10413 #if defined(AST_MISDN_ENHANCEMENTS)
10414       if (bc->div_leg_3_rx_wanted) {
10415          bc->div_leg_3_rx_wanted = 0;
10416 
10417          if (ch->ast) {
10418             ch->ast->redirecting.to.number.presentation =
10419                AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED;
10420             ast_channel_queue_redirecting_update(ch->ast, &ch->ast->redirecting, NULL);
10421          }
10422       }
10423 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
10424 
10425       /* we answer when we've got our very new L3 ID from the NT stack */
10426       misdn_lib_send_event(bc, EVENT_CONNECT_ACKNOWLEDGE);
10427 
10428       if (!ch->ast) {
10429          break;
10430       }
10431 
10432       stop_indicate(ch);
10433 
10434 #if defined(AST_MISDN_ENHANCEMENTS)
10435       if (ch->record_id != -1) {
10436          /*
10437           * We will delete the associated call completion
10438           * record since we now have a completed call.
10439           * We will not wait/depend on the network to tell
10440           * us to delete it.
10441           */
10442          AST_LIST_LOCK(&misdn_cc_records_db);
10443          cc_record = misdn_cc_find_by_id(ch->record_id);
10444          if (cc_record) {
10445             if (cc_record->ptp && cc_record->mode.ptp.bc) {
10446                /* Close the call-completion signaling link */
10447                cc_record->mode.ptp.bc->fac_out.Function = Fac_None;
10448                cc_record->mode.ptp.bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
10449                misdn_lib_send_event(cc_record->mode.ptp.bc, EVENT_RELEASE_COMPLETE);
10450             }
10451             misdn_cc_delete(cc_record);
10452          }
10453          AST_LIST_UNLOCK(&misdn_cc_records_db);
10454          ch->record_id = -1;
10455          if (ch->peer) {
10456             misdn_cc_set_peer_var(ch->peer, MISDN_CC_RECORD_ID, "");
10457 
10458             ao2_ref(ch->peer, -1);
10459             ch->peer = NULL;
10460          }
10461       }
10462 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
10463 
10464       if (!ast_strlen_zero(bc->connected.number)) {
10465          /* Add configured prefix to connected.number */
10466          misdn_add_number_prefix(bc->port, bc->connected.number_type, bc->connected.number, sizeof(bc->connected.number));
10467 
10468          /* Update the connected line information on the other channel */
10469          misdn_update_remote_party(ch->ast, &bc->connected, AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER, bc->incoming_cid_tag);
10470       }
10471 
10472       ch->l3id = bc->l3_id;
10473       ch->addr = bc->addr;
10474 
10475       start_bc_tones(ch);
10476 
10477       ch->state = MISDN_CONNECTED;
10478 
10479       ast_queue_control(ch->ast, AST_CONTROL_ANSWER);
10480       break;
10481    case EVENT_CONNECT_ACKNOWLEDGE:
10482       ch->l3id = bc->l3_id;
10483       ch->addr = bc->addr;
10484 
10485       start_bc_tones(ch);
10486 
10487       ch->state = MISDN_CONNECTED;
10488       break;
10489    case EVENT_DISCONNECT:
10490       /* we might not have an ch->ast ptr here anymore */
10491       if (ch) {
10492          if (bc->fac_in.Function != Fac_None) {
10493             misdn_facility_ie_handler(event, bc, ch);
10494          }
10495 
10496          chan_misdn_log(3, bc->port, " --> org:%d nt:%d, inbandavail:%d state:%d\n", ch->originator, bc->nt, misdn_inband_avail(bc), ch->state);
10497          if (ch->originator == ORG_AST && !bc->nt && misdn_inband_avail(bc) && ch->state != MISDN_CONNECTED) {
10498             /* If there's inband information available (e.g. a
10499                recorded message saying what was wrong with the
10500                dialled number, or perhaps even giving an
10501                alternative number, then play it instead of
10502                immediately releasing the call */
10503             chan_misdn_log(1, bc->port, " --> Inband Info Avail, not sending RELEASE\n");
10504 
10505             ch->state = MISDN_DISCONNECTED;
10506             start_bc_tones(ch);
10507 
10508             if (ch->ast) {
10509                ch->ast->hangupcause = bc->cause;
10510                if (bc->cause == AST_CAUSE_USER_BUSY) {
10511                   ast_queue_control(ch->ast, AST_CONTROL_BUSY);
10512                }
10513             }
10514             ch->need_busy = 0;
10515             break;
10516          }
10517 
10518          bc->need_disconnect = 0;
10519          stop_bc_tones(ch);
10520 
10521          /* Check for held channel, to implement transfer */
10522          held_ch = find_hold_call(bc);
10523          if (!held_ch || !ch->ast || misdn_attempt_transfer(ch, held_ch)) {
10524             hangup_chan(ch, bc);
10525          }
10526       } else {
10527          held_ch = find_hold_call_l3(bc->l3_id);
10528          if (held_ch) {
10529             if (bc->fac_in.Function != Fac_None) {
10530                misdn_facility_ie_handler(event, bc, held_ch);
10531             }
10532 
10533             if (held_ch->hold.state == MISDN_HOLD_ACTIVE) {
10534                bc->need_disconnect = 0;
10535 
10536 #if defined(TRANSFER_ON_HELD_CALL_HANGUP)
10537                /*
10538                 * Some phones disconnect the held call and the active call at the
10539                 * same time to do the transfer.  Unfortunately, either call could
10540                 * be disconnected first.
10541                 */
10542                ch = find_hold_active_call(bc);
10543                if (!ch || misdn_attempt_transfer(ch, held_ch)) {
10544                   held_ch->hold.state = MISDN_HOLD_DISCONNECT;
10545                   hangup_chan(held_ch, bc);
10546                }
10547 #else
10548                hangup_chan(held_ch, bc);
10549 #endif   /* defined(TRANSFER_ON_HELD_CALL_HANGUP) */
10550             }
10551          }
10552       }
10553       bc->out_cause = -1;
10554       if (bc->need_release) {
10555          misdn_lib_send_event(bc, EVENT_RELEASE);
10556       }
10557       break;
10558    case EVENT_RELEASE:
10559       if (!ch) {
10560          ch = find_hold_call_l3(bc->l3_id);
10561          if (!ch) {
10562             chan_misdn_log(1, bc->port,
10563                " --> no Ch, so we've already released. (%s)\n",
10564                manager_isdn_get_info(event));
10565             return -1;
10566          }
10567       }
10568       if (bc->fac_in.Function != Fac_None) {
10569          misdn_facility_ie_handler(event, bc, ch);
10570       }
10571 
10572       bc->need_disconnect = 0;
10573       bc->need_release = 0;
10574 
10575       hangup_chan(ch, bc);
10576       release_chan(ch, bc);
10577       break;
10578    case EVENT_RELEASE_COMPLETE:
10579       if (!ch) {
10580          ch = find_hold_call_l3(bc->l3_id);
10581       }
10582 
10583       bc->need_disconnect = 0;
10584       bc->need_release = 0;
10585       bc->need_release_complete = 0;
10586 
10587       if (ch) {
10588          if (bc->fac_in.Function != Fac_None) {
10589             misdn_facility_ie_handler(event, bc, ch);
10590          }
10591 
10592          stop_bc_tones(ch);
10593          hangup_chan(ch, bc);
10594          release_chan(ch, bc);
10595       } else {
10596 #if defined(AST_MISDN_ENHANCEMENTS)
10597          /*
10598           * A call-completion signaling link established with
10599           * REGISTER does not have a struct chan_list record
10600           * associated with it.
10601           */
10602          AST_LIST_LOCK(&misdn_cc_records_db);
10603          cc_record = misdn_cc_find_by_bc(bc);
10604          if (cc_record) {
10605             /* The call-completion signaling link is closed. */
10606             misdn_cc_delete(cc_record);
10607          }
10608          AST_LIST_UNLOCK(&misdn_cc_records_db);
10609 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
10610 
10611          chan_misdn_log(1, bc->port,
10612             " --> no Ch, so we've already released. (%s)\n",
10613             manager_isdn_get_info(event));
10614       }
10615       break;
10616    case EVENT_BCHAN_ERROR:
10617    case EVENT_CLEANUP:
10618       stop_bc_tones(ch);
10619 
10620       switch (ch->state) {
10621       case MISDN_CALLING:
10622          bc->cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
10623          break;
10624       default:
10625          break;
10626       }
10627 
10628       hangup_chan(ch, bc);
10629       release_chan(ch, bc);
10630       break;
10631    case EVENT_TONE_GENERATE:
10632    {
10633       int tone_len = bc->tone_cnt;
10634       struct ast_channel *ast = ch->ast;
10635       void *tmp;
10636       int res;
10637       int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
10638 
10639       chan_misdn_log(9, bc->port, "TONE_GEN: len:%d\n", tone_len);
10640 
10641       if (!ast) {
10642          break;
10643       }
10644 
10645       if (!ast->generator) {
10646          break;
10647       }
10648 
10649       tmp = ast->generatordata;
10650       ast->generatordata = NULL;
10651       generate = ast->generator->generate;
10652 
10653       if (tone_len < 0 || tone_len > 512) {
10654          ast_log(LOG_NOTICE, "TONE_GEN: len was %d, set to 128\n", tone_len);
10655          tone_len = 128;
10656       }
10657 
10658       res = generate(ast, tmp, tone_len, tone_len);
10659       ast->generatordata = tmp;
10660 
10661       if (res) {
10662          ast_log(LOG_WARNING, "Auto-deactivating generator\n");
10663          ast_deactivate_generator(ast);
10664       } else {
10665          bc->tone_cnt = 0;
10666       }
10667       break;
10668    }
10669    case EVENT_BCHAN_DATA:
10670       if (ch->bc->AOCD_need_export) {
10671          export_aoc_vars(ch->originator, ch->ast, ch->bc);
10672       }
10673       if (!misdn_cap_is_speech(ch->bc->capability)) {
10674          struct ast_frame frame;
10675 
10676          /* In Data Modes we queue frames */
10677          memset(&frame, 0, sizeof(frame));
10678          frame.frametype = AST_FRAME_VOICE; /* we have no data frames yet */
10679          frame.subclass.codec = AST_FORMAT_ALAW;
10680          frame.datalen = bc->bframe_len;
10681          frame.samples = bc->bframe_len;
10682          frame.mallocd = 0;
10683          frame.offset = 0;
10684          frame.delivery = ast_tv(0, 0);
10685          frame.src = NULL;
10686          frame.data.ptr = bc->bframe;
10687 
10688          if (ch->ast) {
10689             ast_queue_frame(ch->ast, &frame);
10690          }
10691       } else {
10692          struct pollfd pfd = { .fd = ch->pipe[1], .events = POLLOUT };
10693          int t;
10694 
10695          t = ast_poll(&pfd, 1, 0);
10696 
10697          if (t < 0) {
10698             chan_misdn_log(-1, bc->port, "poll() error (err=%s)\n", strerror(errno));
10699             break;
10700          }
10701          if (!t) {
10702             chan_misdn_log(9, bc->port, "poll() timed out\n");
10703             break;
10704          }
10705 
10706          if (pfd.revents & POLLOUT) {
10707             chan_misdn_log(9, bc->port, "writing %d bytes to asterisk\n", bc->bframe_len);
10708             if (write(ch->pipe[1], bc->bframe, bc->bframe_len) <= 0) {
10709                chan_misdn_log(0, bc->port, "Write returned <=0 (err=%s) --> hanging up channel\n", strerror(errno));
10710 
10711                stop_bc_tones(ch);
10712                hangup_chan(ch, bc);
10713                release_chan(ch, bc);
10714             }
10715          } else {
10716             chan_misdn_log(1, bc->port, "Write Pipe full!\n");
10717          }
10718       }
10719       break;
10720    case EVENT_TIMEOUT:
10721       if (ch && bc) {
10722          chan_misdn_log(1, bc->port, "--> state: %s\n", misdn_get_ch_state(ch));
10723       }
10724 
10725       switch (ch->state) {
10726       case MISDN_DIALING:
10727       case MISDN_PROGRESS:
10728          if (bc->nt && !ch->nttimeout) {
10729             break;
10730          }
10731          /* fall-through */
10732       case MISDN_CALLING:
10733       case MISDN_ALERTING:
10734       case MISDN_PROCEEDING:
10735       case MISDN_CALLING_ACKNOWLEDGE:
10736          if (bc->nt) {
10737             bc->progress_indicator = INFO_PI_INBAND_AVAILABLE;
10738             hanguptone_indicate(ch);
10739          }
10740 
10741          bc->out_cause = AST_CAUSE_UNALLOCATED;
10742          misdn_lib_send_event(bc, EVENT_DISCONNECT);
10743          break;
10744       case MISDN_WAITING4DIGS:
10745          if (bc->nt) {
10746             bc->progress_indicator = INFO_PI_INBAND_AVAILABLE;
10747             bc->out_cause = AST_CAUSE_UNALLOCATED;
10748             hanguptone_indicate(ch);
10749             misdn_lib_send_event(bc, EVENT_DISCONNECT);
10750          } else {
10751             bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
10752             misdn_lib_send_event(bc, EVENT_RELEASE);
10753          }
10754          break;
10755       case MISDN_CLEANING:
10756          chan_misdn_log(1, bc->port, " --> in state cleaning .. so ignoring, the stack should clean it for us\n");
10757          break;
10758       default:
10759          misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
10760          break;
10761       }
10762       break;
10763 
10764    /****************************/
10765    /** Supplementary Services **/
10766    /****************************/
10767    case EVENT_RETRIEVE:
10768       if (!ch) {
10769          chan_misdn_log(4, bc->port, " --> no CH, searching for held call\n");
10770          ch = find_hold_call_l3(bc->l3_id);
10771          if (!ch || ch->hold.state != MISDN_HOLD_ACTIVE) {
10772             ast_log(LOG_WARNING, "No held call found, cannot Retrieve\n");
10773             misdn_lib_send_event(bc, EVENT_RETRIEVE_REJECT);
10774             break;
10775          }
10776       }
10777 
10778       /* remember the channel again */
10779       ch->bc = bc;
10780 
10781       ch->hold.state = MISDN_HOLD_IDLE;
10782       ch->hold.port = 0;
10783       ch->hold.channel = 0;
10784 
10785       ast_queue_control(ch->ast, AST_CONTROL_UNHOLD);
10786 
10787       if (misdn_lib_send_event(bc, EVENT_RETRIEVE_ACKNOWLEDGE) < 0) {
10788          chan_misdn_log(4, bc->port, " --> RETRIEVE_ACK failed\n");
10789          misdn_lib_send_event(bc, EVENT_RETRIEVE_REJECT);
10790       }
10791       break;
10792    case EVENT_HOLD:
10793    {
10794       int hold_allowed;
10795       struct ast_channel *bridged;
10796 
10797       misdn_cfg_get(bc->port, MISDN_CFG_HOLD_ALLOWED, &hold_allowed, sizeof(hold_allowed));
10798       if (!hold_allowed) {
10799          chan_misdn_log(-1, bc->port, "Hold not allowed this port.\n");
10800          misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
10801          break;
10802       }
10803 
10804       bridged = ast_bridged_channel(ch->ast);
10805       if (bridged) {
10806          chan_misdn_log(2, bc->port, "Bridge Partner is of type: %s\n", bridged->tech->type);
10807          ch->l3id = bc->l3_id;
10808 
10809          /* forget the channel now */
10810          ch->bc = NULL;
10811          ch->hold.state = MISDN_HOLD_ACTIVE;
10812          ch->hold.port = bc->port;
10813          ch->hold.channel = bc->channel;
10814 
10815          ast_queue_control(ch->ast, AST_CONTROL_HOLD);
10816 
10817          misdn_lib_send_event(bc, EVENT_HOLD_ACKNOWLEDGE);
10818       } else {
10819          misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
10820          chan_misdn_log(0, bc->port, "We aren't bridged to anybody\n");
10821       }
10822       break;
10823    }
10824    case EVENT_NOTIFY:
10825       if (bc->redirecting.to_changed) {
10826          /* Add configured prefix to redirecting.to.number */
10827          misdn_add_number_prefix(bc->port, bc->redirecting.to.number_type,
10828             bc->redirecting.to.number, sizeof(bc->redirecting.to.number));
10829       }
10830       switch (bc->notify_description_code) {
10831       case mISDN_NOTIFY_CODE_DIVERSION_ACTIVATED:
10832          /* Ignore for now. */
10833          bc->redirecting.to_changed = 0;
10834          break;
10835       case mISDN_NOTIFY_CODE_CALL_IS_DIVERTING:
10836          if (!bc->redirecting.to_changed) {
10837             break;
10838          }
10839          bc->redirecting.to_changed = 0;
10840          if (!ch || !ch->ast) {
10841             break;
10842          }
10843          switch (ch->state) {
10844          case MISDN_ALERTING:
10845             /* Call is deflecting after we have seen an ALERTING message */
10846             bc->redirecting.reason = mISDN_REDIRECTING_REASON_NO_REPLY;
10847             break;
10848          default:
10849             /* Call is deflecting for call forwarding unconditional or busy reason. */
10850             bc->redirecting.reason = mISDN_REDIRECTING_REASON_UNKNOWN;
10851             break;
10852          }
10853          misdn_copy_redirecting_to_ast(ch->ast, &bc->redirecting, bc->incoming_cid_tag);
10854          ast_channel_queue_redirecting_update(ch->ast, &ch->ast->redirecting, NULL);
10855          break;
10856       case mISDN_NOTIFY_CODE_CALL_TRANSFER_ALERTING:
10857          /*
10858           * It would be preferable to update the connected line information
10859           * only when the message callStatus is active.  However, the
10860           * optional redirection number may not be present in the active
10861           * message if an alerting message were received earlier.
10862           *
10863           * The consequences if we wind up sending two updates is benign.
10864           * The other end will think that it got transferred twice.
10865           */
10866          if (!bc->redirecting.to_changed) {
10867             break;
10868          }
10869          bc->redirecting.to_changed = 0;
10870          if (!ch || !ch->ast) {
10871             break;
10872          }
10873          misdn_update_remote_party(ch->ast, &bc->redirecting.to,
10874             AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER_ALERTING,
10875             bc->incoming_cid_tag);
10876          break;
10877       case mISDN_NOTIFY_CODE_CALL_TRANSFER_ACTIVE:
10878          if (!bc->redirecting.to_changed) {
10879             break;
10880          }
10881          bc->redirecting.to_changed = 0;
10882          if (!ch || !ch->ast) {
10883             break;
10884          }
10885          misdn_update_remote_party(ch->ast, &bc->redirecting.to,
10886             AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER, bc->incoming_cid_tag);
10887          break;
10888       default:
10889          bc->redirecting.to_changed = 0;
10890          chan_misdn_log(0, bc->port," --> not yet handled: notify code:0x%02X\n",
10891             bc->notify_description_code);
10892          break;
10893       }
10894       bc->notify_description_code = mISDN_NOTIFY_CODE_INVALID;
10895       break;
10896    case EVENT_FACILITY:
10897       if (bc->fac_in.Function == Fac_None) {
10898          /* This is a FACILITY message so we MUST have a facility ie */
10899          chan_misdn_log(0, bc->port," --> Missing facility ie or unknown facility ie contents.\n");
10900       } else {
10901          misdn_facility_ie_handler(event, bc, ch);
10902       }
10903 
10904       /* In case it came in on a FACILITY message and we did not handle it. */
10905       bc->redirecting.to_changed = 0;
10906       bc->notify_description_code = mISDN_NOTIFY_CODE_INVALID;
10907       break;
10908    case EVENT_RESTART:
10909       if (!bc->dummy) {
10910          stop_bc_tones(ch);
10911          release_chan(ch, bc);
10912       }
10913       break;
10914    default:
10915       chan_misdn_log(1, 0, "Got Unknown Event\n");
10916       break;
10917    }
10918 
10919    return RESPONSE_OK;
10920 }
10921 
10922 /** TE STUFF END **/
10923 
10924 #if defined(AST_MISDN_ENHANCEMENTS)
10925 /*!
10926  * \internal
10927  * \brief Get call completion record information.
10928  *
10929  * \param chan Asterisk channel to operate upon. (Not used)
10930  * \param function_name Name of the function that called us.
10931  * \param function_args Argument string passed to function (Could be NULL)
10932  * \param buf Buffer to put returned string.
10933  * \param size Size of the supplied buffer including the null terminator.
10934  *
10935  * \retval 0 on success.
10936  * \retval -1 on error.
10937  */
10938 static int misdn_cc_read(struct ast_channel *chan, const char *function_name,
10939    char *function_args, char *buf, size_t size)
10940 {
10941    char *parse;
10942    struct misdn_cc_record *cc_record;
10943 
10944    AST_DECLARE_APP_ARGS(args,
10945       AST_APP_ARG(cc_id);     /* Call completion record ID value. */
10946       AST_APP_ARG(get_name);  /* Name of what to get */
10947       AST_APP_ARG(other);     /* Any extraneous garbage arguments */
10948    );
10949 
10950    /* Ensure that the buffer is empty */
10951    *buf = 0;
10952 
10953    if (ast_strlen_zero(function_args)) {
10954       ast_log(LOG_ERROR, "Function '%s' requires arguments.\n", function_name);
10955       return -1;
10956    }
10957 
10958    parse = ast_strdupa(function_args);
10959    AST_STANDARD_APP_ARGS(args, parse);
10960 
10961    if (!args.argc || ast_strlen_zero(args.cc_id)) {
10962       ast_log(LOG_ERROR, "Function '%s' missing call completion record ID.\n",
10963          function_name);
10964       return -1;
10965    }
10966    if (!isdigit(*args.cc_id)) {
10967       ast_log(LOG_ERROR, "Function '%s' call completion record ID must be numeric.\n",
10968          function_name);
10969       return -1;
10970    }
10971 
10972    if (ast_strlen_zero(args.get_name)) {
10973       ast_log(LOG_ERROR, "Function '%s' missing what-to-get parameter.\n",
10974          function_name);
10975       return -1;
10976    }
10977 
10978    AST_LIST_LOCK(&misdn_cc_records_db);
10979    cc_record = misdn_cc_find_by_id(atoi(args.cc_id));
10980    if (cc_record) {
10981       if (!strcasecmp("a-all", args.get_name)) {
10982          snprintf(buf, size, "\"%s\" <%s>", cc_record->redial.caller.name,
10983             cc_record->redial.caller.number);
10984       } else if (!strcasecmp("a-name", args.get_name)) {
10985          ast_copy_string(buf, cc_record->redial.caller.name, size);
10986       } else if (!strncasecmp("a-num", args.get_name, 5)) {
10987          ast_copy_string(buf, cc_record->redial.caller.number, size);
10988       } else if (!strcasecmp("a-ton", args.get_name)) {
10989          snprintf(buf, size, "%d",
10990             misdn_to_ast_plan(cc_record->redial.caller.number_plan)
10991             | misdn_to_ast_ton(cc_record->redial.caller.number_type));
10992       } else if (!strncasecmp("a-pres", args.get_name, 6)) {
10993          ast_copy_string(buf, ast_named_caller_presentation(
10994             misdn_to_ast_pres(cc_record->redial.caller.presentation)
10995             | misdn_to_ast_screen(cc_record->redial.caller.screening)), size);
10996       } else if (!strcasecmp("a-busy", args.get_name)) {
10997          ast_copy_string(buf, cc_record->party_a_free ? "no" : "yes", size);
10998       } else if (!strncasecmp("b-num", args.get_name, 5)) {
10999          ast_copy_string(buf, cc_record->redial.dialed.number, size);
11000       } else if (!strcasecmp("b-ton", args.get_name)) {
11001          snprintf(buf, size, "%d",
11002             misdn_to_ast_plan(cc_record->redial.dialed.number_plan)
11003             | misdn_to_ast_ton(cc_record->redial.dialed.number_type));
11004       } else if (!strcasecmp("port", args.get_name)) {
11005          snprintf(buf, size, "%d", cc_record->port);
11006       } else if (!strcasecmp("available-notify-priority", args.get_name)) {
11007          snprintf(buf, size, "%d", cc_record->remote_user_free.priority);
11008       } else if (!strcasecmp("available-notify-exten", args.get_name)) {
11009          ast_copy_string(buf, cc_record->remote_user_free.exten, size);
11010       } else if (!strcasecmp("available-notify-context", args.get_name)) {
11011          ast_copy_string(buf, cc_record->remote_user_free.context, size);
11012       } else if (!strcasecmp("busy-notify-priority", args.get_name)) {
11013          snprintf(buf, size, "%d", cc_record->b_free.priority);
11014       } else if (!strcasecmp("busy-notify-exten", args.get_name)) {
11015          ast_copy_string(buf, cc_record->b_free.exten, size);
11016       } else if (!strcasecmp("busy-notify-context", args.get_name)) {
11017          ast_copy_string(buf, cc_record->b_free.context, size);
11018       } else {
11019          AST_LIST_UNLOCK(&misdn_cc_records_db);
11020          ast_log(LOG_ERROR, "Function '%s': Unknown what-to-get '%s'.\n", function_name, args.get_name);
11021          return -1;
11022       }
11023    }
11024    AST_LIST_UNLOCK(&misdn_cc_records_db);
11025 
11026    return 0;
11027 }
11028 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11029 
11030 #if defined(AST_MISDN_ENHANCEMENTS)
11031 static struct ast_custom_function misdn_cc_function = {
11032    .name = "mISDN_CC",
11033    .synopsis = "Get call completion record information.",
11034    .syntax = "mISDN_CC(${MISDN_CC_RECORD_ID},<what-to-get>)",
11035    .desc =
11036       "mISDN_CC(${MISDN_CC_RECORD_ID},<what-to-get>)\n"
11037       "The following can be retrieved:\n"
11038       "\"a-num\", \"a-name\", \"a-all\", \"a-ton\", \"a-pres\", \"a-busy\",\n"
11039       "\"b-num\", \"b-ton\", \"port\",\n"
11040       "  User-A is available for call completion:\n"
11041       "    \"available-notify-priority\",\n"
11042       "    \"available-notify-exten\",\n"
11043       "    \"available-notify-context\",\n"
11044       "  User-A is busy:\n"
11045       "    \"busy-notify-priority\",\n"
11046       "    \"busy-notify-exten\",\n"
11047       "    \"busy-notify-context\"\n",
11048    .read = misdn_cc_read,
11049 };
11050 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11051 
11052 /******************************************
11053  *
11054  *   Asterisk Channel Endpoint END
11055  *
11056  *
11057  *******************************************/
11058 
11059 
11060 
11061 static int unload_module(void)
11062 {
11063    /* First, take us out of the channel loop */
11064    ast_log(LOG_VERBOSE, "-- Unregistering mISDN Channel Driver --\n");
11065 
11066    misdn_tasks_destroy();
11067 
11068    if (!g_config_initialized) {
11069       return 0;
11070    }
11071 
11072    ast_cli_unregister_multiple(chan_misdn_clis, sizeof(chan_misdn_clis) / sizeof(struct ast_cli_entry));
11073 
11074    /* ast_unregister_application("misdn_crypt"); */
11075    ast_unregister_application("misdn_set_opt");
11076    ast_unregister_application("misdn_facility");
11077    ast_unregister_application("misdn_check_l2l1");
11078 #if defined(AST_MISDN_ENHANCEMENTS)
11079    ast_unregister_application(misdn_command_name);
11080    ast_custom_function_unregister(&misdn_cc_function);
11081 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11082 
11083    ast_channel_unregister(&misdn_tech);
11084 
11085    free_robin_list();
11086    misdn_cfg_destroy();
11087    misdn_lib_destroy();
11088 
11089    ast_free(misdn_out_calls);
11090    ast_free(misdn_in_calls);
11091    ast_free(misdn_debug_only);
11092    ast_free(misdn_ports);
11093    ast_free(misdn_debug);
11094 
11095 #if defined(AST_MISDN_ENHANCEMENTS)
11096    misdn_cc_destroy();
11097 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11098 
11099    return 0;
11100 }
11101 
11102 static int load_module(void)
11103 {
11104    int i, port;
11105    int ntflags = 0, ntkc = 0;
11106    char ports[256] = "";
11107    char tempbuf[BUFFERSIZE + 1];
11108    char ntfile[BUFFERSIZE + 1];
11109    struct misdn_lib_iface iface = {
11110       .cb_event = cb_events,
11111       .cb_log = chan_misdn_log,
11112       .cb_jb_empty = chan_misdn_jb_empty,
11113    };
11114 
11115    max_ports = misdn_lib_maxports_get();
11116 
11117    if (max_ports <= 0) {
11118       ast_log(LOG_ERROR, "Unable to initialize mISDN\n");
11119       return AST_MODULE_LOAD_DECLINE;
11120    }
11121 
11122    if (misdn_cfg_init(max_ports, 0)) {
11123       ast_log(LOG_ERROR, "Unable to initialize misdn_config.\n");
11124       return AST_MODULE_LOAD_DECLINE;
11125    }
11126    g_config_initialized = 1;
11127 
11128 #if defined(AST_MISDN_ENHANCEMENTS)
11129    misdn_cc_init();
11130 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11131 
11132    misdn_debug = ast_malloc(sizeof(int) * (max_ports + 1));
11133    if (!misdn_debug) {
11134       ast_log(LOG_ERROR, "Out of memory for misdn_debug\n");
11135       return AST_MODULE_LOAD_DECLINE;
11136    }
11137    misdn_ports = ast_malloc(sizeof(int) * (max_ports + 1));
11138    if (!misdn_ports) {
11139       ast_free(misdn_debug);
11140       ast_log(LOG_ERROR, "Out of memory for misdn_ports\n");
11141       return AST_MODULE_LOAD_DECLINE;
11142    }
11143    misdn_cfg_get(0, MISDN_GEN_DEBUG, &misdn_debug[0], sizeof(misdn_debug[0]));
11144    for (i = 1; i <= max_ports; i++) {
11145       misdn_debug[i] = misdn_debug[0];
11146       misdn_ports[i] = i;
11147    }
11148    *misdn_ports = 0;
11149    misdn_debug_only = ast_calloc(max_ports + 1, sizeof(int));
11150    if (!misdn_debug_only) {
11151       ast_free(misdn_ports);
11152       ast_free(misdn_debug);
11153       ast_log(LOG_ERROR, "Out of memory for misdn_debug_only\n");
11154       return AST_MODULE_LOAD_DECLINE;
11155    }
11156 
11157    misdn_cfg_get(0, MISDN_GEN_TRACEFILE, tempbuf, sizeof(tempbuf));
11158    if (!ast_strlen_zero(tempbuf)) {
11159       tracing = 1;
11160    }
11161 
11162    misdn_in_calls = ast_malloc(sizeof(int) * (max_ports + 1));
11163    if (!misdn_in_calls) {
11164       ast_free(misdn_debug_only);
11165       ast_free(misdn_ports);
11166       ast_free(misdn_debug);
11167       ast_log(LOG_ERROR, "Out of memory for misdn_in_calls\n");
11168       return AST_MODULE_LOAD_DECLINE;
11169    }
11170    misdn_out_calls = ast_malloc(sizeof(int) * (max_ports + 1));
11171    if (!misdn_out_calls) {
11172       ast_free(misdn_in_calls);
11173       ast_free(misdn_debug_only);
11174       ast_free(misdn_ports);
11175       ast_free(misdn_debug);
11176       ast_log(LOG_ERROR, "Out of memory for misdn_out_calls\n");
11177       return AST_MODULE_LOAD_DECLINE;
11178    }
11179 
11180    for (i = 1; i <= max_ports; i++) {
11181       misdn_in_calls[i] = 0;
11182       misdn_out_calls[i] = 0;
11183    }
11184 
11185    ast_mutex_init(&cl_te_lock);
11186    ast_mutex_init(&release_lock);
11187 
11188    misdn_cfg_update_ptp();
11189    misdn_cfg_get_ports_string(ports);
11190 
11191    if (!ast_strlen_zero(ports)) {
11192       chan_misdn_log(0, 0, "Got: %s from get_ports\n", ports);
11193    }
11194    if (misdn_lib_init(ports, &iface, NULL)) {
11195       chan_misdn_log(0, 0, "No te ports initialized\n");
11196    }
11197 
11198    misdn_cfg_get(0, MISDN_GEN_NTDEBUGFLAGS, &ntflags, sizeof(ntflags));
11199    misdn_cfg_get(0, MISDN_GEN_NTDEBUGFILE, &ntfile, sizeof(ntfile));
11200    misdn_cfg_get(0, MISDN_GEN_NTKEEPCALLS, &ntkc, sizeof(ntkc));
11201 
11202    misdn_lib_nt_keepcalls(ntkc);
11203    misdn_lib_nt_debug_init(ntflags, ntfile);
11204 
11205    if (ast_channel_register(&misdn_tech)) {
11206       ast_log(LOG_ERROR, "Unable to register channel class %s\n", misdn_type);
11207       unload_module();
11208       return AST_MODULE_LOAD_DECLINE;
11209    }
11210 
11211    ast_cli_register_multiple(chan_misdn_clis, sizeof(chan_misdn_clis) / sizeof(struct ast_cli_entry));
11212 
11213    ast_register_application("misdn_set_opt", misdn_set_opt_exec, "misdn_set_opt",
11214       "misdn_set_opt(:<opt><optarg>:<opt><optarg>...):\n"
11215       "Sets mISDN opts. and optargs\n"
11216       "\n"
11217       "The available options are:\n"
11218       "    a - Have Asterisk detect DTMF tones on called channel\n"
11219       "    c - Make crypted outgoing call, optarg is keyindex\n"
11220       "    d - Send display text to called phone, text is the optarg\n"
11221       "    e - Perform echo cancellation on this channel,\n"
11222       "        takes taps as optarg (32,64,128,256)\n"
11223       "   e! - Disable echo cancellation on this channel\n"
11224       "    f - Enable fax detection\n"
11225       "    h - Make digital outgoing call\n"
11226       "   h1 - Make HDLC mode digital outgoing call\n"
11227       "    i - Ignore detected DTMF tones, don't signal them to Asterisk,\n"
11228       "        they will be transported inband.\n"
11229       "   jb - Set jitter buffer length, optarg is length\n"
11230       "   jt - Set jitter buffer upper threshold, optarg is threshold\n"
11231       "   jn - Disable jitter buffer\n"
11232       "    n - Disable mISDN DSP on channel.\n"
11233       "        Disables: echo cancel, DTMF detection, and volume control.\n"
11234       "    p - Caller ID presentation,\n"
11235       "        optarg is either 'allowed' or 'restricted'\n"
11236       "    s - Send Non-inband DTMF as inband\n"
11237       "   vr - Rx gain control, optarg is gain\n"
11238       "   vt - Tx gain control, optarg is gain\n"
11239       );
11240 
11241 
11242    ast_register_application("misdn_facility", misdn_facility_exec, "misdn_facility",
11243       "misdn_facility(<FACILITY_TYPE>|<ARG1>|..)\n"
11244       "Sends the Facility Message FACILITY_TYPE with \n"
11245       "the given Arguments to the current ISDN Channel\n"
11246       "Supported Facilities are:\n"
11247       "\n"
11248       "type=calldeflect args=Nr where to deflect\n"
11249 #if defined(AST_MISDN_ENHANCEMENTS)
11250       "type=callrerouting args=Nr where to deflect\n"
11251 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11252       );
11253 
11254 
11255    ast_register_application("misdn_check_l2l1", misdn_check_l2l1, "misdn_check_l2l1",
11256       "misdn_check_l2l1(<port>||g:<groupname>,timeout)\n"
11257       "Checks if the L2 and L1 are up on either the given <port> or\n"
11258       "on the ports in the group with <groupname>\n"
11259       "If the L1/L2 are down, check_l2l1 gets up the L1/L2 and waits\n"
11260       "for <timeout> seconds that this happens. Otherwise, nothing happens\n"
11261       "\n"
11262       "This application, ensures the L1/L2 state of the Ports in a group\n"
11263       "it is intended to make the pmp_l1_check option redundant and to\n"
11264       "fix a buggy switch config from your provider\n"
11265       "\n"
11266       "a sample dialplan would look like:\n\n"
11267       "exten => _X.,1,misdn_check_l2l1(g:out|2)\n"
11268       "exten => _X.,n,dial(mISDN/g:out/${EXTEN})\n"
11269       );
11270 
11271 #if defined(AST_MISDN_ENHANCEMENTS)
11272    ast_register_application(misdn_command_name, misdn_command_exec, misdn_command_name,
11273       "misdn_command(<command>[,<options>])\n"
11274       "The following commands are defined:\n"
11275       "cc-initialize\n"
11276       "  Setup mISDN support for call completion\n"
11277       "  Must call before doing any Dial() involving call completion.\n"
11278       "ccnr-request,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>\n"
11279       "  Request Call Completion No Reply activation\n"
11280       "ccbs-request,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>\n"
11281       "  Request Call Completion Busy Subscriber activation\n"
11282       "cc-b-free,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>\n"
11283       "  Set the dialplan location to notify when User-B is available but User-A is busy.\n"
11284       "  Setting this dialplan location is optional.\n"
11285       "cc-a-busy,${MISDN_CC_RECORD_ID},<yes/no>\n"
11286       "  Set the busy status of call completion User-A\n"
11287       "cc-deactivate,${MISDN_CC_RECORD_ID}\n"
11288       "  Deactivate the identified call completion request\n"
11289       "\n"
11290       "MISDN_CC_RECORD_ID is set when Dial() returns and call completion is possible\n"
11291       "MISDN_CC_STATUS is set to ACTIVATED or ERROR after the call completion\n"
11292       "activation request.\n"
11293       "MISDN_ERROR_MSG is set to a descriptive message on error.\n"
11294       );
11295 
11296    ast_custom_function_register(&misdn_cc_function);
11297 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11298 
11299    misdn_cfg_get(0, MISDN_GEN_TRACEFILE, global_tracefile, sizeof(global_tracefile));
11300 
11301    /* start the l1 watchers */
11302 
11303    for (port = misdn_cfg_get_next_port(0); port >= 0; port = misdn_cfg_get_next_port(port)) {
11304       int l1timeout;
11305       misdn_cfg_get(port, MISDN_CFG_L1_TIMEOUT, &l1timeout, sizeof(l1timeout));
11306       if (l1timeout) {
11307          chan_misdn_log(4, 0, "Adding L1watcher task: port:%d timeout:%ds\n", port, l1timeout);
11308          misdn_tasks_add(l1timeout * 1000, misdn_l1_task, &misdn_ports[port]);
11309       }
11310    }
11311 
11312    chan_misdn_log(0, 0, "-- mISDN Channel Driver Registered --\n");
11313 
11314    return 0;
11315 }
11316 
11317 
11318 
11319 static int reload(void)
11320 {
11321    reload_config();
11322 
11323    return 0;
11324 }
11325 
11326 /*** SOME APPS ;)***/
11327 
11328 #if defined(AST_MISDN_ENHANCEMENTS)
11329 /*!
11330 * \brief misdn_command arguments container.
11331 */
11332 AST_DEFINE_APP_ARGS_TYPE(misdn_command_args,
11333    AST_APP_ARG(name);         /* Subcommand name */
11334    AST_APP_ARG(arg)[10 + 1];  /* Subcommand arguments */
11335 );
11336 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11337 
11338 #if defined(AST_MISDN_ENHANCEMENTS)
11339 static void misdn_cc_caller_destroy(void *obj)
11340 {
11341    /* oh snap! */
11342 }
11343 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11344 
11345 #if defined(AST_MISDN_ENHANCEMENTS)
11346 static struct misdn_cc_caller *misdn_cc_caller_alloc(struct ast_channel *chan)
11347 {
11348    struct misdn_cc_caller *cc_caller;
11349 
11350    if (!(cc_caller = ao2_alloc(sizeof(*cc_caller), misdn_cc_caller_destroy))) {
11351       return NULL;
11352    }
11353 
11354    cc_caller->chan = chan;
11355 
11356    return cc_caller;
11357 }
11358 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11359 
11360 #if defined(AST_MISDN_ENHANCEMENTS)
11361 /*!
11362  * \internal
11363  * \brief misdn_command(cc-initialize) subcommand handler
11364  *
11365  * \param chan Asterisk channel to operate upon.
11366  * \param subcommand Arguments for the subcommand
11367  *
11368  * \retval 0 on success.
11369  * \retval -1 on error.
11370  */
11371 static int misdn_command_cc_initialize(struct ast_channel *chan, struct misdn_command_args *subcommand)
11372 {
11373    struct misdn_cc_caller *cc_caller;
11374    struct ast_datastore *datastore;
11375 
11376    if (!(cc_caller = misdn_cc_caller_alloc(chan))) {
11377       return -1;
11378    }
11379 
11380    if (!(datastore = ast_datastore_alloc(&misdn_cc_ds_info, NULL))) {
11381       ao2_ref(cc_caller, -1);
11382       return -1;
11383    }
11384 
11385    ast_channel_lock(chan);
11386 
11387    /* Inherit reference */
11388    datastore->data = cc_caller;
11389    cc_caller = NULL;
11390 
11391    datastore->inheritance = DATASTORE_INHERIT_FOREVER;
11392 
11393    ast_channel_datastore_add(chan, datastore);
11394 
11395    ast_channel_unlock(chan);
11396 
11397    return 0;
11398 }
11399 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11400 
11401 #if defined(AST_MISDN_ENHANCEMENTS)
11402 /*!
11403  * \internal
11404  * \brief misdn_command(cc-deactivate) subcommand handler
11405  *
11406  * \details
11407  * misdn_command(cc-deactivate,${MISDN_CC_RECORD_ID})
11408  * Deactivate a call completion service instance.
11409  *
11410  * \param chan Asterisk channel to operate upon.
11411  * \param subcommand Arguments for the subcommand
11412  *
11413  * \retval 0 on success.
11414  * \retval -1 on error.
11415  */
11416 static int misdn_command_cc_deactivate(struct ast_channel *chan, struct misdn_command_args *subcommand)
11417 {
11418    long record_id;
11419    const char *error_str;
11420    struct misdn_cc_record *cc_record;
11421    struct misdn_bchannel *bc;
11422    struct misdn_bchannel dummy;
11423 
11424    static const char cmd_help[] = "%s(%s,${MISDN_CC_RECORD_ID})\n";
11425 
11426    if (ast_strlen_zero(subcommand->arg[0]) || !isdigit(*subcommand->arg[0])) {
11427       ast_log(LOG_WARNING, cmd_help, misdn_command_name, subcommand->name);
11428       return -1;
11429    }
11430    record_id = atol(subcommand->arg[0]);
11431 
11432    AST_LIST_LOCK(&misdn_cc_records_db);
11433    cc_record = misdn_cc_find_by_id(record_id);
11434    if (cc_record && 0 <= cc_record->port) {
11435       if (cc_record->ptp) {
11436          if (cc_record->mode.ptp.bc) {
11437             /* Close the call-completion signaling link */
11438             bc = cc_record->mode.ptp.bc;
11439             bc->fac_out.Function = Fac_None;
11440             bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
11441             misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
11442          }
11443          misdn_cc_delete(cc_record);
11444       } else if (cc_record->activated) {
11445          cc_record->error_code = FacError_None;
11446          cc_record->reject_code = FacReject_None;
11447          cc_record->invoke_id = ++misdn_invoke_id;
11448          cc_record->outstanding_message = 1;
11449 
11450          /* Build message */
11451          misdn_make_dummy(&dummy, cc_record->port, 0, misdn_lib_port_is_nt(cc_record->port), 0);
11452          dummy.fac_out.Function = Fac_CCBSDeactivate;
11453          dummy.fac_out.u.CCBSDeactivate.InvokeID = cc_record->invoke_id;
11454          dummy.fac_out.u.CCBSDeactivate.ComponentType = FacComponent_Invoke;
11455          dummy.fac_out.u.CCBSDeactivate.Component.Invoke.CCBSReference = cc_record->mode.ptmp.reference_id;
11456 
11457          /* Send message */
11458          print_facility(&dummy.fac_out, &dummy);
11459          misdn_lib_send_event(&dummy, EVENT_FACILITY);
11460       }
11461    }
11462    AST_LIST_UNLOCK(&misdn_cc_records_db);
11463 
11464    /* Wait for the response to the call completion deactivation request. */
11465    misdn_cc_response_wait(chan, MISDN_CC_REQUEST_WAIT_MAX, record_id);
11466 
11467    AST_LIST_LOCK(&misdn_cc_records_db);
11468    cc_record = misdn_cc_find_by_id(record_id);
11469    if (cc_record) {
11470       if (cc_record->port < 0) {
11471          /* The network did not tell us that call completion was available. */
11472          error_str = NULL;
11473       } else if (cc_record->outstanding_message) {
11474          cc_record->outstanding_message = 0;
11475          error_str = misdn_no_response_from_network;
11476       } else if (cc_record->reject_code != FacReject_None) {
11477          error_str = misdn_to_str_reject_code(cc_record->reject_code);
11478       } else if (cc_record->error_code != FacError_None) {
11479          error_str = misdn_to_str_error_code(cc_record->error_code);
11480       } else {
11481          error_str = NULL;
11482       }
11483 
11484       misdn_cc_delete(cc_record);
11485    } else {
11486       error_str = NULL;
11487    }
11488    AST_LIST_UNLOCK(&misdn_cc_records_db);
11489    if (error_str) {
11490       ast_verb(1, "%s(%s) diagnostic '%s' on channel %s\n",
11491          misdn_command_name, subcommand->name, error_str, chan->name);
11492       pbx_builtin_setvar_helper(chan, MISDN_ERROR_MSG, error_str);
11493    }
11494 
11495    return 0;
11496 }
11497 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11498 
11499 #if defined(AST_MISDN_ENHANCEMENTS)
11500 /*!
11501  * \internal
11502  * \brief misdn_command(cc-a-busy) subcommand handler
11503  *
11504  * \details
11505  * misdn_command(cc-a-busy,${MISDN_CC_RECORD_ID},<yes/no>)
11506  * Set the status of User-A for a call completion service instance.
11507  *
11508  * \param chan Asterisk channel to operate upon.
11509  * \param subcommand Arguments for the subcommand
11510  *
11511  * \retval 0 on success.
11512  * \retval -1 on error.
11513  */
11514 static int misdn_command_cc_a_busy(struct ast_channel *chan, struct misdn_command_args *subcommand)
11515 {
11516    long record_id;
11517    int party_a_free;
11518    struct misdn_cc_record *cc_record;
11519    struct misdn_bchannel *bc;
11520 
11521    static const char cmd_help[] = "%s(%s,${MISDN_CC_RECORD_ID},<yes/no>)\n";
11522 
11523    if (ast_strlen_zero(subcommand->arg[0]) || !isdigit(*subcommand->arg[0])) {
11524       ast_log(LOG_WARNING, cmd_help, misdn_command_name, subcommand->name);
11525       return -1;
11526    }
11527    record_id = atol(subcommand->arg[0]);
11528 
11529    if (ast_true(subcommand->arg[1])) {
11530       party_a_free = 0;
11531    } else if (ast_false(subcommand->arg[1])) {
11532       party_a_free = 1;
11533    } else {
11534       ast_log(LOG_WARNING, cmd_help, misdn_command_name, subcommand->name);
11535       return -1;
11536    }
11537 
11538    AST_LIST_LOCK(&misdn_cc_records_db);
11539    cc_record = misdn_cc_find_by_id(record_id);
11540    if (cc_record && cc_record->party_a_free != party_a_free) {
11541       /* User-A's status has changed */
11542       cc_record->party_a_free = party_a_free;
11543 
11544       if (cc_record->ptp && cc_record->mode.ptp.bc) {
11545          cc_record->error_code = FacError_None;
11546          cc_record->reject_code = FacReject_None;
11547 
11548          /* Build message */
11549          bc = cc_record->mode.ptp.bc;
11550          if (cc_record->party_a_free) {
11551             bc->fac_out.Function = Fac_CCBS_T_Resume;
11552             bc->fac_out.u.CCBS_T_Resume.InvokeID = ++misdn_invoke_id;
11553          } else {
11554             bc->fac_out.Function = Fac_CCBS_T_Suspend;
11555             bc->fac_out.u.CCBS_T_Suspend.InvokeID = ++misdn_invoke_id;
11556          }
11557 
11558          /* Send message */
11559          print_facility(&bc->fac_out, bc);
11560          misdn_lib_send_event(bc, EVENT_FACILITY);
11561       }
11562    }
11563    AST_LIST_UNLOCK(&misdn_cc_records_db);
11564 
11565    return 0;
11566 }
11567 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11568 
11569 #if defined(AST_MISDN_ENHANCEMENTS)
11570 /*!
11571  * \internal
11572  * \brief misdn_command(cc-b-free) subcommand handler
11573  *
11574  * \details
11575  * misdn_command(cc-b-free,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>)
11576  * Set the dialplan location to notify when User-B is free and User-A is busy.
11577  *
11578  * \param chan Asterisk channel to operate upon.
11579  * \param subcommand Arguments for the subcommand
11580  *
11581  * \retval 0 on success.
11582  * \retval -1 on error.
11583  */
11584 static int misdn_command_cc_b_free(struct ast_channel *chan, struct misdn_command_args *subcommand)
11585 {
11586    unsigned index;
11587    long record_id;
11588    int priority;
11589    char *context;
11590    char *exten;
11591    struct misdn_cc_record *cc_record;
11592 
11593    static const char cmd_help[] = "%s(%s,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>)\n";
11594 
11595    /* Check that all arguments are present */
11596    for (index = 0; index < 4; ++index) {
11597       if (ast_strlen_zero(subcommand->arg[index])) {
11598          ast_log(LOG_WARNING, cmd_help, misdn_command_name, subcommand->name);
11599          return -1;
11600       }
11601    }
11602 
11603    /* These must be numeric */
11604    if (!isdigit(*subcommand->arg[0]) || !isdigit(*subcommand->arg[3])) {
11605       ast_log(LOG_WARNING, cmd_help, misdn_command_name, subcommand->name);
11606       return -1;
11607    }
11608 
11609    record_id = atol(subcommand->arg[0]);
11610    context = subcommand->arg[1];
11611    exten = subcommand->arg[2];
11612    priority = atoi(subcommand->arg[3]);
11613 
11614    AST_LIST_LOCK(&misdn_cc_records_db);
11615    cc_record = misdn_cc_find_by_id(record_id);
11616    if (cc_record) {
11617       /* Save User-B free information */
11618       ast_copy_string(cc_record->b_free.context, context, sizeof(cc_record->b_free.context));
11619       ast_copy_string(cc_record->b_free.exten, exten, sizeof(cc_record->b_free.exten));
11620       cc_record->b_free.priority = priority;
11621    }
11622    AST_LIST_UNLOCK(&misdn_cc_records_db);
11623 
11624    return 0;
11625 }
11626 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11627 
11628 #if defined(AST_MISDN_ENHANCEMENTS)
11629 struct misdn_cc_request {
11630    enum FacFunction ptmp;
11631    enum FacFunction ptp;
11632 };
11633 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11634 
11635 #if defined(AST_MISDN_ENHANCEMENTS)
11636 /*!
11637  * \internal
11638  * \brief misdn_command(ccbs-request/ccnr-request) subcommand handler helper
11639  *
11640  * \details
11641  * misdn_command(ccbs-request,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>)
11642  * misdn_command(ccnr-request,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>)
11643  * Set the dialplan location to notify when User-B is free and User-A is free.
11644  *
11645  * \param chan Asterisk channel to operate upon.
11646  * \param subcommand Arguments for the subcommand
11647  * \param request Which call-completion request message to generate.
11648  *
11649  * \retval 0 on success.
11650  * \retval -1 on error.
11651  */
11652 static int misdn_command_cc_request(struct ast_channel *chan, struct misdn_command_args *subcommand, const struct misdn_cc_request *request)
11653 {
11654    unsigned index;
11655    int request_retention;
11656    long record_id;
11657    int priority;
11658    char *context;
11659    char *exten;
11660    const char *error_str;
11661    struct misdn_cc_record *cc_record;
11662    struct misdn_bchannel *bc;
11663    struct misdn_bchannel dummy;
11664    struct misdn_party_id id;
11665 
11666    static const char cmd_help[] = "%s(%s,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>)\n";
11667 
11668    /* Check that all arguments are present */
11669    for (index = 0; index < 4; ++index) {
11670       if (ast_strlen_zero(subcommand->arg[index])) {
11671          ast_log(LOG_WARNING, cmd_help, misdn_command_name, subcommand->name);
11672          return -1;
11673       }
11674    }
11675 
11676    /* These must be numeric */
11677    if (!isdigit(*subcommand->arg[0]) || !isdigit(*subcommand->arg[3])) {
11678       ast_log(LOG_WARNING, cmd_help, misdn_command_name, subcommand->name);
11679       return -1;
11680    }
11681 
11682    record_id = atol(subcommand->arg[0]);
11683    context = subcommand->arg[1];
11684    exten = subcommand->arg[2];
11685    priority = atoi(subcommand->arg[3]);
11686 
11687    AST_LIST_LOCK(&misdn_cc_records_db);
11688    cc_record = misdn_cc_find_by_id(record_id);
11689    if (cc_record) {
11690       /* Save User-B free information */
11691       ast_copy_string(cc_record->remote_user_free.context, context,
11692          sizeof(cc_record->remote_user_free.context));
11693       ast_copy_string(cc_record->remote_user_free.exten, exten,
11694          sizeof(cc_record->remote_user_free.exten));
11695       cc_record->remote_user_free.priority = priority;
11696 
11697       if (0 <= cc_record->port) {
11698          if (cc_record->ptp) {
11699             if (!cc_record->mode.ptp.bc) {
11700                bc = misdn_lib_get_register_bc(cc_record->port);
11701                if (bc) {
11702                   cc_record->mode.ptp.bc = bc;
11703                   cc_record->error_code = FacError_None;
11704                   cc_record->reject_code = FacReject_None;
11705                   cc_record->invoke_id = ++misdn_invoke_id;
11706                   cc_record->outstanding_message = 1;
11707                   cc_record->activation_requested = 1;
11708 
11709                   misdn_cfg_get(bc->port, MISDN_CFG_CC_REQUEST_RETENTION,
11710                      &request_retention, sizeof(request_retention));
11711                   cc_record->mode.ptp.requested_retention = request_retention ? 1 : 0;
11712 
11713                   /* Build message */
11714                   bc->fac_out.Function = request->ptp;
11715                   bc->fac_out.u.CCBS_T_Request.InvokeID = cc_record->invoke_id;
11716                   bc->fac_out.u.CCBS_T_Request.ComponentType = FacComponent_Invoke;
11717                   bc->fac_out.u.CCBS_T_Request.Component.Invoke.Q931ie =
11718                      cc_record->redial.setup_bc_hlc_llc;
11719                   memset(&id, 0, sizeof(id));
11720                   id.number_plan = cc_record->redial.dialed.number_plan;
11721                   id.number_type = cc_record->redial.dialed.number_type;
11722                   ast_copy_string(id.number, cc_record->redial.dialed.number,
11723                      sizeof(id.number));
11724                   misdn_Address_fill(
11725                      &bc->fac_out.u.CCBS_T_Request.Component.Invoke.Destination,
11726                      &id);
11727                   misdn_Address_fill(
11728                      &bc->fac_out.u.CCBS_T_Request.Component.Invoke.Originating,
11729                      &cc_record->redial.caller);
11730                   bc->fac_out.u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicatorPresent = 1;
11731                   bc->fac_out.u.CCBS_T_Request.Component.Invoke.PresentationAllowedIndicator =
11732                      (cc_record->redial.caller.presentation != 0) ? 0 : 1;
11733                   bc->fac_out.u.CCBS_T_Request.Component.Invoke.RetentionSupported =
11734                      request_retention ? 1 : 0;
11735 
11736                   /* Send message */
11737                   print_facility(&bc->fac_out, bc);
11738                   misdn_lib_send_event(bc, EVENT_REGISTER);
11739                }
11740             }
11741          } else {
11742             cc_record->error_code = FacError_None;
11743             cc_record->reject_code = FacReject_None;
11744             cc_record->invoke_id = ++misdn_invoke_id;
11745             cc_record->outstanding_message = 1;
11746             cc_record->activation_requested = 1;
11747 
11748             /* Build message */
11749             misdn_make_dummy(&dummy, cc_record->port, 0,
11750                misdn_lib_port_is_nt(cc_record->port), 0);
11751             dummy.fac_out.Function = request->ptmp;
11752             dummy.fac_out.u.CCBSRequest.InvokeID = cc_record->invoke_id;
11753             dummy.fac_out.u.CCBSRequest.ComponentType = FacComponent_Invoke;
11754             dummy.fac_out.u.CCBSRequest.Component.Invoke.CallLinkageID =
11755                cc_record->mode.ptmp.linkage_id;
11756 
11757             /* Send message */
11758             print_facility(&dummy.fac_out, &dummy);
11759             misdn_lib_send_event(&dummy, EVENT_FACILITY);
11760          }
11761       }
11762    }
11763    AST_LIST_UNLOCK(&misdn_cc_records_db);
11764 
11765    /* Wait for the response to the call completion request. */
11766    misdn_cc_response_wait(chan, MISDN_CC_REQUEST_WAIT_MAX, record_id);
11767 
11768    AST_LIST_LOCK(&misdn_cc_records_db);
11769    cc_record = misdn_cc_find_by_id(record_id);
11770    if (cc_record) {
11771       if (!cc_record->activated) {
11772          if (cc_record->port < 0) {
11773             /* The network did not tell us that call completion was available. */
11774             error_str = "No port number";
11775          } else if (cc_record->outstanding_message) {
11776             cc_record->outstanding_message = 0;
11777             error_str = misdn_no_response_from_network;
11778          } else if (cc_record->reject_code != FacReject_None) {
11779             error_str = misdn_to_str_reject_code(cc_record->reject_code);
11780          } else if (cc_record->error_code != FacError_None) {
11781             error_str = misdn_to_str_error_code(cc_record->error_code);
11782          } else if (cc_record->ptp) {
11783             if (cc_record->mode.ptp.bc) {
11784                error_str = "Call-completion already requested";
11785             } else {
11786                error_str = "Could not allocate call-completion signaling link";
11787             }
11788          } else {
11789             /* Should never happen. */
11790             error_str = "Unexpected error";
11791          }
11792 
11793          /* No need to keep the call completion record. */
11794          if (cc_record->ptp && cc_record->mode.ptp.bc) {
11795             /* Close the call-completion signaling link */
11796             bc = cc_record->mode.ptp.bc;
11797             bc->fac_out.Function = Fac_None;
11798             bc->out_cause = AST_CAUSE_NORMAL_CLEARING;
11799             misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
11800          }
11801          misdn_cc_delete(cc_record);
11802       } else {
11803          error_str = NULL;
11804       }
11805    } else {
11806       error_str = misdn_cc_record_not_found;
11807    }
11808    AST_LIST_UNLOCK(&misdn_cc_records_db);
11809    if (error_str) {
11810       ast_verb(1, "%s(%s) diagnostic '%s' on channel %s\n",
11811          misdn_command_name, subcommand->name, error_str, chan->name);
11812       pbx_builtin_setvar_helper(chan, MISDN_ERROR_MSG, error_str);
11813       pbx_builtin_setvar_helper(chan, MISDN_CC_STATUS, "ERROR");
11814    } else {
11815       pbx_builtin_setvar_helper(chan, MISDN_CC_STATUS, "ACTIVATED");
11816    }
11817 
11818    return 0;
11819 }
11820 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11821 
11822 #if defined(AST_MISDN_ENHANCEMENTS)
11823 /*!
11824  * \internal
11825  * \brief misdn_command(ccbs-request) subcommand handler
11826  *
11827  * \details
11828  * misdn_command(ccbs-request,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>)
11829  * Set the dialplan location to notify when User-B is free and User-A is free.
11830  *
11831  * \param chan Asterisk channel to operate upon.
11832  * \param subcommand Arguments for the subcommand
11833  *
11834  * \retval 0 on success.
11835  * \retval -1 on error.
11836  */
11837 static int misdn_command_ccbs_request(struct ast_channel *chan, struct misdn_command_args *subcommand)
11838 {
11839    static const struct misdn_cc_request request = {
11840       .ptmp = Fac_CCBSRequest,
11841       .ptp = Fac_CCBS_T_Request
11842    };
11843 
11844    return misdn_command_cc_request(chan, subcommand, &request);
11845 }
11846 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11847 
11848 #if defined(AST_MISDN_ENHANCEMENTS)
11849 /*!
11850  * \internal
11851  * \brief misdn_command(ccnr-request) subcommand handler
11852  *
11853  * \details
11854  * misdn_command(ccnr-request,${MISDN_CC_RECORD_ID},<notify-context>,<user-a-extension>,<priority>)
11855  * Set the dialplan location to notify when User-B is free and User-A is free.
11856  *
11857  * \param chan Asterisk channel to operate upon.
11858  * \param subcommand Arguments for the subcommand
11859  *
11860  * \retval 0 on success.
11861  * \retval -1 on error.
11862  */
11863 static int misdn_command_ccnr_request(struct ast_channel *chan, struct misdn_command_args *subcommand)
11864 {
11865    static const struct misdn_cc_request request = {
11866       .ptmp = Fac_CCNRRequest,
11867       .ptp = Fac_CCNR_T_Request
11868    };
11869 
11870    return misdn_command_cc_request(chan, subcommand, &request);
11871 }
11872 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11873 
11874 #if defined(AST_MISDN_ENHANCEMENTS)
11875 struct misdn_command_table {
11876    /*! \brief subcommand name */
11877    const char *name;
11878 
11879    /*! \brief subcommand handler */
11880    int (*func)(struct ast_channel *chan, struct misdn_command_args *subcommand);
11881 
11882    /*! \brief TRUE if the subcommand can only be executed on mISDN channels */
11883    int misdn_only;
11884 };
11885 static const struct misdn_command_table misdn_commands[] = {
11886 /* *INDENT-OFF* */
11887    /* subcommand-name  subcommand-handler              mISDN only */
11888    { "cc-initialize",  misdn_command_cc_initialize,    0 },
11889    { "cc-deactivate",  misdn_command_cc_deactivate,    0 },
11890    { "cc-a-busy",      misdn_command_cc_a_busy,        0 },
11891    { "cc-b-free",      misdn_command_cc_b_free,        0 },
11892    { "ccbs-request",   misdn_command_ccbs_request,     0 },
11893    { "ccnr-request",   misdn_command_ccnr_request,     0 },
11894 /* *INDENT-ON* */
11895 };
11896 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11897 
11898 #if defined(AST_MISDN_ENHANCEMENTS)
11899 /*!
11900  * \internal
11901  * \brief misdn_command() dialplan application.
11902  *
11903  * \param chan Asterisk channel to operate upon.
11904  * \param data Application options string.
11905  *
11906  * \retval 0 on success.
11907  * \retval -1 on error.
11908  */
11909 static int misdn_command_exec(struct ast_channel *chan, const char *data)
11910 {
11911    char *parse;
11912    unsigned index;
11913    struct misdn_command_args subcommand;
11914 
11915    if (ast_strlen_zero((char *) data)) {
11916       ast_log(LOG_ERROR, "%s requires arguments\n", misdn_command_name);
11917       return -1;
11918    }
11919 
11920    ast_log(LOG_DEBUG, "%s(%s)\n", misdn_command_name, (char *) data);
11921 
11922    parse = ast_strdupa(data);
11923    AST_STANDARD_APP_ARGS(subcommand, parse);
11924    if (!subcommand.argc || ast_strlen_zero(subcommand.name)) {
11925       ast_log(LOG_ERROR, "%s requires a subcommand\n", misdn_command_name);
11926       return -1;
11927    }
11928 
11929    for (index = 0; index < ARRAY_LEN(misdn_commands); ++index) {
11930       if (strcasecmp(misdn_commands[index].name, subcommand.name) == 0) {
11931          strcpy(subcommand.name, misdn_commands[index].name);
11932          if (misdn_commands[index].misdn_only
11933             && strcasecmp(chan->tech->type, misdn_type) != 0) {
11934             ast_log(LOG_WARNING,
11935                "%s(%s) only makes sense with %s channels!\n",
11936                misdn_command_name, subcommand.name, misdn_type);
11937             return -1;
11938          }
11939          return misdn_commands[index].func(chan, &subcommand);
11940       }
11941    }
11942 
11943    ast_log(LOG_WARNING, "%s(%s) subcommand is unknown\n", misdn_command_name,
11944       subcommand.name);
11945    return -1;
11946 }
11947 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
11948 
11949 static int misdn_facility_exec(struct ast_channel *chan, const char *data)
11950 {
11951    struct chan_list *ch = MISDN_ASTERISK_TECH_PVT(chan);
11952    char *parse;
11953    unsigned max_len;
11954 
11955    AST_DECLARE_APP_ARGS(args,
11956       AST_APP_ARG(facility_type);
11957       AST_APP_ARG(arg)[99];
11958    );
11959 
11960    chan_misdn_log(0, 0, "TYPE: %s\n", chan->tech->type);
11961 
11962    if (strcasecmp(chan->tech->type, misdn_type)) {
11963       ast_log(LOG_WARNING, "misdn_facility only makes sense with %s channels!\n", misdn_type);
11964       return -1;
11965    }
11966 
11967    if (ast_strlen_zero((char *) data)) {
11968       ast_log(LOG_WARNING, "misdn_facility requires arguments: facility_type[,<args>]\n");
11969       return -1;
11970    }
11971 
11972    parse = ast_strdupa(data);
11973    AST_STANDARD_APP_ARGS(args, parse);
11974 
11975    if (ast_strlen_zero(args.facility_type)) {
11976       ast_log(LOG_WARNING, "misdn_facility requires arguments: facility_type[,<args>]\n");
11977       return -1;
11978    }
11979 
11980    if (!strcasecmp(args.facility_type, "calldeflect")) {
11981       if (ast_strlen_zero(args.arg[0])) {
11982          ast_log(LOG_WARNING, "Facility: Call Deflection requires an argument: Number\n");
11983       }
11984 
11985 #if defined(AST_MISDN_ENHANCEMENTS)
11986       max_len = sizeof(ch->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Party.Number) - 1;
11987       if (max_len < strlen(args.arg[0])) {
11988          ast_log(LOG_WARNING,
11989             "Facility: Number argument too long (up to %u digits are allowed). Ignoring.\n",
11990             max_len);
11991          return 0;
11992       }
11993       ch->bc->fac_out.Function = Fac_CallDeflection;
11994       ch->bc->fac_out.u.CallDeflection.InvokeID = ++misdn_invoke_id;
11995       ch->bc->fac_out.u.CallDeflection.ComponentType = FacComponent_Invoke;
11996       ch->bc->fac_out.u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUserPresent = 1;
11997       ch->bc->fac_out.u.CallDeflection.Component.Invoke.PresentationAllowedToDivertedToUser = 0;
11998       ch->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Party.Type = 0;/* unknown */
11999       ch->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Party.LengthOfNumber = strlen(args.arg[0]);
12000       strcpy((char *) ch->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Party.Number, args.arg[0]);
12001       ch->bc->fac_out.u.CallDeflection.Component.Invoke.Deflection.Subaddress.Length = 0;
12002 
12003 #else /* !defined(AST_MISDN_ENHANCEMENTS) */
12004 
12005       max_len = sizeof(ch->bc->fac_out.u.CDeflection.DeflectedToNumber) - 1;
12006       if (max_len < strlen(args.arg[0])) {
12007          ast_log(LOG_WARNING,
12008             "Facility: Number argument too long (up to %u digits are allowed). Ignoring.\n",
12009             max_len);
12010          return 0;
12011       }
12012       ch->bc->fac_out.Function = Fac_CD;
12013       ch->bc->fac_out.u.CDeflection.PresentationAllowed = 0;
12014       //ch->bc->fac_out.u.CDeflection.DeflectedToSubaddress[0] = 0;
12015       strcpy((char *) ch->bc->fac_out.u.CDeflection.DeflectedToNumber, args.arg[0]);
12016 #endif   /* !defined(AST_MISDN_ENHANCEMENTS) */
12017 
12018       /* Send message */
12019       print_facility(&ch->bc->fac_out, ch->bc);
12020       misdn_lib_send_event(ch->bc, EVENT_FACILITY);
12021 #if defined(AST_MISDN_ENHANCEMENTS)
12022    } else if (!strcasecmp(args.facility_type, "callrerouteing")
12023       || !strcasecmp(args.facility_type, "callrerouting")) {
12024       if (ast_strlen_zero(args.arg[0])) {
12025          ast_log(LOG_WARNING, "Facility: Call rerouting requires an argument: Number\n");
12026       }
12027 
12028       max_len = sizeof(ch->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Party.Number) - 1;
12029       if (max_len < strlen(args.arg[0])) {
12030          ast_log(LOG_WARNING,
12031             "Facility: Number argument too long (up to %u digits are allowed). Ignoring.\n",
12032             max_len);
12033          return 0;
12034       }
12035       ch->bc->fac_out.Function = Fac_CallRerouteing;
12036       ch->bc->fac_out.u.CallRerouteing.InvokeID = ++misdn_invoke_id;
12037       ch->bc->fac_out.u.CallRerouteing.ComponentType = FacComponent_Invoke;
12038 
12039       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.ReroutingReason = 0;/* unknown */
12040       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.ReroutingCounter = 1;
12041 
12042       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Party.Type = 0;/* unknown */
12043       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Party.LengthOfNumber = strlen(args.arg[0]);
12044       strcpy((char *) ch->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Party.Number, args.arg[0]);
12045       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.CalledAddress.Subaddress.Length = 0;
12046 
12047       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.CallingPartySubaddress.Length = 0;
12048 
12049       /* 0x90 0x90 0xa3 3.1 kHz audio, circuit mode, 64kbit/sec, level1/a-Law */
12050       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Bc.Length = 3;
12051       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents[0] = 0x90;
12052       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents[1] = 0x90;
12053       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Bc.Contents[2] = 0xa3;
12054       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Hlc.Length = 0;
12055       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.Llc.Length = 0;
12056       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.Q931ie.UserInfo.Length = 0;
12057 
12058       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.LastRerouting.Type = 1;/* presentationRestricted */
12059       ch->bc->fac_out.u.CallRerouteing.Component.Invoke.SubscriptionOption = 0;/* no notification to caller */
12060 
12061       /* Send message */
12062       print_facility(&ch->bc->fac_out, ch->bc);
12063       misdn_lib_send_event(ch->bc, EVENT_FACILITY);
12064 #endif   /* defined(AST_MISDN_ENHANCEMENTS) */
12065    } else {
12066       chan_misdn_log(1, ch->bc->port, "Unknown Facility: %s\n", args.facility_type);
12067    }
12068 
12069    return 0;
12070 }
12071 
12072 static int misdn_check_l2l1(struct ast_channel *chan, const char *data)
12073 {
12074    char *parse;
12075    char group[BUFFERSIZE + 1];
12076    char *port_str;
12077    int port = 0;
12078    int timeout;
12079    int dowait = 0;
12080    int port_up;
12081 
12082    AST_DECLARE_APP_ARGS(args,
12083       AST_APP_ARG(grouppar);
12084       AST_APP_ARG(timeout);
12085    );
12086 
12087    if (ast_strlen_zero((char *) data)) {
12088       ast_log(LOG_WARNING, "misdn_check_l2l1 Requires arguments\n");
12089       return -1;
12090    }
12091 
12092    parse = ast_strdupa(data);
12093    AST_STANDARD_APP_ARGS(args, parse);
12094 
12095    if (args.argc != 2) {
12096       ast_log(LOG_WARNING, "Wrong argument count\n");
12097       return 0;
12098    }
12099 
12100    /*ast_log(LOG_NOTICE, "Arguments: group/port '%s' timeout '%s'\n", args.grouppar, args.timeout);*/
12101    timeout = atoi(args.timeout);
12102    port_str = args.grouppar;
12103 
12104    if (port_str[0] == 'g' && port_str[1] == ':') {
12105       /* We make a group call lets checkout which ports are in my group */
12106       port_str += 2;
12107       ast_copy_string(group, port_str, sizeof(group));
12108       chan_misdn_log(2, 0, "Checking Ports in group: %s\n", group);
12109 
12110       for (port = misdn_cfg_get_next_port(port);
12111          port > 0;
12112          port = misdn_cfg_get_next_port(port)) {
12113          char cfg_group[BUFFERSIZE + 1];
12114 
12115          chan_misdn_log(2, 0, "trying port %d\n", port);
12116 
12117          misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, sizeof(cfg_group));
12118 
12119          if (!strcasecmp(cfg_group, group)) {
12120             port_up = misdn_lib_port_up(port, 1);
12121             if (!port_up) {
12122                chan_misdn_log(2, 0, " --> port '%d'\n", port);
12123                misdn_lib_get_port_up(port);
12124                dowait = 1;
12125             }
12126          }
12127       }
12128    } else {
12129       port = atoi(port_str);
12130       chan_misdn_log(2, 0, "Checking Port: %d\n", port);
12131       port_up = misdn_lib_port_up(port, 1);
12132       if (!port_up) {
12133          misdn_lib_get_port_up(port);
12134          dowait = 1;
12135       }
12136    }
12137 
12138    if (dowait) {
12139       chan_misdn_log(2, 0, "Waiting for '%d' seconds\n", timeout);
12140       ast_safe_sleep(chan, timeout * 1000);
12141    }
12142 
12143    return 0;
12144 }
12145 
12146 static int misdn_set_opt_exec(struct ast_channel *chan, const char *data)
12147 {
12148    struct chan_list *ch = MISDN_ASTERISK_TECH_PVT(chan);
12149    char *tok;
12150    char *tokb;
12151    char *parse;
12152    int keyidx = 0;
12153    int rxgain = 0;
12154    int txgain = 0;
12155    int change_jitter = 0;
12156 
12157    if (strcasecmp(chan->tech->type, misdn_type)) {
12158       ast_log(LOG_WARNING, "misdn_set_opt makes sense only with %s channels!\n", misdn_type);
12159       return -1;
12160    }
12161 
12162    if (ast_strlen_zero((char *) data)) {
12163       ast_log(LOG_WARNING, "misdn_set_opt Requires arguments\n");
12164       return -1;
12165    }
12166 
12167    parse = ast_strdupa(data);
12168    for (tok = strtok_r(parse, ":", &tokb);
12169       tok;
12170       tok = strtok_r(NULL, ":", &tokb)) {
12171       int neglect = 0;
12172 
12173       if (tok[0] == '!') {
12174          neglect = 1;
12175          tok++;
12176       }
12177 
12178       switch(tok[0]) {
12179       case 'd' :
12180          ast_copy_string(ch->bc->display, ++tok, sizeof(ch->bc->display));
12181          chan_misdn_log(1, ch->bc->port, "SETOPT: Display:%s\n", ch->bc->display);
12182          break;
12183       case 'n':
12184          chan_misdn_log(1, ch->bc->port, "SETOPT: No DSP\n");
12185          ch->bc->nodsp = 1;
12186          break;
12187       case 'j':
12188          chan_misdn_log(1, ch->bc->port, "SETOPT: jitter\n");
12189          tok++;
12190          change_jitter = 1;
12191 
12192          switch (tok[0]) {
12193          case 'b':
12194             ch->jb_len = atoi(++tok);
12195             chan_misdn_log(1, ch->bc->port, " --> buffer_len:%d\n", ch->jb_len);
12196             break;
12197          case 't' :
12198             ch->jb_upper_threshold = atoi(++tok);
12199             chan_misdn_log(1, ch->bc->port, " --> upper_threshold:%d\n", ch->jb_upper_threshold);
12200             break;
12201          case 'n':
12202             ch->bc->nojitter = 1;
12203             chan_misdn_log(1, ch->bc->port, " --> nojitter\n");
12204             break;
12205          default:
12206             ch->jb_len = 4000;
12207             ch->jb_upper_threshold = 0;
12208             chan_misdn_log(1, ch->bc->port, " --> buffer_len:%d (default)\n", ch->jb_len);
12209             chan_misdn_log(1, ch->bc->port, " --> upper_threshold:%d (default)\n", ch->jb_upper_threshold);
12210             break;
12211          }
12212          break;
12213       case 'v':
12214          tok++;
12215 
12216          switch (tok[0]) {
12217          case 'r' :
12218             rxgain = atoi(++tok);
12219             if (rxgain < -8) {
12220                rxgain = -8;
12221             }
12222             if (rxgain > 8) {
12223                rxgain = 8;
12224             }
12225             ch->bc->rxgain = rxgain;
12226             chan_misdn_log(1, ch->bc->port, "SETOPT: Volume:%d\n", rxgain);
12227             break;
12228          case 't':
12229             txgain = atoi(++tok);
12230             if (txgain < -8) {
12231                txgain = -8;
12232             }
12233             if (txgain > 8) {
12234                txgain = 8;
12235             }
12236             ch->bc->txgain = txgain;
12237             chan_misdn_log(1, ch->bc->port, "SETOPT: Volume:%d\n", txgain);
12238             break;
12239          }
12240          break;
12241       case 'c':
12242          keyidx = atoi(++tok);
12243          {
12244             char keys[4096];
12245             char *key = NULL;
12246             char *tmp = keys;
12247             int i;
12248 
12249             misdn_cfg_get(0, MISDN_GEN_CRYPT_KEYS, keys, sizeof(keys));
12250 
12251             for (i = 0; i < keyidx; i++) {
12252                key = strsep(&tmp, ",");
12253             }
12254 
12255             if (key) {
12256                ast_copy_string(ch->bc->crypt_key, key, sizeof(ch->bc->crypt_key));
12257             }
12258 
12259             chan_misdn_log(0, ch->bc->port, "SETOPT: crypt with key:%s\n", ch->bc->crypt_key);
12260             break;
12261          }
12262       case 'e':
12263          chan_misdn_log(1, ch->bc->port, "SETOPT: EchoCancel\n");
12264 
12265          if (neglect) {
12266             chan_misdn_log(1, ch->bc->port, " --> disabled\n");
12267 #ifdef MISDN_1_2
12268             *ch->bc->pipeline = 0;
12269 #else
12270             ch->bc->ec_enable = 0;
12271 #endif
12272          } else {
12273 #ifdef MISDN_1_2
12274             update_pipeline_config(ch->bc);
12275 #else
12276             ch->bc->ec_enable = 1;
12277             ch->bc->orig = ch->originator;
12278             tok++;
12279             if (*tok) {
12280                ch->bc->ec_deftaps = atoi(tok);
12281             }
12282 #endif
12283          }
12284          break;
12285       case 'h':
12286          chan_misdn_log(1, ch->bc->port, "SETOPT: Digital\n");
12287 
12288          if (strlen(tok) > 1 && tok[1] == '1') {
12289             chan_misdn_log(1, ch->bc->port, "SETOPT: HDLC \n");
12290             if (!ch->bc->hdlc) {
12291                ch->bc->hdlc = 1;
12292             }
12293          }
12294          ch->bc->capability = INFO_CAPABILITY_DIGITAL_UNRESTRICTED;
12295          break;
12296       case 's':
12297          chan_misdn_log(1, ch->bc->port, "SETOPT: Send DTMF\n");
12298          ch->bc->send_dtmf = 1;
12299          break;
12300       case 'f':
12301          chan_misdn_log(1, ch->bc->port, "SETOPT: Faxdetect\n");
12302          ch->faxdetect = 1;
12303          misdn_cfg_get(ch->bc->port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
12304          break;
12305       case 'a':
12306          chan_misdn_log(1, ch->bc->port, "SETOPT: AST_DSP (for DTMF)\n");
12307          ch->ast_dsp = 1;
12308          break;
12309       case 'p':
12310          chan_misdn_log(1, ch->bc->port, "SETOPT: callerpres: %s\n", &tok[1]);
12311          /* CRICH: callingpres!!! */
12312          if (strstr(tok, "allowed")) {
12313             ch->bc->presentation = 0;
12314             ch->bc->set_presentation = 1;
12315          } else if (strstr(tok, "restricted")) {
12316             ch->bc->presentation = 1;
12317             ch->bc->set_presentation = 1;
12318          } else if (strstr(tok, "not_screened")) {
12319             chan_misdn_log(0, ch->bc->port, "SETOPT: callerpres: not_screened is deprecated\n");
12320             ch->bc->presentation = 1;
12321             ch->bc->set_presentation = 1;
12322          }
12323          break;
12324       case 'i' :
12325          chan_misdn_log(1, ch->bc->port, "Ignoring dtmf tones, just use them inband\n");
12326          ch->ignore_dtmf = 1;
12327          break;
12328       default:
12329          break;
12330       }
12331    }
12332 
12333    if (change_jitter) {
12334       config_jitterbuffer(ch);
12335    }
12336 
12337    if (ch->faxdetect || ch->ast_dsp) {
12338       if (!ch->dsp) {
12339          ch->dsp = ast_dsp_new();
12340       }
12341       if (ch->dsp) {
12342          ast_dsp_set_features(ch->dsp, DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_FAX_DETECT);
12343       }
12344    }
12345 
12346    if (ch->ast_dsp) {
12347       chan_misdn_log(1, ch->bc->port, "SETOPT: with AST_DSP we deactivate mISDN_dsp\n");
12348       ch->bc->nodsp = 1;
12349    }
12350 
12351    return 0;
12352 }
12353 
12354 
12355 int chan_misdn_jb_empty(struct misdn_bchannel *bc, char *buf, int len)
12356 {
12357    struct chan_list *ch = find_chan_by_bc(bc);
12358 
12359    if (ch && ch->jb) {
12360       return misdn_jb_empty(ch->jb, buf, len);
12361    }
12362 
12363    return -1;
12364 }
12365 
12366 
12367 
12368 /*******************************************************/
12369 /***************** JITTERBUFFER ************************/
12370 /*******************************************************/
12371 
12372 
12373 /* allocates the jb-structure and initialize the elements*/
12374 struct misdn_jb *misdn_jb_init(int size, int upper_threshold)
12375 {
12376    int i;
12377    struct misdn_jb *jb;
12378 
12379    jb = ast_malloc(sizeof(*jb));
12380    if (!jb) {
12381        chan_misdn_log(-1, 0, "No free Mem for jb\n");
12382        return NULL;
12383    }
12384    jb->size = size;
12385    jb->upper_threshold = upper_threshold;
12386    jb->wp = 0;
12387    jb->rp = 0;
12388    jb->state_full = 0;
12389    jb->state_empty = 0;
12390    jb->bytes_wrote = 0;
12391    jb->samples = ast_malloc(size * sizeof(char));
12392    if (!jb->samples) {
12393       ast_free(jb);
12394       chan_misdn_log(-1, 0, "No free Mem for jb->samples\n");
12395       return NULL;
12396    }
12397 
12398    jb->ok = ast_malloc(size * sizeof(char));
12399    if (!jb->ok) {
12400       ast_free(jb->samples);
12401       ast_free(jb);
12402       chan_misdn_log(-1, 0, "No free Mem for jb->ok\n");
12403       return NULL;
12404    }
12405 
12406    for (i = 0; i < size; i++) {
12407       jb->ok[i] = 0;
12408    }
12409 
12410    ast_mutex_init(&jb->mutexjb);
12411 
12412    return jb;
12413 }
12414 
12415 /* frees the data and destroys the given jitterbuffer struct */
12416 void misdn_jb_destroy(struct misdn_jb *jb)
12417 {
12418    ast_mutex_destroy(&jb->mutexjb);
12419 
12420    ast_free(jb->ok);
12421    ast_free(jb->samples);
12422    ast_free(jb);
12423 }
12424 
12425 /* fills the jitterbuffer with len data returns < 0 if there was an
12426    error (buffer overflow). */
12427 int misdn_jb_fill(struct misdn_jb *jb, const char *data, int len)
12428 {
12429    int i;
12430    int j;
12431    int rp;
12432    int wp;
12433 
12434    if (!jb || ! data) {
12435       return 0;
12436    }
12437 
12438    ast_mutex_lock(&jb->mutexjb);
12439 
12440    wp = jb->wp;
12441    rp = jb->rp;
12442 
12443    for (i = 0; i < len; i++) {
12444       jb->samples[wp] = data[i];
12445       jb->ok[wp] = 1;
12446       wp = (wp != jb->size - 1) ? wp + 1 : 0;
12447 
12448       if (wp == jb->rp) {
12449          jb->state_full = 1;
12450       }
12451    }
12452 
12453    if (wp >= rp) {
12454       jb->state_buffer = wp - rp;
12455    } else {
12456       jb->state_buffer = jb->size - rp + wp;
12457    }
12458    chan_misdn_log(9, 0, "misdn_jb_fill: written:%d | Buffer status:%d p:%p\n", len, jb->state_buffer, jb);
12459 
12460    if (jb->state_full) {
12461       jb->wp = wp;
12462 
12463       rp = wp;
12464       for (j = 0; j < jb->upper_threshold; j++) {
12465          rp = (rp != 0) ? rp - 1 : jb->size - 1;
12466       }
12467       jb->rp = rp;
12468       jb->state_full = 0;
12469       jb->state_empty = 1;
12470 
12471       ast_mutex_unlock(&jb->mutexjb);
12472 
12473       return -1;
12474    }
12475 
12476    if (!jb->state_empty) {
12477       jb->bytes_wrote += len;
12478       if (jb->bytes_wrote >= jb->upper_threshold) {
12479          jb->state_empty = 1;
12480          jb->bytes_wrote = 0;
12481       }
12482    }
12483    jb->wp = wp;
12484 
12485    ast_mutex_unlock(&jb->mutexjb);
12486 
12487    return 0;
12488 }
12489 
12490 /* gets len bytes out of the jitterbuffer if available, else only the
12491 available data is returned and the return value indicates the number
12492 of data. */
12493 int misdn_jb_empty(struct misdn_jb *jb, char *data, int len)
12494 {
12495    int i;
12496    int wp;
12497    int rp;
12498    int read = 0;
12499 
12500    ast_mutex_lock(&jb->mutexjb);
12501 
12502    rp = jb->rp;
12503    wp = jb->wp;
12504 
12505    if (jb->state_empty) {
12506       for (i = 0; i < len; i++) {
12507          if (wp == rp) {
12508             jb->rp = rp;
12509             jb->state_empty = 0;
12510 
12511             ast_mutex_unlock(&jb->mutexjb);
12512 
12513             return read;
12514          } else {
12515             if (jb->ok[rp] == 1) {
12516                data[i] = jb->samples[rp];
12517                jb->ok[rp] = 0;
12518                rp = (rp != jb->size - 1) ? rp + 1 : 0;
12519                read += 1;
12520             }
12521          }
12522       }
12523 
12524       if (wp >= rp) {
12525          jb->state_buffer = wp - rp;
12526       } else {
12527          jb->state_buffer = jb->size - rp + wp;
12528       }
12529       chan_misdn_log(9, 0, "misdn_jb_empty: read:%d | Buffer status:%d p:%p\n", len, jb->state_buffer, jb);
12530 
12531       jb->rp = rp;
12532    } else {
12533       chan_misdn_log(9, 0, "misdn_jb_empty: Wait...requested:%d p:%p\n", len, jb);
12534    }
12535 
12536    ast_mutex_unlock(&jb->mutexjb);
12537 
12538    return read;
12539 }
12540 
12541 /*******************************************************/
12542 /*************** JITTERBUFFER  END *********************/
12543 /*******************************************************/
12544 
12545 static void chan_misdn_log(int level, int port, char *tmpl, ...)
12546 {
12547    va_list ap;
12548    char buf[1024];
12549    char port_buf[8];
12550 
12551    if (!(0 <= port && port <= max_ports)) {
12552       ast_log(LOG_WARNING, "cb_log called with out-of-range port number! (%d)\n", port);
12553       port = 0;
12554       level = -1;
12555    } else if (!(level == -1
12556       || (misdn_debug_only[port]
12557          ? (level == 1 && misdn_debug[port]) || level == misdn_debug[port]
12558          : level <= misdn_debug[port])
12559       || (level <= misdn_debug[0] && !ast_strlen_zero(global_tracefile)))) {
12560       /*
12561        * We are not going to print anything so lets not
12562        * go to all the work of generating a string.
12563        */
12564       return;
12565    }
12566 
12567    snprintf(port_buf, sizeof(port_buf), "P[%2d] ", port);
12568    va_start(ap, tmpl);
12569    vsnprintf(buf, sizeof(buf), tmpl, ap);
12570    va_end(ap);
12571 
12572    if (level == -1) {
12573       ast_log(LOG_WARNING, "%s", buf);
12574    } else if (misdn_debug_only[port]
12575       ? (level == 1 && misdn_debug[port]) || level == misdn_debug[port]
12576       : level <= misdn_debug[port]) {
12577       ast_console_puts(port_buf);
12578       ast_console_puts(buf);
12579    }
12580 
12581    if (level <= misdn_debug[0] && !ast_strlen_zero(global_tracefile)) {
12582       char ctimebuf[30];
12583       time_t tm;
12584       char *tmp;
12585       char *p;
12586       FILE *fp;
12587 
12588       fp = fopen(global_tracefile, "a+");
12589       if (!fp) {
12590          ast_console_puts("Error opening Tracefile: [ ");
12591          ast_console_puts(global_tracefile);
12592          ast_console_puts(" ] ");
12593 
12594          ast_console_puts(strerror(errno));
12595          ast_console_puts("\n");
12596          return;
12597       }
12598 
12599       tm = time(NULL);
12600       tmp = ctime_r(&tm, ctimebuf);
12601       p = strchr(tmp, '\n');
12602       if (p) {
12603          *p = ':';
12604       }
12605       fputs(tmp, fp);
12606       fputs(" ", fp);
12607       fputs(port_buf, fp);
12608       fputs(" ", fp);
12609       fputs(buf, fp);
12610 
12611       fclose(fp);
12612    }
12613 }
12614 
12615 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Channel driver for mISDN Support (BRI/PRI)",
12616    .load = load_module,
12617    .unload = unload_module,
12618    .reload = reload,
12619    .load_pri = AST_MODPRI_CHANNEL_DRIVER,
12620 );

Generated on Sat Mar 26 11:07:11 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9