Thu Apr 3 08:20:24 2014

Asterisk developer's documentation


sig_pri.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2009, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.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 /*! \file
00020  *
00021  * \brief PRI signaling module
00022  *
00023  * \author Matthew Fredrickson <creslin@digium.com>
00024  */
00025 
00026 /*** MODULEINFO
00027    <support_level>core</support_level>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 #ifdef HAVE_PRI
00033 
00034 #include <errno.h>
00035 #include <ctype.h>
00036 #include <signal.h>
00037 
00038 #include "asterisk/utils.h"
00039 #include "asterisk/options.h"
00040 #include "asterisk/pbx.h"
00041 #include "asterisk/app.h"
00042 #include "asterisk/file.h"
00043 #include "asterisk/callerid.h"
00044 #include "asterisk/say.h"
00045 #include "asterisk/manager.h"
00046 #include "asterisk/astdb.h"
00047 #include "asterisk/causes.h"
00048 #include "asterisk/musiconhold.h"
00049 #include "asterisk/cli.h"
00050 #include "asterisk/transcap.h"
00051 #include "asterisk/features.h"
00052 #include "asterisk/aoc.h"
00053 
00054 #include "sig_pri.h"
00055 #ifndef PRI_EVENT_FACILITY
00056 #error "Upgrade your libpri"
00057 #endif
00058 
00059 /* define this to send PRI user-user information elements */
00060 #undef SUPPORT_USERUSER
00061 
00062 /*!
00063  * Define to make always pick a channel if allowed.  Useful for
00064  * testing channel shifting.
00065  */
00066 //#define ALWAYS_PICK_CHANNEL 1
00067 
00068 /*!
00069  * Define to force a RESTART on a channel that returns a cause
00070  * code of PRI_CAUSE_REQUESTED_CHAN_UNAVAIL(44).  If the cause
00071  * is because of a stuck channel on the peer and the channel is
00072  * always the next channel we pick for an outgoing call then
00073  * this can help.
00074  */
00075 #define FORCE_RESTART_UNAVAIL_CHANS    1
00076 
00077 #if defined(HAVE_PRI_CCSS)
00078 struct sig_pri_cc_agent_prv {
00079    /*! Asterisk span D channel control structure. */
00080    struct sig_pri_span *pri;
00081    /*! CC id value to use with libpri. -1 if invalid. */
00082    long cc_id;
00083    /*! TRUE if CC has been requested and we are waiting for the response. */
00084    unsigned char cc_request_response_pending;
00085 };
00086 
00087 struct sig_pri_cc_monitor_instance {
00088    /*! \brief Asterisk span D channel control structure. */
00089    struct sig_pri_span *pri;
00090    /*! CC id value to use with libpri. (-1 if already canceled). */
00091    long cc_id;
00092    /*! CC core id value. */
00093    int core_id;
00094    /*! Device name(Channel name less sequence number) */
00095    char name[1];
00096 };
00097 
00098 /*! Upper level agent/monitor type name. */
00099 static const char *sig_pri_cc_type_name;
00100 /*! Container of sig_pri monitor instances. */
00101 static struct ao2_container *sig_pri_cc_monitors;
00102 #endif   /* defined(HAVE_PRI_CCSS) */
00103 
00104 static int pri_matchdigittimeout = 3000;
00105 
00106 static int pri_gendigittimeout = 8000;
00107 
00108 #define DCHAN_NOTINALARM  (1 << 0)
00109 #define DCHAN_UP          (1 << 1)
00110 
00111 /* Defines to help decode the encoded event channel id. */
00112 #define PRI_CHANNEL(p)  ((p) & 0xff)
00113 #define PRI_SPAN(p)     (((p) >> 8) & 0xff)
00114 #define PRI_EXPLICIT (1 << 16)
00115 #define PRI_CIS_CALL (1 << 17)   /* Call is using the D channel only. */
00116 #define PRI_HELD_CALL   (1 << 18)
00117 
00118 
00119 #define DCHAN_AVAILABLE (DCHAN_NOTINALARM | DCHAN_UP)
00120 
00121 static int pri_active_dchan_index(struct sig_pri_span *pri);
00122 
00123 static const char *sig_pri_call_level2str(enum sig_pri_call_level level)
00124 {
00125    switch (level) {
00126    case SIG_PRI_CALL_LEVEL_IDLE:
00127       return "Idle";
00128    case SIG_PRI_CALL_LEVEL_SETUP:
00129       return "Setup";
00130    case SIG_PRI_CALL_LEVEL_OVERLAP:
00131       return "Overlap";
00132    case SIG_PRI_CALL_LEVEL_PROCEEDING:
00133       return "Proceeding";
00134    case SIG_PRI_CALL_LEVEL_ALERTING:
00135       return "Alerting";
00136    case SIG_PRI_CALL_LEVEL_DEFER_DIAL:
00137       return "DeferDial";
00138    case SIG_PRI_CALL_LEVEL_CONNECT:
00139       return "Connect";
00140    }
00141    return "Unknown";
00142 }
00143 
00144 static inline void pri_rel(struct sig_pri_span *pri)
00145 {
00146    ast_mutex_unlock(&pri->lock);
00147 }
00148 
00149 static unsigned int PVT_TO_CHANNEL(struct sig_pri_chan *p)
00150 {
00151    int res = (((p)->prioffset) | ((p)->logicalspan << 8) | (p->mastertrunkgroup ? PRI_EXPLICIT : 0));
00152    ast_debug(5, "prioffset: %d mastertrunkgroup: %d logicalspan: %d result: %d\n",
00153       p->prioffset, p->mastertrunkgroup, p->logicalspan, res);
00154 
00155    return res;
00156 }
00157 
00158 static void sig_pri_handle_dchan_exception(struct sig_pri_span *pri, int index)
00159 {
00160    if (pri->calls->handle_dchan_exception)
00161       pri->calls->handle_dchan_exception(pri, index);
00162 }
00163 
00164 static void sig_pri_set_dialing(struct sig_pri_chan *p, int is_dialing)
00165 {
00166    if (p->calls->set_dialing) {
00167       p->calls->set_dialing(p->chan_pvt, is_dialing);
00168    }
00169 }
00170 
00171 static void sig_pri_set_digital(struct sig_pri_chan *p, int is_digital)
00172 {
00173    p->digital = is_digital;
00174    if (p->calls->set_digital) {
00175       p->calls->set_digital(p->chan_pvt, is_digital);
00176    }
00177 }
00178 
00179 static void sig_pri_set_outgoing(struct sig_pri_chan *p, int is_outgoing)
00180 {
00181    p->outgoing = is_outgoing;
00182    if (p->calls->set_outgoing) {
00183       p->calls->set_outgoing(p->chan_pvt, is_outgoing);
00184    }
00185 }
00186 
00187 void sig_pri_set_alarm(struct sig_pri_chan *p, int in_alarm)
00188 {
00189    if (sig_pri_is_alarm_ignored(p->pri)) {
00190       /* Always set not in alarm */
00191       in_alarm = 0;
00192    }
00193 
00194    /*
00195     * Clear the channel restart state when the channel alarm
00196     * changes to prevent the state from getting stuck when the link
00197     * goes down.
00198     */
00199    p->resetting = SIG_PRI_RESET_IDLE;
00200 
00201    p->inalarm = in_alarm;
00202    if (p->calls->set_alarm) {
00203       p->calls->set_alarm(p->chan_pvt, in_alarm);
00204    }
00205 }
00206 
00207 static const char *sig_pri_get_orig_dialstring(struct sig_pri_chan *p)
00208 {
00209    if (p->calls->get_orig_dialstring) {
00210       return p->calls->get_orig_dialstring(p->chan_pvt);
00211    }
00212    ast_log(LOG_ERROR, "get_orig_dialstring callback not defined\n");
00213    return "";
00214 }
00215 
00216 #if defined(HAVE_PRI_CCSS)
00217 static void sig_pri_make_cc_dialstring(struct sig_pri_chan *p, char *buf, size_t buf_size)
00218 {
00219    if (p->calls->make_cc_dialstring) {
00220       p->calls->make_cc_dialstring(p->chan_pvt, buf, buf_size);
00221    } else {
00222       ast_log(LOG_ERROR, "make_cc_dialstring callback not defined\n");
00223       buf[0] = '\0';
00224    }
00225 }
00226 #endif   /* defined(HAVE_PRI_CCSS) */
00227 
00228 static void sig_pri_dial_digits(struct sig_pri_chan *p, const char *dial_string)
00229 {
00230    if (p->calls->dial_digits) {
00231       p->calls->dial_digits(p->chan_pvt, dial_string);
00232    }
00233 }
00234 
00235 /*!
00236  * \internal
00237  * \brief Reevaluate the PRI span device state.
00238  * \since 1.8
00239  *
00240  * \param pri PRI span control structure.
00241  *
00242  * \return Nothing
00243  *
00244  * \note Assumes the pri->lock is already obtained.
00245  */
00246 static void sig_pri_span_devstate_changed(struct sig_pri_span *pri)
00247 {
00248    if (pri->calls->update_span_devstate) {
00249       pri->calls->update_span_devstate(pri);
00250    }
00251 }
00252 
00253 /*!
00254  * \internal
00255  * \brief Set the caller id information in the parent module.
00256  * \since 1.8
00257  *
00258  * \param p sig_pri channel structure.
00259  *
00260  * \return Nothing
00261  */
00262 static void sig_pri_set_caller_id(struct sig_pri_chan *p)
00263 {
00264    struct ast_party_caller caller;
00265 
00266    if (p->calls->set_callerid) {
00267       ast_party_caller_init(&caller);
00268 
00269       caller.id.name.str = p->cid_name;
00270       caller.id.name.presentation = p->callingpres;
00271       caller.id.name.valid = 1;
00272 
00273       caller.id.number.str = p->cid_num;
00274       caller.id.number.plan = p->cid_ton;
00275       caller.id.number.presentation = p->callingpres;
00276       caller.id.number.valid = 1;
00277 
00278       if (!ast_strlen_zero(p->cid_subaddr)) {
00279          caller.id.subaddress.valid = 1;
00280          //caller.id.subaddress.type = 0;/* nsap */
00281          //caller.id.subaddress.odd_even_indicator = 0;
00282          caller.id.subaddress.str = p->cid_subaddr;
00283       }
00284       caller.id.tag = p->user_tag;
00285 
00286       caller.ani.number.str = p->cid_ani;
00287       //caller.ani.number.plan = p->xxx;
00288       //caller.ani.number.presentation = p->xxx;
00289       caller.ani.number.valid = 1;
00290 
00291       caller.ani2 = p->cid_ani2;
00292       p->calls->set_callerid(p->chan_pvt, &caller);
00293    }
00294 }
00295 
00296 /*!
00297  * \internal
00298  * \brief Set the Dialed Number Identifier.
00299  * \since 1.8
00300  *
00301  * \param p sig_pri channel structure.
00302  * \param dnid Dialed Number Identifier string.
00303  *
00304  * \return Nothing
00305  */
00306 static void sig_pri_set_dnid(struct sig_pri_chan *p, const char *dnid)
00307 {
00308    if (p->calls->set_dnid) {
00309       p->calls->set_dnid(p->chan_pvt, dnid);
00310    }
00311 }
00312 
00313 /*!
00314  * \internal
00315  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
00316  * \since 1.8
00317  *
00318  * \param p sig_pri channel structure.
00319  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
00320  *
00321  * \return Nothing
00322  */
00323 static void sig_pri_set_rdnis(struct sig_pri_chan *p, const char *rdnis)
00324 {
00325    if (p->calls->set_rdnis) {
00326       p->calls->set_rdnis(p->chan_pvt, rdnis);
00327    }
00328 }
00329 
00330 static void sig_pri_unlock_private(struct sig_pri_chan *p)
00331 {
00332    if (p->calls->unlock_private)
00333       p->calls->unlock_private(p->chan_pvt);
00334 }
00335 
00336 static void sig_pri_lock_private(struct sig_pri_chan *p)
00337 {
00338    if (p->calls->lock_private)
00339       p->calls->lock_private(p->chan_pvt);
00340 }
00341 
00342 static inline int pri_grab(struct sig_pri_chan *p, struct sig_pri_span *pri)
00343 {
00344    /* Grab the lock first */
00345    while (ast_mutex_trylock(&pri->lock)) {
00346       /* Avoid deadlock */
00347       sig_pri_unlock_private(p);
00348       sched_yield();
00349       sig_pri_lock_private(p);
00350    }
00351    /* Then break the poll */
00352    if (pri->master != AST_PTHREADT_NULL) {
00353       pthread_kill(pri->master, SIGURG);
00354    }
00355    return 0;
00356 }
00357 
00358 /*!
00359  * \internal
00360  * \brief Convert PRI redirecting reason to asterisk version.
00361  * \since 1.8
00362  *
00363  * \param pri_reason PRI redirecting reason.
00364  *
00365  * \return Equivalent asterisk redirecting reason value.
00366  */
00367 static enum AST_REDIRECTING_REASON pri_to_ast_reason(int pri_reason)
00368 {
00369    enum AST_REDIRECTING_REASON ast_reason;
00370 
00371    switch (pri_reason) {
00372    case PRI_REDIR_FORWARD_ON_BUSY:
00373       ast_reason = AST_REDIRECTING_REASON_USER_BUSY;
00374       break;
00375    case PRI_REDIR_FORWARD_ON_NO_REPLY:
00376       ast_reason = AST_REDIRECTING_REASON_NO_ANSWER;
00377       break;
00378    case PRI_REDIR_DEFLECTION:
00379       ast_reason = AST_REDIRECTING_REASON_DEFLECTION;
00380       break;
00381    case PRI_REDIR_UNCONDITIONAL:
00382       ast_reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
00383       break;
00384    case PRI_REDIR_UNKNOWN:
00385    default:
00386       ast_reason = AST_REDIRECTING_REASON_UNKNOWN;
00387       break;
00388    }
00389 
00390    return ast_reason;
00391 }
00392 
00393 /*!
00394  * \internal
00395  * \brief Convert asterisk redirecting reason to PRI version.
00396  * \since 1.8
00397  *
00398  * \param ast_reason Asterisk redirecting reason.
00399  *
00400  * \return Equivalent PRI redirecting reason value.
00401  */
00402 static int ast_to_pri_reason(enum AST_REDIRECTING_REASON ast_reason)
00403 {
00404    int pri_reason;
00405 
00406    switch (ast_reason) {
00407    case AST_REDIRECTING_REASON_USER_BUSY:
00408       pri_reason = PRI_REDIR_FORWARD_ON_BUSY;
00409       break;
00410    case AST_REDIRECTING_REASON_NO_ANSWER:
00411       pri_reason = PRI_REDIR_FORWARD_ON_NO_REPLY;
00412       break;
00413    case AST_REDIRECTING_REASON_UNCONDITIONAL:
00414       pri_reason = PRI_REDIR_UNCONDITIONAL;
00415       break;
00416    case AST_REDIRECTING_REASON_DEFLECTION:
00417       pri_reason = PRI_REDIR_DEFLECTION;
00418       break;
00419    case AST_REDIRECTING_REASON_UNKNOWN:
00420    default:
00421       pri_reason = PRI_REDIR_UNKNOWN;
00422       break;
00423    }
00424 
00425    return pri_reason;
00426 }
00427 
00428 /*!
00429  * \internal
00430  * \brief Convert PRI number presentation to asterisk version.
00431  * \since 1.8
00432  *
00433  * \param pri_presentation PRI number presentation.
00434  *
00435  * \return Equivalent asterisk number presentation value.
00436  */
00437 static int pri_to_ast_presentation(int pri_presentation)
00438 {
00439    int ast_presentation;
00440 
00441    switch (pri_presentation) {
00442    case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED:
00443       ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_UNSCREENED;
00444       break;
00445    case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
00446       ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_PASSED_SCREEN;
00447       break;
00448    case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
00449       ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_FAILED_SCREEN;
00450       break;
00451    case PRI_PRES_ALLOWED | PRI_PRES_NETWORK_NUMBER:
00452       ast_presentation = AST_PRES_ALLOWED | AST_PRES_NETWORK_NUMBER;
00453       break;
00454 
00455    case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED:
00456       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED;
00457       break;
00458    case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
00459       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_PASSED_SCREEN;
00460       break;
00461    case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
00462       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_FAILED_SCREEN;
00463       break;
00464    case PRI_PRES_RESTRICTED | PRI_PRES_NETWORK_NUMBER:
00465       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_NETWORK_NUMBER;
00466       break;
00467 
00468    case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_UNSCREENED:
00469    case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
00470    case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
00471    case PRI_PRES_UNAVAILABLE | PRI_PRES_NETWORK_NUMBER:
00472       ast_presentation = AST_PRES_NUMBER_NOT_AVAILABLE;
00473       break;
00474 
00475    default:
00476       ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED;
00477       break;
00478    }
00479 
00480    return ast_presentation;
00481 }
00482 
00483 /*!
00484  * \internal
00485  * \brief Convert asterisk number presentation to PRI version.
00486  * \since 1.8
00487  *
00488  * \param ast_presentation Asterisk number presentation.
00489  *
00490  * \return Equivalent PRI number presentation value.
00491  */
00492 static int ast_to_pri_presentation(int ast_presentation)
00493 {
00494    int pri_presentation;
00495 
00496    switch (ast_presentation) {
00497    case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_UNSCREENED:
00498       pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED;
00499       break;
00500    case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_PASSED_SCREEN:
00501       pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_PASSED_SCREEN;
00502       break;
00503    case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_FAILED_SCREEN:
00504       pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_FAILED_SCREEN;
00505       break;
00506    case AST_PRES_ALLOWED | AST_PRES_NETWORK_NUMBER:
00507       pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_NETWORK_NUMBER;
00508       break;
00509 
00510    case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED:
00511       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
00512       break;
00513    case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_PASSED_SCREEN:
00514       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_PASSED_SCREEN;
00515       break;
00516    case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_FAILED_SCREEN:
00517       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_FAILED_SCREEN;
00518       break;
00519    case AST_PRES_RESTRICTED | AST_PRES_NETWORK_NUMBER:
00520       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_NETWORK_NUMBER;
00521       break;
00522 
00523    case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_UNSCREENED:
00524    case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_PASSED_SCREEN:
00525    case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_FAILED_SCREEN:
00526    case AST_PRES_UNAVAILABLE | AST_PRES_NETWORK_NUMBER:
00527       pri_presentation = PRES_NUMBER_NOT_AVAILABLE;
00528       break;
00529 
00530    default:
00531       pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
00532       break;
00533    }
00534 
00535    return pri_presentation;
00536 }
00537 
00538 /*!
00539  * \internal
00540  * \brief Convert PRI name char_set to asterisk version.
00541  * \since 1.8
00542  *
00543  * \param pri_char_set PRI name char_set.
00544  *
00545  * \return Equivalent asterisk name char_set value.
00546  */
00547 static enum AST_PARTY_CHAR_SET pri_to_ast_char_set(int pri_char_set)
00548 {
00549    enum AST_PARTY_CHAR_SET ast_char_set;
00550 
00551    switch (pri_char_set) {
00552    default:
00553    case PRI_CHAR_SET_UNKNOWN:
00554       ast_char_set = AST_PARTY_CHAR_SET_UNKNOWN;
00555       break;
00556    case PRI_CHAR_SET_ISO8859_1:
00557       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_1;
00558       break;
00559    case PRI_CHAR_SET_WITHDRAWN:
00560       ast_char_set = AST_PARTY_CHAR_SET_WITHDRAWN;
00561       break;
00562    case PRI_CHAR_SET_ISO8859_2:
00563       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_2;
00564       break;
00565    case PRI_CHAR_SET_ISO8859_3:
00566       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_3;
00567       break;
00568    case PRI_CHAR_SET_ISO8859_4:
00569       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_4;
00570       break;
00571    case PRI_CHAR_SET_ISO8859_5:
00572       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_5;
00573       break;
00574    case PRI_CHAR_SET_ISO8859_7:
00575       ast_char_set = AST_PARTY_CHAR_SET_ISO8859_7;
00576       break;
00577    case PRI_CHAR_SET_ISO10646_BMPSTRING:
00578       ast_char_set = AST_PARTY_CHAR_SET_ISO10646_BMPSTRING;
00579       break;
00580    case PRI_CHAR_SET_ISO10646_UTF_8STRING:
00581       ast_char_set = AST_PARTY_CHAR_SET_ISO10646_UTF_8STRING;
00582       break;
00583    }
00584 
00585    return ast_char_set;
00586 }
00587 
00588 /*!
00589  * \internal
00590  * \brief Convert asterisk name char_set to PRI version.
00591  * \since 1.8
00592  *
00593  * \param ast_char_set Asterisk name char_set.
00594  *
00595  * \return Equivalent PRI name char_set value.
00596  */
00597 static int ast_to_pri_char_set(enum AST_PARTY_CHAR_SET ast_char_set)
00598 {
00599    int pri_char_set;
00600 
00601    switch (ast_char_set) {
00602    default:
00603    case AST_PARTY_CHAR_SET_UNKNOWN:
00604       pri_char_set = PRI_CHAR_SET_UNKNOWN;
00605       break;
00606    case AST_PARTY_CHAR_SET_ISO8859_1:
00607       pri_char_set = PRI_CHAR_SET_ISO8859_1;
00608       break;
00609    case AST_PARTY_CHAR_SET_WITHDRAWN:
00610       pri_char_set = PRI_CHAR_SET_WITHDRAWN;
00611       break;
00612    case AST_PARTY_CHAR_SET_ISO8859_2:
00613       pri_char_set = PRI_CHAR_SET_ISO8859_2;
00614       break;
00615    case AST_PARTY_CHAR_SET_ISO8859_3:
00616       pri_char_set = PRI_CHAR_SET_ISO8859_3;
00617       break;
00618    case AST_PARTY_CHAR_SET_ISO8859_4:
00619       pri_char_set = PRI_CHAR_SET_ISO8859_4;
00620       break;
00621    case AST_PARTY_CHAR_SET_ISO8859_5:
00622       pri_char_set = PRI_CHAR_SET_ISO8859_5;
00623       break;
00624    case AST_PARTY_CHAR_SET_ISO8859_7:
00625       pri_char_set = PRI_CHAR_SET_ISO8859_7;
00626       break;
00627    case AST_PARTY_CHAR_SET_ISO10646_BMPSTRING:
00628       pri_char_set = PRI_CHAR_SET_ISO10646_BMPSTRING;
00629       break;
00630    case AST_PARTY_CHAR_SET_ISO10646_UTF_8STRING:
00631       pri_char_set = PRI_CHAR_SET_ISO10646_UTF_8STRING;
00632       break;
00633    }
00634 
00635    return pri_char_set;
00636 }
00637 
00638 #if defined(HAVE_PRI_SUBADDR)
00639 /*!
00640  * \internal
00641  * \brief Fill in the asterisk party subaddress from the given PRI party subaddress.
00642  * \since 1.8
00643  *
00644  * \param ast_subaddress Asterisk party subaddress structure.
00645  * \param pri_subaddress PRI party subaddress structure.
00646  *
00647  * \return Nothing
00648  *
00649  */
00650 static void sig_pri_set_subaddress(struct ast_party_subaddress *ast_subaddress, const struct pri_party_subaddress *pri_subaddress)
00651 {
00652    char *cnum, *ptr;
00653    int x, len;
00654 
00655    if (ast_subaddress->str) {
00656       ast_free(ast_subaddress->str);
00657    }
00658    if (pri_subaddress->length <= 0) {
00659       ast_party_subaddress_init(ast_subaddress);
00660       return;
00661    }
00662 
00663    if (!pri_subaddress->type) {
00664       /* NSAP */
00665       ast_subaddress->str = ast_strdup((char *) pri_subaddress->data);
00666    } else {
00667       /* User Specified */
00668       if (!(cnum = ast_malloc(2 * pri_subaddress->length + 1))) {
00669          ast_party_subaddress_init(ast_subaddress);
00670          return;
00671       }
00672 
00673       ptr = cnum;
00674       len = pri_subaddress->length - 1; /* -1 account for zero based indexing */
00675       for (x = 0; x < len; ++x) {
00676          ptr += sprintf(ptr, "%02x", pri_subaddress->data[x]);
00677       }
00678 
00679       if (pri_subaddress->odd_even_indicator) {
00680          /* ODD */
00681          sprintf(ptr, "%01x", (pri_subaddress->data[len]) >> 4);
00682       } else {
00683          /* EVEN */
00684          sprintf(ptr, "%02x", pri_subaddress->data[len]);
00685       }
00686       ast_subaddress->str = cnum;
00687    }
00688    ast_subaddress->type = pri_subaddress->type;
00689    ast_subaddress->odd_even_indicator = pri_subaddress->odd_even_indicator;
00690    ast_subaddress->valid = 1;
00691 }
00692 #endif   /* defined(HAVE_PRI_SUBADDR) */
00693 
00694 #if defined(HAVE_PRI_SUBADDR)
00695 static unsigned char ast_pri_pack_hex_char(char c)
00696 {
00697    unsigned char res;
00698 
00699    if (c < '0') {
00700       res = 0;
00701    } else if (c < ('9' + 1)) {
00702       res = c - '0';
00703    } else if (c < 'A') {
00704       res = 0;
00705    } else if (c < ('F' + 1)) {
00706       res = c - 'A' + 10;
00707    } else if (c < 'a') {
00708       res = 0;
00709    } else if (c < ('f' + 1)) {
00710       res = c - 'a' + 10;
00711    } else {
00712       res = 0;
00713    }
00714    return res;
00715 }
00716 #endif   /* defined(HAVE_PRI_SUBADDR) */
00717 
00718 #if defined(HAVE_PRI_SUBADDR)
00719 /*!
00720  * \internal
00721  * \brief Convert a null terminated hexadecimal string to a packed hex byte array.
00722  * \details left justified, with 0 padding if odd length.
00723  * \since 1.8
00724  *
00725  * \param dst pointer to packed byte array.
00726  * \param src pointer to null terminated hexadecimal string.
00727  * \param maxlen destination array size.
00728  *
00729  * \return Length of byte array
00730  *
00731  * \note The dst is not an ASCIIz string.
00732  * \note The src is an ASCIIz hex string.
00733  */
00734 static int ast_pri_pack_hex_string(unsigned char *dst, char *src, int maxlen)
00735 {
00736    int res = 0;
00737    int len = strlen(src);
00738 
00739    if (len > (2 * maxlen)) {
00740       len = 2 * maxlen;
00741    }
00742 
00743    res = len / 2 + len % 2;
00744 
00745    while (len > 1) {
00746       *dst = ast_pri_pack_hex_char(*src) << 4;
00747       src++;
00748       *dst |= ast_pri_pack_hex_char(*src);
00749       dst++, src++;
00750       len -= 2;
00751    }
00752    if (len) { /* 1 left */
00753       *dst = ast_pri_pack_hex_char(*src) << 4;
00754    }
00755    return res;
00756 }
00757 #endif   /* defined(HAVE_PRI_SUBADDR) */
00758 
00759 #if defined(HAVE_PRI_SUBADDR)
00760 /*!
00761  * \internal
00762  * \brief Fill in the PRI party subaddress from the given asterisk party subaddress.
00763  * \since 1.8
00764  *
00765  * \param pri_subaddress PRI party subaddress structure.
00766  * \param ast_subaddress Asterisk party subaddress structure.
00767  *
00768  * \return Nothing
00769  *
00770  * \note Assumes that pri_subaddress has been previously memset to zero.
00771  */
00772 static void sig_pri_party_subaddress_from_ast(struct pri_party_subaddress *pri_subaddress, const struct ast_party_subaddress *ast_subaddress)
00773 {
00774    if (ast_subaddress->valid && !ast_strlen_zero(ast_subaddress->str)) {
00775       pri_subaddress->type = ast_subaddress->type;
00776       if (!ast_subaddress->type) {
00777          /* 0 = NSAP */
00778          ast_copy_string((char *) pri_subaddress->data, ast_subaddress->str,
00779             sizeof(pri_subaddress->data));
00780          pri_subaddress->length = strlen((char *) pri_subaddress->data);
00781          pri_subaddress->odd_even_indicator = 0;
00782          pri_subaddress->valid = 1;
00783       } else {
00784          /* 2 = User Specified */
00785          /*
00786           * Copy HexString to packed HexData,
00787           * if odd length then right pad trailing byte with 0
00788           */
00789          int length = ast_pri_pack_hex_string(pri_subaddress->data,
00790             ast_subaddress->str, sizeof(pri_subaddress->data));
00791 
00792          pri_subaddress->length = length; /* packed data length */
00793 
00794          length = strlen(ast_subaddress->str);
00795          if (length > 2 * sizeof(pri_subaddress->data)) {
00796             pri_subaddress->odd_even_indicator = 0;
00797          } else {
00798             pri_subaddress->odd_even_indicator = (length & 1);
00799          }
00800          pri_subaddress->valid = 1;
00801       }
00802    }
00803 }
00804 #endif   /* defined(HAVE_PRI_SUBADDR) */
00805 
00806 /*!
00807  * \internal
00808  * \brief Fill in the PRI party name from the given asterisk party name.
00809  * \since 1.8
00810  *
00811  * \param pri_name PRI party name structure.
00812  * \param ast_name Asterisk party name structure.
00813  *
00814  * \return Nothing
00815  *
00816  * \note Assumes that pri_name has been previously memset to zero.
00817  */
00818 static void sig_pri_party_name_from_ast(struct pri_party_name *pri_name, const struct ast_party_name *ast_name)
00819 {
00820    if (!ast_name->valid) {
00821       return;
00822    }
00823    pri_name->valid = 1;
00824    pri_name->presentation = ast_to_pri_presentation(ast_name->presentation);
00825    pri_name->char_set = ast_to_pri_char_set(ast_name->char_set);
00826    if (!ast_strlen_zero(ast_name->str)) {
00827       ast_copy_string(pri_name->str, ast_name->str, sizeof(pri_name->str));
00828    }
00829 }
00830 
00831 /*!
00832  * \internal
00833  * \brief Fill in the PRI party number from the given asterisk party number.
00834  * \since 1.8
00835  *
00836  * \param pri_number PRI party number structure.
00837  * \param ast_number Asterisk party number structure.
00838  *
00839  * \return Nothing
00840  *
00841  * \note Assumes that pri_number has been previously memset to zero.
00842  */
00843 static void sig_pri_party_number_from_ast(struct pri_party_number *pri_number, const struct ast_party_number *ast_number)
00844 {
00845    if (!ast_number->valid) {
00846       return;
00847    }
00848    pri_number->valid = 1;
00849    pri_number->presentation = ast_to_pri_presentation(ast_number->presentation);
00850    pri_number->plan = ast_number->plan;
00851    if (!ast_strlen_zero(ast_number->str)) {
00852       ast_copy_string(pri_number->str, ast_number->str, sizeof(pri_number->str));
00853    }
00854 }
00855 
00856 /*!
00857  * \internal
00858  * \brief Fill in the PRI party id from the given asterisk party id.
00859  * \since 1.8
00860  *
00861  * \param pri_id PRI party id structure.
00862  * \param ast_id Asterisk party id structure.
00863  *
00864  * \return Nothing
00865  *
00866  * \note Assumes that pri_id has been previously memset to zero.
00867  */
00868 static void sig_pri_party_id_from_ast(struct pri_party_id *pri_id, const struct ast_party_id *ast_id)
00869 {
00870    sig_pri_party_name_from_ast(&pri_id->name, &ast_id->name);
00871    sig_pri_party_number_from_ast(&pri_id->number, &ast_id->number);
00872 #if defined(HAVE_PRI_SUBADDR)
00873    sig_pri_party_subaddress_from_ast(&pri_id->subaddress, &ast_id->subaddress);
00874 #endif   /* defined(HAVE_PRI_SUBADDR) */
00875 }
00876 
00877 /*!
00878  * \internal
00879  * \brief Update the PRI redirecting information for the current call.
00880  * \since 1.8
00881  *
00882  * \param pvt sig_pri private channel structure.
00883  * \param ast Asterisk channel
00884  *
00885  * \return Nothing
00886  *
00887  * \note Assumes that the PRI lock is already obtained.
00888  */
00889 static void sig_pri_redirecting_update(struct sig_pri_chan *pvt, struct ast_channel *ast)
00890 {
00891    struct pri_party_redirecting pri_redirecting;
00892 
00893 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
00894 
00895    memset(&pri_redirecting, 0, sizeof(pri_redirecting));
00896    sig_pri_party_id_from_ast(&pri_redirecting.from, &ast->redirecting.from);
00897    sig_pri_party_id_from_ast(&pri_redirecting.to, &ast->redirecting.to);
00898    pri_redirecting.count = ast->redirecting.count;
00899    pri_redirecting.reason = ast_to_pri_reason(ast->redirecting.reason);
00900 
00901    pri_redirecting_update(pvt->pri->pri, pvt->call, &pri_redirecting);
00902 }
00903 
00904 /*!
00905  * \internal
00906  * \brief Reset DTMF detector.
00907  * \since 1.8
00908  *
00909  * \param p sig_pri channel structure.
00910  *
00911  * \return Nothing
00912  */
00913 static void sig_pri_dsp_reset_and_flush_digits(struct sig_pri_chan *p)
00914 {
00915    if (p->calls->dsp_reset_and_flush_digits) {
00916       p->calls->dsp_reset_and_flush_digits(p->chan_pvt);
00917    }
00918 }
00919 
00920 static int sig_pri_set_echocanceller(struct sig_pri_chan *p, int enable)
00921 {
00922    if (p->calls->set_echocanceller)
00923       return p->calls->set_echocanceller(p->chan_pvt, enable);
00924    else
00925       return -1;
00926 }
00927 
00928 static void sig_pri_fixup_chans(struct sig_pri_chan *old_chan, struct sig_pri_chan *new_chan)
00929 {
00930    if (old_chan->calls->fixup_chans)
00931       old_chan->calls->fixup_chans(old_chan->chan_pvt, new_chan->chan_pvt);
00932 }
00933 
00934 static int sig_pri_play_tone(struct sig_pri_chan *p, enum sig_pri_tone tone)
00935 {
00936    if (p->calls->play_tone)
00937       return p->calls->play_tone(p->chan_pvt, tone);
00938    else
00939       return -1;
00940 }
00941 
00942 static struct ast_channel *sig_pri_new_ast_channel(struct sig_pri_chan *p, int state, int ulaw, int transfercapability, char *exten, const struct ast_channel *requestor)
00943 {
00944    struct ast_channel *c;
00945 
00946    if (p->calls->new_ast_channel) {
00947       c = p->calls->new_ast_channel(p->chan_pvt, state, ulaw, exten, requestor);
00948    } else {
00949       return NULL;
00950    }
00951    if (!c) {
00952       return NULL;
00953    }
00954 
00955    if (!p->owner)
00956       p->owner = c;
00957    p->isidlecall = 0;
00958    p->alreadyhungup = 0;
00959    c->transfercapability = transfercapability;
00960    pbx_builtin_setvar_helper(c, "TRANSFERCAPABILITY",
00961       ast_transfercapability2str(transfercapability));
00962    if (transfercapability & AST_TRANS_CAP_DIGITAL) {
00963       sig_pri_set_digital(p, 1);
00964    }
00965    if (p->pri) {
00966       ast_mutex_lock(&p->pri->lock);
00967       sig_pri_span_devstate_changed(p->pri);
00968       ast_mutex_unlock(&p->pri->lock);
00969    }
00970 
00971    return c;
00972 }
00973 
00974 /*!
00975  * \internal
00976  * \brief Open the PRI channel media path.
00977  * \since 1.8
00978  *
00979  * \param p Channel private control structure.
00980  *
00981  * \return Nothing
00982  */
00983 static void sig_pri_open_media(struct sig_pri_chan *p)
00984 {
00985    if (p->no_b_channel) {
00986       return;
00987    }
00988 
00989    if (p->calls->open_media) {
00990       p->calls->open_media(p->chan_pvt);
00991    }
00992 }
00993 
00994 /*!
00995  * \internal
00996  * \brief Post an AMI B channel association event.
00997  * \since 1.8
00998  *
00999  * \param p Channel private control structure.
01000  *
01001  * \note Assumes the private and owner are locked.
01002  *
01003  * \return Nothing
01004  */
01005 static void sig_pri_ami_channel_event(struct sig_pri_chan *p)
01006 {
01007    if (p->calls->ami_channel_event) {
01008       p->calls->ami_channel_event(p->chan_pvt, p->owner);
01009    }
01010 }
01011 
01012 struct ast_channel *sig_pri_request(struct sig_pri_chan *p, enum sig_pri_law law, const struct ast_channel *requestor, int transfercapability)
01013 {
01014    struct ast_channel *ast;
01015 
01016    ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
01017 
01018    sig_pri_set_outgoing(p, 1);
01019    ast = sig_pri_new_ast_channel(p, AST_STATE_RESERVED, law, transfercapability, p->exten, requestor);
01020    if (!ast) {
01021       sig_pri_set_outgoing(p, 0);
01022    }
01023    return ast;
01024 }
01025 
01026 int pri_is_up(struct sig_pri_span *pri)
01027 {
01028    int x;
01029    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
01030       if (pri->dchanavail[x] == DCHAN_AVAILABLE)
01031          return 1;
01032    }
01033    return 0;
01034 }
01035 
01036 static const char *pri_order(int level)
01037 {
01038    switch (level) {
01039    case 0:
01040       return "Primary";
01041    case 1:
01042       return "Secondary";
01043    case 2:
01044       return "Tertiary";
01045    case 3:
01046       return "Quaternary";
01047    default:
01048       return "<Unknown>";
01049    }
01050 }
01051 
01052 /* Returns index of the active dchan */
01053 static int pri_active_dchan_index(struct sig_pri_span *pri)
01054 {
01055    int x;
01056 
01057    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
01058       if ((pri->dchans[x] == pri->pri))
01059          return x;
01060    }
01061 
01062    ast_log(LOG_WARNING, "No active dchan found!\n");
01063    return -1;
01064 }
01065 
01066 static void pri_find_dchan(struct sig_pri_span *pri)
01067 {
01068    struct pri *old;
01069    int oldslot = -1;
01070    int newslot = -1;
01071    int idx;
01072 
01073    old = pri->pri;
01074    for (idx = 0; idx < SIG_PRI_NUM_DCHANS; ++idx) {
01075       if (!pri->dchans[idx]) {
01076          /* No more D channels defined on the span. */
01077          break;
01078       }
01079       if (pri->dchans[idx] == old) {
01080          oldslot = idx;
01081       }
01082       if (newslot < 0 && pri->dchanavail[idx] == DCHAN_AVAILABLE) {
01083          newslot = idx;
01084       }
01085    }
01086    /* At this point, idx is a count of how many D-channels are defined on the span. */
01087 
01088    if (1 < idx) {
01089       /* We have several D-channels defined on the span.  (NFAS PRI setup) */
01090       if (newslot < 0) {
01091          /* No D-channels available.  Default to the primary D-channel. */
01092          newslot = 0;
01093 
01094          if (!pri->no_d_channels) {
01095             pri->no_d_channels = 1;
01096             if (old && oldslot != newslot) {
01097                ast_log(LOG_WARNING,
01098                   "Span %d: No D-channels up!  Switching selected D-channel from %s to %s.\n",
01099                   pri->span, pri_order(oldslot), pri_order(newslot));
01100             } else {
01101                ast_log(LOG_WARNING, "Span %d: No D-channels up!\n", pri->span);
01102             }
01103          }
01104       } else {
01105          pri->no_d_channels = 0;
01106       }
01107       if (old && oldslot != newslot) {
01108          ast_log(LOG_NOTICE,
01109             "Switching selected D-channel from %s (fd %d) to %s (fd %d)!\n",
01110             pri_order(oldslot), pri->fds[oldslot],
01111             pri_order(newslot), pri->fds[newslot]);
01112       }
01113    } else {
01114       if (newslot < 0) {
01115          /* The only D-channel is not up. */
01116          newslot = 0;
01117 
01118          if (!pri->no_d_channels) {
01119             pri->no_d_channels = 1;
01120 
01121             /*
01122              * This is annoying to see on non-persistent layer 2
01123              * connections.  Let's not complain in that case.
01124              */
01125             if (pri->sig != SIG_BRI_PTMP) {
01126                ast_log(LOG_WARNING, "Span %d: D-channel is down!\n", pri->span);
01127             }
01128          }
01129       } else {
01130          pri->no_d_channels = 0;
01131       }
01132    }
01133    pri->pri = pri->dchans[newslot];
01134 }
01135 
01136 /*!
01137  * \internal
01138  * \brief Determine if a private channel structure is in use.
01139  * \since 1.8
01140  *
01141  * \param pvt Channel to determine if in use.
01142  *
01143  * \return TRUE if the channel is in use.
01144  */
01145 static int sig_pri_is_chan_in_use(struct sig_pri_chan *pvt)
01146 {
01147    return pvt->owner || pvt->call || pvt->allocated || pvt->inalarm
01148       || pvt->resetting != SIG_PRI_RESET_IDLE;
01149 }
01150 
01151 /*!
01152  * \brief Determine if a private channel structure is available.
01153  * \since 1.8
01154  *
01155  * \param pvt Channel to determine if available.
01156  *
01157  * \return TRUE if the channel is available.
01158  */
01159 int sig_pri_is_chan_available(struct sig_pri_chan *pvt)
01160 {
01161    return !sig_pri_is_chan_in_use(pvt)
01162 #if defined(HAVE_PRI_SERVICE_MESSAGES)
01163       /* And not out-of-service */
01164       && !pvt->service_status
01165 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
01166       ;
01167 }
01168 
01169 /*!
01170  * \internal
01171  * \brief Obtain the sig_pri owner channel lock if the owner exists.
01172  * \since 1.8
01173  *
01174  * \param pri PRI span control structure.
01175  * \param chanpos Channel position in the span.
01176  *
01177  * \note Assumes the pri->lock is already obtained.
01178  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
01179  *
01180  * \return Nothing
01181  */
01182 static void sig_pri_lock_owner(struct sig_pri_span *pri, int chanpos)
01183 {
01184    for (;;) {
01185       if (!pri->pvts[chanpos]->owner) {
01186          /* There is no owner lock to get. */
01187          break;
01188       }
01189       if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
01190          /* We got the lock */
01191          break;
01192       }
01193 
01194       /* Avoid deadlock */
01195       sig_pri_unlock_private(pri->pvts[chanpos]);
01196       DEADLOCK_AVOIDANCE(&pri->lock);
01197       sig_pri_lock_private(pri->pvts[chanpos]);
01198    }
01199 }
01200 
01201 /*!
01202  * \internal
01203  * \brief Queue the given frame onto the owner channel.
01204  * \since 1.8
01205  *
01206  * \param pri PRI span control structure.
01207  * \param chanpos Channel position in the span.
01208  * \param frame Frame to queue onto the owner channel.
01209  *
01210  * \note Assumes the pri->lock is already obtained.
01211  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
01212  *
01213  * \return Nothing
01214  */
01215 static void pri_queue_frame(struct sig_pri_span *pri, int chanpos, struct ast_frame *frame)
01216 {
01217    sig_pri_lock_owner(pri, chanpos);
01218    if (pri->pvts[chanpos]->owner) {
01219       ast_queue_frame(pri->pvts[chanpos]->owner, frame);
01220       ast_channel_unlock(pri->pvts[chanpos]->owner);
01221    }
01222 }
01223 
01224 /*!
01225  * \internal
01226  * \brief Queue a control frame of the specified subclass onto the owner channel.
01227  * \since 1.8
01228  *
01229  * \param pri PRI span control structure.
01230  * \param chanpos Channel position in the span.
01231  * \param subclass Control frame subclass to queue onto the owner channel.
01232  *
01233  * \note Assumes the pri->lock is already obtained.
01234  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
01235  *
01236  * \return Nothing
01237  */
01238 static void pri_queue_control(struct sig_pri_span *pri, int chanpos, int subclass)
01239 {
01240    struct ast_frame f = {AST_FRAME_CONTROL, };
01241    struct sig_pri_chan *p = pri->pvts[chanpos];
01242 
01243    if (p->calls->queue_control) {
01244       p->calls->queue_control(p->chan_pvt, subclass);
01245    }
01246 
01247    f.subclass.integer = subclass;
01248    pri_queue_frame(pri, chanpos, &f);
01249 }
01250 
01251 /*!
01252  * \internal
01253  * \brief Find the channel associated with the libpri call.
01254  * \since 1.10
01255  *
01256  * \param pri PRI span control structure.
01257  * \param call LibPRI opaque call pointer to find.
01258  *
01259  * \note Assumes the pri->lock is already obtained.
01260  *
01261  * \retval array-index into private pointer array on success.
01262  * \retval -1 on error.
01263  */
01264 static int pri_find_principle_by_call(struct sig_pri_span *pri, q931_call *call)
01265 {
01266    int idx;
01267 
01268    if (!call) {
01269       /* Cannot find a call without a call. */
01270       return -1;
01271    }
01272    for (idx = 0; idx < pri->numchans; ++idx) {
01273       if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
01274          /* Found the principle */
01275          return idx;
01276       }
01277    }
01278    return -1;
01279 }
01280 
01281 /*!
01282  * \internal
01283  * \brief Kill the call.
01284  * \since 1.10
01285  *
01286  * \param pri PRI span control structure.
01287  * \param call LibPRI opaque call pointer to find.
01288  * \param cause Reason call was killed.
01289  *
01290  * \note Assumes the pvt->pri->lock is already obtained.
01291  *
01292  * \return Nothing
01293  */
01294 static void sig_pri_kill_call(struct sig_pri_span *pri, q931_call *call, int cause)
01295 {
01296    int chanpos;
01297 
01298    chanpos = pri_find_principle_by_call(pri, call);
01299    if (chanpos < 0) {
01300       pri_hangup(pri->pri, call, cause);
01301       return;
01302    }
01303    sig_pri_lock_private(pri->pvts[chanpos]);
01304    if (!pri->pvts[chanpos]->owner) {
01305       pri_hangup(pri->pri, call, cause);
01306       pri->pvts[chanpos]->call = NULL;
01307       sig_pri_unlock_private(pri->pvts[chanpos]);
01308       sig_pri_span_devstate_changed(pri);
01309       return;
01310    }
01311    pri->pvts[chanpos]->owner->hangupcause = cause;
01312    pri_queue_control(pri, chanpos, AST_CONTROL_HANGUP);
01313    sig_pri_unlock_private(pri->pvts[chanpos]);
01314 }
01315 
01316 /*!
01317  * \internal
01318  * \brief Find the private structure for the libpri call.
01319  *
01320  * \param pri PRI span control structure.
01321  * \param channel LibPRI encoded channel ID.
01322  * \param call LibPRI opaque call pointer.
01323  *
01324  * \note Assumes the pri->lock is already obtained.
01325  *
01326  * \retval array-index into private pointer array on success.
01327  * \retval -1 on error.
01328  */
01329 static int pri_find_principle(struct sig_pri_span *pri, int channel, q931_call *call)
01330 {
01331    int x;
01332    int span;
01333    int principle;
01334    int prioffset;
01335 
01336    if (channel < 0) {
01337       /* Channel is not picked yet. */
01338       return -1;
01339    }
01340 
01341    prioffset = PRI_CHANNEL(channel);
01342    if (!prioffset || (channel & PRI_HELD_CALL)) {
01343       if (!call) {
01344          /* Cannot find a call waiting call or held call without a call. */
01345          return -1;
01346       }
01347       principle = -1;
01348       for (x = 0; x < pri->numchans; ++x) {
01349          if (pri->pvts[x]
01350             && pri->pvts[x]->call == call) {
01351             principle = x;
01352             break;
01353          }
01354       }
01355       return principle;
01356    }
01357 
01358    span = PRI_SPAN(channel);
01359    if (!(channel & PRI_EXPLICIT)) {
01360       int index;
01361 
01362       index = pri_active_dchan_index(pri);
01363       if (index == -1) {
01364          return -1;
01365       }
01366       span = pri->dchan_logical_span[index];
01367    }
01368 
01369    principle = -1;
01370    for (x = 0; x < pri->numchans; x++) {
01371       if (pri->pvts[x]
01372          && pri->pvts[x]->prioffset == prioffset
01373          && pri->pvts[x]->logicalspan == span
01374          && !pri->pvts[x]->no_b_channel) {
01375          principle = x;
01376          break;
01377       }
01378    }
01379 
01380    return principle;
01381 }
01382 
01383 /*!
01384  * \internal
01385  * \brief Fixup the private structure associated with the libpri call.
01386  *
01387  * \param pri PRI span control structure.
01388  * \param principle Array-index into private array to move call to if not already there.
01389  * \param call LibPRI opaque call pointer to find if need to move call.
01390  *
01391  * \note Assumes the pri->lock is already obtained.
01392  *
01393  * \retval principle on success.
01394  * \retval -1 on error.
01395  */
01396 static int pri_fixup_principle(struct sig_pri_span *pri, int principle, q931_call *call)
01397 {
01398    int x;
01399 
01400    if (principle < 0 || pri->numchans <= principle) {
01401       /* Out of rannge */
01402       return -1;
01403    }
01404    if (!call) {
01405       /* No call */
01406       return principle;
01407    }
01408    if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
01409       /* Call is already on the specified principle. */
01410       return principle;
01411    }
01412 
01413    /* Find the old principle location. */
01414    for (x = 0; x < pri->numchans; x++) {
01415       struct sig_pri_chan *new_chan;
01416       struct sig_pri_chan *old_chan;
01417 
01418       if (!pri->pvts[x] || pri->pvts[x]->call != call) {
01419          continue;
01420       }
01421 
01422       /* Found our call */
01423       new_chan = pri->pvts[principle];
01424       old_chan = pri->pvts[x];
01425 
01426       /* Get locks to safely move to the new private structure. */
01427       sig_pri_lock_private(old_chan);
01428       sig_pri_lock_owner(pri, x);
01429       sig_pri_lock_private(new_chan);
01430 
01431       ast_verb(3, "Moving call (%s) from channel %d to %d.\n",
01432          old_chan->owner ? old_chan->owner->name : "",
01433          old_chan->channel, new_chan->channel);
01434       if (!sig_pri_is_chan_available(new_chan)) {
01435          ast_log(LOG_WARNING,
01436             "Can't move call (%s) from channel %d to %d.  It is already in use.\n",
01437             old_chan->owner ? old_chan->owner->name : "",
01438             old_chan->channel, new_chan->channel);
01439          sig_pri_unlock_private(new_chan);
01440          if (old_chan->owner) {
01441             ast_channel_unlock(old_chan->owner);
01442          }
01443          sig_pri_unlock_private(old_chan);
01444          return -1;
01445       }
01446 
01447       sig_pri_fixup_chans(old_chan, new_chan);
01448 
01449       /* Fix it all up now */
01450       new_chan->owner = old_chan->owner;
01451       old_chan->owner = NULL;
01452 
01453       new_chan->call = old_chan->call;
01454       old_chan->call = NULL;
01455 
01456       /* Transfer flags from the old channel. */
01457 #if defined(HAVE_PRI_AOC_EVENTS)
01458       new_chan->aoc_s_request_invoke_id_valid = old_chan->aoc_s_request_invoke_id_valid;
01459       new_chan->waiting_for_aoce = old_chan->waiting_for_aoce;
01460       new_chan->holding_aoce = old_chan->holding_aoce;
01461 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
01462       new_chan->alreadyhungup = old_chan->alreadyhungup;
01463       new_chan->isidlecall = old_chan->isidlecall;
01464       new_chan->progress = old_chan->progress;
01465       new_chan->allocated = old_chan->allocated;
01466       new_chan->outgoing = old_chan->outgoing;
01467       new_chan->digital = old_chan->digital;
01468 #if defined(HAVE_PRI_CALL_WAITING)
01469       new_chan->is_call_waiting = old_chan->is_call_waiting;
01470 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
01471 
01472 #if defined(HAVE_PRI_AOC_EVENTS)
01473       old_chan->aoc_s_request_invoke_id_valid = 0;
01474       old_chan->waiting_for_aoce = 0;
01475       old_chan->holding_aoce = 0;
01476 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
01477       old_chan->alreadyhungup = 0;
01478       old_chan->isidlecall = 0;
01479       old_chan->progress = 0;
01480       old_chan->allocated = 0;
01481       old_chan->outgoing = 0;
01482       old_chan->digital = 0;
01483 #if defined(HAVE_PRI_CALL_WAITING)
01484       old_chan->is_call_waiting = 0;
01485 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
01486 
01487       /* More stuff to transfer to the new channel. */
01488       new_chan->call_level = old_chan->call_level;
01489       old_chan->call_level = SIG_PRI_CALL_LEVEL_IDLE;
01490 #if defined(HAVE_PRI_REVERSE_CHARGE)
01491       new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
01492 #endif   /* defined(HAVE_PRI_REVERSE_CHARGE) */
01493 #if defined(HAVE_PRI_SETUP_KEYPAD)
01494       strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
01495 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
01496       strcpy(new_chan->deferred_digits, old_chan->deferred_digits);
01497 #if defined(HAVE_PRI_AOC_EVENTS)
01498       new_chan->aoc_s_request_invoke_id = old_chan->aoc_s_request_invoke_id;
01499       new_chan->aoc_e = old_chan->aoc_e;
01500 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
01501       strcpy(new_chan->user_tag, old_chan->user_tag);
01502 
01503       if (new_chan->no_b_channel) {
01504          /* Copy the real channel configuration to the no B channel interface. */
01505          new_chan->hidecallerid = old_chan->hidecallerid;
01506          new_chan->hidecalleridname = old_chan->hidecalleridname;
01507          new_chan->immediate = old_chan->immediate;
01508          new_chan->priexclusive = old_chan->priexclusive;
01509          new_chan->priindication_oob = old_chan->priindication_oob;
01510          new_chan->use_callerid = old_chan->use_callerid;
01511          new_chan->use_callingpres = old_chan->use_callingpres;
01512          new_chan->stripmsd = old_chan->stripmsd;
01513          strcpy(new_chan->context, old_chan->context);
01514          strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
01515 
01516          /* Become a member of the old channel span/trunk-group. */
01517          new_chan->logicalspan = old_chan->logicalspan;
01518          new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
01519       } else if (old_chan->no_b_channel) {
01520          /*
01521           * We are transitioning from a held/call-waiting channel to a
01522           * real channel so we need to make sure that the media path is
01523           * open.  (Needed especially if the channel is natively
01524           * bridged.)
01525           */
01526          sig_pri_open_media(new_chan);
01527       }
01528 
01529       if (new_chan->owner) {
01530          sig_pri_ami_channel_event(new_chan);
01531       }
01532 
01533       sig_pri_unlock_private(old_chan);
01534       if (new_chan->owner) {
01535          ast_channel_unlock(new_chan->owner);
01536       }
01537       sig_pri_unlock_private(new_chan);
01538 
01539       return principle;
01540    }
01541    ast_verb(3, "Call specified, but not found.\n");
01542    return -1;
01543 }
01544 
01545 /*!
01546  * \internal
01547  * \brief Find and fixup the private structure associated with the libpri call.
01548  *
01549  * \param pri PRI span control structure.
01550  * \param channel LibPRI encoded channel ID.
01551  * \param call LibPRI opaque call pointer.
01552  *
01553  * \details
01554  * This is a combination of pri_find_principle() and pri_fixup_principle()
01555  * to reduce code redundancy and to make handling several PRI_EVENT_xxx's
01556  * consistent for the current architecture.
01557  *
01558  * \note Assumes the pri->lock is already obtained.
01559  *
01560  * \retval array-index into private pointer array on success.
01561  * \retval -1 on error.
01562  */
01563 static int pri_find_fixup_principle(struct sig_pri_span *pri, int channel, q931_call *call)
01564 {
01565    int chanpos;
01566 
01567    chanpos = pri_find_principle(pri, channel, call);
01568    if (chanpos < 0) {
01569       ast_log(LOG_WARNING, "Span %d: PRI requested channel %d/%d is unconfigured.\n",
01570          pri->span, PRI_SPAN(channel), PRI_CHANNEL(channel));
01571       sig_pri_kill_call(pri, call, PRI_CAUSE_IDENTIFIED_CHANNEL_NOTEXIST);
01572       return -1;
01573    }
01574    chanpos = pri_fixup_principle(pri, chanpos, call);
01575    if (chanpos < 0) {
01576       ast_log(LOG_WARNING, "Span %d: PRI requested channel %d/%d is not available.\n",
01577          pri->span, PRI_SPAN(channel), PRI_CHANNEL(channel));
01578       /*
01579        * Using Q.931 section 5.2.3.1 b) as the reason for picking
01580        * PRI_CAUSE_CHANNEL_UNACCEPTABLE.  Receiving a
01581        * PRI_CAUSE_REQUESTED_CHAN_UNAVAIL would cause us to restart
01582        * that channel (which is not specified by Q.931) and kill some
01583        * other call which would be bad.
01584        */
01585       sig_pri_kill_call(pri, call, PRI_CAUSE_CHANNEL_UNACCEPTABLE);
01586       return -1;
01587    }
01588    return chanpos;
01589 }
01590 
01591 static char * redirectingreason2str(int redirectingreason)
01592 {
01593    switch (redirectingreason) {
01594    case 0:
01595       return "UNKNOWN";
01596    case 1:
01597       return "BUSY";
01598    case 2:
01599       return "NO_REPLY";
01600    case 0xF:
01601       return "UNCONDITIONAL";
01602    default:
01603       return "NOREDIRECT";
01604    }
01605 }
01606 
01607 static char *dialplan2str(int dialplan)
01608 {
01609    if (dialplan == -1) {
01610       return("Dynamically set dialplan in ISDN");
01611    }
01612    return (pri_plan2str(dialplan));
01613 }
01614 
01615 /*!
01616  * \internal
01617  * \brief Apply numbering plan prefix to the given number.
01618  *
01619  * \param buf Buffer to put number into.
01620  * \param size Size of given buffer.
01621  * \param pri PRI span control structure.
01622  * \param number Number to apply numbering plan.
01623  * \param plan Numbering plan to apply.
01624  *
01625  * \return Nothing
01626  */
01627 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_span *pri, const char *number, int plan)
01628 {
01629    switch (plan) {
01630    case PRI_INTERNATIONAL_ISDN:     /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
01631       snprintf(buf, size, "%s%s", pri->internationalprefix, number);
01632       break;
01633    case PRI_NATIONAL_ISDN:       /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
01634       snprintf(buf, size, "%s%s", pri->nationalprefix, number);
01635       break;
01636    case PRI_LOCAL_ISDN:       /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
01637       snprintf(buf, size, "%s%s", pri->localprefix, number);
01638       break;
01639    case PRI_PRIVATE:       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
01640       snprintf(buf, size, "%s%s", pri->privateprefix, number);
01641       break;
01642    case PRI_UNKNOWN:       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
01643       snprintf(buf, size, "%s%s", pri->unknownprefix, number);
01644       break;
01645    default:          /* other Q.931 dialplan => don't twiddle with callingnum */
01646       snprintf(buf, size, "%s", number);
01647       break;
01648    }
01649 }
01650 
01651 /*!
01652  * \internal
01653  * \brief Apply numbering plan prefix to the given number if the number exists.
01654  *
01655  * \param buf Buffer to put number into.
01656  * \param size Size of given buffer.
01657  * \param pri PRI span control structure.
01658  * \param number Number to apply numbering plan.
01659  * \param plan Numbering plan to apply.
01660  *
01661  * \return Nothing
01662  */
01663 static void apply_plan_to_existing_number(char *buf, size_t size, const struct sig_pri_span *pri, const char *number, int plan)
01664 {
01665    /* Make sure a number exists so the prefix isn't placed on an empty string. */
01666    if (ast_strlen_zero(number)) {
01667       if (size) {
01668          *buf = '\0';
01669       }
01670       return;
01671    }
01672    apply_plan_to_number(buf, size, pri, number, plan);
01673 }
01674 
01675 /*!
01676  * \internal
01677  * \brief Restart the next channel we think is idle on the span.
01678  *
01679  * \param pri PRI span control structure.
01680  *
01681  * \note Assumes the pri->lock is already obtained.
01682  *
01683  * \return Nothing
01684  */
01685 static void pri_check_restart(struct sig_pri_span *pri)
01686 {
01687 #if defined(HAVE_PRI_SERVICE_MESSAGES)
01688    unsigned why;
01689 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
01690 
01691    for (++pri->resetpos; pri->resetpos < pri->numchans; ++pri->resetpos) {
01692       if (!pri->pvts[pri->resetpos]
01693          || pri->pvts[pri->resetpos]->no_b_channel
01694          || sig_pri_is_chan_in_use(pri->pvts[pri->resetpos])) {
01695          continue;
01696       }
01697 #if defined(HAVE_PRI_SERVICE_MESSAGES)
01698       why = pri->pvts[pri->resetpos]->service_status;
01699       if (why) {
01700          ast_log(LOG_NOTICE,
01701             "Span %d: channel %d out-of-service (reason: %s), not sending RESTART\n",
01702             pri->span, pri->pvts[pri->resetpos]->channel,
01703             (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
01704          continue;
01705       }
01706 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
01707       break;
01708    }
01709    if (pri->resetpos < pri->numchans) {
01710       /* Mark the channel as resetting and restart it */
01711       pri->pvts[pri->resetpos]->resetting = SIG_PRI_RESET_ACTIVE;
01712       pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
01713    } else {
01714       pri->resetting = 0;
01715       time(&pri->lastreset);
01716       sig_pri_span_devstate_changed(pri);
01717    }
01718 }
01719 
01720 #if defined(HAVE_PRI_CALL_WAITING)
01721 /*!
01722  * \internal
01723  * \brief Init the private channel configuration using the span controller.
01724  * \since 1.8
01725  *
01726  * \param pvt Channel to init the configuration.
01727  * \param pri PRI span control structure.
01728  *
01729  * \note Assumes the pri->lock is already obtained.
01730  *
01731  * \return Nothing
01732  */
01733 static void sig_pri_init_config(struct sig_pri_chan *pvt, struct sig_pri_span *pri)
01734 {
01735    pvt->stripmsd = pri->ch_cfg.stripmsd;
01736    pvt->hidecallerid = pri->ch_cfg.hidecallerid;
01737    pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
01738    pvt->immediate = pri->ch_cfg.immediate;
01739    pvt->priexclusive = pri->ch_cfg.priexclusive;
01740    pvt->priindication_oob = pri->ch_cfg.priindication_oob;
01741    pvt->use_callerid = pri->ch_cfg.use_callerid;
01742    pvt->use_callingpres = pri->ch_cfg.use_callingpres;
01743    ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
01744    ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
01745 
01746    if (pri->calls->init_config) {
01747       pri->calls->init_config(pvt->chan_pvt, pri);
01748    }
01749 }
01750 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
01751 
01752 /*!
01753  * \internal
01754  * \brief Find an empty B-channel interface to use.
01755  *
01756  * \param pri PRI span control structure.
01757  * \param backwards TRUE if the search starts from higher channels.
01758  *
01759  * \note Assumes the pri->lock is already obtained.
01760  *
01761  * \retval array-index into private pointer array on success.
01762  * \retval -1 on error.
01763  */
01764 static int pri_find_empty_chan(struct sig_pri_span *pri, int backwards)
01765 {
01766    int x;
01767    if (backwards)
01768       x = pri->numchans;
01769    else
01770       x = 0;
01771    for (;;) {
01772       if (backwards && (x < 0))
01773          break;
01774       if (!backwards && (x >= pri->numchans))
01775          break;
01776       if (pri->pvts[x]
01777          && !pri->pvts[x]->no_b_channel
01778          && sig_pri_is_chan_available(pri->pvts[x])) {
01779          ast_debug(1, "Found empty available channel %d/%d\n",
01780             pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
01781          return x;
01782       }
01783       if (backwards)
01784          x--;
01785       else
01786          x++;
01787    }
01788    return -1;
01789 }
01790 
01791 #if defined(HAVE_PRI_CALL_HOLD)
01792 /*!
01793  * \internal
01794  * \brief Find or create an empty no-B-channel interface to use.
01795  * \since 1.8
01796  *
01797  * \param pri PRI span control structure.
01798  *
01799  * \note Assumes the pri->lock is already obtained.
01800  *
01801  * \retval array-index into private pointer array on success.
01802  * \retval -1 on error.
01803  */
01804 static int pri_find_empty_nobch(struct sig_pri_span *pri)
01805 {
01806    int idx;
01807 
01808    for (idx = 0; idx < pri->numchans; ++idx) {
01809       if (pri->pvts[idx]
01810          && pri->pvts[idx]->no_b_channel
01811          && sig_pri_is_chan_available(pri->pvts[idx])) {
01812          ast_debug(1, "Found empty available no B channel interface\n");
01813          return idx;
01814       }
01815    }
01816 
01817    /* Need to create a new interface. */
01818    if (pri->calls->new_nobch_intf) {
01819       idx = pri->calls->new_nobch_intf(pri);
01820    } else {
01821       idx = -1;
01822    }
01823    return idx;
01824 }
01825 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
01826 
01827 static void *do_idle_thread(void *v_pvt)
01828 {
01829    struct sig_pri_chan *pvt = v_pvt;
01830    struct ast_channel *chan = pvt->owner;
01831    struct ast_frame *f;
01832    char ex[80];
01833    /* Wait up to 30 seconds for an answer */
01834    int timeout_ms = 30000;
01835    int ms;
01836    struct timeval start;
01837 
01838    ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
01839    snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
01840    if (ast_call(chan, ex, 0)) {
01841       ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
01842       ast_hangup(chan);
01843       return NULL;
01844    }
01845    start = ast_tvnow();
01846    while ((ms = ast_remaining_ms(start, timeout_ms))) {
01847       if (ast_waitfor(chan, ms) <= 0) {
01848          break;
01849       }
01850 
01851       f = ast_read(chan);
01852       if (!f) {
01853          /* Got hangup */
01854          break;
01855       }
01856       if (f->frametype == AST_FRAME_CONTROL) {
01857          switch (f->subclass.integer) {
01858          case AST_CONTROL_ANSWER:
01859             /* Launch the PBX */
01860             ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
01861             ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
01862             chan->priority = 1;
01863             ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
01864             ast_pbx_run(chan);
01865             /* It's already hungup, return immediately */
01866             return NULL;
01867          case AST_CONTROL_BUSY:
01868             ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
01869             break;
01870          case AST_CONTROL_CONGESTION:
01871             ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
01872             break;
01873          };
01874       }
01875       ast_frfree(f);
01876    }
01877    /* Hangup the channel since nothing happend */
01878    ast_hangup(chan);
01879    return NULL;
01880 }
01881 
01882 static void *pri_ss_thread(void *data)
01883 {
01884    struct sig_pri_chan *p = data;
01885    struct ast_channel *chan = p->owner;
01886    char exten[AST_MAX_EXTENSION];
01887    int res;
01888    int len;
01889    int timeout;
01890 
01891    if (!chan) {
01892       /* We lost the owner before we could get started. */
01893       return NULL;
01894    }
01895 
01896    /*
01897     * In the bizarre case where the channel has become a zombie before we
01898     * even get started here, abort safely.
01899     */
01900    if (!chan->tech_pvt) {
01901       ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
01902       ast_hangup(chan);
01903       return NULL;
01904    }
01905 
01906    ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
01907 
01908    sig_pri_dsp_reset_and_flush_digits(p);
01909 
01910    /* Now loop looking for an extension */
01911    ast_copy_string(exten, p->exten, sizeof(exten));
01912    len = strlen(exten);
01913    res = 0;
01914    while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
01915       if (len && !ast_ignore_pattern(chan->context, exten))
01916          sig_pri_play_tone(p, -1);
01917       else
01918          sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
01919       if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
01920          timeout = pri_matchdigittimeout;
01921       else
01922          timeout = pri_gendigittimeout;
01923       res = ast_waitfordigit(chan, timeout);
01924       if (res < 0) {
01925          ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
01926          ast_hangup(chan);
01927          return NULL;
01928       } else if (res) {
01929          exten[len++] = res;
01930          exten[len] = '\0';
01931       } else
01932          break;
01933    }
01934    /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
01935    if (ast_strlen_zero(exten)) {
01936       ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
01937       exten[0] = 's';
01938       exten[1] = '\0';
01939    } else {
01940       ast_free(chan->dialed.number.str);
01941       chan->dialed.number.str = ast_strdup(exten);
01942 
01943       if (p->pri->append_msn_to_user_tag && p->pri->nodetype != PRI_NETWORK) {
01944          /*
01945           * Update the user tag for party id's from this device for this call
01946           * now that we have a complete MSN from the network.
01947           */
01948          snprintf(p->user_tag, sizeof(p->user_tag), "%s_%s", p->pri->initial_user_tag,
01949             exten);
01950          ast_free(chan->caller.id.tag);
01951          chan->caller.id.tag = ast_strdup(p->user_tag);
01952       }
01953    }
01954    sig_pri_play_tone(p, -1);
01955    if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
01956       /* Start the real PBX */
01957       ast_copy_string(chan->exten, exten, sizeof(chan->exten));
01958       sig_pri_dsp_reset_and_flush_digits(p);
01959 #if defined(ISSUE_16789)
01960       /*
01961        * Conditionaled out this code to effectively revert the Mantis
01962        * issue 16789 change.  It breaks overlap dialing through
01963        * Asterisk.  There is not enough information available at this
01964        * point to know if dialing is complete.  The
01965        * ast_exists_extension(), ast_matchmore_extension(), and
01966        * ast_canmatch_extension() calls are not adequate to detect a
01967        * dial through extension pattern of "_9!".
01968        *
01969        * Workaround is to use the dialplan Proceeding() application
01970        * early on non-dial through extensions.
01971        */
01972       if ((p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
01973          && !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
01974          sig_pri_lock_private(p);
01975          if (p->pri->pri) {
01976             pri_grab(p, p->pri);
01977             if (p->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING) {
01978                p->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
01979             }
01980             pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
01981             pri_rel(p->pri);
01982          }
01983          sig_pri_unlock_private(p);
01984       }
01985 #endif   /* defined(ISSUE_16789) */
01986 
01987       sig_pri_set_echocanceller(p, 1);
01988       ast_setstate(chan, AST_STATE_RING);
01989       res = ast_pbx_run(chan);
01990       if (res) {
01991          ast_log(LOG_WARNING, "PBX exited non-zero!\n");
01992       }
01993    } else {
01994       ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
01995       chan->hangupcause = AST_CAUSE_UNALLOCATED;
01996       ast_hangup(chan);
01997       p->exten[0] = '\0';
01998       /* Since we send release complete here, we won't get one */
01999       p->call = NULL;
02000       ast_mutex_lock(&p->pri->lock);
02001       sig_pri_span_devstate_changed(p->pri);
02002       ast_mutex_unlock(&p->pri->lock);
02003    }
02004    return NULL;
02005 }
02006 
02007 void pri_event_alarm(struct sig_pri_span *pri, int index, int before_start_pri)
02008 {
02009    pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
02010    if (!before_start_pri) {
02011       pri_find_dchan(pri);
02012    }
02013 }
02014 
02015 void pri_event_noalarm(struct sig_pri_span *pri, int index, int before_start_pri)
02016 {
02017    pri->dchanavail[index] |= DCHAN_NOTINALARM;
02018    if (!before_start_pri)
02019       pri_restart(pri->dchans[index]);
02020 }
02021 
02022 /*!
02023  * \internal
02024  * \brief Convert libpri party name into asterisk party name.
02025  * \since 1.8
02026  *
02027  * \param ast_name Asterisk party name structure to fill.  Must already be set initialized.
02028  * \param pri_name libpri party name structure containing source information.
02029  *
02030  * \note The filled in ast_name structure needs to be destroyed by
02031  * ast_party_name_free() when it is no longer needed.
02032  *
02033  * \return Nothing
02034  */
02035 static void sig_pri_party_name_convert(struct ast_party_name *ast_name, const struct pri_party_name *pri_name)
02036 {
02037    ast_name->str = ast_strdup(pri_name->str);
02038    ast_name->char_set = pri_to_ast_char_set(pri_name->char_set);
02039    ast_name->presentation = pri_to_ast_presentation(pri_name->presentation);
02040    ast_name->valid = 1;
02041 }
02042 
02043 /*!
02044  * \internal
02045  * \brief Convert libpri party number into asterisk party number.
02046  * \since 1.8
02047  *
02048  * \param ast_number Asterisk party number structure to fill.  Must already be set initialized.
02049  * \param pri_number libpri party number structure containing source information.
02050  * \param pri PRI span control structure.
02051  *
02052  * \note The filled in ast_number structure needs to be destroyed by
02053  * ast_party_number_free() when it is no longer needed.
02054  *
02055  * \return Nothing
02056  */
02057 static void sig_pri_party_number_convert(struct ast_party_number *ast_number, const struct pri_party_number *pri_number, struct sig_pri_span *pri)
02058 {
02059    char number[AST_MAX_EXTENSION];
02060 
02061    apply_plan_to_existing_number(number, sizeof(number), pri, pri_number->str,
02062       pri_number->plan);
02063    ast_number->str = ast_strdup(number);
02064    ast_number->plan = pri_number->plan;
02065    ast_number->presentation = pri_to_ast_presentation(pri_number->presentation);
02066    ast_number->valid = 1;
02067 }
02068 
02069 /*!
02070  * \internal
02071  * \brief Convert libpri party id into asterisk party id.
02072  * \since 1.8
02073  *
02074  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
02075  * \param pri_id libpri party id structure containing source information.
02076  * \param pri PRI span control structure.
02077  *
02078  * \note The filled in ast_id structure needs to be destroyed by
02079  * ast_party_id_free() when it is no longer needed.
02080  *
02081  * \return Nothing
02082  */
02083 static void sig_pri_party_id_convert(struct ast_party_id *ast_id, const struct pri_party_id *pri_id, struct sig_pri_span *pri)
02084 {
02085    if (pri_id->name.valid) {
02086       sig_pri_party_name_convert(&ast_id->name, &pri_id->name);
02087    }
02088    if (pri_id->number.valid) {
02089       sig_pri_party_number_convert(&ast_id->number, &pri_id->number, pri);
02090    }
02091 #if defined(HAVE_PRI_SUBADDR)
02092    if (pri_id->subaddress.valid) {
02093       sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
02094    }
02095 #endif   /* defined(HAVE_PRI_SUBADDR) */
02096 }
02097 
02098 /*!
02099  * \internal
02100  * \brief Convert libpri redirecting information into asterisk redirecting information.
02101  * \since 1.8
02102  *
02103  * \param ast_redirecting Asterisk redirecting structure to fill.
02104  * \param pri_redirecting libpri redirecting structure containing source information.
02105  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
02106  * \param pri PRI span control structure.
02107  *
02108  * \note The filled in ast_redirecting structure needs to be destroyed by
02109  * ast_party_redirecting_free() when it is no longer needed.
02110  *
02111  * \return Nothing
02112  */
02113 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
02114    const struct pri_party_redirecting *pri_redirecting,
02115    const struct ast_party_redirecting *ast_guide,
02116    struct sig_pri_span *pri)
02117 {
02118    ast_party_redirecting_set_init(ast_redirecting, ast_guide);
02119 
02120    sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
02121    sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
02122    ast_redirecting->count = pri_redirecting->count;
02123    ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
02124 }
02125 
02126 /*!
02127  * \internal
02128  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
02129  * \since 1.8
02130  *
02131  * \param msn_patterns Comma separated list of MSN patterns to match.
02132  * \param exten Extension to match in the MSN list.
02133  *
02134  * \retval 1 if matches.
02135  * \retval 0 if no match.
02136  */
02137 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
02138 {
02139    char *pattern;
02140    char *msn_list;
02141    char *list_tail;
02142 
02143    msn_list = ast_strdupa(msn_patterns);
02144 
02145    list_tail = NULL;
02146    pattern = strtok_r(msn_list, ",", &list_tail);
02147    while (pattern) {
02148       pattern = ast_strip(pattern);
02149       if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
02150          /* Extension matched the pattern. */
02151          return 1;
02152       }
02153       pattern = strtok_r(NULL, ",", &list_tail);
02154    }
02155    /* Did not match any pattern in the list. */
02156    return 0;
02157 }
02158 
02159 #if defined(HAVE_PRI_MCID)
02160 /*!
02161  * \internal
02162  * \brief Append the given party id to the event string.
02163  * \since 1.8
02164  *
02165  * \param msg Event message string being built.
02166  * \param prefix Prefix to add to the party id lines.
02167  * \param party Party information to encode.
02168  *
02169  * \return Nothing
02170  */
02171 static void sig_pri_event_party_id(struct ast_str **msg, const char *prefix, struct ast_party_id *party)
02172 {
02173    int pres;
02174 
02175    /* Combined party presentation */
02176    pres = ast_party_id_presentation(party);
02177    ast_str_append(msg, 0, "%sPres: %d (%s)\r\n", prefix, pres,
02178       ast_describe_caller_presentation(pres));
02179 
02180    /* Party number */
02181    ast_str_append(msg, 0, "%sNumValid: %d\r\n", prefix,
02182       (unsigned) party->number.valid);
02183    ast_str_append(msg, 0, "%sNum: %s\r\n", prefix,
02184       S_COR(party->number.valid, party->number.str, ""));
02185    ast_str_append(msg, 0, "%ston: %d\r\n", prefix, party->number.plan);
02186    if (party->number.valid) {
02187       ast_str_append(msg, 0, "%sNumPlan: %d\r\n", prefix, party->number.plan);
02188       ast_str_append(msg, 0, "%sNumPres: %d (%s)\r\n", prefix,
02189          party->number.presentation,
02190          ast_describe_caller_presentation(party->number.presentation));
02191    }
02192 
02193    /* Party name */
02194    ast_str_append(msg, 0, "%sNameValid: %d\r\n", prefix,
02195       (unsigned) party->name.valid);
02196    ast_str_append(msg, 0, "%sName: %s\r\n", prefix,
02197       S_COR(party->name.valid, party->name.str, ""));
02198    if (party->name.valid) {
02199       ast_str_append(msg, 0, "%sNameCharSet: %s\r\n", prefix,
02200          ast_party_name_charset_describe(party->name.char_set));
02201       ast_str_append(msg, 0, "%sNamePres: %d (%s)\r\n", prefix,
02202          party->name.presentation,
02203          ast_describe_caller_presentation(party->name.presentation));
02204    }
02205 
02206 #if defined(HAVE_PRI_SUBADDR)
02207    /* Party subaddress */
02208    if (party->subaddress.valid) {
02209       static const char subaddress[] = "Subaddr";
02210 
02211       ast_str_append(msg, 0, "%s%s: %s\r\n", prefix, subaddress,
02212          S_OR(party->subaddress.str, ""));
02213       ast_str_append(msg, 0, "%s%sType: %d\r\n", prefix, subaddress,
02214          party->subaddress.type);
02215       ast_str_append(msg, 0, "%s%sOdd: %d\r\n", prefix, subaddress,
02216          party->subaddress.odd_even_indicator);
02217    }
02218 #endif   /* defined(HAVE_PRI_SUBADDR) */
02219 }
02220 #endif   /* defined(HAVE_PRI_MCID) */
02221 
02222 #if defined(HAVE_PRI_MCID)
02223 /*!
02224  * \internal
02225  * \brief Handle the MCID event.
02226  * \since 1.8
02227  *
02228  * \param pri PRI span control structure.
02229  * \param mcid MCID event parameters.
02230  * \param owner Asterisk channel associated with the call.
02231  * NULL if Asterisk no longer has the ast_channel struct.
02232  *
02233  * \note Assumes the pri->lock is already obtained.
02234  * \note Assumes the owner channel lock is already obtained if still present.
02235  *
02236  * \return Nothing
02237  */
02238 static void sig_pri_mcid_event(struct sig_pri_span *pri, const struct pri_subcmd_mcid_req *mcid, struct ast_channel *owner)
02239 {
02240    struct ast_channel *chans[1];
02241    struct ast_str *msg;
02242    struct ast_party_id party;
02243 
02244    msg = ast_str_create(4096);
02245    if (!msg) {
02246       return;
02247    }
02248 
02249    if (owner) {
02250       /* The owner channel is present. */
02251       ast_str_append(&msg, 0, "Channel: %s\r\n", owner->name);
02252       ast_str_append(&msg, 0, "UniqueID: %s\r\n", owner->uniqueid);
02253 
02254       sig_pri_event_party_id(&msg, "CallerID", &owner->connected.id);
02255    } else {
02256       /*
02257        * Since we no longer have an owner channel,
02258        * we have to use the caller information supplied by libpri.
02259        */
02260       ast_party_id_init(&party);
02261       sig_pri_party_id_convert(&party, &mcid->originator, pri);
02262       sig_pri_event_party_id(&msg, "CallerID", &party);
02263       ast_party_id_free(&party);
02264    }
02265 
02266    /* Always use libpri's called party information. */
02267    ast_party_id_init(&party);
02268    sig_pri_party_id_convert(&party, &mcid->answerer, pri);
02269    sig_pri_event_party_id(&msg, "ConnectedID", &party);
02270    ast_party_id_free(&party);
02271 
02272    chans[0] = owner;
02273    ast_manager_event_multichan(EVENT_FLAG_CALL, "MCID", owner ? 1 : 0, chans, "%s",
02274       ast_str_buffer(msg));
02275    ast_free(msg);
02276 }
02277 #endif   /* defined(HAVE_PRI_MCID) */
02278 
02279 #if defined(HAVE_PRI_TRANSFER)
02280 struct xfer_rsp_data {
02281    struct sig_pri_span *pri;
02282    /*! Call to send transfer success/fail response over. */
02283    q931_call *call;
02284    /*! Invocation ID to use when sending a reply to the transfer request. */
02285    int invoke_id;
02286 };
02287 #endif   /* defined(HAVE_PRI_TRANSFER) */
02288 
02289 #if defined(HAVE_PRI_TRANSFER)
02290 /*!
02291  * \internal
02292  * \brief Send the transfer success/fail response message.
02293  * \since 1.8
02294  *
02295  * \param data Callback user data pointer
02296  * \param is_successful TRUE if the transfer was successful.
02297  *
02298  * \return Nothing
02299  */
02300 static void sig_pri_transfer_rsp(void *data, int is_successful)
02301 {
02302    struct xfer_rsp_data *rsp = data;
02303 
02304    pri_transfer_rsp(rsp->pri->pri, rsp->call, rsp->invoke_id, is_successful);
02305 }
02306 #endif   /* defined(HAVE_PRI_TRANSFER) */
02307 
02308 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
02309 /*!
02310  * \brief Protocol callback to indicate if transfer will happen.
02311  * \since 1.8
02312  *
02313  * \param data Callback user data pointer
02314  * \param is_successful TRUE if the transfer will happen.
02315  *
02316  * \return Nothing
02317  */
02318 typedef void (*xfer_rsp_callback)(void *data, int is_successful);
02319 #endif   /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
02320 
02321 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
02322 /*!
02323  * \internal
02324  * \brief Attempt to transfer the two calls to each other.
02325  * \since 1.8
02326  *
02327  * \param pri PRI span control structure.
02328  * \param call_1_pri First call involved in the transfer. (transferee; usually on hold)
02329  * \param call_1_held TRUE if call_1_pri is on hold.
02330  * \param call_2_pri Second call involved in the transfer. (target; usually active/ringing)
02331  * \param call_2_held TRUE if call_2_pri is on hold.
02332  * \param rsp_callback Protocol callback to indicate if transfer will happen. NULL if not used.
02333  * \param data Callback user data pointer
02334  *
02335  * \note Assumes the pri->lock is already obtained.
02336  *
02337  * \retval 0 on success.
02338  * \retval -1 on error.
02339  */
02340 static int sig_pri_attempt_transfer(struct sig_pri_span *pri, q931_call *call_1_pri, int call_1_held, q931_call *call_2_pri, int call_2_held, xfer_rsp_callback rsp_callback, void *data)
02341 {
02342    struct attempt_xfer_call {
02343       q931_call *pri;
02344       struct ast_channel *ast;
02345       int held;
02346       int chanpos;
02347    };
02348    int retval;
02349    struct ast_channel *transferee;
02350    struct attempt_xfer_call *call_1;
02351    struct attempt_xfer_call *call_2;
02352    struct attempt_xfer_call *swap_call;
02353    struct attempt_xfer_call c1;
02354    struct attempt_xfer_call c2;
02355 
02356    c1.pri = call_1_pri;
02357    c1.held = call_1_held;
02358    call_1 = &c1;
02359 
02360    c2.pri = call_2_pri;
02361    c2.held = call_2_held;
02362    call_2 = &c2;
02363 
02364    call_1->chanpos = pri_find_principle_by_call(pri, call_1->pri);
02365    call_2->chanpos = pri_find_principle_by_call(pri, call_2->pri);
02366    if (call_1->chanpos < 0 || call_2->chanpos < 0) {
02367       /* Calls not found in span control. */
02368       if (rsp_callback) {
02369          /* Transfer failed. */
02370          rsp_callback(data, 0);
02371       }
02372       return -1;
02373    }
02374 
02375    /* Attempt to make transferee and target consistent. */
02376    if (!call_1->held && call_2->held) {
02377       /*
02378        * Swap call_1 and call_2 to make call_1 the transferee(held call)
02379        * and call_2 the target(active call).
02380        */
02381       swap_call = call_1;
02382       call_1 = call_2;
02383       call_2 = swap_call;
02384    }
02385 
02386    /* Deadlock avoidance is attempted. */
02387    sig_pri_lock_private(pri->pvts[call_1->chanpos]);
02388    sig_pri_lock_owner(pri, call_1->chanpos);
02389    sig_pri_lock_private(pri->pvts[call_2->chanpos]);
02390    sig_pri_lock_owner(pri, call_2->chanpos);
02391 
02392    call_1->ast = pri->pvts[call_1->chanpos]->owner;
02393    call_2->ast = pri->pvts[call_2->chanpos]->owner;
02394    if (!call_1->ast || !call_2->ast) {
02395       /* At least one owner is not present. */
02396       if (call_1->ast) {
02397          ast_channel_unlock(call_1->ast);
02398       }
02399       if (call_2->ast) {
02400          ast_channel_unlock(call_2->ast);
02401       }
02402       sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
02403       sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
02404       if (rsp_callback) {
02405          /* Transfer failed. */
02406          rsp_callback(data, 0);
02407       }
02408       return -1;
02409    }
02410 
02411    for (;;) {
02412       transferee = ast_bridged_channel(call_1->ast);
02413       if (transferee) {
02414          break;
02415       }
02416 
02417       /* Try masquerading the other way. */
02418       swap_call = call_1;
02419       call_1 = call_2;
02420       call_2 = swap_call;
02421 
02422       transferee = ast_bridged_channel(call_1->ast);
02423       if (transferee) {
02424          break;
02425       }
02426 
02427       /* Could not transfer.  Neither call is bridged. */
02428       ast_channel_unlock(call_1->ast);
02429       ast_channel_unlock(call_2->ast);
02430       sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
02431       sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
02432 
02433       if (rsp_callback) {
02434          /* Transfer failed. */
02435          rsp_callback(data, 0);
02436       }
02437       return -1;
02438    }
02439 
02440    ast_verb(3, "TRANSFERRING %s to %s\n", call_1->ast->name, call_2->ast->name);
02441 
02442    /*
02443     * Setup transfer masquerade.
02444     *
02445     * Note:  There is an extremely nasty deadlock avoidance issue
02446     * with ast_channel_transfer_masquerade().  Deadlock may be possible if
02447     * the channels involved are proxies (chan_agent channels) and
02448     * it is called with locks.  Unfortunately, there is no simple
02449     * or even merely difficult way to guarantee deadlock avoidance
02450     * and still be able to send an ECT success response without the
02451     * possibility of the bridged channel hanging up on us.
02452     */
02453    ast_mutex_unlock(&pri->lock);
02454    retval = ast_channel_transfer_masquerade(
02455       call_2->ast,
02456       &call_2->ast->connected,
02457       call_2->held,
02458       transferee,
02459       &call_1->ast->connected,
02460       call_1->held);
02461 
02462    /* Reacquire the pri->lock to hold off completion of the transfer masquerade. */
02463    ast_mutex_lock(&pri->lock);
02464 
02465    ast_channel_unlock(call_1->ast);
02466    ast_channel_unlock(call_2->ast);
02467    sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
02468    sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
02469 
02470    if (rsp_callback) {
02471       /*
02472        * Report transfer status.
02473        *
02474        * Must do the callback before the masquerade completes to ensure
02475        * that the protocol message goes out before the call leg is
02476        * disconnected.
02477        */
02478       rsp_callback(data, retval ? 0 : 1);
02479    }
02480    return retval;
02481 }
02482 #endif   /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
02483 
02484 #if defined(HAVE_PRI_CCSS)
02485 /*!
02486  * \internal
02487  * \brief Compare the CC agent private data by libpri cc_id.
02488  * \since 1.8
02489  *
02490  * \param obj pointer to the (user-defined part) of an object.
02491  * \param arg callback argument from ao2_callback()
02492  * \param flags flags from ao2_callback()
02493  *
02494  * \return values are a combination of enum _cb_results.
02495  */
02496 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
02497 {
02498    struct ast_cc_agent *agent_1 = obj;
02499    struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
02500    struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
02501 
02502    return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
02503       && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
02504 }
02505 #endif   /* defined(HAVE_PRI_CCSS) */
02506 
02507 #if defined(HAVE_PRI_CCSS)
02508 /*!
02509  * \internal
02510  * \brief Find the CC agent by libpri cc_id.
02511  * \since 1.8
02512  *
02513  * \param pri PRI span control structure.
02514  * \param cc_id CC record ID to find.
02515  *
02516  * \note
02517  * Since agents are refcounted, and this function returns
02518  * a reference to the agent, it is imperative that you decrement
02519  * the refcount of the agent once you have finished using it.
02520  *
02521  * \retval agent on success.
02522  * \retval NULL not found.
02523  */
02524 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_span *pri, long cc_id)
02525 {
02526    struct sig_pri_cc_agent_prv finder = {
02527       .pri = pri,
02528       .cc_id = cc_id,
02529    };
02530 
02531    return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
02532       sig_pri_cc_type_name);
02533 }
02534 #endif   /* defined(HAVE_PRI_CCSS) */
02535 
02536 #if defined(HAVE_PRI_CCSS)
02537 /*!
02538  * \internal
02539  * \brief Compare the CC monitor instance by libpri cc_id.
02540  * \since 1.8
02541  *
02542  * \param obj pointer to the (user-defined part) of an object.
02543  * \param arg callback argument from ao2_callback()
02544  * \param flags flags from ao2_callback()
02545  *
02546  * \return values are a combination of enum _cb_results.
02547  */
02548 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
02549 {
02550    struct sig_pri_cc_monitor_instance *monitor_1 = obj;
02551    struct sig_pri_cc_monitor_instance *monitor_2 = arg;
02552 
02553    return (monitor_1->pri == monitor_2->pri
02554       && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
02555 }
02556 #endif   /* defined(HAVE_PRI_CCSS) */
02557 
02558 #if defined(HAVE_PRI_CCSS)
02559 /*!
02560  * \internal
02561  * \brief Find the CC monitor instance by libpri cc_id.
02562  * \since 1.8
02563  *
02564  * \param pri PRI span control structure.
02565  * \param cc_id CC record ID to find.
02566  *
02567  * \note
02568  * Since monitor_instances are refcounted, and this function returns
02569  * a reference to the instance, it is imperative that you decrement
02570  * the refcount of the instance once you have finished using it.
02571  *
02572  * \retval monitor_instance on success.
02573  * \retval NULL not found.
02574  */
02575 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_span *pri, long cc_id)
02576 {
02577    struct sig_pri_cc_monitor_instance finder = {
02578       .pri = pri,
02579       .cc_id = cc_id,
02580    };
02581 
02582    return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
02583 }
02584 #endif   /* defined(HAVE_PRI_CCSS) */
02585 
02586 #if defined(HAVE_PRI_CCSS)
02587 /*!
02588  * \internal
02589  * \brief Destroy the given monitor instance.
02590  * \since 1.8
02591  *
02592  * \param data Monitor instance to destroy.
02593  *
02594  * \return Nothing
02595  */
02596 static void sig_pri_cc_monitor_instance_destroy(void *data)
02597 {
02598    struct sig_pri_cc_monitor_instance *monitor_instance = data;
02599 
02600    if (monitor_instance->cc_id != -1) {
02601       ast_mutex_lock(&monitor_instance->pri->lock);
02602       pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
02603       ast_mutex_unlock(&monitor_instance->pri->lock);
02604    }
02605    monitor_instance->pri->calls->module_unref();
02606 }
02607 #endif   /* defined(HAVE_PRI_CCSS) */
02608 
02609 #if defined(HAVE_PRI_CCSS)
02610 /*!
02611  * \internal
02612  * \brief Construct a new monitor instance.
02613  * \since 1.8
02614  *
02615  * \param core_id CC core ID.
02616  * \param pri PRI span control structure.
02617  * \param cc_id CC record ID.
02618  * \param device_name Name of device (Asterisk channel name less sequence number).
02619  *
02620  * \note
02621  * Since monitor_instances are refcounted, and this function returns
02622  * a reference to the instance, it is imperative that you decrement
02623  * the refcount of the instance once you have finished using it.
02624  *
02625  * \retval monitor_instance on success.
02626  * \retval NULL on error.
02627  */
02628 static struct sig_pri_cc_monitor_instance *sig_pri_cc_monitor_instance_init(int core_id, struct sig_pri_span *pri, long cc_id, const char *device_name)
02629 {
02630    struct sig_pri_cc_monitor_instance *monitor_instance;
02631 
02632    if (!pri->calls->module_ref || !pri->calls->module_unref) {
02633       return NULL;
02634    }
02635 
02636    monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
02637       sig_pri_cc_monitor_instance_destroy);
02638    if (!monitor_instance) {
02639       return NULL;
02640    }
02641 
02642    monitor_instance->cc_id = cc_id;
02643    monitor_instance->pri = pri;
02644    monitor_instance->core_id = core_id;
02645    strcpy(monitor_instance->name, device_name);
02646 
02647    pri->calls->module_ref();
02648 
02649    ao2_link(sig_pri_cc_monitors, monitor_instance);
02650    return monitor_instance;
02651 }
02652 #endif   /* defined(HAVE_PRI_CCSS) */
02653 
02654 #if defined(HAVE_PRI_CCSS)
02655 /*!
02656  * \internal
02657  * \brief Announce to the CC core that protocol CC monitor is available for this call.
02658  * \since 1.8
02659  *
02660  * \param pri PRI span control structure.
02661  * \param chanpos Channel position in the span.
02662  * \param cc_id CC record ID.
02663  * \param service CCBS/CCNR indication.
02664  *
02665  * \note Assumes the pri->lock is already obtained.
02666  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
02667  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
02668  *
02669  * \retval 0 on success.
02670  * \retval -1 on error.
02671  */
02672 static int sig_pri_cc_available(struct sig_pri_span *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
02673 {
02674    struct sig_pri_chan *pvt;
02675    struct ast_cc_config_params *cc_params;
02676    struct sig_pri_cc_monitor_instance *monitor;
02677    enum ast_cc_monitor_policies monitor_policy;
02678    int core_id;
02679    int res;
02680    char device_name[AST_CHANNEL_NAME];
02681    char dialstring[AST_CHANNEL_NAME];
02682 
02683    pvt = pri->pvts[chanpos];
02684 
02685    core_id = ast_cc_get_current_core_id(pvt->owner);
02686    if (core_id == -1) {
02687       return -1;
02688    }
02689 
02690    cc_params = ast_channel_get_cc_config_params(pvt->owner);
02691    if (!cc_params) {
02692       return -1;
02693    }
02694 
02695    res = -1;
02696    monitor_policy = ast_get_cc_monitor_policy(cc_params);
02697    switch (monitor_policy) {
02698    case AST_CC_MONITOR_NEVER:
02699       /* CCSS is not enabled. */
02700       break;
02701    case AST_CC_MONITOR_NATIVE:
02702    case AST_CC_MONITOR_ALWAYS:
02703       /*
02704        * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
02705        * later in the call to sig_pri_cc_generic_check().
02706        */
02707       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02708       sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
02709       monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
02710       if (!monitor) {
02711          break;
02712       }
02713       res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
02714          monitor);
02715       if (res) {
02716          monitor->cc_id = -1;
02717          ao2_unlink(sig_pri_cc_monitors, monitor);
02718          ao2_ref(monitor, -1);
02719       }
02720       break;
02721    case AST_CC_MONITOR_GENERIC:
02722       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
02723          sig_pri_get_orig_dialstring(pvt), service, NULL);
02724       /* Say it failed to force caller to cancel native CC. */
02725       break;
02726    }
02727    return res;
02728 }
02729 #endif   /* defined(HAVE_PRI_CCSS) */
02730 
02731 /*!
02732  * \internal
02733  * \brief Check if generic CC monitor is needed and request it.
02734  * \since 1.8
02735  *
02736  * \param pri PRI span control structure.
02737  * \param chanpos Channel position in the span.
02738  * \param service CCBS/CCNR indication.
02739  *
02740  * \note Assumes the pri->lock is already obtained.
02741  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
02742  *
02743  * \return Nothing
02744  */
02745 static void sig_pri_cc_generic_check(struct sig_pri_span *pri, int chanpos, enum ast_cc_service_type service)
02746 {
02747    struct ast_channel *owner;
02748    struct ast_cc_config_params *cc_params;
02749 #if defined(HAVE_PRI_CCSS)
02750    struct ast_cc_monitor *monitor;
02751    char device_name[AST_CHANNEL_NAME];
02752 #endif   /* defined(HAVE_PRI_CCSS) */
02753    enum ast_cc_monitor_policies monitor_policy;
02754    int core_id;
02755 
02756    if (!pri->pvts[chanpos]->outgoing) {
02757       /* This is not an outgoing call so it cannot be CC monitor. */
02758       return;
02759    }
02760 
02761    sig_pri_lock_owner(pri, chanpos);
02762    owner = pri->pvts[chanpos]->owner;
02763    if (!owner) {
02764       return;
02765    }
02766    core_id = ast_cc_get_current_core_id(owner);
02767    if (core_id == -1) {
02768       /* No CC core setup */
02769       goto done;
02770    }
02771 
02772    cc_params = ast_channel_get_cc_config_params(owner);
02773    if (!cc_params) {
02774       /* Could not get CC config parameters. */
02775       goto done;
02776    }
02777 
02778 #if defined(HAVE_PRI_CCSS)
02779    ast_channel_get_device_name(owner, device_name, sizeof(device_name));
02780    monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
02781    if (monitor) {
02782       /* CC monitor is already present so no need for generic CC. */
02783       ao2_ref(monitor, -1);
02784       goto done;
02785    }
02786 #endif   /* defined(HAVE_PRI_CCSS) */
02787 
02788    monitor_policy = ast_get_cc_monitor_policy(cc_params);
02789    switch (monitor_policy) {
02790    case AST_CC_MONITOR_NEVER:
02791       /* CCSS is not enabled. */
02792       break;
02793    case AST_CC_MONITOR_NATIVE:
02794       if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
02795          /* Request generic CC monitor. */
02796          ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
02797             sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
02798       }
02799       break;
02800    case AST_CC_MONITOR_ALWAYS:
02801       if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
02802          /*
02803           * Cannot monitor PTMP TE side since this is not defined.
02804           * We are playing the roll of a phone in this case and
02805           * a phone cannot monitor a party over the network without
02806           * protocol help.
02807           */
02808          break;
02809       }
02810       /*
02811        * We are either falling back or this is a PTMP NT span.
02812        * Request generic CC monitor.
02813        */
02814       ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
02815          sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
02816       break;
02817    case AST_CC_MONITOR_GENERIC:
02818       if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
02819          /* Request generic CC monitor. */
02820          ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
02821             sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
02822       }
02823       break;
02824    }
02825 
02826 done:
02827    ast_channel_unlock(owner);
02828 }
02829 
02830 #if defined(HAVE_PRI_CCSS)
02831 /*!
02832  * \internal
02833  * \brief The CC link canceled the CC instance.
02834  * \since 1.8
02835  *
02836  * \param pri PRI span control structure.
02837  * \param cc_id CC record ID.
02838  * \param is_agent TRUE if the cc_id is for an agent.
02839  *
02840  * \return Nothing
02841  */
02842 static void sig_pri_cc_link_canceled(struct sig_pri_span *pri, long cc_id, int is_agent)
02843 {
02844    if (is_agent) {
02845       struct ast_cc_agent *agent;
02846 
02847       agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
02848       if (!agent) {
02849          return;
02850       }
02851       ast_cc_failed(agent->core_id, "%s agent got canceled by link",
02852          sig_pri_cc_type_name);
02853       ao2_ref(agent, -1);
02854    } else {
02855       struct sig_pri_cc_monitor_instance *monitor;
02856 
02857       monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
02858       if (!monitor) {
02859          return;
02860       }
02861       monitor->cc_id = -1;
02862       ast_cc_monitor_failed(monitor->core_id, monitor->name,
02863          "%s monitor got canceled by link", sig_pri_cc_type_name);
02864       ao2_ref(monitor, -1);
02865    }
02866 }
02867 #endif   /* defined(HAVE_PRI_CCSS) */
02868 
02869 #if defined(HAVE_PRI_AOC_EVENTS)
02870 /*!
02871  * \internal
02872  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
02873  * \since 1.8
02874  *
02875  * \param value Value to convert to string.
02876  *
02877  * \return PRI_AOC_CHARGED_ITEM
02878  */
02879 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
02880 {
02881    switch (value) {
02882    case AST_AOC_CHARGED_ITEM_NA:
02883       return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
02884    case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
02885       return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
02886    case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
02887       return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
02888    case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
02889       return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
02890    case AST_AOC_CHARGED_ITEM_CALL_SETUP:
02891       return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
02892    case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
02893       return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
02894    case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
02895       return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
02896    }
02897    return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
02898 }
02899 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
02900 
02901 #if defined(HAVE_PRI_AOC_EVENTS)
02902 /*!
02903  * \internal
02904  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
02905  * \since 1.8
02906  *
02907  * \param value Value to convert to string.
02908  *
02909  * \return ast_aoc_charged_item
02910  */
02911 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
02912 {
02913    switch (value) {
02914    case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
02915       return AST_AOC_CHARGED_ITEM_NA;
02916    case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
02917       return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
02918    case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
02919       return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
02920    case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
02921       return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
02922    case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
02923       return AST_AOC_CHARGED_ITEM_CALL_SETUP;
02924    case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
02925       return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
02926    case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
02927       return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
02928    }
02929    return AST_AOC_CHARGED_ITEM_NA;
02930 }
02931 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
02932 
02933 #if defined(HAVE_PRI_AOC_EVENTS)
02934 /*!
02935  * \internal
02936  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
02937  * \since 1.8
02938  *
02939  * \return pri enum equivalent.
02940  */
02941 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
02942 {
02943    switch (mult) {
02944    case AST_AOC_MULT_ONETHOUSANDTH:
02945       return PRI_AOC_MULTIPLIER_THOUSANDTH;
02946    case AST_AOC_MULT_ONEHUNDREDTH:
02947       return PRI_AOC_MULTIPLIER_HUNDREDTH;
02948    case AST_AOC_MULT_ONETENTH:
02949       return PRI_AOC_MULTIPLIER_TENTH;
02950    case AST_AOC_MULT_ONE:
02951       return PRI_AOC_MULTIPLIER_ONE;
02952    case AST_AOC_MULT_TEN:
02953       return PRI_AOC_MULTIPLIER_TEN;
02954    case AST_AOC_MULT_HUNDRED:
02955       return PRI_AOC_MULTIPLIER_HUNDRED;
02956    case AST_AOC_MULT_THOUSAND:
02957       return PRI_AOC_MULTIPLIER_THOUSAND;
02958    default:
02959       return PRI_AOC_MULTIPLIER_ONE;
02960    }
02961 }
02962 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
02963 
02964 #if defined(HAVE_PRI_AOC_EVENTS)
02965 /*!
02966  * \internal
02967  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
02968  * \since 1.8
02969  *
02970  * \return ast enum equivalent.
02971  */
02972 static int sig_pri_aoc_multiplier_from_pri(const int mult)
02973 {
02974    switch (mult) {
02975    case PRI_AOC_MULTIPLIER_THOUSANDTH:
02976       return AST_AOC_MULT_ONETHOUSANDTH;
02977    case PRI_AOC_MULTIPLIER_HUNDREDTH:
02978       return AST_AOC_MULT_ONEHUNDREDTH;
02979    case PRI_AOC_MULTIPLIER_TENTH:
02980       return AST_AOC_MULT_ONETENTH;
02981    case PRI_AOC_MULTIPLIER_ONE:
02982       return AST_AOC_MULT_ONE;
02983    case PRI_AOC_MULTIPLIER_TEN:
02984       return AST_AOC_MULT_TEN;
02985    case PRI_AOC_MULTIPLIER_HUNDRED:
02986       return AST_AOC_MULT_HUNDRED;
02987    case PRI_AOC_MULTIPLIER_THOUSAND:
02988       return AST_AOC_MULT_THOUSAND;
02989    default:
02990       return AST_AOC_MULT_ONE;
02991    }
02992 }
02993 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
02994 
02995 #if defined(HAVE_PRI_AOC_EVENTS)
02996 /*!
02997  * \internal
02998  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
02999  * \since 1.8
03000  *
03001  * \param value Value to convert to ast representation
03002  *
03003  * \return PRI_AOC_TIME_SCALE
03004  */
03005 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
03006 {
03007    switch (value) {
03008    default:
03009    case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
03010       return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
03011    case AST_AOC_TIME_SCALE_TENTH_SECOND:
03012       return PRI_AOC_TIME_SCALE_TENTH_SECOND;
03013    case AST_AOC_TIME_SCALE_SECOND:
03014       return PRI_AOC_TIME_SCALE_SECOND;
03015    case AST_AOC_TIME_SCALE_TEN_SECOND:
03016       return PRI_AOC_TIME_SCALE_TEN_SECOND;
03017    case AST_AOC_TIME_SCALE_MINUTE:
03018       return PRI_AOC_TIME_SCALE_MINUTE;
03019    case AST_AOC_TIME_SCALE_HOUR:
03020       return PRI_AOC_TIME_SCALE_HOUR;
03021    case AST_AOC_TIME_SCALE_DAY:
03022       return PRI_AOC_TIME_SCALE_DAY;
03023    }
03024 }
03025 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03026 
03027 #if defined(HAVE_PRI_AOC_EVENTS)
03028 /*!
03029  * \internal
03030  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
03031  * \since 1.8
03032  *
03033  * \param value Value to convert to ast representation
03034  *
03035  * \return ast aoc time scale
03036  */
03037 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
03038 {
03039    switch (value) {
03040    default:
03041    case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
03042       return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
03043    case PRI_AOC_TIME_SCALE_TENTH_SECOND:
03044       return AST_AOC_TIME_SCALE_TENTH_SECOND;
03045    case PRI_AOC_TIME_SCALE_SECOND:
03046       return AST_AOC_TIME_SCALE_SECOND;
03047    case PRI_AOC_TIME_SCALE_TEN_SECOND:
03048       return AST_AOC_TIME_SCALE_TEN_SECOND;
03049    case PRI_AOC_TIME_SCALE_MINUTE:
03050       return AST_AOC_TIME_SCALE_MINUTE;
03051    case PRI_AOC_TIME_SCALE_HOUR:
03052       return AST_AOC_TIME_SCALE_HOUR;
03053    case PRI_AOC_TIME_SCALE_DAY:
03054       return AST_AOC_TIME_SCALE_DAY;
03055    }
03056    return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
03057 }
03058 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03059 
03060 #if defined(HAVE_PRI_AOC_EVENTS)
03061 /*!
03062  * \internal
03063  * \brief Handle AOC-S control frame
03064  * \since 1.8
03065  *
03066  * \param aoc_s AOC-S event parameters.
03067  * \param owner Asterisk channel associated with the call.
03068  * \param passthrough indicating if this message should be queued on the ast channel
03069  *
03070  * \note Assumes the pri->lock is already obtained.
03071  * \note Assumes the sig_pri private is locked
03072  * \note Assumes the owner channel lock is already obtained.
03073  *
03074  * \return Nothing
03075  */
03076 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
03077 {
03078    struct ast_aoc_decoded *decoded = NULL;
03079    struct ast_aoc_encoded *encoded = NULL;
03080    size_t encoded_size = 0;
03081    int idx;
03082 
03083    if (!owner || !aoc_s) {
03084       return;
03085    }
03086 
03087    if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
03088       return;
03089    }
03090 
03091    for (idx = 0; idx < aoc_s->num_items; ++idx) {
03092       enum ast_aoc_s_charged_item charged_item;
03093 
03094       charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
03095       if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
03096          /* Delete the unknown charged item from the list. */
03097          continue;
03098       }
03099       switch (aoc_s->item[idx].rate_type) {
03100       case PRI_AOC_RATE_TYPE_DURATION:
03101          ast_aoc_s_add_rate_duration(decoded,
03102             charged_item,
03103             aoc_s->item[idx].rate.duration.amount.cost,
03104             sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
03105             aoc_s->item[idx].rate.duration.currency,
03106             aoc_s->item[idx].rate.duration.time.length,
03107             sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
03108             aoc_s->item[idx].rate.duration.granularity.length,
03109             sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
03110             aoc_s->item[idx].rate.duration.charging_type);
03111          break;
03112       case PRI_AOC_RATE_TYPE_FLAT:
03113          ast_aoc_s_add_rate_flat(decoded,
03114             charged_item,
03115             aoc_s->item[idx].rate.flat.amount.cost,
03116             sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
03117             aoc_s->item[idx].rate.flat.currency);
03118          break;
03119       case PRI_AOC_RATE_TYPE_VOLUME:
03120          ast_aoc_s_add_rate_volume(decoded,
03121             charged_item,
03122             aoc_s->item[idx].rate.volume.unit,
03123             aoc_s->item[idx].rate.volume.amount.cost,
03124             sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
03125             aoc_s->item[idx].rate.volume.currency);
03126          break;
03127       case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
03128          ast_aoc_s_add_rate_special_charge_code(decoded,
03129             charged_item,
03130             aoc_s->item[idx].rate.special);
03131          break;
03132       case PRI_AOC_RATE_TYPE_FREE:
03133          ast_aoc_s_add_rate_free(decoded, charged_item, 0);
03134          break;
03135       case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
03136          ast_aoc_s_add_rate_free(decoded, charged_item, 1);
03137          break;
03138       default:
03139          ast_aoc_s_add_rate_na(decoded, charged_item);
03140          break;
03141       }
03142    }
03143 
03144    if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
03145       ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
03146    }
03147 
03148    ast_aoc_manager_event(decoded, owner);
03149 
03150    ast_aoc_destroy_decoded(decoded);
03151    ast_aoc_destroy_encoded(encoded);
03152 }
03153 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03154 
03155 #if defined(HAVE_PRI_AOC_EVENTS)
03156 /*!
03157  * \internal
03158  * \brief Generate AOC Request Response
03159  * \since 1.8
03160  *
03161  * \param aoc_request
03162  *
03163  * \note Assumes the pri->lock is already obtained.
03164  * \note Assumes the sig_pri private is locked
03165  * \note Assumes the owner channel lock is already obtained.
03166  *
03167  * \return Nothing
03168  */
03169 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
03170 {
03171    int request;
03172 
03173    if (!aoc_request) {
03174       return;
03175    }
03176 
03177    request = aoc_request->charging_request;
03178 
03179    if (request & PRI_AOC_REQUEST_S) {
03180       if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
03181          /* An AOC-S response must come from the other side, so save off this invoke_id
03182           * and see if an AOC-S message comes in before the call is answered. */
03183          pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
03184          pvt->aoc_s_request_invoke_id_valid = 1;
03185 
03186       } else {
03187          pri_aoc_s_request_response_send(pvt->pri->pri,
03188             call,
03189             aoc_request->invoke_id,
03190             NULL);
03191       }
03192    }
03193 
03194    if (request & PRI_AOC_REQUEST_D) {
03195       if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
03196          pri_aoc_de_request_response_send(pvt->pri->pri,
03197             call,
03198             PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
03199             aoc_request->invoke_id);
03200       } else {
03201          pri_aoc_de_request_response_send(pvt->pri->pri,
03202             call,
03203             PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
03204             aoc_request->invoke_id);
03205       }
03206    }
03207 
03208    if (request & PRI_AOC_REQUEST_E) {
03209       if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
03210          pri_aoc_de_request_response_send(pvt->pri->pri,
03211             call,
03212             PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
03213             aoc_request->invoke_id);
03214       } else {
03215          pri_aoc_de_request_response_send(pvt->pri->pri,
03216             call,
03217             PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
03218             aoc_request->invoke_id);
03219       }
03220    }
03221 }
03222 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03223 
03224 #if defined(HAVE_PRI_AOC_EVENTS)
03225 /*!
03226  * \internal
03227  * \brief Generate AOC-D AST_CONTROL_AOC frame
03228  * \since 1.8
03229  *
03230  * \param aoc_e AOC-D event parameters.
03231  * \param owner Asterisk channel associated with the call.
03232  * \param passthrough indicating if this message should be queued on the ast channel
03233  *
03234  * \note Assumes the pri->lock is already obtained.
03235  * \note Assumes the sig_pri private is locked
03236  * \note Assumes the owner channel lock is already obtained.
03237  *
03238  * \return Nothing
03239  */
03240 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
03241 {
03242    struct ast_aoc_decoded *decoded = NULL;
03243    struct ast_aoc_encoded *encoded = NULL;
03244    size_t encoded_size = 0;
03245    enum ast_aoc_charge_type type;
03246 
03247    if (!owner || !aoc_d) {
03248       return;
03249    }
03250 
03251    switch (aoc_d->charge) {
03252    case PRI_AOC_DE_CHARGE_CURRENCY:
03253       type = AST_AOC_CHARGE_CURRENCY;
03254       break;
03255    case PRI_AOC_DE_CHARGE_UNITS:
03256       type = AST_AOC_CHARGE_UNIT;
03257       break;
03258    case PRI_AOC_DE_CHARGE_FREE:
03259       type = AST_AOC_CHARGE_FREE;
03260       break;
03261    default:
03262       type = AST_AOC_CHARGE_NA;
03263       break;
03264    }
03265 
03266    if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
03267       return;
03268    }
03269 
03270    switch (aoc_d->billing_accumulation) {
03271    default:
03272       ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
03273          aoc_d->billing_accumulation);
03274       /* Fall through */
03275    case 0:/* subTotal */
03276       ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
03277       break;
03278    case 1:/* total */
03279       ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
03280       break;
03281    }
03282 
03283    switch (aoc_d->billing_id) {
03284    case PRI_AOC_D_BILLING_ID_NORMAL:
03285       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
03286       break;
03287    case PRI_AOC_D_BILLING_ID_REVERSE:
03288       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
03289       break;
03290    case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
03291       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
03292       break;
03293    case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
03294    default:
03295       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
03296       break;
03297    }
03298 
03299    switch (aoc_d->charge) {
03300    case PRI_AOC_DE_CHARGE_CURRENCY:
03301       ast_aoc_set_currency_info(decoded,
03302          aoc_d->recorded.money.amount.cost,
03303          sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
03304          aoc_d->recorded.money.currency);
03305       break;
03306    case PRI_AOC_DE_CHARGE_UNITS:
03307       {
03308          int i;
03309          for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
03310             /* if type or number are negative, then they are not present */
03311             ast_aoc_add_unit_entry(decoded,
03312                (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
03313                aoc_d->recorded.unit.item[i].number,
03314                (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
03315                aoc_d->recorded.unit.item[i].type);
03316          }
03317       }
03318       break;
03319    }
03320 
03321    if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
03322       ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
03323    }
03324 
03325    ast_aoc_manager_event(decoded, owner);
03326 
03327    ast_aoc_destroy_decoded(decoded);
03328    ast_aoc_destroy_encoded(encoded);
03329 }
03330 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03331 
03332 #if defined(HAVE_PRI_AOC_EVENTS)
03333 /*!
03334  * \internal
03335  * \brief Generate AOC-E AST_CONTROL_AOC frame
03336  * \since 1.8
03337  *
03338  * \param aoc_e AOC-E event parameters.
03339  * \param owner Asterisk channel associated with the call.
03340  * \param passthrough indicating if this message should be queued on the ast channel
03341  *
03342  * \note Assumes the pri->lock is already obtained.
03343  * \note Assumes the sig_pri private is locked
03344  * \note Assumes the owner channel lock is already obtained.
03345  * \note owner channel may be NULL. In that case, generate event only
03346  *
03347  * \return Nothing
03348  */
03349 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
03350 {
03351    struct ast_aoc_decoded *decoded = NULL;
03352    struct ast_aoc_encoded *encoded = NULL;
03353    size_t encoded_size = 0;
03354    enum ast_aoc_charge_type type;
03355 
03356    if (!aoc_e) {
03357       return;
03358    }
03359 
03360    switch (aoc_e->charge) {
03361    case PRI_AOC_DE_CHARGE_CURRENCY:
03362       type = AST_AOC_CHARGE_CURRENCY;
03363       break;
03364    case PRI_AOC_DE_CHARGE_UNITS:
03365       type = AST_AOC_CHARGE_UNIT;
03366       break;
03367    case PRI_AOC_DE_CHARGE_FREE:
03368       type = AST_AOC_CHARGE_FREE;
03369       break;
03370    default:
03371       type = AST_AOC_CHARGE_NA;
03372       break;
03373    }
03374 
03375    if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
03376       return;
03377    }
03378 
03379    switch (aoc_e->associated.charging_type) {
03380    case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
03381       if (!aoc_e->associated.charge.number.valid) {
03382          break;
03383       }
03384       ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
03385       break;
03386    case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
03387       ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
03388       break;
03389    default:
03390       break;
03391    }
03392 
03393    switch (aoc_e->billing_id) {
03394    case PRI_AOC_E_BILLING_ID_NORMAL:
03395       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
03396       break;
03397    case PRI_AOC_E_BILLING_ID_REVERSE:
03398       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
03399       break;
03400    case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
03401       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
03402       break;
03403    case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
03404       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
03405       break;
03406    case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
03407       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
03408       break;
03409    case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
03410       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
03411       break;
03412    case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
03413       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
03414       break;
03415    case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
03416       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
03417       break;
03418    case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
03419    default:
03420       ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
03421       break;
03422    }
03423 
03424    switch (aoc_e->charge) {
03425    case PRI_AOC_DE_CHARGE_CURRENCY:
03426       ast_aoc_set_currency_info(decoded,
03427          aoc_e->recorded.money.amount.cost,
03428          sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
03429          aoc_e->recorded.money.currency);
03430       break;
03431    case PRI_AOC_DE_CHARGE_UNITS:
03432       {
03433          int i;
03434          for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
03435             /* if type or number are negative, then they are not present */
03436             ast_aoc_add_unit_entry(decoded,
03437                (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
03438                aoc_e->recorded.unit.item[i].number,
03439                (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
03440                aoc_e->recorded.unit.item[i].type);
03441          }
03442       }
03443    }
03444 
03445    if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
03446       ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
03447    }
03448 
03449    ast_aoc_manager_event(decoded, owner);
03450 
03451    ast_aoc_destroy_decoded(decoded);
03452    ast_aoc_destroy_encoded(encoded);
03453 }
03454 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03455 
03456 #if defined(HAVE_PRI_AOC_EVENTS)
03457 /*!
03458  * \internal
03459  * \brief send an AOC-S message on the current call
03460  *
03461  * \param pvt sig_pri private channel structure.
03462  * \param generic decoded ast AOC message
03463  *
03464  * \return Nothing
03465  *
03466  * \note Assumes that the PRI lock is already obtained.
03467  */
03468 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
03469 {
03470    struct pri_subcmd_aoc_s aoc_s = { 0, };
03471    const struct ast_aoc_s_entry *entry;
03472    int idx;
03473 
03474    for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
03475       if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
03476          break;
03477       }
03478 
03479       aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
03480 
03481       switch (entry->rate_type) {
03482       case AST_AOC_RATE_TYPE_DURATION:
03483          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
03484          aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
03485          aoc_s.item[idx].rate.duration.amount.multiplier =
03486             sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
03487          aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
03488          aoc_s.item[idx].rate.duration.time.scale =
03489             sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
03490          aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
03491          aoc_s.item[idx].rate.duration.granularity.scale =
03492             sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
03493          aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
03494 
03495          if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
03496             ast_copy_string(aoc_s.item[idx].rate.duration.currency,
03497                entry->rate.duration.currency_name,
03498                sizeof(aoc_s.item[idx].rate.duration.currency));
03499          }
03500          break;
03501       case AST_AOC_RATE_TYPE_FLAT:
03502          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
03503          aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
03504          aoc_s.item[idx].rate.flat.amount.multiplier =
03505             sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
03506 
03507          if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
03508             ast_copy_string(aoc_s.item[idx].rate.flat.currency,
03509                entry->rate.flat.currency_name,
03510                sizeof(aoc_s.item[idx].rate.flat.currency));
03511          }
03512          break;
03513       case AST_AOC_RATE_TYPE_VOLUME:
03514          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_VOLUME;
03515          aoc_s.item[idx].rate.volume.unit = entry->rate.volume.volume_unit;
03516          aoc_s.item[idx].rate.volume.amount.cost = entry->rate.volume.amount;
03517          aoc_s.item[idx].rate.volume.amount.multiplier =
03518             sig_pri_aoc_multiplier_from_ast(entry->rate.volume.multiplier);
03519 
03520          if (!ast_strlen_zero(entry->rate.volume.currency_name)) {
03521             ast_copy_string(aoc_s.item[idx].rate.volume.currency,
03522                entry->rate.volume.currency_name,
03523                sizeof(aoc_s.item[idx].rate.volume.currency));
03524          }
03525          break;
03526       case AST_AOC_RATE_TYPE_SPECIAL_CODE:
03527          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_SPECIAL_CODE;
03528          aoc_s.item[idx].rate.special = entry->rate.special_code;
03529          break;
03530       case AST_AOC_RATE_TYPE_FREE:
03531          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE;
03532          break;
03533       case AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
03534          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
03535          break;
03536       default:
03537       case AST_AOC_RATE_TYPE_NA:
03538          aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_NOT_AVAILABLE;
03539          break;
03540       }
03541    }
03542    aoc_s.num_items = idx;
03543 
03544    /* if this rate should be sent as a response to an AOC-S request we will
03545     * have an aoc_s_request_invoke_id associated with this pvt */
03546    if (pvt->aoc_s_request_invoke_id_valid) {
03547       pri_aoc_s_request_response_send(pvt->pri->pri, pvt->call, pvt->aoc_s_request_invoke_id, &aoc_s);
03548       pvt->aoc_s_request_invoke_id_valid = 0;
03549    } else {
03550       pri_aoc_s_send(pvt->pri->pri, pvt->call, &aoc_s);
03551    }
03552 }
03553 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03554 
03555 #if defined(HAVE_PRI_AOC_EVENTS)
03556 /*!
03557  * \internal
03558  * \brief send an AOC-D message on the current call
03559  *
03560  * \param pvt sig_pri private channel structure.
03561  * \param generic decoded ast AOC message
03562  *
03563  * \return Nothing
03564  *
03565  * \note Assumes that the PRI lock is already obtained.
03566  */
03567 static void sig_pri_aoc_d_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
03568 {
03569    struct pri_subcmd_aoc_d aoc_d = { 0, };
03570 
03571    aoc_d.billing_accumulation = (ast_aoc_get_total_type(decoded) == AST_AOC_TOTAL) ? 1 : 0;
03572 
03573    switch (ast_aoc_get_billing_id(decoded)) {
03574    case AST_AOC_BILLING_NORMAL:
03575       aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NORMAL;
03576       break;
03577    case AST_AOC_BILLING_REVERSE_CHARGE:
03578       aoc_d.billing_id = PRI_AOC_D_BILLING_ID_REVERSE;
03579       break;
03580    case AST_AOC_BILLING_CREDIT_CARD:
03581       aoc_d.billing_id = PRI_AOC_D_BILLING_ID_CREDIT_CARD;
03582       break;
03583    case AST_AOC_BILLING_NA:
03584    default:
03585       aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NOT_AVAILABLE;
03586       break;
03587    }
03588 
03589    switch (ast_aoc_get_charge_type(decoded)) {
03590    case AST_AOC_CHARGE_FREE:
03591       aoc_d.charge = PRI_AOC_DE_CHARGE_FREE;
03592       break;
03593    case AST_AOC_CHARGE_CURRENCY:
03594       {
03595          const char *currency_name = ast_aoc_get_currency_name(decoded);
03596          aoc_d.charge = PRI_AOC_DE_CHARGE_CURRENCY;
03597          aoc_d.recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
03598          aoc_d.recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
03599          if (!ast_strlen_zero(currency_name)) {
03600             ast_copy_string(aoc_d.recorded.money.currency, currency_name, sizeof(aoc_d.recorded.money.currency));
03601          }
03602       }
03603       break;
03604    case AST_AOC_CHARGE_UNIT:
03605       {
03606          const struct ast_aoc_unit_entry *entry;
03607          int i;
03608          aoc_d.charge = PRI_AOC_DE_CHARGE_UNITS;
03609          for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
03610             if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_d.recorded.unit.item)) {
03611                if (entry->valid_amount) {
03612                   aoc_d.recorded.unit.item[i].number = entry->amount;
03613                } else {
03614                   aoc_d.recorded.unit.item[i].number = -1;
03615                }
03616                if (entry->valid_type) {
03617                   aoc_d.recorded.unit.item[i].type = entry->type;
03618                } else {
03619                   aoc_d.recorded.unit.item[i].type = -1;
03620                }
03621                aoc_d.recorded.unit.num_items++;
03622             } else {
03623                break;
03624             }
03625          }
03626       }
03627       break;
03628    case AST_AOC_CHARGE_NA:
03629    default:
03630       aoc_d.charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
03631       break;
03632    }
03633 
03634    pri_aoc_d_send(pvt->pri->pri, pvt->call, &aoc_d);
03635 }
03636 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03637 
03638 #if defined(HAVE_PRI_AOC_EVENTS)
03639 /*!
03640  * \internal
03641  * \brief send an AOC-E message on the current call
03642  *
03643  * \param pvt sig_pri private channel structure.
03644  * \param generic decoded ast AOC message
03645  *
03646  * \return Nothing
03647  *
03648  * \note Assumes that the PRI lock is already obtained.
03649  */
03650 static void sig_pri_aoc_e_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
03651 {
03652    struct pri_subcmd_aoc_e *aoc_e = &pvt->aoc_e;
03653    const struct ast_aoc_charging_association *ca = ast_aoc_get_association_info(decoded);
03654 
03655    memset(aoc_e, 0, sizeof(*aoc_e));
03656    pvt->holding_aoce = 1;
03657 
03658    switch (ca->charging_type) {
03659    case AST_AOC_CHARGING_ASSOCIATION_NUMBER:
03660       aoc_e->associated.charge.number.valid = 1;
03661       ast_copy_string(aoc_e->associated.charge.number.str,
03662          ca->charge.number.number,
03663          sizeof(aoc_e->associated.charge.number.str));
03664       aoc_e->associated.charge.number.plan = ca->charge.number.plan;
03665       aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER;
03666       break;
03667    case AST_AOC_CHARGING_ASSOCIATION_ID:
03668       aoc_e->associated.charge.id = ca->charge.id;
03669       aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_ID;
03670       break;
03671    case AST_AOC_CHARGING_ASSOCIATION_NA:
03672    default:
03673       break;
03674    }
03675 
03676    switch (ast_aoc_get_billing_id(decoded)) {
03677    case AST_AOC_BILLING_NORMAL:
03678       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NORMAL;
03679       break;
03680    case AST_AOC_BILLING_REVERSE_CHARGE:
03681       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_REVERSE;
03682       break;
03683    case AST_AOC_BILLING_CREDIT_CARD:
03684       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CREDIT_CARD;
03685       break;
03686    case AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL:
03687       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL;
03688       break;
03689    case AST_AOC_BILLING_CALL_FWD_BUSY:
03690       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY;
03691       break;
03692    case AST_AOC_BILLING_CALL_FWD_NO_REPLY:
03693       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY;
03694       break;
03695    case AST_AOC_BILLING_CALL_DEFLECTION:
03696       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_DEFLECTION;
03697       break;
03698    case AST_AOC_BILLING_CALL_TRANSFER:
03699       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_TRANSFER;
03700       break;
03701    case AST_AOC_BILLING_NA:
03702    default:
03703       aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NOT_AVAILABLE;
03704       break;
03705    }
03706 
03707    switch (ast_aoc_get_charge_type(decoded)) {
03708    case AST_AOC_CHARGE_FREE:
03709       aoc_e->charge = PRI_AOC_DE_CHARGE_FREE;
03710       break;
03711    case AST_AOC_CHARGE_CURRENCY:
03712       {
03713          const char *currency_name = ast_aoc_get_currency_name(decoded);
03714          aoc_e->charge = PRI_AOC_DE_CHARGE_CURRENCY;
03715          aoc_e->recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
03716          aoc_e->recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
03717          if (!ast_strlen_zero(currency_name)) {
03718             ast_copy_string(aoc_e->recorded.money.currency, currency_name, sizeof(aoc_e->recorded.money.currency));
03719          }
03720       }
03721       break;
03722    case AST_AOC_CHARGE_UNIT:
03723       {
03724          const struct ast_aoc_unit_entry *entry;
03725          int i;
03726          aoc_e->charge = PRI_AOC_DE_CHARGE_UNITS;
03727          for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
03728             if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_e->recorded.unit.item)) {
03729                if (entry->valid_amount) {
03730                   aoc_e->recorded.unit.item[i].number = entry->amount;
03731                } else {
03732                   aoc_e->recorded.unit.item[i].number = -1;
03733                }
03734                if (entry->valid_type) {
03735                   aoc_e->recorded.unit.item[i].type = entry->type;
03736                } else {
03737                   aoc_e->recorded.unit.item[i].type = -1;
03738                }
03739                aoc_e->recorded.unit.num_items++;
03740             }
03741          }
03742       }
03743       break;
03744    case AST_AOC_CHARGE_NA:
03745    default:
03746       aoc_e->charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
03747       break;
03748    }
03749 }
03750 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03751 
03752 #if defined(HAVE_PRI_AOC_EVENTS)
03753 /*!
03754  * \internal
03755  * \brief send an AOC-E termination request on ast_channel and set
03756  * hangup delay.
03757  *
03758  * \param pri PRI span control structure.
03759  * \param chanpos Channel position in the span.
03760  * \param ms to delay hangup
03761  *
03762  * \note Assumes the pri->lock is already obtained.
03763  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
03764  *
03765  * \return Nothing
03766  */
03767 static void sig_pri_send_aoce_termination_request(struct sig_pri_span *pri, int chanpos, unsigned int ms)
03768 {
03769    struct sig_pri_chan *pvt;
03770    struct ast_aoc_decoded *decoded = NULL;
03771    struct ast_aoc_encoded *encoded = NULL;
03772    size_t encoded_size;
03773    struct timeval whentohangup = { 0, };
03774 
03775    sig_pri_lock_owner(pri, chanpos);
03776    pvt = pri->pvts[chanpos];
03777    if (!pvt->owner) {
03778       return;
03779    }
03780 
03781    if (!(decoded = ast_aoc_create(AST_AOC_REQUEST, 0, AST_AOC_REQUEST_E))) {
03782       ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
03783       goto cleanup_termination_request;
03784    }
03785 
03786    ast_aoc_set_termination_request(decoded);
03787 
03788    if (!(encoded = ast_aoc_encode(decoded, &encoded_size, pvt->owner))) {
03789       ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
03790       goto cleanup_termination_request;
03791    }
03792 
03793    /* convert ms to timeval */
03794    whentohangup.tv_usec = (ms % 1000) * 1000;
03795    whentohangup.tv_sec = ms / 1000;
03796 
03797    if (ast_queue_control_data(pvt->owner, AST_CONTROL_AOC, encoded, encoded_size)) {
03798       ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
03799       goto cleanup_termination_request;
03800    }
03801 
03802    pvt->waiting_for_aoce = 1;
03803    ast_channel_setwhentohangup_tv(pvt->owner, whentohangup);
03804    ast_log(LOG_DEBUG, "Delaying hangup on %s for aoc-e msg\n", pvt->owner->name);
03805 
03806 cleanup_termination_request:
03807    ast_channel_unlock(pvt->owner);
03808    ast_aoc_destroy_decoded(decoded);
03809    ast_aoc_destroy_encoded(encoded);
03810 }
03811 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
03812 
03813 /*!
03814  * \internal
03815  * \brief TRUE if PRI event came in on a CIS call.
03816  * \since 1.8
03817  *
03818  * \param channel PRI encoded span/channel
03819  *
03820  * \retval non-zero if CIS call.
03821  */
03822 static int sig_pri_is_cis_call(int channel)
03823 {
03824    return channel != -1 && (channel & PRI_CIS_CALL);
03825 }
03826 
03827 /*!
03828  * \internal
03829  * \brief Handle the CIS associated PRI subcommand events.
03830  * \since 1.8
03831  *
03832  * \param pri PRI span control structure.
03833  * \param event_id PRI event id
03834  * \param subcmds Subcommands to process if any. (Could be NULL).
03835  * \param call_rsp libpri opaque call structure to send any responses toward.
03836  * Could be NULL either because it is not available or the call is for the
03837  * dummy call reference.  However, this should not be NULL in the cases that
03838  * need to use the pointer to send a response message back.
03839  *
03840  * \note Assumes the pri->lock is already obtained.
03841  *
03842  * \return Nothing
03843  */
03844 static void sig_pri_handle_cis_subcmds(struct sig_pri_span *pri, int event_id,
03845    const struct pri_subcommands *subcmds, q931_call *call_rsp)
03846 {
03847    int index;
03848 #if defined(HAVE_PRI_CCSS)
03849    struct ast_cc_agent *agent;
03850    struct sig_pri_cc_agent_prv *agent_prv;
03851    struct sig_pri_cc_monitor_instance *monitor;
03852 #endif   /* defined(HAVE_PRI_CCSS) */
03853 
03854    if (!subcmds) {
03855       return;
03856    }
03857    for (index = 0; index < subcmds->counter_subcmd; ++index) {
03858       const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
03859 
03860       switch (subcmd->cmd) {
03861 #if defined(STATUS_REQUEST_PLACE_HOLDER)
03862       case PRI_SUBCMD_STATUS_REQ:
03863       case PRI_SUBCMD_STATUS_REQ_RSP:
03864          /* Ignore for now. */
03865          break;
03866 #endif   /* defined(STATUS_REQUEST_PLACE_HOLDER) */
03867 #if defined(HAVE_PRI_CCSS)
03868       case PRI_SUBCMD_CC_REQ:
03869          agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_request.cc_id);
03870          if (!agent) {
03871             pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
03872             break;
03873          }
03874          if (!ast_cc_request_is_within_limits()) {
03875             if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
03876                5/* queue_full */)) {
03877                pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
03878             }
03879             ast_cc_failed(agent->core_id, "%s agent system CC queue full",
03880                sig_pri_cc_type_name);
03881             ao2_ref(agent, -1);
03882             break;
03883          }
03884          agent_prv = agent->private_data;
03885          agent_prv->cc_request_response_pending = 1;
03886          if (ast_cc_agent_accept_request(agent->core_id,
03887             "%s caller accepted CC offer.", sig_pri_cc_type_name)) {
03888             agent_prv->cc_request_response_pending = 0;
03889             if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
03890                2/* short_term_denial */)) {
03891                pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
03892             }
03893             ast_cc_failed(agent->core_id, "%s agent CC core request accept failed",
03894                sig_pri_cc_type_name);
03895          }
03896          ao2_ref(agent, -1);
03897          break;
03898 #endif   /* defined(HAVE_PRI_CCSS) */
03899 #if defined(HAVE_PRI_CCSS)
03900       case PRI_SUBCMD_CC_REQ_RSP:
03901          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
03902             subcmd->u.cc_request_rsp.cc_id);
03903          if (!monitor) {
03904             pri_cc_cancel(pri->pri, subcmd->u.cc_request_rsp.cc_id);
03905             break;
03906          }
03907          switch (subcmd->u.cc_request_rsp.status) {
03908          case 0:/* success */
03909             ast_cc_monitor_request_acked(monitor->core_id,
03910                "%s far end accepted CC request", sig_pri_cc_type_name);
03911             break;
03912          case 1:/* timeout */
03913             ast_verb(2, "core_id:%d %s CC request timeout\n", monitor->core_id,
03914                sig_pri_cc_type_name);
03915             ast_cc_monitor_failed(monitor->core_id, monitor->name,
03916                "%s CC request timeout", sig_pri_cc_type_name);
03917             break;
03918          case 2:/* error */
03919             ast_verb(2, "core_id:%d %s CC request error: %s\n", monitor->core_id,
03920                sig_pri_cc_type_name,
03921                pri_facility_error2str(subcmd->u.cc_request_rsp.fail_code));
03922             ast_cc_monitor_failed(monitor->core_id, monitor->name,
03923                "%s CC request error", sig_pri_cc_type_name);
03924             break;
03925          case 3:/* reject */
03926             ast_verb(2, "core_id:%d %s CC request reject: %s\n", monitor->core_id,
03927                sig_pri_cc_type_name,
03928                pri_facility_reject2str(subcmd->u.cc_request_rsp.fail_code));
03929             ast_cc_monitor_failed(monitor->core_id, monitor->name,
03930                "%s CC request reject", sig_pri_cc_type_name);
03931             break;
03932          default:
03933             ast_verb(2, "core_id:%d %s CC request unknown status %d\n",
03934                monitor->core_id, sig_pri_cc_type_name,
03935                subcmd->u.cc_request_rsp.status);
03936             ast_cc_monitor_failed(monitor->core_id, monitor->name,
03937                "%s CC request unknown status", sig_pri_cc_type_name);
03938             break;
03939          }
03940          ao2_ref(monitor, -1);
03941          break;
03942 #endif   /* defined(HAVE_PRI_CCSS) */
03943 #if defined(HAVE_PRI_CCSS)
03944       case PRI_SUBCMD_CC_REMOTE_USER_FREE:
03945          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
03946             subcmd->u.cc_remote_user_free.cc_id);
03947          if (!monitor) {
03948             pri_cc_cancel(pri->pri, subcmd->u.cc_remote_user_free.cc_id);
03949             break;
03950          }
03951          ast_cc_monitor_callee_available(monitor->core_id,
03952             "%s callee has become available", sig_pri_cc_type_name);
03953          ao2_ref(monitor, -1);
03954          break;
03955 #endif   /* defined(HAVE_PRI_CCSS) */
03956 #if defined(HAVE_PRI_CCSS)
03957       case PRI_SUBCMD_CC_B_FREE:
03958          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
03959             subcmd->u.cc_b_free.cc_id);
03960          if (!monitor) {
03961             pri_cc_cancel(pri->pri, subcmd->u.cc_b_free.cc_id);
03962             break;
03963          }
03964          ast_cc_monitor_party_b_free(monitor->core_id);
03965          ao2_ref(monitor, -1);
03966          break;
03967 #endif   /* defined(HAVE_PRI_CCSS) */
03968 #if defined(HAVE_PRI_CCSS)
03969       case PRI_SUBCMD_CC_STATUS_REQ:
03970          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
03971             subcmd->u.cc_status_req.cc_id);
03972          if (!monitor) {
03973             pri_cc_cancel(pri->pri, subcmd->u.cc_status_req.cc_id);
03974             break;
03975          }
03976          ast_cc_monitor_status_request(monitor->core_id);
03977          ao2_ref(monitor, -1);
03978          break;
03979 #endif   /* defined(HAVE_PRI_CCSS) */
03980 #if defined(HAVE_PRI_CCSS)
03981       case PRI_SUBCMD_CC_STATUS_REQ_RSP:
03982          agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status_req_rsp.cc_id);
03983          if (!agent) {
03984             pri_cc_cancel(pri->pri, subcmd->u.cc_status_req_rsp.cc_id);
03985             break;
03986          }
03987          ast_cc_agent_status_response(agent->core_id,
03988             subcmd->u.cc_status_req_rsp.status ? AST_DEVICE_INUSE
03989             : AST_DEVICE_NOT_INUSE);
03990          ao2_ref(agent, -1);
03991          break;
03992 #endif   /* defined(HAVE_PRI_CCSS) */
03993 #if defined(HAVE_PRI_CCSS)
03994       case PRI_SUBCMD_CC_STATUS:
03995          agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status.cc_id);
03996          if (!agent) {
03997             pri_cc_cancel(pri->pri, subcmd->u.cc_status.cc_id);
03998             break;
03999          }
04000          if (subcmd->u.cc_status.status) {
04001             ast_cc_agent_caller_busy(agent->core_id, "%s agent caller is busy",
04002                sig_pri_cc_type_name);
04003          } else {
04004             ast_cc_agent_caller_available(agent->core_id,
04005                "%s agent caller is available", sig_pri_cc_type_name);
04006          }
04007          ao2_ref(agent, -1);
04008          break;
04009 #endif   /* defined(HAVE_PRI_CCSS) */
04010 #if defined(HAVE_PRI_CCSS)
04011       case PRI_SUBCMD_CC_CANCEL:
04012          sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
04013             subcmd->u.cc_cancel.is_agent);
04014          break;
04015 #endif   /* defined(HAVE_PRI_CCSS) */
04016 #if defined(HAVE_PRI_CCSS)
04017       case PRI_SUBCMD_CC_STOP_ALERTING:
04018          monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
04019             subcmd->u.cc_stop_alerting.cc_id);
04020          if (!monitor) {
04021             pri_cc_cancel(pri->pri, subcmd->u.cc_stop_alerting.cc_id);
04022             break;
04023          }
04024          ast_cc_monitor_stop_ringing(monitor->core_id);
04025          ao2_ref(monitor, -1);
04026          break;
04027 #endif   /* defined(HAVE_PRI_CCSS) */
04028 #if defined(HAVE_PRI_AOC_EVENTS)
04029       case PRI_SUBCMD_AOC_E:
04030          /* Queue AST_CONTROL_AOC frame */
04031          sig_pri_aoc_e_from_pri(&subcmd->u.aoc_e, NULL, 0);
04032          break;
04033 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04034       default:
04035          ast_debug(2,
04036             "Unknown CIS subcommand(%d) in %s event on span %d.\n",
04037             subcmd->cmd, pri_event2str(event_id), pri->span);
04038          break;
04039       }
04040    }
04041 }
04042 
04043 #if defined(HAVE_PRI_AOC_EVENTS)
04044 /*!
04045  * \internal
04046  * \brief detect if AOC-S subcmd is present.
04047  * \since 1.8
04048  *
04049  * \param subcmds Subcommands to process if any. (Could be NULL).
04050  *
04051  * \note Knowing whether or not an AOC-E subcmd is present on certain
04052  * PRI hangup events is necessary to determine what method to use to hangup
04053  * the ast_channel.  If an AOC-E subcmd just came in, then a new AOC-E was queued
04054  * on the ast_channel.  If a soft hangup is used, the AOC-E msg will never make it
04055  * across the bridge, but if a AST_CONTROL_HANGUP frame is queued behind it
04056  * we can ensure the AOC-E frame makes it to it's destination before the hangup
04057  * frame is read.
04058  *
04059  *
04060  * \retval 0 AOC-E is not present in subcmd list
04061  * \retval 1 AOC-E is present in subcmd list
04062  */
04063 static int detect_aoc_e_subcmd(const struct pri_subcommands *subcmds)
04064 {
04065    int i;
04066 
04067    if (!subcmds) {
04068       return 0;
04069    }
04070    for (i = 0; i < subcmds->counter_subcmd; ++i) {
04071       const struct pri_subcommand *subcmd = &subcmds->subcmd[i];
04072       if (subcmd->cmd == PRI_SUBCMD_AOC_E) {
04073          return 1;
04074       }
04075    }
04076    return 0;
04077 }
04078 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04079 
04080 /*!
04081  * \internal
04082  * \brief Handle the call associated PRI subcommand events.
04083  * \since 1.8
04084  *
04085  * \param pri PRI span control structure.
04086  * \param chanpos Channel position in the span.
04087  * \param event_id PRI event id
04088  * \param channel PRI encoded span/channel
04089  * \param subcmds Subcommands to process if any. (Could be NULL).
04090  * \param call_rsp libpri opaque call structure to send any responses toward.
04091  * Could be NULL either because it is not available or the call is for the
04092  * dummy call reference.  However, this should not be NULL in the cases that
04093  * need to use the pointer to send a response message back.
04094  *
04095  * \note Assumes the pri->lock is already obtained.
04096  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
04097  *
04098  * \return Nothing
04099  */
04100 static void sig_pri_handle_subcmds(struct sig_pri_span *pri, int chanpos, int event_id,
04101    int channel, const struct pri_subcommands *subcmds, q931_call *call_rsp)
04102 {
04103    int index;
04104    struct ast_channel *owner;
04105    struct ast_party_redirecting ast_redirecting;
04106 #if defined(HAVE_PRI_TRANSFER)
04107    struct xfer_rsp_data xfer_rsp;
04108 #endif   /* defined(HAVE_PRI_TRANSFER) */
04109 
04110    if (!subcmds) {
04111       return;
04112    }
04113    for (index = 0; index < subcmds->counter_subcmd; ++index) {
04114       const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
04115 
04116       switch (subcmd->cmd) {
04117       case PRI_SUBCMD_CONNECTED_LINE:
04118          sig_pri_lock_owner(pri, chanpos);
04119          owner = pri->pvts[chanpos]->owner;
04120          if (owner) {
04121             struct ast_party_connected_line ast_connected;
04122             int caller_id_update;
04123 
04124             /* Extract the connected line information */
04125             ast_party_connected_line_init(&ast_connected);
04126             sig_pri_party_id_convert(&ast_connected.id, &subcmd->u.connected_line.id,
04127                pri);
04128             ast_connected.id.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04129 
04130             caller_id_update = 0;
04131             if (ast_connected.id.name.str) {
04132                /* Save name for Caller-ID update */
04133                ast_copy_string(pri->pvts[chanpos]->cid_name,
04134                   ast_connected.id.name.str, sizeof(pri->pvts[chanpos]->cid_name));
04135                caller_id_update = 1;
04136             }
04137             if (ast_connected.id.number.str) {
04138                /* Save number for Caller-ID update */
04139                ast_copy_string(pri->pvts[chanpos]->cid_num,
04140                   ast_connected.id.number.str, sizeof(pri->pvts[chanpos]->cid_num));
04141                pri->pvts[chanpos]->cid_ton = ast_connected.id.number.plan;
04142                caller_id_update = 1;
04143             }
04144             ast_connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
04145 
04146             pri->pvts[chanpos]->cid_subaddr[0] = '\0';
04147 #if defined(HAVE_PRI_SUBADDR)
04148             if (ast_connected.id.subaddress.valid) {
04149                ast_party_subaddress_set(&owner->caller.id.subaddress,
04150                   &ast_connected.id.subaddress);
04151                if (ast_connected.id.subaddress.str) {
04152                   ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
04153                      ast_connected.id.subaddress.str,
04154                      sizeof(pri->pvts[chanpos]->cid_subaddr));
04155                }
04156             }
04157 #endif   /* defined(HAVE_PRI_SUBADDR) */
04158             if (caller_id_update) {
04159                struct ast_party_caller ast_caller;
04160 
04161                pri->pvts[chanpos]->callingpres =
04162                   ast_party_id_presentation(&ast_connected.id);
04163                sig_pri_set_caller_id(pri->pvts[chanpos]);
04164 
04165                ast_party_caller_set_init(&ast_caller, &owner->caller);
04166                ast_caller.id = ast_connected.id;
04167                ast_caller.ani = ast_connected.id;
04168                ast_channel_set_caller_event(owner, &ast_caller, NULL);
04169             }
04170 
04171             /* Update the connected line information on the other channel */
04172             if (event_id != PRI_EVENT_RING) {
04173                /* This connected_line update was not from a SETUP message. */
04174                ast_channel_queue_connected_line_update(owner, &ast_connected, NULL);
04175             }
04176 
04177             ast_party_connected_line_free(&ast_connected);
04178             ast_channel_unlock(owner);
04179          }
04180          break;
04181       case PRI_SUBCMD_REDIRECTING:
04182          sig_pri_lock_owner(pri, chanpos);
04183          owner = pri->pvts[chanpos]->owner;
04184          if (owner) {
04185             sig_pri_redirecting_convert(&ast_redirecting, &subcmd->u.redirecting,
04186                &owner->redirecting, pri);
04187             ast_redirecting.from.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04188             ast_redirecting.to.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04189 
04190 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
04191 
04192             ast_channel_set_redirecting(owner, &ast_redirecting, NULL);
04193             if (event_id != PRI_EVENT_RING) {
04194                /* This redirection was not from a SETUP message. */
04195                ast_channel_queue_redirecting_update(owner, &ast_redirecting, NULL);
04196             }
04197             ast_party_redirecting_free(&ast_redirecting);
04198 
04199             ast_channel_unlock(owner);
04200          }
04201          break;
04202 #if defined(HAVE_PRI_CALL_REROUTING)
04203       case PRI_SUBCMD_REROUTING:
04204          sig_pri_lock_owner(pri, chanpos);
04205          owner = pri->pvts[chanpos]->owner;
04206          if (owner) {
04207             struct pri_party_redirecting pri_deflection;
04208 
04209             if (!call_rsp) {
04210                ast_log(LOG_WARNING,
04211                   "Span %d: %s tried CallRerouting/CallDeflection to '%s' without call!\n",
04212                   pri->span, owner->name, subcmd->u.rerouting.deflection.to.number.str);
04213                ast_channel_unlock(owner);
04214                break;
04215             }
04216             if (ast_strlen_zero(subcmd->u.rerouting.deflection.to.number.str)) {
04217                ast_log(LOG_WARNING,
04218                   "Span %d: %s tried CallRerouting/CallDeflection to empty number!\n",
04219                   pri->span, owner->name);
04220                pri_rerouting_rsp(pri->pri, call_rsp, subcmd->u.rerouting.invoke_id,
04221                   PRI_REROUTING_RSP_INVALID_NUMBER);
04222                ast_channel_unlock(owner);
04223                break;
04224             }
04225 
04226             ast_verb(3, "Span %d: %s is CallRerouting/CallDeflection to '%s'.\n",
04227                pri->span, owner->name, subcmd->u.rerouting.deflection.to.number.str);
04228 
04229             /*
04230              * Send back positive ACK to CallRerouting/CallDeflection.
04231              *
04232              * Note:  This call will be hungup by the core when it processes
04233              * the call_forward string.
04234              */
04235             pri_rerouting_rsp(pri->pri, call_rsp, subcmd->u.rerouting.invoke_id,
04236                PRI_REROUTING_RSP_OK_CLEAR);
04237 
04238             pri_deflection = subcmd->u.rerouting.deflection;
04239 
04240             /* Adjust the deflecting to number based upon the subscription option. */
04241             switch (subcmd->u.rerouting.subscription_option) {
04242             case 0:  /* noNotification */
04243             case 1:  /* notificationWithoutDivertedToNr */
04244                /* Delete the number because the far end is not supposed to see it. */
04245                pri_deflection.to.number.presentation =
04246                   PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
04247                pri_deflection.to.number.plan =
04248                   (PRI_TON_UNKNOWN << 4) | PRI_NPI_E163_E164;
04249                pri_deflection.to.number.str[0] = '\0';
04250                break;
04251             case 2:  /* notificationWithDivertedToNr */
04252                break;
04253             case 3:  /* notApplicable */
04254             default:
04255                break;
04256             }
04257             sig_pri_redirecting_convert(&ast_redirecting, &pri_deflection,
04258                &owner->redirecting, pri);
04259             ast_redirecting.from.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04260             ast_redirecting.to.tag = ast_strdup(pri->pvts[chanpos]->user_tag);
04261             ast_channel_set_redirecting(owner, &ast_redirecting, NULL);
04262             ast_party_redirecting_free(&ast_redirecting);
04263 
04264             /* Request the core to forward to the new number. */
04265             ast_string_field_set(owner, call_forward,
04266                subcmd->u.rerouting.deflection.to.number.str);
04267 
04268             /* Wake up the channel. */
04269             ast_queue_frame(owner, &ast_null_frame);
04270 
04271             ast_channel_unlock(owner);
04272          }
04273          break;
04274 #endif   /* defined(HAVE_PRI_CALL_REROUTING) */
04275 #if defined(HAVE_PRI_CCSS)
04276       case PRI_SUBCMD_CC_AVAILABLE:
04277          sig_pri_lock_owner(pri, chanpos);
04278          owner = pri->pvts[chanpos]->owner;
04279          if (owner) {
04280             enum ast_cc_service_type service;
04281 
04282             switch (event_id) {
04283             case PRI_EVENT_RINGING:
04284                service = AST_CC_CCNR;
04285                break;
04286             case PRI_EVENT_HANGUP_REQ:
04287                /* We will assume that the cause was busy/congestion. */
04288                service = AST_CC_CCBS;
04289                break;
04290             default:
04291                service = AST_CC_NONE;
04292                break;
04293             }
04294             if (service == AST_CC_NONE
04295                || sig_pri_cc_available(pri, chanpos, subcmd->u.cc_available.cc_id,
04296                service)) {
04297                pri_cc_cancel(pri->pri, subcmd->u.cc_available.cc_id);
04298             }
04299             ast_channel_unlock(owner);
04300          } else {
04301             /* No asterisk channel. */
04302             pri_cc_cancel(pri->pri, subcmd->u.cc_available.cc_id);
04303          }
04304          break;
04305 #endif   /* defined(HAVE_PRI_CCSS) */
04306 #if defined(HAVE_PRI_CCSS)
04307       case PRI_SUBCMD_CC_CALL:
04308          sig_pri_lock_owner(pri, chanpos);
04309          owner = pri->pvts[chanpos]->owner;
04310          if (owner) {
04311             struct ast_cc_agent *agent;
04312 
04313             agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_call.cc_id);
04314             if (agent) {
04315                ast_setup_cc_recall_datastore(owner, agent->core_id);
04316                ast_cc_agent_set_interfaces_chanvar(owner);
04317                ast_cc_agent_recalling(agent->core_id,
04318                   "%s caller is attempting recall", sig_pri_cc_type_name);
04319                ao2_ref(agent, -1);
04320             }
04321 
04322             ast_channel_unlock(owner);
04323          }
04324          break;
04325 #endif   /* defined(HAVE_PRI_CCSS) */
04326 #if defined(HAVE_PRI_CCSS)
04327       case PRI_SUBCMD_CC_CANCEL:
04328          sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
04329             subcmd->u.cc_cancel.is_agent);
04330          break;
04331 #endif   /* defined(HAVE_PRI_CCSS) */
04332 #if defined(HAVE_PRI_TRANSFER)
04333       case PRI_SUBCMD_TRANSFER_CALL:
04334          if (!call_rsp) {
04335             /* Should never happen. */
04336             ast_log(LOG_ERROR,
04337                "Call transfer subcommand without call to send response!\n");
04338             break;
04339          }
04340 
04341          sig_pri_unlock_private(pri->pvts[chanpos]);
04342          xfer_rsp.pri = pri;
04343          xfer_rsp.call = call_rsp;
04344          xfer_rsp.invoke_id = subcmd->u.transfer.invoke_id;
04345          sig_pri_attempt_transfer(pri,
04346             subcmd->u.transfer.call_1, subcmd->u.transfer.is_call_1_held,
04347             subcmd->u.transfer.call_2, subcmd->u.transfer.is_call_2_held,
04348             sig_pri_transfer_rsp, &xfer_rsp);
04349          sig_pri_lock_private(pri->pvts[chanpos]);
04350          break;
04351 #endif   /* defined(HAVE_PRI_TRANSFER) */
04352 #if defined(HAVE_PRI_AOC_EVENTS)
04353       case PRI_SUBCMD_AOC_S:
04354          sig_pri_lock_owner(pri, chanpos);
04355          owner = pri->pvts[chanpos]->owner;
04356          if (owner) {
04357             sig_pri_aoc_s_from_pri(&subcmd->u.aoc_s, owner,
04358                (pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S));
04359             ast_channel_unlock(owner);
04360          }
04361          break;
04362 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04363 #if defined(HAVE_PRI_AOC_EVENTS)
04364       case PRI_SUBCMD_AOC_D:
04365          sig_pri_lock_owner(pri, chanpos);
04366          owner = pri->pvts[chanpos]->owner;
04367          if (owner) {
04368             /* Queue AST_CONTROL_AOC frame on channel */
04369             sig_pri_aoc_d_from_pri(&subcmd->u.aoc_d, owner,
04370                (pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D));
04371             ast_channel_unlock(owner);
04372          }
04373          break;
04374 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04375 #if defined(HAVE_PRI_AOC_EVENTS)
04376       case PRI_SUBCMD_AOC_E:
04377          sig_pri_lock_owner(pri, chanpos);
04378          owner = pri->pvts[chanpos]->owner;
04379          /* Queue AST_CONTROL_AOC frame */
04380          sig_pri_aoc_e_from_pri(&subcmd->u.aoc_e, owner,
04381             (pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E));
04382          if (owner) {
04383             ast_channel_unlock(owner);
04384          }
04385          break;
04386 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04387 #if defined(HAVE_PRI_AOC_EVENTS)
04388       case PRI_SUBCMD_AOC_CHARGING_REQ:
04389          sig_pri_lock_owner(pri, chanpos);
04390          owner = pri->pvts[chanpos]->owner;
04391          if (owner) {
04392             sig_pri_aoc_request_from_pri(&subcmd->u.aoc_request, pri->pvts[chanpos],
04393                call_rsp);
04394             ast_channel_unlock(owner);
04395          }
04396          break;
04397 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04398 #if defined(HAVE_PRI_AOC_EVENTS)
04399       case PRI_SUBCMD_AOC_CHARGING_REQ_RSP:
04400          /*
04401           * An AOC request response may contain an AOC-S rate list.
04402           * If this is the case handle this just like we
04403           * would an incoming AOC-S msg.
04404           */
04405          if (subcmd->u.aoc_request_response.valid_aoc_s) {
04406             sig_pri_lock_owner(pri, chanpos);
04407             owner = pri->pvts[chanpos]->owner;
04408             if (owner) {
04409                sig_pri_aoc_s_from_pri(&subcmd->u.aoc_request_response.aoc_s, owner,
04410                   (pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S));
04411                ast_channel_unlock(owner);
04412             }
04413          }
04414          break;
04415 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
04416 #if defined(HAVE_PRI_MCID)
04417       case PRI_SUBCMD_MCID_REQ:
04418          sig_pri_lock_owner(pri, chanpos);
04419          owner = pri->pvts[chanpos]->owner;
04420          sig_pri_mcid_event(pri, &subcmd->u.mcid_req, owner);
04421          if (owner) {
04422             ast_channel_unlock(owner);
04423          }
04424          break;
04425 #endif   /* defined(HAVE_PRI_MCID) */
04426 #if defined(HAVE_PRI_MCID)
04427       case PRI_SUBCMD_MCID_RSP:
04428          /* Ignore for now. */
04429          break;
04430 #endif   /* defined(HAVE_PRI_MCID) */
04431       default:
04432          ast_debug(2,
04433             "Unknown call subcommand(%d) in %s event on channel %d/%d on span %d.\n",
04434             subcmd->cmd, pri_event2str(event_id), PRI_SPAN(channel),
04435             PRI_CHANNEL(channel), pri->span);
04436          break;
04437       }
04438    }
04439 }
04440 
04441 #if defined(HAVE_PRI_CALL_HOLD)
04442 /*!
04443  * \internal
04444  * \brief Handle the hold event from libpri.
04445  * \since 1.8
04446  *
04447  * \param pri PRI span control structure.
04448  * \param ev Hold event received.
04449  *
04450  * \note Assumes the pri->lock is already obtained.
04451  *
04452  * \retval 0 on success.
04453  * \retval -1 on error.
04454  */
04455 static int sig_pri_handle_hold(struct sig_pri_span *pri, pri_event *ev)
04456 {
04457    int retval;
04458    int chanpos_old;
04459    int chanpos_new;
04460    struct ast_channel *owner;
04461 
04462    chanpos_old = pri_find_principle_by_call(pri, ev->hold.call);
04463    if (chanpos_old < 0) {
04464       ast_log(LOG_WARNING, "Span %d: Received HOLD for unknown call.\n", pri->span);
04465       return -1;
04466    }
04467    if (pri->pvts[chanpos_old]->no_b_channel) {
04468       /* Call is already on hold or is call waiting call. */
04469       return -1;
04470    }
04471 
04472    chanpos_new = -1;
04473 
04474    sig_pri_lock_private(pri->pvts[chanpos_old]);
04475    sig_pri_lock_owner(pri, chanpos_old);
04476    owner = pri->pvts[chanpos_old]->owner;
04477    if (!owner) {
04478       goto done_with_private;
04479    }
04480    if (pri->pvts[chanpos_old]->call_level != SIG_PRI_CALL_LEVEL_CONNECT) {
04481       /*
04482        * Make things simple.  Don't allow placing a call on hold that
04483        * is not connected.
04484        */
04485       goto done_with_owner;
04486    }
04487    chanpos_new = pri_find_empty_nobch(pri);
04488    if (chanpos_new < 0) {
04489       /* No hold channel available. */
04490       goto done_with_owner;
04491    }
04492    sig_pri_handle_subcmds(pri, chanpos_old, ev->e, ev->hold.channel, ev->hold.subcmds,
04493       ev->hold.call);
04494    chanpos_new = pri_fixup_principle(pri, chanpos_new, ev->hold.call);
04495    if (chanpos_new < 0) {
04496       /* Should never happen. */
04497    } else {
04498       struct ast_frame f = { AST_FRAME_CONTROL, };
04499 
04500       /*
04501        * Things are in an odd state here so we cannot use pri_queue_control().
04502        * However, we already have the owner lock so we can simply queue the frame.
04503        */
04504       f.subclass.integer = AST_CONTROL_HOLD;
04505       ast_queue_frame(owner, &f);
04506    }
04507 
04508 done_with_owner:;
04509    ast_channel_unlock(owner);
04510 done_with_private:;
04511    sig_pri_unlock_private(pri->pvts[chanpos_old]);
04512 
04513    if (chanpos_new < 0) {
04514       retval = -1;
04515    } else {
04516       sig_pri_span_devstate_changed(pri);
04517       retval = 0;
04518    }
04519 
04520    return retval;
04521 }
04522 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
04523 
04524 #if defined(HAVE_PRI_CALL_HOLD)
04525 /*!
04526  * \internal
04527  * \brief Handle the retrieve event from libpri.
04528  * \since 1.8
04529  *
04530  * \param pri PRI span control structure.
04531  * \param ev Retrieve event received.
04532  *
04533  * \note Assumes the pri->lock is already obtained.
04534  *
04535  * \return Nothing
04536  */
04537 static void sig_pri_handle_retrieve(struct sig_pri_span *pri, pri_event *ev)
04538 {
04539    int chanpos;
04540 
04541    if (!(ev->retrieve.channel & PRI_HELD_CALL)) {
04542       /* The call is not currently held. */
04543       pri_retrieve_rej(pri->pri, ev->retrieve.call,
04544          PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
04545       return;
04546    }
04547    if (pri_find_principle_by_call(pri, ev->retrieve.call) < 0) {
04548       ast_log(LOG_WARNING, "Span %d: Received RETRIEVE for unknown call.\n", pri->span);
04549       pri_retrieve_rej(pri->pri, ev->retrieve.call,
04550          PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
04551       return;
04552    }
04553    if (PRI_CHANNEL(ev->retrieve.channel) == 0xFF) {
04554       chanpos = pri_find_empty_chan(pri, 1);
04555    } else {
04556       chanpos = pri_find_principle(pri,
04557          ev->retrieve.channel & ~PRI_HELD_CALL, ev->retrieve.call);
04558       if (ev->retrieve.flexible
04559          && (chanpos < 0 || !sig_pri_is_chan_available(pri->pvts[chanpos]))) {
04560          /*
04561           * Channel selection is flexible and the requested channel
04562           * is bad or not available.  Pick another channel.
04563           */
04564          chanpos = pri_find_empty_chan(pri, 1);
04565       }
04566    }
04567    if (chanpos < 0) {
04568       pri_retrieve_rej(pri->pri, ev->retrieve.call,
04569          ev->retrieve.flexible ? PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION
04570          : PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
04571       return;
04572    }
04573    chanpos = pri_fixup_principle(pri, chanpos, ev->retrieve.call);
04574    if (chanpos < 0) {
04575       /* Channel is already in use. */
04576       pri_retrieve_rej(pri->pri, ev->retrieve.call,
04577          PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
04578       return;
04579    }
04580    sig_pri_lock_private(pri->pvts[chanpos]);
04581    sig_pri_handle_subcmds(pri, chanpos, ev->e, ev->retrieve.channel,
04582       ev->retrieve.subcmds, ev->retrieve.call);
04583    pri_queue_control(pri, chanpos, AST_CONTROL_UNHOLD);
04584    sig_pri_unlock_private(pri->pvts[chanpos]);
04585    pri_retrieve_ack(pri->pri, ev->retrieve.call,
04586       PVT_TO_CHANNEL(pri->pvts[chanpos]));
04587    sig_pri_span_devstate_changed(pri);
04588 }
04589 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
04590 
04591 static void *pri_dchannel(void *vpri)
04592 {
04593    struct sig_pri_span *pri = vpri;
04594    pri_event *e;
04595    struct pollfd fds[SIG_PRI_NUM_DCHANS];
04596    int res;
04597    int chanpos = 0;
04598    int x;
04599    int law;
04600    struct ast_channel *c;
04601    struct timeval tv, lowest, *next;
04602    int doidling=0;
04603    char *cc;
04604    time_t t;
04605    int i, which=-1;
04606    int numdchans;
04607    pthread_t threadid;
04608    char ani2str[6];
04609    char plancallingnum[AST_MAX_EXTENSION];
04610    char plancallingani[AST_MAX_EXTENSION];
04611    char calledtonstr[10];
04612    struct timeval lastidle = { 0, 0 };
04613    pthread_t p;
04614    struct ast_channel *idle;
04615    char idlen[80];
04616    int nextidle = -1;
04617    int haveidles;
04618    int activeidles;
04619    unsigned int len;
04620 
04621    gettimeofday(&lastidle, NULL);
04622    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
04623 
04624    if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
04625       /* Need to do idle dialing, check to be sure though */
04626       cc = strchr(pri->idleext, '@');
04627       if (cc) {
04628          *cc = '\0';
04629          cc++;
04630          ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
04631 #if 0
04632          /* Extensions may not be loaded yet */
04633          if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
04634             ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
04635          else
04636 #endif
04637             doidling = 1;
04638       } else
04639          ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
04640    }
04641    for (;;) {
04642       for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
04643          if (!pri->dchans[i])
04644             break;
04645          fds[i].fd = pri->fds[i];
04646          fds[i].events = POLLIN | POLLPRI;
04647          fds[i].revents = 0;
04648       }
04649       numdchans = i;
04650       time(&t);
04651       ast_mutex_lock(&pri->lock);
04652       if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->sig != SIG_BRI_PTMP) && (pri->resetinterval > 0)) {
04653          if (pri->resetting && pri_is_up(pri)) {
04654             if (pri->resetpos < 0) {
04655                pri_check_restart(pri);
04656                if (pri->resetting) {
04657                   sig_pri_span_devstate_changed(pri);
04658                }
04659             }
04660          } else {
04661             if (!pri->resetting  && (t - pri->lastreset) >= pri->resetinterval) {
04662                pri->resetting = 1;
04663                pri->resetpos = -1;
04664             }
04665          }
04666       }
04667       /* Look for any idle channels if appropriate */
04668       if (doidling && pri_is_up(pri)) {
04669          nextidle = -1;
04670          haveidles = 0;
04671          activeidles = 0;
04672          for (x = pri->numchans; x >= 0; x--) {
04673             if (pri->pvts[x] && !pri->pvts[x]->no_b_channel) {
04674                if (sig_pri_is_chan_available(pri->pvts[x])) {
04675                   if (haveidles < pri->minunused) {
04676                      haveidles++;
04677                   } else {
04678                      nextidle = x;
04679                      break;
04680                   }
04681                } else if (pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
04682                   activeidles++;
04683                }
04684             }
04685          }
04686          if (nextidle > -1) {
04687             if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
04688                /* Don't create a new idle call more than once per second */
04689                snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
04690                pri->pvts[nextidle]->allocated = 1;
04691                /*
04692                 * Release the PRI lock while we create the channel so other
04693                 * threads can send D channel messages.
04694                 */
04695                ast_mutex_unlock(&pri->lock);
04696                /*
04697                 * We already have the B channel reserved for this call.  We
04698                 * just need to make sure that sig_pri_hangup() has completed
04699                 * cleaning up before continuing.
04700                 */
04701                sig_pri_lock_private(pri->pvts[nextidle]);
04702                sig_pri_unlock_private(pri->pvts[nextidle]);
04703                idle = sig_pri_request(pri->pvts[nextidle], AST_FORMAT_ULAW, NULL, 0);
04704                ast_mutex_lock(&pri->lock);
04705                if (idle) {
04706                   pri->pvts[nextidle]->isidlecall = 1;
04707                   if (ast_pthread_create_background(&p, NULL, do_idle_thread, pri->pvts[nextidle])) {
04708                      ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
04709                      ast_mutex_unlock(&pri->lock);
04710                      ast_hangup(idle);
04711                      ast_mutex_lock(&pri->lock);
04712                   }
04713                } else {
04714                   pri->pvts[nextidle]->allocated = 0;
04715                   ast_log(LOG_WARNING, "Unable to request channel 'DAHDI/%s' for idle call\n", idlen);
04716                }
04717                gettimeofday(&lastidle, NULL);
04718             }
04719          } else if ((haveidles < pri->minunused) &&
04720             (activeidles > pri->minidle)) {
04721             /* Mark something for hangup if there is something
04722                that can be hungup */
04723             for (x = pri->numchans; x >= 0; x--) {
04724                /* find a candidate channel */
04725                if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
04726                   pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04727                   haveidles++;
04728                   /* Stop if we have enough idle channels or
04729                     can't spare any more active idle ones */
04730                   if ((haveidles >= pri->minunused) ||
04731                      (activeidles <= pri->minidle))
04732                      break;
04733                }
04734             }
04735          }
04736       }
04737       /* Start with reasonable max */
04738       if (doidling || pri->resetting) {
04739          /*
04740           * Make sure we stop at least once per second if we're
04741           * monitoring idle channels
04742           */
04743          lowest = ast_tv(1, 0);
04744       } else {
04745          /* Don't poll for more than 60 seconds */
04746          lowest = ast_tv(60, 0);
04747       }
04748       for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
04749          if (!pri->dchans[i]) {
04750             /* We scanned all D channels on this span. */
04751             break;
04752          }
04753          next = pri_schedule_next(pri->dchans[i]);
04754          if (next) {
04755             /* We need relative time here */
04756             tv = ast_tvsub(*next, ast_tvnow());
04757             if (tv.tv_sec < 0) {
04758                /*
04759                 * A timer has already expired.
04760                 * By definition zero time is the lowest so we can quit early.
04761                 */
04762                lowest = ast_tv(0, 0);
04763                break;
04764             }
04765             if (ast_tvcmp(tv, lowest) < 0) {
04766                lowest = tv;
04767             }
04768          }
04769       }
04770       ast_mutex_unlock(&pri->lock);
04771 
04772       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
04773       pthread_testcancel();
04774       e = NULL;
04775       res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
04776       pthread_testcancel();
04777       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
04778 
04779       ast_mutex_lock(&pri->lock);
04780       if (!res) {
04781          for (which = 0; which < SIG_PRI_NUM_DCHANS; which++) {
04782             if (!pri->dchans[which])
04783                break;
04784             /* Just a timeout, run the scheduler */
04785             e = pri_schedule_run(pri->dchans[which]);
04786             if (e)
04787                break;
04788          }
04789       } else if (res > -1) {
04790          for (which = 0; which < SIG_PRI_NUM_DCHANS; which++) {
04791             if (!pri->dchans[which])
04792                break;
04793             if (fds[which].revents & POLLPRI) {
04794                sig_pri_handle_dchan_exception(pri, which);
04795             } else if (fds[which].revents & POLLIN) {
04796                e = pri_check_event(pri->dchans[which]);
04797             }
04798             if (e)
04799                break;
04800          }
04801       } else if (errno != EINTR)
04802          ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
04803 
04804       if (e) {
04805          if (pri->debug) {
04806             ast_verbose("Span %d: Processing event %s\n",
04807                pri->span, pri_event2str(e->e));
04808          }
04809 
04810          if (e->e != PRI_EVENT_DCHAN_DOWN) {
04811             if (!(pri->dchanavail[which] & DCHAN_UP)) {
04812                ast_verb(2, "%s D-Channel on span %d up\n", pri_order(which), pri->span);
04813             }
04814             pri->dchanavail[which] |= DCHAN_UP;
04815          } else {
04816             if (pri->dchanavail[which] & DCHAN_UP) {
04817                ast_verb(2, "%s D-Channel on span %d down\n", pri_order(which), pri->span);
04818             }
04819             pri->dchanavail[which] &= ~DCHAN_UP;
04820          }
04821 
04822          if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
04823             /* Must be an NFAS group that has the secondary dchan active */
04824             pri->pri = pri->dchans[which];
04825 
04826          switch (e->e) {
04827          case PRI_EVENT_DCHAN_UP:
04828             pri->no_d_channels = 0;
04829             if (!pri->pri) {
04830                pri_find_dchan(pri);
04831             }
04832 
04833             /* Note presense of D-channel */
04834             time(&pri->lastreset);
04835 
04836             /* Restart in 5 seconds */
04837             if (pri->resetinterval > -1) {
04838                pri->lastreset -= pri->resetinterval;
04839                pri->lastreset += 5;
04840             }
04841             /* Take the channels from inalarm condition */
04842             pri->resetting = 0;
04843             for (i = 0; i < pri->numchans; i++) {
04844                if (pri->pvts[i]) {
04845                   sig_pri_set_alarm(pri->pvts[i], 0);
04846                }
04847             }
04848             sig_pri_span_devstate_changed(pri);
04849             break;
04850          case PRI_EVENT_DCHAN_DOWN:
04851             pri_find_dchan(pri);
04852             if (!pri_is_up(pri)) {
04853                if (pri->sig == SIG_BRI_PTMP) {
04854                   /*
04855                    * For PTMP connections with non-persistent layer 2 we want to
04856                    * *not* declare inalarm unless there actually is an alarm.
04857                    */
04858                   break;
04859                }
04860                /* Hangup active channels and put them in alarm mode */
04861                pri->resetting = 0;
04862                for (i = 0; i < pri->numchans; i++) {
04863                   struct sig_pri_chan *p = pri->pvts[i];
04864 
04865                   if (p) {
04866                      if (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
04867                         /* T309 is not enabled : destroy calls when alarm occurs */
04868                         if (p->call) {
04869                            pri_destroycall(p->pri->pri, p->call);
04870                            p->call = NULL;
04871                         }
04872                         if (p->owner)
04873                            p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04874                      }
04875                      sig_pri_set_alarm(p, 1);
04876                   }
04877                }
04878                sig_pri_span_devstate_changed(pri);
04879             }
04880             break;
04881          case PRI_EVENT_RESTART:
04882             if (e->restart.channel > -1 && PRI_CHANNEL(e->restart.channel) != 0xFF) {
04883                chanpos = pri_find_principle(pri, e->restart.channel, NULL);
04884                if (chanpos < 0)
04885                   ast_log(LOG_WARNING,
04886                      "Span %d: Restart requested on odd/unavailable channel number %d/%d\n",
04887                      pri->span, PRI_SPAN(e->restart.channel),
04888                      PRI_CHANNEL(e->restart.channel));
04889                else {
04890                   int skipit = 0;
04891 #if defined(HAVE_PRI_SERVICE_MESSAGES)
04892                   unsigned why;
04893 
04894                   why = pri->pvts[chanpos]->service_status;
04895                   if (why) {
04896                      ast_log(LOG_NOTICE,
04897                         "Span %d: Channel %d/%d out-of-service (reason: %s), ignoring RESTART\n",
04898                         pri->span, PRI_SPAN(e->restart.channel),
04899                         PRI_CHANNEL(e->restart.channel),
04900                         (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
04901                      skipit = 1;
04902                   }
04903 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
04904                   sig_pri_lock_private(pri->pvts[chanpos]);
04905                   if (!skipit) {
04906                      ast_verb(3, "Span %d: Channel %d/%d restarted\n", pri->span,
04907                         PRI_SPAN(e->restart.channel),
04908                         PRI_CHANNEL(e->restart.channel));
04909                      if (pri->pvts[chanpos]->call) {
04910                         pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
04911                         pri->pvts[chanpos]->call = NULL;
04912                      }
04913                   }
04914                   /* Force soft hangup if appropriate */
04915                   if (pri->pvts[chanpos]->owner)
04916                      pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04917                   sig_pri_unlock_private(pri->pvts[chanpos]);
04918                }
04919             } else {
04920                ast_verb(3, "Restart requested on entire span %d\n", pri->span);
04921                for (x = 0; x < pri->numchans; x++)
04922                   if (pri->pvts[x]) {
04923                      sig_pri_lock_private(pri->pvts[x]);
04924                      if (pri->pvts[x]->call) {
04925                         pri_destroycall(pri->pri, pri->pvts[x]->call);
04926                         pri->pvts[x]->call = NULL;
04927                      }
04928                      if (pri->pvts[x]->owner)
04929                         pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04930                      sig_pri_unlock_private(pri->pvts[x]);
04931                   }
04932             }
04933             sig_pri_span_devstate_changed(pri);
04934             break;
04935          case PRI_EVENT_KEYPAD_DIGIT:
04936             if (sig_pri_is_cis_call(e->digit.channel)) {
04937                sig_pri_handle_cis_subcmds(pri, e->e, e->digit.subcmds,
04938                   e->digit.call);
04939                break;
04940             }
04941             chanpos = pri_find_principle_by_call(pri, e->digit.call);
04942             if (chanpos < 0) {
04943                ast_log(LOG_WARNING,
04944                   "Span %d: Received keypad digits for unknown call.\n", pri->span);
04945                break;
04946             }
04947             sig_pri_lock_private(pri->pvts[chanpos]);
04948             sig_pri_handle_subcmds(pri, chanpos, e->e, e->digit.channel,
04949                e->digit.subcmds, e->digit.call);
04950             /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
04951             if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
04952                && pri->pvts[chanpos]->owner) {
04953                /* how to do that */
04954                int digitlen = strlen(e->digit.digits);
04955                int i;
04956 
04957                for (i = 0; i < digitlen; i++) {
04958                   struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->digit.digits[i], };
04959 
04960                   pri_queue_frame(pri, chanpos, &f);
04961                }
04962             }
04963             sig_pri_unlock_private(pri->pvts[chanpos]);
04964             break;
04965 
04966          case PRI_EVENT_INFO_RECEIVED:
04967             if (sig_pri_is_cis_call(e->ring.channel)) {
04968                sig_pri_handle_cis_subcmds(pri, e->e, e->ring.subcmds,
04969                   e->ring.call);
04970                break;
04971             }
04972             chanpos = pri_find_principle_by_call(pri, e->ring.call);
04973             if (chanpos < 0) {
04974                ast_log(LOG_WARNING,
04975                   "Span %d: Received INFORMATION for unknown call.\n", pri->span);
04976                break;
04977             }
04978             sig_pri_lock_private(pri->pvts[chanpos]);
04979             sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
04980                e->ring.subcmds, e->ring.call);
04981             /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
04982             if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
04983                && pri->pvts[chanpos]->owner) {
04984                /* how to do that */
04985                int digitlen = strlen(e->ring.callednum);
04986                int i;
04987 
04988                for (i = 0; i < digitlen; i++) {
04989                   struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->ring.callednum[i], };
04990 
04991                   pri_queue_frame(pri, chanpos, &f);
04992                }
04993             }
04994             sig_pri_unlock_private(pri->pvts[chanpos]);
04995             break;
04996 #if defined(HAVE_PRI_SERVICE_MESSAGES)
04997          case PRI_EVENT_SERVICE:
04998             chanpos = pri_find_principle(pri, e->service.channel, NULL);
04999             if (chanpos < 0) {
05000                ast_log(LOG_WARNING, "Received service change status %d on unconfigured channel %d/%d span %d\n",
05001                   e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
05002             } else {
05003                char db_chan_name[20];
05004                char db_answer[5];
05005                int ch;
05006                unsigned *why;
05007 
05008                ch = pri->pvts[chanpos]->channel;
05009                snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->span, ch);
05010                why = &pri->pvts[chanpos]->service_status;
05011                switch (e->service.changestatus) {
05012                case 0: /* in-service */
05013                   /* Far end wants to be in service now. */
05014                   ast_db_del(db_chan_name, SRVST_DBKEY);
05015                   *why &= ~SRVST_FAREND;
05016                   if (*why) {
05017                      snprintf(db_answer, sizeof(db_answer), "%s:%u",
05018                         SRVST_TYPE_OOS, *why);
05019                      ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
05020                   } else {
05021                      sig_pri_span_devstate_changed(pri);
05022                   }
05023                   break;
05024                case 2: /* out-of-service */
05025                   /* Far end wants to be out-of-service now. */
05026                   ast_db_del(db_chan_name, SRVST_DBKEY);
05027                   *why |= SRVST_FAREND;
05028                   snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS,
05029                      *why);
05030                   ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
05031                   sig_pri_span_devstate_changed(pri);
05032                   break;
05033                default:
05034                   ast_log(LOG_ERROR, "Huh?  changestatus is: %d\n", e->service.changestatus);
05035                   break;
05036                }
05037                ast_log(LOG_NOTICE, "Channel %d/%d span %d (logical: %d) received a change of service message, status '%d'\n",
05038                   PRI_SPAN(e->service.channel), PRI_CHANNEL(e->service.channel), pri->span, ch, e->service.changestatus);
05039             }
05040             break;
05041          case PRI_EVENT_SERVICE_ACK:
05042             chanpos = pri_find_principle(pri, e->service_ack.channel, NULL);
05043             if (chanpos < 0) {
05044                ast_log(LOG_WARNING, "Received service acknowledge change status '%d' on unconfigured channel %d/%d span %d\n",
05045                   e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
05046             } else {
05047                ast_debug(2, "Channel %d/%d span %d received a change os service acknowledgement message, status '%d'\n",
05048                   PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span, e->service_ack.changestatus);
05049             }
05050             break;
05051 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
05052          case PRI_EVENT_RING:
05053             if (!ast_strlen_zero(pri->msn_list)
05054                && !sig_pri_msn_match(pri->msn_list, e->ring.callednum)) {
05055                /* The call is not for us so ignore it. */
05056                ast_verb(3,
05057                   "Ignoring call to '%s' on span %d.  Its not in the MSN list: %s\n",
05058                   e->ring.callednum, pri->span, pri->msn_list);
05059                pri_destroycall(pri->pri, e->ring.call);
05060                break;
05061             }
05062             if (sig_pri_is_cis_call(e->ring.channel)) {
05063                sig_pri_handle_cis_subcmds(pri, e->e, e->ring.subcmds,
05064                   e->ring.call);
05065                break;
05066             }
05067             chanpos = pri_find_principle_by_call(pri, e->ring.call);
05068             if (-1 < chanpos) {
05069                /* Libpri has already filtered out duplicate SETUPs. */
05070                ast_log(LOG_WARNING,
05071                   "Span %d: Got SETUP with duplicate call ptr (%p).  Dropping call.\n",
05072                   pri->span, e->ring.call);
05073                pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_TEMPORARY_FAILURE);
05074                break;
05075             }
05076             if (e->ring.channel == -1 || PRI_CHANNEL(e->ring.channel) == 0xFF) {
05077                /* Any channel requested. */
05078                chanpos = pri_find_empty_chan(pri, 1);
05079             } else if (PRI_CHANNEL(e->ring.channel) == 0x00) {
05080                /* No channel specified. */
05081 #if defined(HAVE_PRI_CALL_WAITING)
05082                if (!pri->allow_call_waiting_calls)
05083 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05084                {
05085                   /* We will not accept incoming call waiting calls. */
05086                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
05087                   break;
05088                }
05089 #if defined(HAVE_PRI_CALL_WAITING)
05090                chanpos = pri_find_empty_nobch(pri);
05091                if (chanpos < 0) {
05092                   /* We could not find/create a call interface. */
05093                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
05094                   break;
05095                }
05096                /* Setup the call interface to use. */
05097                sig_pri_init_config(pri->pvts[chanpos], pri);
05098 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05099             } else {
05100                /* A channel is specified. */
05101                chanpos = pri_find_principle(pri, e->ring.channel, e->ring.call);
05102                if (chanpos < 0) {
05103                   ast_log(LOG_WARNING,
05104                      "Span %d: SETUP on unconfigured channel %d/%d\n",
05105                      pri->span, PRI_SPAN(e->ring.channel),
05106                      PRI_CHANNEL(e->ring.channel));
05107                } else {
05108                   switch (pri->pvts[chanpos]->resetting) {
05109                   case SIG_PRI_RESET_IDLE:
05110                      break;
05111                   case SIG_PRI_RESET_ACTIVE:
05112                      /*
05113                       * The peer may have lost the expected ack or not received the
05114                       * RESTART yet.
05115                       */
05116                      pri->pvts[chanpos]->resetting = SIG_PRI_RESET_NO_ACK;
05117                      break;
05118                   case SIG_PRI_RESET_NO_ACK:
05119                      /* The peer likely is not going to ack the RESTART. */
05120                      ast_debug(1,
05121                         "Span %d: Second SETUP while waiting for RESTART ACKNOWLEDGE on channel %d/%d\n",
05122                         pri->span, PRI_SPAN(e->ring.channel),
05123                         PRI_CHANNEL(e->ring.channel));
05124 
05125                      /* Assume we got the ack. */
05126                      pri->pvts[chanpos]->resetting = SIG_PRI_RESET_IDLE;
05127                      if (pri->resetting) {
05128                         /* Go on to the next idle channel to RESTART. */
05129                         pri_check_restart(pri);
05130                      }
05131                      break;
05132                   }
05133                   if (!sig_pri_is_chan_available(pri->pvts[chanpos])) {
05134                      /* This is where we handle initial glare */
05135                      ast_debug(1,
05136                         "Span %d: SETUP requested unavailable channel %d/%d.  Attempting to renegotiate.\n",
05137                         pri->span, PRI_SPAN(e->ring.channel),
05138                         PRI_CHANNEL(e->ring.channel));
05139                      chanpos = -1;
05140                   }
05141                }
05142 #if defined(ALWAYS_PICK_CHANNEL)
05143                if (e->ring.flexible) {
05144                   chanpos = -1;
05145                }
05146 #endif   /* defined(ALWAYS_PICK_CHANNEL) */
05147                if (chanpos < 0 && e->ring.flexible) {
05148                   /* We can try to pick another channel. */
05149                   chanpos = pri_find_empty_chan(pri, 1);
05150                }
05151             }
05152             if (chanpos < 0) {
05153                if (e->ring.flexible) {
05154                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
05155                } else {
05156                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
05157                }
05158                break;
05159             }
05160 
05161             sig_pri_lock_private(pri->pvts[chanpos]);
05162 
05163             /* Mark channel as in use so noone else will steal it. */
05164             pri->pvts[chanpos]->call = e->ring.call;
05165 
05166             /* Use plancallingnum as a scratch buffer since it is initialized next. */
05167             apply_plan_to_existing_number(plancallingnum, sizeof(plancallingnum), pri,
05168                e->ring.redirectingnum, e->ring.callingplanrdnis);
05169             sig_pri_set_rdnis(pri->pvts[chanpos], plancallingnum);
05170 
05171             /* Setup caller-id info */
05172             apply_plan_to_existing_number(plancallingnum, sizeof(plancallingnum), pri,
05173                e->ring.callingnum, e->ring.callingplan);
05174             pri->pvts[chanpos]->cid_ani2 = 0;
05175             if (pri->pvts[chanpos]->use_callerid) {
05176                ast_shrink_phone_number(plancallingnum);
05177                ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
05178 #ifdef PRI_ANI
05179                apply_plan_to_existing_number(plancallingani, sizeof(plancallingani),
05180                   pri, e->ring.callingani, e->ring.callingplanani);
05181                ast_shrink_phone_number(plancallingani);
05182                ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani,
05183                   sizeof(pri->pvts[chanpos]->cid_ani));
05184 #endif
05185                pri->pvts[chanpos]->cid_subaddr[0] = '\0';
05186 #if defined(HAVE_PRI_SUBADDR)
05187                if (e->ring.calling.subaddress.valid) {
05188                   struct ast_party_subaddress calling_subaddress;
05189 
05190                   ast_party_subaddress_init(&calling_subaddress);
05191                   sig_pri_set_subaddress(&calling_subaddress,
05192                      &e->ring.calling.subaddress);
05193                   if (calling_subaddress.str) {
05194                      ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
05195                         calling_subaddress.str,
05196                         sizeof(pri->pvts[chanpos]->cid_subaddr));
05197                   }
05198                   ast_party_subaddress_free(&calling_subaddress);
05199                }
05200 #endif /* defined(HAVE_PRI_SUBADDR) */
05201                ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
05202                pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
05203                pri->pvts[chanpos]->callingpres = e->ring.callingpres;
05204                if (e->ring.ani2 >= 0) {
05205                   pri->pvts[chanpos]->cid_ani2 = e->ring.ani2;
05206                }
05207             } else {
05208                pri->pvts[chanpos]->cid_num[0] = '\0';
05209                pri->pvts[chanpos]->cid_subaddr[0] = '\0';
05210                pri->pvts[chanpos]->cid_ani[0] = '\0';
05211                pri->pvts[chanpos]->cid_name[0] = '\0';
05212                pri->pvts[chanpos]->cid_ton = 0;
05213                pri->pvts[chanpos]->callingpres = 0;
05214             }
05215 
05216             /* Setup the user tag for party id's from this device for this call. */
05217             if (pri->append_msn_to_user_tag) {
05218                snprintf(pri->pvts[chanpos]->user_tag,
05219                   sizeof(pri->pvts[chanpos]->user_tag), "%s_%s",
05220                   pri->initial_user_tag,
05221                   pri->nodetype == PRI_NETWORK
05222                      ? plancallingnum : e->ring.callednum);
05223             } else {
05224                ast_copy_string(pri->pvts[chanpos]->user_tag,
05225                   pri->initial_user_tag, sizeof(pri->pvts[chanpos]->user_tag));
05226             }
05227 
05228             sig_pri_set_caller_id(pri->pvts[chanpos]);
05229 
05230             /* Set DNID on all incoming calls -- even immediate */
05231             sig_pri_set_dnid(pri->pvts[chanpos], e->ring.callednum);
05232 
05233             /* If immediate=yes go to s|1 */
05234             if (pri->pvts[chanpos]->immediate) {
05235                ast_verb(3, "Going to extension s|1 because of immediate=yes\n");
05236                pri->pvts[chanpos]->exten[0] = 's';
05237                pri->pvts[chanpos]->exten[1] = '\0';
05238             }
05239             /* Get called number */
05240             else if (!ast_strlen_zero(e->ring.callednum)) {
05241                ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
05242             } else if (pri->overlapdial)
05243                pri->pvts[chanpos]->exten[0] = '\0';
05244             else {
05245                /* Some PRI circuits are set up to send _no_ digits.  Handle them as 's'. */
05246                pri->pvts[chanpos]->exten[0] = 's';
05247                pri->pvts[chanpos]->exten[1] = '\0';
05248             }
05249             /* No number yet, but received "sending complete"? */
05250             if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
05251                ast_verb(3, "Going to extension s|1 because of Complete received\n");
05252                pri->pvts[chanpos]->exten[0] = 's';
05253                pri->pvts[chanpos]->exten[1] = '\0';
05254             }
05255 
05256             /* Make sure extension exists (or in overlap dial mode, can exist) */
05257             if (((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
05258                ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
05259                /* Select audio companding mode. */
05260                switch (e->ring.layer1) {
05261                case PRI_LAYER_1_ALAW:
05262                   law = SIG_PRI_ALAW;
05263                   break;
05264                case PRI_LAYER_1_ULAW:
05265                   law = SIG_PRI_ULAW;
05266                   break;
05267                default:
05268                   /* This is a data call to us. */
05269                   law = SIG_PRI_DEFLAW;
05270                   break;
05271                }
05272 
05273                if (e->ring.complete || !(pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
05274                   /* Just announce proceeding */
05275                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
05276                   pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
05277                } else if (pri->switchtype == PRI_SWITCH_GR303_TMC) {
05278                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_CONNECT;
05279                   pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
05280                } else {
05281                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_OVERLAP;
05282                   pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
05283                }
05284 
05285                /* Start PBX */
05286                if (!e->ring.complete
05287                   && (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
05288                   && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
05289                   /*
05290                    * Release the PRI lock while we create the channel so other
05291                    * threads can send D channel messages.  We must also release
05292                    * the private lock to prevent deadlock while creating the
05293                    * channel.
05294                    */
05295                   sig_pri_unlock_private(pri->pvts[chanpos]);
05296                   ast_mutex_unlock(&pri->lock);
05297                   c = sig_pri_new_ast_channel(pri->pvts[chanpos],
05298                      AST_STATE_RESERVED, law, e->ring.ctype,
05299                      pri->pvts[chanpos]->exten, NULL);
05300                   ast_mutex_lock(&pri->lock);
05301                   sig_pri_lock_private(pri->pvts[chanpos]);
05302                   if (c) {
05303 #if defined(HAVE_PRI_SUBADDR)
05304                      if (e->ring.calling.subaddress.valid) {
05305                         /* Set Calling Subaddress */
05306                         sig_pri_lock_owner(pri, chanpos);
05307                         sig_pri_set_subaddress(
05308                            &pri->pvts[chanpos]->owner->caller.id.subaddress,
05309                            &e->ring.calling.subaddress);
05310                         if (!e->ring.calling.subaddress.type
05311                            && !ast_strlen_zero(
05312                               (char *) e->ring.calling.subaddress.data)) {
05313                            /* NSAP */
05314                            pbx_builtin_setvar_helper(c, "CALLINGSUBADDR",
05315                               (char *) e->ring.calling.subaddress.data);
05316                         }
05317                         ast_channel_unlock(c);
05318                      }
05319                      if (e->ring.called_subaddress.valid) {
05320                         /* Set Called Subaddress */
05321                         sig_pri_lock_owner(pri, chanpos);
05322                         sig_pri_set_subaddress(
05323                            &pri->pvts[chanpos]->owner->dialed.subaddress,
05324                            &e->ring.called_subaddress);
05325                         if (!e->ring.called_subaddress.type
05326                            && !ast_strlen_zero(
05327                               (char *) e->ring.called_subaddress.data)) {
05328                            /* NSAP */
05329                            pbx_builtin_setvar_helper(c, "CALLEDSUBADDR",
05330                               (char *) e->ring.called_subaddress.data);
05331                         }
05332                         ast_channel_unlock(c);
05333                      }
05334 #else
05335                      if (!ast_strlen_zero(e->ring.callingsubaddr)) {
05336                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
05337                      }
05338 #endif /* !defined(HAVE_PRI_SUBADDR) */
05339                      if (e->ring.ani2 >= 0) {
05340                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
05341                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
05342                      }
05343 
05344 #ifdef SUPPORT_USERUSER
05345                      if (!ast_strlen_zero(e->ring.useruserinfo)) {
05346                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
05347                      }
05348 #endif
05349 
05350                      snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
05351                      pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
05352                      ast_channel_lock(c);
05353                      c->dialed.number.plan = e->ring.calledplan;
05354                      ast_channel_unlock(c);
05355 
05356                      if (e->ring.redirectingreason >= 0) {
05357                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
05358                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
05359                      }
05360 #if defined(HAVE_PRI_REVERSE_CHARGE)
05361                      pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
05362 #endif
05363 #if defined(HAVE_PRI_SETUP_KEYPAD)
05364                      ast_copy_string(pri->pvts[chanpos]->keypad_digits,
05365                         e->ring.keypad_digits,
05366                         sizeof(pri->pvts[chanpos]->keypad_digits));
05367 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
05368 
05369                      sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
05370                         e->ring.subcmds, e->ring.call);
05371 
05372                      if (!pri->pvts[chanpos]->digital
05373                         && !pri->pvts[chanpos]->no_b_channel) {
05374                         /*
05375                          * Call has a channel.
05376                          * Indicate that we are providing dialtone.
05377                          */
05378                         pri->pvts[chanpos]->progress = 1;/* No need to send plain PROGRESS again. */
05379 #ifdef HAVE_PRI_PROG_W_CAUSE
05380                         pri_progress_with_cause(pri->pri, e->ring.call,
05381                            PVT_TO_CHANNEL(pri->pvts[chanpos]), 1, -1);/* no cause at all */
05382 #else
05383                         pri_progress(pri->pri, e->ring.call,
05384                            PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
05385 #endif
05386                      }
05387                   }
05388                   if (c && !ast_pthread_create_detached(&threadid, NULL, pri_ss_thread, pri->pvts[chanpos])) {
05389                      ast_verb(3, "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
05390                         plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
05391                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
05392                   } else {
05393                      ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
05394                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
05395                      if (c) {
05396                         /* Avoid deadlock while destroying channel */
05397                         sig_pri_unlock_private(pri->pvts[chanpos]);
05398                         ast_mutex_unlock(&pri->lock);
05399                         ast_hangup(c);
05400                         ast_mutex_lock(&pri->lock);
05401                      } else {
05402                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
05403                         pri->pvts[chanpos]->call = NULL;
05404                         sig_pri_unlock_private(pri->pvts[chanpos]);
05405                         sig_pri_span_devstate_changed(pri);
05406                      }
05407                      break;
05408                   }
05409                } else {
05410                   /*
05411                    * Release the PRI lock while we create the channel so other
05412                    * threads can send D channel messages.  We must also release
05413                    * the private lock to prevent deadlock while creating the
05414                    * channel.
05415                    */
05416                   sig_pri_unlock_private(pri->pvts[chanpos]);
05417                   ast_mutex_unlock(&pri->lock);
05418                   c = sig_pri_new_ast_channel(pri->pvts[chanpos],
05419                      AST_STATE_RING, law, e->ring.ctype,
05420                      pri->pvts[chanpos]->exten, NULL);
05421                   ast_mutex_lock(&pri->lock);
05422                   sig_pri_lock_private(pri->pvts[chanpos]);
05423                   if (c) {
05424                      /*
05425                       * It is reasonably safe to set the following
05426                       * channel variables while the PRI and DAHDI private
05427                       * structures are locked.  The PBX has not been
05428                       * started yet and it is unlikely that any other task
05429                       * will do anything with the channel we have just
05430                       * created.
05431                       */
05432 #if defined(HAVE_PRI_SUBADDR)
05433                      if (e->ring.calling.subaddress.valid) {
05434                         /* Set Calling Subaddress */
05435                         sig_pri_lock_owner(pri, chanpos);
05436                         sig_pri_set_subaddress(
05437                            &pri->pvts[chanpos]->owner->caller.id.subaddress,
05438                            &e->ring.calling.subaddress);
05439                         if (!e->ring.calling.subaddress.type
05440                            && !ast_strlen_zero(
05441                               (char *) e->ring.calling.subaddress.data)) {
05442                            /* NSAP */
05443                            pbx_builtin_setvar_helper(c, "CALLINGSUBADDR",
05444                               (char *) e->ring.calling.subaddress.data);
05445                         }
05446                         ast_channel_unlock(c);
05447                      }
05448                      if (e->ring.called_subaddress.valid) {
05449                         /* Set Called Subaddress */
05450                         sig_pri_lock_owner(pri, chanpos);
05451                         sig_pri_set_subaddress(
05452                            &pri->pvts[chanpos]->owner->dialed.subaddress,
05453                            &e->ring.called_subaddress);
05454                         if (!e->ring.called_subaddress.type
05455                            && !ast_strlen_zero(
05456                               (char *) e->ring.called_subaddress.data)) {
05457                            /* NSAP */
05458                            pbx_builtin_setvar_helper(c, "CALLEDSUBADDR",
05459                               (char *) e->ring.called_subaddress.data);
05460                         }
05461                         ast_channel_unlock(c);
05462                      }
05463 #else
05464                      if (!ast_strlen_zero(e->ring.callingsubaddr)) {
05465                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
05466                      }
05467 #endif /* !defined(HAVE_PRI_SUBADDR) */
05468                      if (e->ring.ani2 >= 0) {
05469                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
05470                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
05471                      }
05472 
05473 #ifdef SUPPORT_USERUSER
05474                      if (!ast_strlen_zero(e->ring.useruserinfo)) {
05475                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
05476                      }
05477 #endif
05478 
05479                      if (e->ring.redirectingreason >= 0) {
05480                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
05481                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
05482                      }
05483 #if defined(HAVE_PRI_REVERSE_CHARGE)
05484                      pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
05485 #endif
05486 #if defined(HAVE_PRI_SETUP_KEYPAD)
05487                      ast_copy_string(pri->pvts[chanpos]->keypad_digits,
05488                         e->ring.keypad_digits,
05489                         sizeof(pri->pvts[chanpos]->keypad_digits));
05490 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
05491 
05492                      snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
05493                      pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
05494                      ast_channel_lock(c);
05495                      c->dialed.number.plan = e->ring.calledplan;
05496                      ast_channel_unlock(c);
05497 
05498                      sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
05499                         e->ring.subcmds, e->ring.call);
05500                   }
05501                   if (c && !ast_pbx_start(c)) {
05502                      ast_verb(3, "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
05503                         plancallingnum, pri->pvts[chanpos]->exten,
05504                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
05505                      sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
05506                   } else {
05507                      ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
05508                         pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
05509                      if (c) {
05510                         /* Avoid deadlock while destroying channel */
05511                         sig_pri_unlock_private(pri->pvts[chanpos]);
05512                         ast_mutex_unlock(&pri->lock);
05513                         ast_hangup(c);
05514                         ast_mutex_lock(&pri->lock);
05515                      } else {
05516                         pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
05517                         pri->pvts[chanpos]->call = NULL;
05518                         sig_pri_unlock_private(pri->pvts[chanpos]);
05519                         sig_pri_span_devstate_changed(pri);
05520                      }
05521                      break;
05522                   }
05523                }
05524             } else {
05525                ast_verb(3,
05526                   "Span %d: Extension %s@%s does not exist.  Rejecting call from '%s'.\n",
05527                   pri->span, pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context,
05528                   pri->pvts[chanpos]->cid_num);
05529                pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
05530                pri->pvts[chanpos]->call = NULL;
05531                pri->pvts[chanpos]->exten[0] = '\0';
05532                sig_pri_unlock_private(pri->pvts[chanpos]);
05533                sig_pri_span_devstate_changed(pri);
05534                break;
05535             }
05536             sig_pri_unlock_private(pri->pvts[chanpos]);
05537             break;
05538          case PRI_EVENT_RINGING:
05539             if (sig_pri_is_cis_call(e->ringing.channel)) {
05540                sig_pri_handle_cis_subcmds(pri, e->e, e->ringing.subcmds,
05541                   e->ringing.call);
05542                break;
05543             }
05544             chanpos = pri_find_fixup_principle(pri, e->ringing.channel,
05545                e->ringing.call);
05546             if (chanpos < 0) {
05547                break;
05548             }
05549             sig_pri_lock_private(pri->pvts[chanpos]);
05550 
05551             sig_pri_handle_subcmds(pri, chanpos, e->e, e->ringing.channel,
05552                e->ringing.subcmds, e->ringing.call);
05553             sig_pri_cc_generic_check(pri, chanpos, AST_CC_CCNR);
05554             sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
05555             sig_pri_lock_owner(pri, chanpos);
05556             if (pri->pvts[chanpos]->owner) {
05557                ast_setstate(pri->pvts[chanpos]->owner, AST_STATE_RINGING);
05558                ast_channel_unlock(pri->pvts[chanpos]->owner);
05559             }
05560             pri_queue_control(pri, chanpos, AST_CONTROL_RINGING);
05561             if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_ALERTING) {
05562                pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_ALERTING;
05563             }
05564 
05565             if (!pri->pvts[chanpos]->progress
05566                && !pri->pvts[chanpos]->no_b_channel
05567 #ifdef PRI_PROGRESS_MASK
05568                && (e->ringing.progressmask
05569                   & (PRI_PROG_CALL_NOT_E2E_ISDN | PRI_PROG_INBAND_AVAILABLE))
05570 #else
05571                && e->ringing.progress == 8
05572 #endif
05573                ) {
05574                /* Bring voice path up */
05575                pri_queue_control(pri, chanpos, AST_CONTROL_PROGRESS);
05576                pri->pvts[chanpos]->progress = 1;
05577                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05578                sig_pri_open_media(pri->pvts[chanpos]);
05579             }
05580 
05581 #ifdef SUPPORT_USERUSER
05582             if (!ast_strlen_zero(e->ringing.useruserinfo)) {
05583                struct ast_channel *owner;
05584 
05585                sig_pri_lock_owner(pri, chanpos);
05586                owner = pri->pvts[chanpos]->owner;
05587                if (owner) {
05588                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
05589                      e->ringing.useruserinfo);
05590                   ast_channel_unlock(owner);
05591                }
05592             }
05593 #endif
05594 
05595             sig_pri_unlock_private(pri->pvts[chanpos]);
05596             break;
05597          case PRI_EVENT_PROGRESS:
05598             if (sig_pri_is_cis_call(e->proceeding.channel)) {
05599                sig_pri_handle_cis_subcmds(pri, e->e, e->proceeding.subcmds,
05600                   e->proceeding.call);
05601                break;
05602             }
05603             chanpos = pri_find_fixup_principle(pri, e->proceeding.channel,
05604                e->proceeding.call);
05605             if (chanpos < 0) {
05606                break;
05607             }
05608             sig_pri_lock_private(pri->pvts[chanpos]);
05609             sig_pri_handle_subcmds(pri, chanpos, e->e, e->proceeding.channel,
05610                e->proceeding.subcmds, e->proceeding.call);
05611 
05612             if (e->proceeding.cause > -1) {
05613                ast_verb(3, "PROGRESS with cause code %d received\n", e->proceeding.cause);
05614 
05615                /* Work around broken, out of spec USER_BUSY cause in a progress message */
05616                if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
05617                   if (pri->pvts[chanpos]->owner) {
05618                      ast_verb(3, "PROGRESS with 'user busy' received, signaling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
05619 
05620                      pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
05621                      pri_queue_control(pri, chanpos, AST_CONTROL_BUSY);
05622                   }
05623                }
05624             }
05625 
05626             if (!pri->pvts[chanpos]->progress
05627                && !pri->pvts[chanpos]->no_b_channel
05628 #ifdef PRI_PROGRESS_MASK
05629                && (e->proceeding.progressmask
05630                   & (PRI_PROG_CALL_NOT_E2E_ISDN | PRI_PROG_INBAND_AVAILABLE))
05631 #else
05632                && e->proceeding.progress == 8
05633 #endif
05634                ) {
05635                /* Bring voice path up */
05636                ast_debug(1,
05637                   "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
05638                   pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,
05639                   pri->span);
05640                pri_queue_control(pri, chanpos, AST_CONTROL_PROGRESS);
05641                pri->pvts[chanpos]->progress = 1;
05642                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05643                sig_pri_open_media(pri->pvts[chanpos]);
05644             }
05645             sig_pri_unlock_private(pri->pvts[chanpos]);
05646             break;
05647          case PRI_EVENT_PROCEEDING:
05648             if (sig_pri_is_cis_call(e->proceeding.channel)) {
05649                sig_pri_handle_cis_subcmds(pri, e->e, e->proceeding.subcmds,
05650                   e->proceeding.call);
05651                break;
05652             }
05653             chanpos = pri_find_fixup_principle(pri, e->proceeding.channel,
05654                e->proceeding.call);
05655             if (chanpos < 0) {
05656                break;
05657             }
05658             sig_pri_lock_private(pri->pvts[chanpos]);
05659             sig_pri_handle_subcmds(pri, chanpos, e->e, e->proceeding.channel,
05660                e->proceeding.subcmds, e->proceeding.call);
05661             if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING) {
05662                pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
05663                ast_debug(1,
05664                   "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
05665                   pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,
05666                   pri->span);
05667                pri_queue_control(pri, chanpos, AST_CONTROL_PROCEEDING);
05668             }
05669             if (!pri->pvts[chanpos]->progress
05670                && !pri->pvts[chanpos]->no_b_channel
05671 #ifdef PRI_PROGRESS_MASK
05672                && (e->proceeding.progressmask
05673                   & (PRI_PROG_CALL_NOT_E2E_ISDN | PRI_PROG_INBAND_AVAILABLE))
05674 #else
05675                && e->proceeding.progress == 8
05676 #endif
05677                ) {
05678                /* Bring voice path up */
05679                pri_queue_control(pri, chanpos, AST_CONTROL_PROGRESS);
05680                pri->pvts[chanpos]->progress = 1;
05681                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05682                sig_pri_open_media(pri->pvts[chanpos]);
05683             } else if (pri->inband_on_proceeding) {
05684                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05685             }
05686             sig_pri_unlock_private(pri->pvts[chanpos]);
05687             break;
05688          case PRI_EVENT_FACILITY:
05689             if (!e->facility.call || sig_pri_is_cis_call(e->facility.channel)) {
05690                /* Event came in on the dummy channel or a CIS call. */
05691 #if defined(HAVE_PRI_CALL_REROUTING)
05692                sig_pri_handle_cis_subcmds(pri, e->e, e->facility.subcmds,
05693                   e->facility.subcall);
05694 #else
05695                sig_pri_handle_cis_subcmds(pri, e->e, e->facility.subcmds,
05696                   e->facility.call);
05697 #endif   /* !defined(HAVE_PRI_CALL_REROUTING) */
05698                break;
05699             }
05700             chanpos = pri_find_principle_by_call(pri, e->facility.call);
05701             if (chanpos < 0) {
05702                ast_log(LOG_WARNING, "Span %d: Received facility for unknown call.\n",
05703                   pri->span);
05704                break;
05705             }
05706             sig_pri_lock_private(pri->pvts[chanpos]);
05707 #if defined(HAVE_PRI_CALL_REROUTING)
05708             sig_pri_handle_subcmds(pri, chanpos, e->e, e->facility.channel,
05709                e->facility.subcmds, e->facility.subcall);
05710 #else
05711             sig_pri_handle_subcmds(pri, chanpos, e->e, e->facility.channel,
05712                e->facility.subcmds, e->facility.call);
05713 #endif   /* !defined(HAVE_PRI_CALL_REROUTING) */
05714             sig_pri_unlock_private(pri->pvts[chanpos]);
05715             break;
05716          case PRI_EVENT_ANSWER:
05717             if (sig_pri_is_cis_call(e->answer.channel)) {
05718 #if defined(HAVE_PRI_CALL_WAITING)
05719                /* Call is CIS so do normal CONNECT_ACKNOWLEDGE. */
05720                pri_connect_ack(pri->pri, e->answer.call, 0);
05721 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05722                sig_pri_handle_cis_subcmds(pri, e->e, e->answer.subcmds,
05723                   e->answer.call);
05724                break;
05725             }
05726             chanpos = pri_find_fixup_principle(pri, e->answer.channel, e->answer.call);
05727             if (chanpos < 0) {
05728                break;
05729             }
05730 #if defined(HAVE_PRI_CALL_WAITING)
05731             if (pri->pvts[chanpos]->is_call_waiting) {
05732                if (pri->pvts[chanpos]->no_b_channel) {
05733                   int new_chanpos;
05734 
05735                   /*
05736                    * Need to find a free channel now or
05737                    * kill the call with PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION.
05738                    */
05739                   new_chanpos = pri_find_empty_chan(pri, 1);
05740                   if (0 <= new_chanpos) {
05741                      new_chanpos = pri_fixup_principle(pri, new_chanpos,
05742                         e->answer.call);
05743                   }
05744                   if (new_chanpos < 0) {
05745                      /*
05746                       * Either no channel was available or someone stole
05747                       * the channel!
05748                       */
05749                      ast_verb(3,
05750                         "Span %d: Channel not available for call waiting call.\n",
05751                         pri->span);
05752                      sig_pri_lock_private(pri->pvts[chanpos]);
05753                      sig_pri_handle_subcmds(pri, chanpos, e->e, e->answer.channel,
05754                         e->answer.subcmds, e->answer.call);
05755                      sig_pri_cc_generic_check(pri, chanpos, AST_CC_CCBS);
05756                      sig_pri_lock_owner(pri, chanpos);
05757                      if (pri->pvts[chanpos]->owner) {
05758                         pri->pvts[chanpos]->owner->hangupcause = PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION;
05759                         switch (pri->pvts[chanpos]->owner->_state) {
05760                         case AST_STATE_BUSY:
05761                         case AST_STATE_UP:
05762                            ast_softhangup_nolock(pri->pvts[chanpos]->owner, AST_SOFTHANGUP_DEV);
05763                            break;
05764                         default:
05765                            pri_queue_control(pri, chanpos, AST_CONTROL_CONGESTION);
05766                            break;
05767                         }
05768                         ast_channel_unlock(pri->pvts[chanpos]->owner);
05769                      } else {
05770                         pri->pvts[chanpos]->is_call_waiting = 0;
05771                         ast_atomic_fetchadd_int(&pri->num_call_waiting_calls, -1);
05772                         pri_hangup(pri->pri, e->answer.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
05773                         pri->pvts[chanpos]->call = NULL;
05774                      }
05775                      sig_pri_unlock_private(pri->pvts[chanpos]);
05776                      sig_pri_span_devstate_changed(pri);
05777                      break;
05778                   }
05779                   chanpos = new_chanpos;
05780                }
05781                pri_connect_ack(pri->pri, e->answer.call, PVT_TO_CHANNEL(pri->pvts[chanpos]));
05782                sig_pri_span_devstate_changed(pri);
05783             } else {
05784                /* Call is normal so do normal CONNECT_ACKNOWLEDGE. */
05785                pri_connect_ack(pri->pri, e->answer.call, 0);
05786             }
05787 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05788             sig_pri_lock_private(pri->pvts[chanpos]);
05789 
05790 #if defined(HAVE_PRI_CALL_WAITING)
05791             if (pri->pvts[chanpos]->is_call_waiting) {
05792                pri->pvts[chanpos]->is_call_waiting = 0;
05793                ast_atomic_fetchadd_int(&pri->num_call_waiting_calls, -1);
05794             }
05795 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05796             sig_pri_handle_subcmds(pri, chanpos, e->e, e->answer.channel,
05797                e->answer.subcmds, e->answer.call);
05798             if (!ast_strlen_zero(pri->pvts[chanpos]->deferred_digits)) {
05799                /* We have some 'w' deferred digits to dial now. */
05800                ast_verb(3,
05801                   "Span %d: Channel %d/%d dialing deferred digit string: %s\n",
05802                   pri->span, pri->pvts[chanpos]->logicalspan,
05803                   pri->pvts[chanpos]->prioffset,
05804                   pri->pvts[chanpos]->deferred_digits);
05805                if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_DEFER_DIAL) {
05806                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_DEFER_DIAL;
05807                }
05808                sig_pri_dial_digits(pri->pvts[chanpos],
05809                   pri->pvts[chanpos]->deferred_digits);
05810             } else {
05811                if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_CONNECT) {
05812                   pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_CONNECT;
05813                }
05814                sig_pri_open_media(pri->pvts[chanpos]);
05815                pri_queue_control(pri, chanpos, AST_CONTROL_ANSWER);
05816                sig_pri_set_dialing(pri->pvts[chanpos], 0);
05817                /* Enable echo cancellation if it's not on already */
05818                sig_pri_set_echocanceller(pri->pvts[chanpos], 1);
05819             }
05820 
05821 #ifdef SUPPORT_USERUSER
05822             if (!ast_strlen_zero(e->answer.useruserinfo)) {
05823                struct ast_channel *owner;
05824 
05825                sig_pri_lock_owner(pri, chanpos);
05826                owner = pri->pvts[chanpos]->owner;
05827                if (owner) {
05828                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
05829                      e->answer.useruserinfo);
05830                   ast_channel_unlock(owner);
05831                }
05832             }
05833 #endif
05834 
05835             sig_pri_unlock_private(pri->pvts[chanpos]);
05836             break;
05837 #if defined(HAVE_PRI_CALL_WAITING)
05838          case PRI_EVENT_CONNECT_ACK:
05839             if (sig_pri_is_cis_call(e->connect_ack.channel)) {
05840                sig_pri_handle_cis_subcmds(pri, e->e, e->connect_ack.subcmds,
05841                   e->connect_ack.call);
05842                break;
05843             }
05844             chanpos = pri_find_fixup_principle(pri, e->connect_ack.channel,
05845                e->connect_ack.call);
05846             if (chanpos < 0) {
05847                break;
05848             }
05849 
05850             sig_pri_lock_private(pri->pvts[chanpos]);
05851             sig_pri_handle_subcmds(pri, chanpos, e->e, e->connect_ack.channel,
05852                e->connect_ack.subcmds, e->connect_ack.call);
05853             sig_pri_open_media(pri->pvts[chanpos]);
05854             sig_pri_unlock_private(pri->pvts[chanpos]);
05855             sig_pri_span_devstate_changed(pri);
05856             break;
05857 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
05858          case PRI_EVENT_HANGUP:
05859             if (sig_pri_is_cis_call(e->hangup.channel)) {
05860                sig_pri_handle_cis_subcmds(pri, e->e, e->hangup.subcmds,
05861                   e->hangup.call);
05862                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
05863                break;
05864             }
05865             chanpos = pri_find_principle_by_call(pri, e->hangup.call);
05866             if (chanpos < 0) {
05867                /*
05868                 * Continue hanging up the call even though
05869                 * we do not remember it (if we ever did).
05870                 */
05871                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
05872                break;
05873             }
05874             sig_pri_lock_private(pri->pvts[chanpos]);
05875             sig_pri_handle_subcmds(pri, chanpos, e->e, e->hangup.channel,
05876                e->hangup.subcmds, e->hangup.call);
05877             switch (e->hangup.cause) {
05878             case PRI_CAUSE_INVALID_CALL_REFERENCE:
05879                /*
05880                 * The peer denies the existence of this call so we must
05881                 * continue hanging it up and forget about it.
05882                 */
05883                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
05884                pri->pvts[chanpos]->call = NULL;
05885                break;
05886             default:
05887                break;
05888             }
05889             if (!pri->pvts[chanpos]->alreadyhungup) {
05890                /* we're calling here dahdi_hangup so once we get there we need to clear p->call after calling pri_hangup */
05891                pri->pvts[chanpos]->alreadyhungup = 1;
05892                switch (e->hangup.cause) {
05893                case PRI_CAUSE_USER_BUSY:
05894                case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
05895                   sig_pri_cc_generic_check(pri, chanpos, AST_CC_CCBS);
05896                   break;
05897                default:
05898                   break;
05899                }
05900                if (pri->pvts[chanpos]->owner) {
05901                   int do_hangup = 0;
05902 
05903                   /* Queue a BUSY instead of a hangup if our cause is appropriate */
05904                   pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
05905                   switch (pri->pvts[chanpos]->owner->_state) {
05906                   case AST_STATE_BUSY:
05907                   case AST_STATE_UP:
05908                      do_hangup = 1;
05909                      break;
05910                   default:
05911                      if (!pri->pvts[chanpos]->outgoing) {
05912                         /*
05913                          * The incoming call leg hung up before getting
05914                          * connected so just hangup the call.
05915                          */
05916                         do_hangup = 1;
05917                         break;
05918                      }
05919                      switch (e->hangup.cause) {
05920                      case PRI_CAUSE_USER_BUSY:
05921                         pri_queue_control(pri, chanpos, AST_CONTROL_BUSY);
05922                         break;
05923                      case PRI_CAUSE_CALL_REJECTED:
05924                      case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
05925                      case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
05926                      case PRI_CAUSE_SWITCH_CONGESTION:
05927                      case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
05928                      case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
05929                         pri_queue_control(pri, chanpos, AST_CONTROL_CONGESTION);
05930                         break;
05931                      default:
05932                         do_hangup = 1;
05933                         break;
05934                      }
05935                      break;
05936                   }
05937 
05938                   if (do_hangup) {
05939 #if defined(HAVE_PRI_AOC_EVENTS)
05940                      if (detect_aoc_e_subcmd(e->hangup.subcmds)) {
05941                         /* If a AOC-E msg was sent during the release, we must use a
05942                          * AST_CONTROL_HANGUP frame to guarantee that frame gets read before hangup */
05943                         pri_queue_control(pri, chanpos, AST_CONTROL_HANGUP);
05944                      } else {
05945                         pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05946                      }
05947 #else
05948                      pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05949 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
05950                   }
05951                } else {
05952                   /*
05953                    * Continue hanging up the call even though
05954                    * we do not have an owner.
05955                    */
05956                   pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
05957                   pri->pvts[chanpos]->call = NULL;
05958                }
05959                ast_verb(3, "Span %d: Channel %d/%d got hangup, cause %d\n",
05960                   pri->span, pri->pvts[chanpos]->logicalspan,
05961                   pri->pvts[chanpos]->prioffset, e->hangup.cause);
05962             } else {
05963                /* Continue hanging up the call. */
05964                pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
05965                pri->pvts[chanpos]->call = NULL;
05966             }
05967 #if defined(FORCE_RESTART_UNAVAIL_CHANS)
05968             if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL
05969                && pri->sig != SIG_BRI_PTMP && !pri->resetting
05970                && pri->pvts[chanpos]->resetting == SIG_PRI_RESET_IDLE) {
05971                ast_verb(3,
05972                   "Span %d: Forcing restart of channel %d/%d since channel reported in use\n",
05973                   pri->span, pri->pvts[chanpos]->logicalspan,
05974                   pri->pvts[chanpos]->prioffset);
05975                pri->pvts[chanpos]->resetting = SIG_PRI_RESET_ACTIVE;
05976                pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
05977             }
05978 #endif   /* defined(FORCE_RESTART_UNAVAIL_CHANS) */
05979             if (e->hangup.aoc_units > -1)
05980                ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
05981                   pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
05982 
05983 #ifdef SUPPORT_USERUSER
05984             if (!ast_strlen_zero(e->hangup.useruserinfo)) {
05985                struct ast_channel *owner;
05986 
05987                sig_pri_lock_owner(pri, chanpos);
05988                owner = pri->pvts[chanpos]->owner;
05989                if (owner) {
05990                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
05991                      e->hangup.useruserinfo);
05992                   ast_channel_unlock(owner);
05993                }
05994             }
05995 #endif
05996 
05997             sig_pri_unlock_private(pri->pvts[chanpos]);
05998             sig_pri_span_devstate_changed(pri);
05999             break;
06000          case PRI_EVENT_HANGUP_REQ:
06001             if (sig_pri_is_cis_call(e->hangup.channel)) {
06002                sig_pri_handle_cis_subcmds(pri, e->e, e->hangup.subcmds,
06003                   e->hangup.call);
06004                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
06005                break;
06006             }
06007             chanpos = pri_find_principle_by_call(pri, e->hangup.call);
06008             if (chanpos < 0) {
06009                /*
06010                 * Continue hanging up the call even though
06011                 * we do not remember it (if we ever did).
06012                 */
06013                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
06014                break;
06015             }
06016             sig_pri_lock_private(pri->pvts[chanpos]);
06017             sig_pri_handle_subcmds(pri, chanpos, e->e, e->hangup.channel,
06018                e->hangup.subcmds, e->hangup.call);
06019 #if defined(HAVE_PRI_CALL_HOLD)
06020             if (e->hangup.call_active && e->hangup.call_held
06021                && pri->hold_disconnect_transfer) {
06022                /* We are to transfer the call instead of simply hanging up. */
06023                sig_pri_unlock_private(pri->pvts[chanpos]);
06024                if (!sig_pri_attempt_transfer(pri, e->hangup.call_held, 1,
06025                   e->hangup.call_active, 0, NULL, NULL)) {
06026                   break;
06027                }
06028                sig_pri_lock_private(pri->pvts[chanpos]);
06029             }
06030 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06031             switch (e->hangup.cause) {
06032             case PRI_CAUSE_USER_BUSY:
06033             case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
06034                sig_pri_cc_generic_check(pri, chanpos, AST_CC_CCBS);
06035                break;
06036             case PRI_CAUSE_INVALID_CALL_REFERENCE:
06037                /*
06038                 * The peer denies the existence of this call so we must
06039                 * continue hanging it up and forget about it.  We should not
06040                 * get this cause here, but for completeness we will handle it
06041                 * anyway.
06042                 */
06043                pri_hangup(pri->pri, e->hangup.call, e->hangup.cause);
06044                pri->pvts[chanpos]->call = NULL;
06045                break;
06046             default:
06047                break;
06048             }
06049             if (pri->pvts[chanpos]->owner) {
06050                int do_hangup = 0;
06051 
06052                pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
06053                switch (pri->pvts[chanpos]->owner->_state) {
06054                case AST_STATE_BUSY:
06055                case AST_STATE_UP:
06056                   do_hangup = 1;
06057                   break;
06058                default:
06059                   if (!pri->pvts[chanpos]->outgoing) {
06060                      /*
06061                       * The incoming call leg hung up before getting
06062                       * connected so just hangup the call.
06063                       */
06064                      do_hangup = 1;
06065                      break;
06066                   }
06067                   switch (e->hangup.cause) {
06068                   case PRI_CAUSE_USER_BUSY:
06069                      pri_queue_control(pri, chanpos, AST_CONTROL_BUSY);
06070                      break;
06071                   case PRI_CAUSE_CALL_REJECTED:
06072                   case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
06073                   case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
06074                   case PRI_CAUSE_SWITCH_CONGESTION:
06075                   case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
06076                   case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
06077                      pri_queue_control(pri, chanpos, AST_CONTROL_CONGESTION);
06078                      break;
06079                   default:
06080                      do_hangup = 1;
06081                      break;
06082                   }
06083                   break;
06084                }
06085 
06086                if (do_hangup) {
06087 #if defined(HAVE_PRI_AOC_EVENTS)
06088                   if (!pri->pvts[chanpos]->holding_aoce
06089                      && pri->aoce_delayhangup
06090                      && ast_bridged_channel(pri->pvts[chanpos]->owner)) {
06091                      sig_pri_send_aoce_termination_request(pri, chanpos,
06092                         pri_get_timer(pri->pri, PRI_TIMER_T305) / 2);
06093                   } else if (detect_aoc_e_subcmd(e->hangup.subcmds)) {
06094                      /* If a AOC-E msg was sent during the Disconnect, we must use a AST_CONTROL_HANGUP frame
06095                       * to guarantee that frame gets read before hangup */
06096                      pri_queue_control(pri, chanpos, AST_CONTROL_HANGUP);
06097                   } else {
06098                      pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06099                   }
06100 #else
06101                   pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06102 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
06103                }
06104                ast_verb(3, "Span %d: Channel %d/%d got hangup request, cause %d\n",
06105                   pri->span, pri->pvts[chanpos]->logicalspan,
06106                   pri->pvts[chanpos]->prioffset, e->hangup.cause);
06107             } else {
06108                /*
06109                 * Continue hanging up the call even though
06110                 * we do not have an owner.
06111                 */
06112                pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
06113                pri->pvts[chanpos]->call = NULL;
06114             }
06115 #if defined(FORCE_RESTART_UNAVAIL_CHANS)
06116             if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL
06117                && pri->sig != SIG_BRI_PTMP && !pri->resetting
06118                && pri->pvts[chanpos]->resetting == SIG_PRI_RESET_IDLE) {
06119                ast_verb(3,
06120                   "Span %d: Forcing restart of channel %d/%d since channel reported in use\n",
06121                   pri->span, pri->pvts[chanpos]->logicalspan,
06122                   pri->pvts[chanpos]->prioffset);
06123                pri->pvts[chanpos]->resetting = SIG_PRI_RESET_ACTIVE;
06124                pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
06125             }
06126 #endif   /* defined(FORCE_RESTART_UNAVAIL_CHANS) */
06127 
06128 #ifdef SUPPORT_USERUSER
06129             if (!ast_strlen_zero(e->hangup.useruserinfo)) {
06130                struct ast_channel *owner;
06131 
06132                sig_pri_lock_owner(pri, chanpos);
06133                owner = pri->pvts[chanpos]->owner;
06134                if (owner) {
06135                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
06136                      e->hangup.useruserinfo);
06137                   ast_channel_unlock(owner);
06138                }
06139             }
06140 #endif
06141 
06142             sig_pri_unlock_private(pri->pvts[chanpos]);
06143             sig_pri_span_devstate_changed(pri);
06144             break;
06145          case PRI_EVENT_HANGUP_ACK:
06146             if (sig_pri_is_cis_call(e->hangup.channel)) {
06147                sig_pri_handle_cis_subcmds(pri, e->e, e->hangup.subcmds,
06148                   e->hangup.call);
06149                break;
06150             }
06151             chanpos = pri_find_principle_by_call(pri, e->hangup.call);
06152             if (chanpos < 0) {
06153                break;
06154             }
06155             sig_pri_lock_private(pri->pvts[chanpos]);
06156             pri->pvts[chanpos]->call = NULL;
06157             if (pri->pvts[chanpos]->owner) {
06158                ast_verb(3, "Span %d: Channel %d/%d got hangup ACK\n", pri->span,
06159                   pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset);
06160             }
06161 #ifdef SUPPORT_USERUSER
06162             if (!ast_strlen_zero(e->hangup.useruserinfo)) {
06163                struct ast_channel *owner;
06164 
06165                sig_pri_lock_owner(pri, chanpos);
06166                owner = pri->pvts[chanpos]->owner;
06167                if (owner) {
06168                   pbx_builtin_setvar_helper(owner, "USERUSERINFO",
06169                      e->hangup.useruserinfo);
06170                   ast_channel_unlock(owner);
06171                }
06172             }
06173 #endif
06174             sig_pri_unlock_private(pri->pvts[chanpos]);
06175             sig_pri_span_devstate_changed(pri);
06176             break;
06177          case PRI_EVENT_CONFIG_ERR:
06178             ast_log(LOG_WARNING, "PRI Error on span %d: %s\n", pri->span, e->err.err);
06179             break;
06180          case PRI_EVENT_RESTART_ACK:
06181             chanpos = pri_find_principle(pri, e->restartack.channel, NULL);
06182             if (chanpos < 0) {
06183                /* Sometime switches (e.g. I421 / British Telecom) don't give us the
06184                   channel number, so we have to figure it out...  This must be why
06185                   everybody resets exactly a channel at a time. */
06186                for (x = 0; x < pri->numchans; x++) {
06187                   if (pri->pvts[x]
06188                      && pri->pvts[x]->resetting != SIG_PRI_RESET_IDLE) {
06189                      chanpos = x;
06190                      sig_pri_lock_private(pri->pvts[chanpos]);
06191                      ast_debug(1,
06192                         "Span %d: Assuming restart ack is for channel %d/%d\n",
06193                         pri->span, pri->pvts[chanpos]->logicalspan,
06194                         pri->pvts[chanpos]->prioffset);
06195                      if (pri->pvts[chanpos]->owner) {
06196                         ast_log(LOG_WARNING,
06197                            "Span %d: Got restart ack on channel %d/%d with owner\n",
06198                            pri->span, pri->pvts[chanpos]->logicalspan,
06199                            pri->pvts[chanpos]->prioffset);
06200                         pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06201                      }
06202                      pri->pvts[chanpos]->resetting = SIG_PRI_RESET_IDLE;
06203                      ast_verb(3,
06204                         "Span %d: Channel %d/%d successfully restarted\n",
06205                         pri->span, pri->pvts[chanpos]->logicalspan,
06206                         pri->pvts[chanpos]->prioffset);
06207                      sig_pri_unlock_private(pri->pvts[chanpos]);
06208                      if (pri->resetting)
06209                         pri_check_restart(pri);
06210                      break;
06211                   }
06212                }
06213                if (chanpos < 0) {
06214                   ast_log(LOG_WARNING,
06215                      "Span %d: Restart ACK on strange channel %d/%d\n",
06216                      pri->span, PRI_SPAN(e->restartack.channel),
06217                      PRI_CHANNEL(e->restartack.channel));
06218                }
06219             } else {
06220                sig_pri_lock_private(pri->pvts[chanpos]);
06221                if (pri->pvts[chanpos]->resetting == SIG_PRI_RESET_IDLE) {
06222                   /* The channel is not in the resetting state. */
06223                   ast_debug(1,
06224                      "Span %d: Unexpected or late restart ack on channel %d/%d (Ignoring)\n",
06225                      pri->span, pri->pvts[chanpos]->logicalspan,
06226                      pri->pvts[chanpos]->prioffset);
06227                   sig_pri_unlock_private(pri->pvts[chanpos]);
06228                   break;
06229                }
06230                if (pri->pvts[chanpos]->owner) {
06231                   ast_log(LOG_WARNING,
06232                      "Span %d: Got restart ack on channel %d/%d with owner\n",
06233                      pri->span, pri->pvts[chanpos]->logicalspan,
06234                      pri->pvts[chanpos]->prioffset);
06235                   pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06236                }
06237                pri->pvts[chanpos]->resetting = SIG_PRI_RESET_IDLE;
06238                ast_verb(3,
06239                   "Span %d: Channel %d/%d successfully restarted\n",
06240                   pri->span, pri->pvts[chanpos]->logicalspan,
06241                   pri->pvts[chanpos]->prioffset);
06242                sig_pri_unlock_private(pri->pvts[chanpos]);
06243                if (pri->resetting)
06244                   pri_check_restart(pri);
06245             }
06246             break;
06247          case PRI_EVENT_SETUP_ACK:
06248             if (sig_pri_is_cis_call(e->setup_ack.channel)) {
06249                sig_pri_handle_cis_subcmds(pri, e->e, e->setup_ack.subcmds,
06250                   e->setup_ack.call);
06251                break;
06252             }
06253             chanpos = pri_find_fixup_principle(pri, e->setup_ack.channel,
06254                e->setup_ack.call);
06255             if (chanpos < 0) {
06256                break;
06257             }
06258             sig_pri_lock_private(pri->pvts[chanpos]);
06259             sig_pri_handle_subcmds(pri, chanpos, e->e, e->setup_ack.channel,
06260                e->setup_ack.subcmds, e->setup_ack.call);
06261             if (pri->pvts[chanpos]->call_level < SIG_PRI_CALL_LEVEL_OVERLAP) {
06262                pri->pvts[chanpos]->call_level = SIG_PRI_CALL_LEVEL_OVERLAP;
06263             }
06264 
06265             /* Send any queued digits */
06266             len = strlen(pri->pvts[chanpos]->dialdest);
06267             for (x = 0; x < len; ++x) {
06268                ast_debug(1, "Sending pending digit '%c'\n", pri->pvts[chanpos]->dialdest[x]);
06269                pri_information(pri->pri, pri->pvts[chanpos]->call,
06270                   pri->pvts[chanpos]->dialdest[x]);
06271             }
06272 
06273             if (!pri->pvts[chanpos]->progress
06274                && (pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING)
06275                && !pri->pvts[chanpos]->digital
06276                && !pri->pvts[chanpos]->no_b_channel) {
06277                /*
06278                 * Call has a channel.
06279                 * Indicate for overlap dialing that dialtone may be present.
06280                 */
06281                pri_queue_control(pri, chanpos, AST_CONTROL_PROGRESS);
06282                pri->pvts[chanpos]->progress = 1;/* Claim to have seen inband-information */
06283                sig_pri_set_dialing(pri->pvts[chanpos], 0);
06284                sig_pri_open_media(pri->pvts[chanpos]);
06285             }
06286             sig_pri_unlock_private(pri->pvts[chanpos]);
06287             break;
06288          case PRI_EVENT_NOTIFY:
06289             if (sig_pri_is_cis_call(e->notify.channel)) {
06290 #if defined(HAVE_PRI_CALL_HOLD)
06291                sig_pri_handle_cis_subcmds(pri, e->e, e->notify.subcmds,
06292                   e->notify.call);
06293 #else
06294                sig_pri_handle_cis_subcmds(pri, e->e, e->notify.subcmds, NULL);
06295 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
06296                break;
06297             }
06298 #if defined(HAVE_PRI_CALL_HOLD)
06299             chanpos = pri_find_principle_by_call(pri, e->notify.call);
06300             if (chanpos < 0) {
06301                ast_log(LOG_WARNING, "Span %d: Received NOTIFY for unknown call.\n",
06302                   pri->span);
06303                break;
06304             }
06305 #else
06306             /*
06307              * This version of libpri does not supply a call pointer for
06308              * this message.  We are just going to have to trust that the
06309              * correct principle is found.
06310              */
06311             chanpos = pri_find_principle(pri, e->notify.channel, NULL);
06312             if (chanpos < 0) {
06313                ast_log(LOG_WARNING, "Received NOTIFY on unconfigured channel %d/%d span %d\n",
06314                   PRI_SPAN(e->notify.channel), PRI_CHANNEL(e->notify.channel), pri->span);
06315                break;
06316             }
06317 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
06318             sig_pri_lock_private(pri->pvts[chanpos]);
06319 #if defined(HAVE_PRI_CALL_HOLD)
06320             sig_pri_handle_subcmds(pri, chanpos, e->e, e->notify.channel,
06321                e->notify.subcmds, e->notify.call);
06322 #else
06323             sig_pri_handle_subcmds(pri, chanpos, e->e, e->notify.channel,
06324                e->notify.subcmds, NULL);
06325 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
06326             switch (e->notify.info) {
06327             case PRI_NOTIFY_REMOTE_HOLD:
06328                if (!pri->discardremoteholdretrieval) {
06329                   pri_queue_control(pri, chanpos, AST_CONTROL_HOLD);
06330                }
06331                break;
06332             case PRI_NOTIFY_REMOTE_RETRIEVAL:
06333                if (!pri->discardremoteholdretrieval) {
06334                   pri_queue_control(pri, chanpos, AST_CONTROL_UNHOLD);
06335                }
06336                break;
06337             }
06338             sig_pri_unlock_private(pri->pvts[chanpos]);
06339             break;
06340 #if defined(HAVE_PRI_CALL_HOLD)
06341          case PRI_EVENT_HOLD:
06342             /* We should not be getting any CIS calls with this message type. */
06343             if (sig_pri_handle_hold(pri, e)) {
06344                pri_hold_rej(pri->pri, e->hold.call,
06345                   PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
06346             } else {
06347                pri_hold_ack(pri->pri, e->hold.call);
06348             }
06349             break;
06350 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06351 #if defined(HAVE_PRI_CALL_HOLD)
06352          case PRI_EVENT_HOLD_ACK:
06353             ast_debug(1, "Event: HOLD_ACK\n");
06354             break;
06355 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06356 #if defined(HAVE_PRI_CALL_HOLD)
06357          case PRI_EVENT_HOLD_REJ:
06358             ast_debug(1, "Event: HOLD_REJ\n");
06359             break;
06360 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06361 #if defined(HAVE_PRI_CALL_HOLD)
06362          case PRI_EVENT_RETRIEVE:
06363             /* We should not be getting any CIS calls with this message type. */
06364             sig_pri_handle_retrieve(pri, e);
06365             break;
06366 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06367 #if defined(HAVE_PRI_CALL_HOLD)
06368          case PRI_EVENT_RETRIEVE_ACK:
06369             ast_debug(1, "Event: RETRIEVE_ACK\n");
06370             break;
06371 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06372 #if defined(HAVE_PRI_CALL_HOLD)
06373          case PRI_EVENT_RETRIEVE_REJ:
06374             ast_debug(1, "Event: RETRIEVE_REJ\n");
06375             break;
06376 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
06377          default:
06378             ast_debug(1, "Event: %d\n", e->e);
06379             break;
06380          }
06381       }
06382       ast_mutex_unlock(&pri->lock);
06383    }
06384    /* Never reached */
06385    return NULL;
06386 }
06387 
06388 void sig_pri_init_pri(struct sig_pri_span *pri)
06389 {
06390    int i;
06391 
06392    memset(pri, 0, sizeof(*pri));
06393 
06394    ast_mutex_init(&pri->lock);
06395 
06396    pri->master = AST_PTHREADT_NULL;
06397    for (i = 0; i < SIG_PRI_NUM_DCHANS; i++)
06398       pri->fds[i] = -1;
06399 }
06400 
06401 int sig_pri_hangup(struct sig_pri_chan *p, struct ast_channel *ast)
06402 {
06403    ast_debug(1, "%s %d\n", __FUNCTION__, p->channel);
06404    if (!ast->tech_pvt) {
06405       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
06406       return 0;
06407    }
06408 
06409    sig_pri_set_outgoing(p, 0);
06410    sig_pri_set_digital(p, 0); /* push up to parent for EC*/
06411 #if defined(HAVE_PRI_CALL_WAITING)
06412    if (p->is_call_waiting) {
06413       p->is_call_waiting = 0;
06414       ast_atomic_fetchadd_int(&p->pri->num_call_waiting_calls, -1);
06415    }
06416 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
06417    p->call_level = SIG_PRI_CALL_LEVEL_IDLE;
06418    p->progress = 0;
06419    p->cid_num[0] = '\0';
06420    p->cid_subaddr[0] = '\0';
06421    p->cid_name[0] = '\0';
06422    p->user_tag[0] = '\0';
06423    p->exten[0] = '\0';
06424    sig_pri_set_dialing(p, 0);
06425 
06426    /* Make sure we really have a call */
06427    pri_grab(p, p->pri);
06428    if (p->call) {
06429 #if defined(SUPPORT_USERUSER)
06430       const char *useruser = pbx_builtin_getvar_helper(ast, "USERUSERINFO");
06431 
06432       if (!ast_strlen_zero(useruser)) {
06433          pri_call_set_useruser(p->call, useruser);
06434       }
06435 #endif   /* defined(SUPPORT_USERUSER) */
06436 
06437 #if defined(HAVE_PRI_AOC_EVENTS)
06438       if (p->holding_aoce) {
06439          pri_aoc_e_send(p->pri->pri, p->call, &p->aoc_e);
06440       }
06441 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
06442 
06443       if (p->alreadyhungup) {
06444          ast_debug(1, "Already hungup...  Calling hangup once, and clearing call\n");
06445 
06446          pri_hangup(p->pri->pri, p->call, -1);
06447          p->call = NULL;
06448       } else {
06449          const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
06450          int icause = ast->hangupcause ? ast->hangupcause : -1;
06451 
06452          p->alreadyhungup = 1;
06453          if (!ast_strlen_zero(cause)) {
06454             if (atoi(cause)) {
06455                icause = atoi(cause);
06456             }
06457          }
06458          ast_debug(1,
06459             "Not yet hungup...  Calling hangup with cause %d, and clearing call\n",
06460             icause);
06461 
06462          pri_hangup(p->pri->pri, p->call, icause);
06463       }
06464    }
06465 #if defined(HAVE_PRI_AOC_EVENTS)
06466    p->aoc_s_request_invoke_id_valid = 0;
06467    p->holding_aoce = 0;
06468    p->waiting_for_aoce = 0;
06469 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
06470 
06471    p->allocated = 0;
06472    p->owner = NULL;
06473 
06474    sig_pri_span_devstate_changed(p->pri);
06475    pri_rel(p->pri);
06476    return 0;
06477 }
06478 
06479 /*!
06480  * \brief Extract the called number and subaddress from the dial string.
06481  * \since 1.8
06482  *
06483  * \param p sig_pri channel structure.
06484  * \param rdest Dial string buffer to extract called number and subaddress.
06485  * \param called Buffer to fill with extracted <number>[:<subaddress>]
06486  * \param called_buff_size Size of buffer to fill.
06487  *
06488  * \note Parsing must remain in sync with sig_pri_call().
06489  *
06490  * \return Nothing
06491  */
06492 void sig_pri_extract_called_num_subaddr(struct sig_pri_chan *p, const char *rdest, char *called, size_t called_buff_size)
06493 {
06494    char *dial;
06495    char *number;
06496    char *subaddr;
06497    AST_DECLARE_APP_ARGS(args,
06498       AST_APP_ARG(group);  /* channel/group token */
06499       AST_APP_ARG(ext); /* extension token */
06500       //AST_APP_ARG(opts); /* options token */
06501       AST_APP_ARG(other);  /* Any remining unused arguments */
06502    );
06503 
06504    /* Get private copy of dial string and break it up. */
06505    dial = ast_strdupa(rdest);
06506    AST_NONSTANDARD_APP_ARGS(args, dial, '/');
06507 
06508    number = args.ext;
06509    if (!number) {
06510       number = "";
06511    }
06512 
06513    /* Find and extract dialed_subaddress */
06514    subaddr = strchr(number, ':');
06515    if (subaddr) {
06516       *subaddr++ = '\0';
06517 
06518       /* Skip subaddress type prefix. */
06519       switch (*subaddr) {
06520       case 'U':
06521       case 'u':
06522       case 'N':
06523       case 'n':
06524          ++subaddr;
06525          break;
06526       default:
06527          break;
06528       }
06529    }
06530 
06531    /* Skip type-of-number/dial-plan prefix characters. */
06532    if (strlen(number) < p->stripmsd) {
06533       number = "";
06534    } else {
06535       char *deferred;
06536 
06537       number += p->stripmsd;
06538       deferred = strchr(number, 'w');
06539       if (deferred) {
06540          /* Remove any 'w' deferred digits. */
06541          *deferred = '\0';
06542       }
06543       while (isalpha(*number)) {
06544          ++number;
06545       }
06546    }
06547 
06548    /* Fill buffer with extracted number and subaddress. */
06549    if (ast_strlen_zero(subaddr)) {
06550       /* Put in called number only since there is no subaddress. */
06551       snprintf(called, called_buff_size, "%s", number);
06552    } else {
06553       /* Put in called number and subaddress. */
06554       snprintf(called, called_buff_size, "%s:%s", number, subaddr);
06555    }
06556 }
06557 
06558 enum SIG_PRI_CALL_OPT_FLAGS {
06559    OPT_KEYPAD =         (1 << 0),
06560    OPT_REVERSE_CHARGE = (1 << 1),   /* Collect call */
06561    OPT_AOC_REQUEST =    (1 << 2),   /* AOC Request */
06562 };
06563 enum SIG_PRI_CALL_OPT_ARGS {
06564    OPT_ARG_KEYPAD = 0,
06565    OPT_ARG_AOC_REQUEST,
06566 
06567    /* note: this entry _MUST_ be the last one in the enum */
06568    OPT_ARG_ARRAY_SIZE,
06569 };
06570 
06571 AST_APP_OPTIONS(sig_pri_call_opts, BEGIN_OPTIONS
06572    AST_APP_OPTION_ARG('K', OPT_KEYPAD, OPT_ARG_KEYPAD),
06573    AST_APP_OPTION('R', OPT_REVERSE_CHARGE),
06574    AST_APP_OPTION_ARG('A', OPT_AOC_REQUEST, OPT_ARG_AOC_REQUEST),
06575 END_OPTIONS);
06576 
06577 /*! \note Parsing must remain in sync with sig_pri_extract_called_num_subaddr(). */
06578 int sig_pri_call(struct sig_pri_chan *p, struct ast_channel *ast, char *rdest, int timeout, int layer1)
06579 {
06580    char dest[256]; /* must be same length as p->dialdest */
06581    struct ast_party_subaddress dialed_subaddress; /* Called subaddress */
06582    struct pri_sr *sr;
06583    char *c, *l, *n, *s;
06584 #ifdef SUPPORT_USERUSER
06585    const char *useruser;
06586 #endif
06587    int core_id;
06588    int pridialplan;
06589    int dp_strip;
06590    int prilocaldialplan;
06591    int ldp_strip;
06592    int exclusive;
06593 #if defined(HAVE_PRI_SETUP_KEYPAD)
06594    const char *keypad;
06595 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
06596    AST_DECLARE_APP_ARGS(args,
06597       AST_APP_ARG(group);  /* channel/group token */
06598       AST_APP_ARG(ext); /* extension token */
06599       AST_APP_ARG(opts);   /* options token */
06600       AST_APP_ARG(other);  /* Any remining unused arguments */
06601    );
06602    struct ast_flags opts;
06603    char *opt_args[OPT_ARG_ARRAY_SIZE];
06604 
06605    ast_log(LOG_DEBUG, "CALLER NAME: %s NUM: %s\n",
06606       S_COR(ast->connected.id.name.valid, ast->connected.id.name.str, ""),
06607       S_COR(ast->connected.id.number.valid, ast->connected.id.number.str, ""));
06608 
06609    if (!p->pri) {
06610       ast_log(LOG_ERROR, "Could not find pri on channel %d\n", p->channel);
06611       return -1;
06612    }
06613 
06614    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
06615       ast_log(LOG_WARNING, "sig_pri_call called on %s, neither down nor reserved\n", ast->name);
06616       return -1;
06617    }
06618 
06619    p->dialdest[0] = '\0';
06620    sig_pri_set_outgoing(p, 1);
06621 
06622    ast_copy_string(dest, rdest, sizeof(dest));
06623    AST_NONSTANDARD_APP_ARGS(args, dest, '/');
06624    if (ast_app_parse_options(sig_pri_call_opts, &opts, opt_args, args.opts)) {
06625       /* General invalid option syntax. */
06626       return -1;
06627    }
06628 
06629    c = args.ext;
06630    if (!c) {
06631       c = "";
06632    }
06633 
06634    /* setup dialed_subaddress if found */
06635    ast_party_subaddress_init(&dialed_subaddress);
06636    s = strchr(c, ':');
06637    if (s) {
06638       *s = '\0';
06639       s++;
06640       /* prefix */
06641       /* 'n' = NSAP */
06642       /* 'u' = User Specified */
06643       /* Default = NSAP */
06644       switch (*s) {
06645       case 'U':
06646       case 'u':
06647          s++;
06648          dialed_subaddress.type = 2;
06649          break;
06650       case 'N':
06651       case 'n':
06652          s++;
06653          /* default already covered with ast_party_subaddress_init */
06654          break;
06655       }
06656       dialed_subaddress.str = s;
06657       dialed_subaddress.valid = 1;
06658    }
06659 
06660    l = NULL;
06661    n = NULL;
06662    if (!p->hidecallerid) {
06663       if (ast->connected.id.number.valid) {
06664          /* If we get to the end of this loop without breaking, there's no
06665           * calleridnum.  This is done instead of testing for "unknown" or
06666           * the thousands of other ways that the calleridnum could be
06667           * invalid. */
06668          for (l = ast->connected.id.number.str; l && *l; l++) {
06669             if (strchr("0123456789", *l)) {
06670                l = ast->connected.id.number.str;
06671                break;
06672             }
06673          }
06674       } else {
06675          l = NULL;
06676       }
06677       if (!p->hidecalleridname) {
06678          n = ast->connected.id.name.valid ? ast->connected.id.name.str : NULL;
06679       }
06680    }
06681 
06682    if (strlen(c) < p->stripmsd) {
06683       ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
06684       return -1;
06685    }
06686 
06687    /* Extract any 'w' deferred digits. */
06688    s = strchr(c + p->stripmsd, 'w');
06689    if (s) {
06690       *s++ = '\0';
06691       ast_copy_string(p->deferred_digits, s, sizeof(p->deferred_digits));
06692       /*
06693        * Since we have a 'w', this means that there will not be any
06694        * more normal dialed digits.  Therefore, the sending complete
06695        * ie needs to be sent with any normal digits.
06696        */
06697    } else {
06698       p->deferred_digits[0] = '\0';
06699    }
06700 
06701    pri_grab(p, p->pri);
06702    if (!(p->call = pri_new_call(p->pri->pri))) {
06703       ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
06704       pri_rel(p->pri);
06705       return -1;
06706    }
06707    if (!(sr = pri_sr_new())) {
06708       ast_log(LOG_WARNING, "Failed to allocate setup request on channel %d\n",
06709          p->channel);
06710       pri_destroycall(p->pri->pri, p->call);
06711       p->call = NULL;
06712       pri_rel(p->pri);
06713       return -1;
06714    }
06715 
06716    sig_pri_set_digital(p, IS_DIGITAL(ast->transfercapability));   /* push up to parent for EC */
06717 
06718 #if defined(HAVE_PRI_CALL_WAITING)
06719    if (p->is_call_waiting) {
06720       /*
06721        * Indicate that this is a call waiting call.
06722        * i.e., Normal call but with no B channel.
06723        */
06724       pri_sr_set_channel(sr, 0, 0, 1);
06725    } else
06726 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
06727    {
06728       /* Should the picked channel be used exclusively? */
06729       if (p->priexclusive || p->pri->nodetype == PRI_NETWORK) {
06730          exclusive = 1;
06731       } else {
06732          exclusive = 0;
06733       }
06734       pri_sr_set_channel(sr, PVT_TO_CHANNEL(p), exclusive, 1);
06735    }
06736 
06737    pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability,
06738       (p->digital ? -1 : layer1));
06739 
06740    if (p->pri->facilityenable)
06741       pri_facility_enable(p->pri->pri);
06742 
06743    ast_verb(3, "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
06744    dp_strip = 0;
06745    pridialplan = p->pri->dialplan - 1;
06746    if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
06747       if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
06748          if (pridialplan == -2) {
06749             dp_strip = strlen(p->pri->internationalprefix);
06750          }
06751          pridialplan = PRI_INTERNATIONAL_ISDN;
06752       } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
06753          if (pridialplan == -2) {
06754             dp_strip = strlen(p->pri->nationalprefix);
06755          }
06756          pridialplan = PRI_NATIONAL_ISDN;
06757       } else {
06758          pridialplan = PRI_LOCAL_ISDN;
06759       }
06760    }
06761    while (c[p->stripmsd] > '9' && c[p->stripmsd] != '*' && c[p->stripmsd] != '#') {
06762       switch (c[p->stripmsd]) {
06763       case 'U':
06764          pridialplan = (PRI_TON_UNKNOWN << 4) | (pridialplan & 0xf);
06765          break;
06766       case 'I':
06767          pridialplan = (PRI_TON_INTERNATIONAL << 4) | (pridialplan & 0xf);
06768          break;
06769       case 'N':
06770          pridialplan = (PRI_TON_NATIONAL << 4) | (pridialplan & 0xf);
06771          break;
06772       case 'L':
06773          pridialplan = (PRI_TON_NET_SPECIFIC << 4) | (pridialplan & 0xf);
06774          break;
06775       case 'S':
06776          pridialplan = (PRI_TON_SUBSCRIBER << 4) | (pridialplan & 0xf);
06777          break;
06778       case 'V':
06779          pridialplan = (PRI_TON_ABBREVIATED << 4) | (pridialplan & 0xf);
06780          break;
06781       case 'R':
06782          pridialplan = (PRI_TON_RESERVED << 4) | (pridialplan & 0xf);
06783          break;
06784       case 'u':
06785          pridialplan = PRI_NPI_UNKNOWN | (pridialplan & 0xf0);
06786          break;
06787       case 'e':
06788          pridialplan = PRI_NPI_E163_E164 | (pridialplan & 0xf0);
06789          break;
06790       case 'x':
06791          pridialplan = PRI_NPI_X121 | (pridialplan & 0xf0);
06792          break;
06793       case 'f':
06794          pridialplan = PRI_NPI_F69 | (pridialplan & 0xf0);
06795          break;
06796       case 'n':
06797          pridialplan = PRI_NPI_NATIONAL | (pridialplan & 0xf0);
06798          break;
06799       case 'p':
06800          pridialplan = PRI_NPI_PRIVATE | (pridialplan & 0xf0);
06801          break;
06802       case 'r':
06803          pridialplan = PRI_NPI_RESERVED | (pridialplan & 0xf0);
06804          break;
06805       default:
06806          if (isalpha(c[p->stripmsd])) {
06807             ast_log(LOG_WARNING, "Unrecognized pridialplan %s modifier: %c\n",
06808                c[p->stripmsd] > 'Z' ? "NPI" : "TON", c[p->stripmsd]);
06809          }
06810          break;
06811       }
06812       c++;
06813    }
06814 #if defined(HAVE_PRI_SETUP_KEYPAD)
06815    if (ast_test_flag(&opts, OPT_KEYPAD)
06816       && !ast_strlen_zero(opt_args[OPT_ARG_KEYPAD])) {
06817       /* We have a keypad facility digits option with digits. */
06818       keypad = opt_args[OPT_ARG_KEYPAD];
06819       pri_sr_set_keypad_digits(sr, keypad);
06820    } else {
06821       keypad = NULL;
06822    }
06823    if (!keypad || !ast_strlen_zero(c + p->stripmsd + dp_strip))
06824 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
06825    {
06826       pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
06827    }
06828 
06829 #if defined(HAVE_PRI_SUBADDR)
06830    if (dialed_subaddress.valid) {
06831       struct pri_party_subaddress subaddress;
06832 
06833       memset(&subaddress, 0, sizeof(subaddress));
06834       sig_pri_party_subaddress_from_ast(&subaddress, &dialed_subaddress);
06835       pri_sr_set_called_subaddress(sr, &subaddress);
06836    }
06837 #endif   /* defined(HAVE_PRI_SUBADDR) */
06838 #if defined(HAVE_PRI_REVERSE_CHARGE)
06839    if (ast_test_flag(&opts, OPT_REVERSE_CHARGE)) {
06840       pri_sr_set_reversecharge(sr, PRI_REVERSECHARGE_REQUESTED);
06841    }
06842 #endif   /* defined(HAVE_PRI_REVERSE_CHARGE) */
06843 #if defined(HAVE_PRI_AOC_EVENTS)
06844    if (ast_test_flag(&opts, OPT_AOC_REQUEST)
06845       && !ast_strlen_zero(opt_args[OPT_ARG_AOC_REQUEST])) {
06846       if (strchr(opt_args[OPT_ARG_AOC_REQUEST], 's')) {
06847          pri_sr_set_aoc_charging_request(sr, PRI_AOC_REQUEST_S);
06848       }
06849       if (strchr(opt_args[OPT_ARG_AOC_REQUEST], 'd')) {
06850          pri_sr_set_aoc_charging_request(sr, PRI_AOC_REQUEST_D);
06851       }
06852       if (strchr(opt_args[OPT_ARG_AOC_REQUEST], 'e')) {
06853          pri_sr_set_aoc_charging_request(sr, PRI_AOC_REQUEST_E);
06854       }
06855    }
06856 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
06857 
06858    /* Setup the user tag for party id's from this device for this call. */
06859    if (p->pri->append_msn_to_user_tag) {
06860       snprintf(p->user_tag, sizeof(p->user_tag), "%s_%s", p->pri->initial_user_tag,
06861          p->pri->nodetype == PRI_NETWORK
06862             ? c + p->stripmsd + dp_strip
06863             : S_COR(ast->connected.id.number.valid,
06864                ast->connected.id.number.str, ""));
06865    } else {
06866       ast_copy_string(p->user_tag, p->pri->initial_user_tag, sizeof(p->user_tag));
06867    }
06868 
06869    /*
06870     * Replace the caller id tag from the channel creation
06871     * with the actual tag value.
06872     */
06873    ast_free(ast->caller.id.tag);
06874    ast->caller.id.tag = ast_strdup(p->user_tag);
06875 
06876    ldp_strip = 0;
06877    prilocaldialplan = p->pri->localdialplan - 1;
06878    if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
06879       if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
06880          if (prilocaldialplan == -2) {
06881             ldp_strip = strlen(p->pri->internationalprefix);
06882          }
06883          prilocaldialplan = PRI_INTERNATIONAL_ISDN;
06884       } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
06885          if (prilocaldialplan == -2) {
06886             ldp_strip = strlen(p->pri->nationalprefix);
06887          }
06888          prilocaldialplan = PRI_NATIONAL_ISDN;
06889       } else {
06890          prilocaldialplan = PRI_LOCAL_ISDN;
06891       }
06892    }
06893    if (l != NULL) {
06894       while (*l > '9' && *l != '*' && *l != '#') {
06895          switch (*l) {
06896          case 'U':
06897             prilocaldialplan = (PRI_TON_UNKNOWN << 4) | (prilocaldialplan & 0xf);
06898             break;
06899          case 'I':
06900             prilocaldialplan = (PRI_TON_INTERNATIONAL << 4) | (prilocaldialplan & 0xf);
06901             break;
06902          case 'N':
06903             prilocaldialplan = (PRI_TON_NATIONAL << 4) | (prilocaldialplan & 0xf);
06904             break;
06905          case 'L':
06906             prilocaldialplan = (PRI_TON_NET_SPECIFIC << 4) | (prilocaldialplan & 0xf);
06907             break;
06908          case 'S':
06909             prilocaldialplan = (PRI_TON_SUBSCRIBER << 4) | (prilocaldialplan & 0xf);
06910             break;
06911          case 'V':
06912             prilocaldialplan = (PRI_TON_ABBREVIATED << 4) | (prilocaldialplan & 0xf);
06913             break;
06914          case 'R':
06915             prilocaldialplan = (PRI_TON_RESERVED << 4) | (prilocaldialplan & 0xf);
06916             break;
06917          case 'u':
06918             prilocaldialplan = PRI_NPI_UNKNOWN | (prilocaldialplan & 0xf0);
06919             break;
06920          case 'e':
06921             prilocaldialplan = PRI_NPI_E163_E164 | (prilocaldialplan & 0xf0);
06922             break;
06923          case 'x':
06924             prilocaldialplan = PRI_NPI_X121 | (prilocaldialplan & 0xf0);
06925             break;
06926          case 'f':
06927             prilocaldialplan = PRI_NPI_F69 | (prilocaldialplan & 0xf0);
06928             break;
06929          case 'n':
06930             prilocaldialplan = PRI_NPI_NATIONAL | (prilocaldialplan & 0xf0);
06931             break;
06932          case 'p':
06933             prilocaldialplan = PRI_NPI_PRIVATE | (prilocaldialplan & 0xf0);
06934             break;
06935          case 'r':
06936             prilocaldialplan = PRI_NPI_RESERVED | (prilocaldialplan & 0xf0);
06937             break;
06938          default:
06939             if (isalpha(*l)) {
06940                ast_log(LOG_WARNING,
06941                   "Unrecognized prilocaldialplan %s modifier: %c\n",
06942                   *l > 'Z' ? "NPI" : "TON", *l);
06943             }
06944             break;
06945          }
06946          l++;
06947       }
06948    }
06949    pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
06950       p->use_callingpres ? ast->connected.id.number.presentation : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
06951 
06952 #if defined(HAVE_PRI_SUBADDR)
06953    if (ast->connected.id.subaddress.valid) {
06954       struct pri_party_subaddress subaddress;
06955 
06956       memset(&subaddress, 0, sizeof(subaddress));
06957       sig_pri_party_subaddress_from_ast(&subaddress, &ast->connected.id.subaddress);
06958       pri_sr_set_caller_subaddress(sr, &subaddress);
06959    }
06960 #endif   /* defined(HAVE_PRI_SUBADDR) */
06961 
06962    sig_pri_redirecting_update(p, ast);
06963 
06964 #ifdef SUPPORT_USERUSER
06965    /* User-user info */
06966    useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
06967    if (useruser)
06968       pri_sr_set_useruser(sr, useruser);
06969 #endif
06970 
06971 #if defined(HAVE_PRI_CCSS)
06972    if (ast_cc_is_recall(ast, &core_id, sig_pri_cc_type_name)) {
06973       struct ast_cc_monitor *monitor;
06974       char device_name[AST_CHANNEL_NAME];
06975 
06976       /* This is a CC recall call. */
06977       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
06978       monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
06979       if (monitor) {
06980          struct sig_pri_cc_monitor_instance *instance;
06981 
06982          instance = monitor->private_data;
06983 
06984          /* If this fails then we have monitor instance ambiguity. */
06985          ast_assert(p->pri == instance->pri);
06986 
06987          if (pri_cc_call(p->pri->pri, instance->cc_id, p->call, sr)) {
06988             /* The CC recall call failed for some reason. */
06989             ast_log(LOG_WARNING, "Unable to setup CC recall call to device %s\n",
06990                device_name);
06991             ao2_ref(monitor, -1);
06992             pri_destroycall(p->pri->pri, p->call);
06993             p->call = NULL;
06994             pri_rel(p->pri);
06995             pri_sr_free(sr);
06996             return -1;
06997          }
06998          ao2_ref(monitor, -1);
06999       } else {
07000          core_id = -1;
07001       }
07002    } else
07003 #endif   /* defined(HAVE_PRI_CCSS) */
07004    {
07005       core_id = -1;
07006    }
07007    if (core_id == -1 && pri_setup(p->pri->pri, p->call, sr)) {
07008       ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n",
07009          c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
07010       pri_destroycall(p->pri->pri, p->call);
07011       p->call = NULL;
07012       pri_rel(p->pri);
07013       pri_sr_free(sr);
07014       return -1;
07015    }
07016    p->call_level = SIG_PRI_CALL_LEVEL_SETUP;
07017    pri_sr_free(sr);
07018    ast_setstate(ast, AST_STATE_DIALING);
07019    sig_pri_set_dialing(p, 1);
07020    pri_rel(p->pri);
07021    return 0;
07022 }
07023 
07024 int sig_pri_indicate(struct sig_pri_chan *p, struct ast_channel *chan, int condition, const void *data, size_t datalen)
07025 {
07026    int res = -1;
07027 
07028    switch (condition) {
07029    case AST_CONTROL_BUSY:
07030       if (p->priindication_oob || p->no_b_channel) {
07031          chan->hangupcause = AST_CAUSE_USER_BUSY;
07032          chan->_softhangup |= AST_SOFTHANGUP_DEV;
07033          res = 0;
07034          break;
07035       }
07036       res = sig_pri_play_tone(p, SIG_PRI_TONE_BUSY);
07037       if (p->call_level < SIG_PRI_CALL_LEVEL_ALERTING && !p->outgoing) {
07038          chan->hangupcause = AST_CAUSE_USER_BUSY;
07039          p->progress = 1;/* No need to send plain PROGRESS after this. */
07040          if (p->pri && p->pri->pri) {
07041             pri_grab(p, p->pri);
07042 #ifdef HAVE_PRI_PROG_W_CAUSE
07043             pri_progress_with_cause(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 1, chan->hangupcause);
07044 #else
07045             pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07046 #endif
07047             pri_rel(p->pri);
07048          }
07049       }
07050       break;
07051    case AST_CONTROL_RINGING:
07052       if (p->call_level < SIG_PRI_CALL_LEVEL_ALERTING && !p->outgoing) {
07053          p->call_level = SIG_PRI_CALL_LEVEL_ALERTING;
07054          if (p->pri && p->pri->pri) {
07055             pri_grab(p, p->pri);
07056             pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p),
07057                p->no_b_channel || p->digital ? 0 : 1);
07058             pri_rel(p->pri);
07059          }
07060       }
07061       res = sig_pri_play_tone(p, SIG_PRI_TONE_RINGTONE);
07062       if (chan->_state != AST_STATE_UP) {
07063          if (chan->_state != AST_STATE_RING)
07064             ast_setstate(chan, AST_STATE_RINGING);
07065       }
07066       break;
07067    case AST_CONTROL_PROCEEDING:
07068       ast_debug(1,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
07069       if (p->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING && !p->outgoing) {
07070          p->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
07071          if (p->pri && p->pri->pri) {
07072             pri_grab(p, p->pri);
07073             pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p),
07074                p->no_b_channel || p->digital ? 0 : 1);
07075             if (!p->no_b_channel && !p->digital) {
07076                sig_pri_set_dialing(p, 0);
07077             }
07078             pri_rel(p->pri);
07079          }
07080       }
07081       /* don't continue in ast_indicate */
07082       res = 0;
07083       break;
07084    case AST_CONTROL_PROGRESS:
07085       ast_debug(1,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
07086       sig_pri_set_digital(p, 0); /* Digital-only calls isn't allowing any inband progress messages */
07087       if (!p->progress && p->call_level < SIG_PRI_CALL_LEVEL_ALERTING && !p->outgoing
07088          && !p->no_b_channel) {
07089          p->progress = 1;/* No need to send plain PROGRESS again. */
07090          if (p->pri && p->pri->pri) {
07091             pri_grab(p, p->pri);
07092 #ifdef HAVE_PRI_PROG_W_CAUSE
07093             pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, -1);  /* no cause at all */
07094 #else
07095             pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07096 #endif
07097             pri_rel(p->pri);
07098          }
07099       }
07100       /* don't continue in ast_indicate */
07101       res = 0;
07102       break;
07103    case AST_CONTROL_INCOMPLETE:
07104       /* If we are connected or if we support overlap dialing, wait for additional digits */
07105       if (p->call_level == SIG_PRI_CALL_LEVEL_CONNECT || (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07106          res = 0;
07107          break;
07108       }
07109       /* Otherwise, treat as congestion */
07110       chan->hangupcause = AST_CAUSE_INVALID_NUMBER_FORMAT;
07111       /* Falls through */
07112    case AST_CONTROL_CONGESTION:
07113       if (p->priindication_oob || p->no_b_channel) {
07114          /* There are many cause codes that generate an AST_CONTROL_CONGESTION. */
07115          switch (chan->hangupcause) {
07116          case AST_CAUSE_USER_BUSY:
07117          case AST_CAUSE_NORMAL_CLEARING:
07118          case 0:/* Cause has not been set. */
07119             /* Supply a more appropriate cause. */
07120             chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07121             break;
07122          default:
07123             break;
07124          }
07125          chan->_softhangup |= AST_SOFTHANGUP_DEV;
07126          res = 0;
07127          break;
07128       }
07129       res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
07130       if (p->call_level < SIG_PRI_CALL_LEVEL_ALERTING && !p->outgoing) {
07131          /* There are many cause codes that generate an AST_CONTROL_CONGESTION. */
07132          switch (chan->hangupcause) {
07133          case AST_CAUSE_USER_BUSY:
07134          case AST_CAUSE_NORMAL_CLEARING:
07135          case 0:/* Cause has not been set. */
07136             /* Supply a more appropriate cause. */
07137             chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07138             break;
07139          default:
07140             break;
07141          }
07142          p->progress = 1;/* No need to send plain PROGRESS after this. */
07143          if (p->pri && p->pri->pri) {
07144             pri_grab(p, p->pri);
07145 #ifdef HAVE_PRI_PROG_W_CAUSE
07146             pri_progress_with_cause(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 1, chan->hangupcause);
07147 #else
07148             pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07149 #endif
07150             pri_rel(p->pri);
07151          }
07152       }
07153       break;
07154    case AST_CONTROL_HOLD:
07155       if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
07156          pri_grab(p, p->pri);
07157          res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
07158          pri_rel(p->pri);
07159       } else
07160          ast_moh_start(chan, data, p->mohinterpret);
07161       break;
07162    case AST_CONTROL_UNHOLD:
07163       if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
07164          pri_grab(p, p->pri);
07165          res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
07166          pri_rel(p->pri);
07167       } else
07168          ast_moh_stop(chan);
07169       break;
07170    case AST_CONTROL_SRCUPDATE:
07171       res = 0;
07172       break;
07173    case -1:
07174       res = sig_pri_play_tone(p, -1);
07175       break;
07176    case AST_CONTROL_CONNECTED_LINE:
07177       ast_debug(1, "Received AST_CONTROL_CONNECTED_LINE on %s\n", chan->name);
07178       if (p->pri) {
07179          struct pri_party_connected_line connected;
07180 
07181          pri_grab(p, p->pri);
07182          memset(&connected, 0, sizeof(connected));
07183          sig_pri_party_id_from_ast(&connected.id, &chan->connected.id);
07184 
07185          pri_connected_line_update(p->pri->pri, p->call, &connected);
07186          pri_rel(p->pri);
07187       }
07188       break;
07189    case AST_CONTROL_REDIRECTING:
07190       ast_debug(1, "Received AST_CONTROL_REDIRECTING on %s\n", chan->name);
07191       if (p->pri) {
07192          pri_grab(p, p->pri);
07193          sig_pri_redirecting_update(p, chan);
07194          pri_rel(p->pri);
07195       }
07196       break;
07197    case AST_CONTROL_AOC:
07198 #if defined(HAVE_PRI_AOC_EVENTS)
07199       {
07200          struct ast_aoc_decoded *decoded
07201             = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, chan);
07202          ast_debug(1, "Received AST_CONTROL_AOC on %s\n", chan->name);
07203          if (decoded && p->pri) {
07204             pri_grab(p, p->pri);
07205             switch (ast_aoc_get_msg_type(decoded)) {
07206             case AST_AOC_S:
07207                if (p->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
07208                   sig_pri_aoc_s_from_ast(p, decoded);
07209                }
07210                break;
07211             case AST_AOC_D:
07212                if (p->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
07213                   sig_pri_aoc_d_from_ast(p, decoded);
07214                }
07215                break;
07216             case AST_AOC_E:
07217                if (p->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
07218                   sig_pri_aoc_e_from_ast(p, decoded);
07219                }
07220                /* if hangup was delayed for this AOC-E msg, waiting_for_aoc
07221                 * will be set.  A hangup is already occuring via a timeout during
07222                 * this delay.  Instead of waiting for that timeout to occur, go ahead
07223                 * and initiate the softhangup since the delay is no longer necessary */
07224                if (p->waiting_for_aoce) {
07225                   p->waiting_for_aoce = 0;
07226                   ast_log(LOG_DEBUG,
07227                      "Received final AOC-E msg, continue with hangup on %s\n",
07228                      chan->name);
07229                   ast_softhangup_nolock(chan, AST_SOFTHANGUP_DEV);
07230                }
07231                break;
07232             case AST_AOC_REQUEST:
07233                /* We do not pass through AOC requests, So unless this
07234                 * is an AOC termination request it will be ignored */
07235                if (ast_aoc_get_termination_request(decoded)) {
07236                   pri_hangup(p->pri->pri, p->call, -1);
07237                }
07238                break;
07239             default:
07240                break;
07241             }
07242             pri_rel(p->pri);
07243          }
07244          ast_aoc_destroy_decoded(decoded);
07245       }
07246 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
07247       break;
07248    }
07249 
07250    return res;
07251 }
07252 
07253 int sig_pri_answer(struct sig_pri_chan *p, struct ast_channel *ast)
07254 {
07255    int res;
07256 
07257    /* Send a pri acknowledge */
07258    pri_grab(p, p->pri);
07259 #if defined(HAVE_PRI_AOC_EVENTS)
07260    if (p->aoc_s_request_invoke_id_valid) {
07261       /* if AOC-S was requested and the invoke id is still present on answer.  That means
07262        * no AOC-S rate list was provided, so send a NULL response which will indicate that
07263        * AOC-S is not available */
07264       pri_aoc_s_request_response_send(p->pri->pri, p->call,
07265          p->aoc_s_request_invoke_id, NULL);
07266       p->aoc_s_request_invoke_id_valid = 0;
07267    }
07268 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
07269    if (p->call_level < SIG_PRI_CALL_LEVEL_CONNECT) {
07270       p->call_level = SIG_PRI_CALL_LEVEL_CONNECT;
07271    }
07272    sig_pri_set_dialing(p, 0);
07273    sig_pri_open_media(p);
07274    res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
07275    pri_rel(p->pri);
07276    ast_setstate(ast, AST_STATE_UP);
07277    return res;
07278 }
07279 
07280 /*!
07281  * \internal
07282  * \brief Simple check if the channel is available to use.
07283  * \since 1.8
07284  *
07285  * \param pvt Private channel control structure.
07286  *
07287  * \retval 0 Interface not available.
07288  * \retval 1 Interface is available.
07289  */
07290 static int sig_pri_available_check(struct sig_pri_chan *pvt)
07291 {
07292    /*
07293     * If interface has a B channel and is available for use
07294     * then the channel is available.
07295     */
07296    if (!pvt->no_b_channel && sig_pri_is_chan_available(pvt)) {
07297       return 1;
07298    }
07299    return 0;
07300 }
07301 
07302 #if defined(HAVE_PRI_CALL_WAITING)
07303 /*!
07304  * \internal
07305  * \brief Get an available call waiting interface.
07306  * \since 1.8
07307  *
07308  * \param pri PRI span control structure.
07309  *
07310  * \note Assumes the pri->lock is already obtained.
07311  *
07312  * \retval cw Call waiting interface to use.
07313  * \retval NULL if no call waiting interface available.
07314  */
07315 static struct sig_pri_chan *sig_pri_cw_available(struct sig_pri_span *pri)
07316 {
07317    struct sig_pri_chan *cw;
07318    int idx;
07319 
07320    cw = NULL;
07321    if (pri->num_call_waiting_calls < pri->max_call_waiting_calls) {
07322       if (!pri->num_call_waiting_calls) {
07323          /*
07324           * There are no outstanding call waiting calls.  Check to see
07325           * if the span is in a congested state for the first call
07326           * waiting call.
07327           */
07328          for (idx = 0; idx < pri->numchans; ++idx) {
07329             if (pri->pvts[idx] && sig_pri_available_check(pri->pvts[idx])) {
07330                /* There is another channel that is available on this span. */
07331                return cw;
07332             }
07333          }
07334       }
07335       idx = pri_find_empty_nobch(pri);
07336       if (0 <= idx) {
07337          /* Setup the call waiting interface to use. */
07338          cw = pri->pvts[idx];
07339          cw->is_call_waiting = 1;
07340          sig_pri_init_config(cw, pri);
07341          ast_atomic_fetchadd_int(&pri->num_call_waiting_calls, 1);
07342       }
07343    }
07344    return cw;
07345 }
07346 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
07347 
07348 int sig_pri_available(struct sig_pri_chan **pvt, int is_specific_channel)
07349 {
07350    struct sig_pri_chan *p = *pvt;
07351    struct sig_pri_span *pri;
07352 
07353    if (!p->pri) {
07354       /* Something is wrong here.  A PRI channel without the pri pointer? */
07355       return 0;
07356    }
07357    pri = p->pri;
07358 
07359    ast_mutex_lock(&pri->lock);
07360    if (
07361 #if defined(HAVE_PRI_CALL_WAITING)
07362       /*
07363        * Only do call waiting calls if we have any
07364        * call waiting call outstanding.  We do not
07365        * want new calls to steal a B channel
07366        * freed for an earlier call waiting call.
07367        */
07368       !pri->num_call_waiting_calls &&
07369 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
07370       sig_pri_available_check(p)) {
07371       p->allocated = 1;
07372       ast_mutex_unlock(&pri->lock);
07373       return 1;
07374    }
07375 
07376 #if defined(HAVE_PRI_CALL_WAITING)
07377    if (!is_specific_channel) {
07378       struct sig_pri_chan *cw;
07379 
07380       cw = sig_pri_cw_available(pri);
07381       if (cw) {
07382          /* We have a call waiting interface to use instead. */
07383          cw->allocated = 1;
07384          *pvt = cw;
07385          ast_mutex_unlock(&pri->lock);
07386          return 1;
07387       }
07388    }
07389 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
07390    ast_mutex_unlock(&pri->lock);
07391    return 0;
07392 }
07393 
07394 /* If return 0, it means this function was able to handle it (pre setup digits).  If non zero, the user of this
07395  * functions should handle it normally (generate inband DTMF) */
07396 int sig_pri_digit_begin(struct sig_pri_chan *pvt, struct ast_channel *ast, char digit)
07397 {
07398    if (ast->_state == AST_STATE_DIALING) {
07399       if (pvt->call_level < SIG_PRI_CALL_LEVEL_OVERLAP) {
07400          unsigned int len;
07401 
07402          len = strlen(pvt->dialdest);
07403          if (len < sizeof(pvt->dialdest) - 1) {
07404             ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n",
07405                digit);
07406             pvt->dialdest[len++] = digit;
07407             pvt->dialdest[len] = '\0';
07408          } else {
07409             ast_log(LOG_WARNING,
07410                "Span %d: Deferred digit buffer overflow for digit '%c'.\n",
07411                pvt->pri->span, digit);
07412          }
07413          return 0;
07414       }
07415       if (pvt->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING) {
07416          pri_grab(pvt, pvt->pri);
07417          pri_information(pvt->pri->pri, pvt->call, digit);
07418          pri_rel(pvt->pri);
07419          return 0;
07420       }
07421       if (pvt->call_level < SIG_PRI_CALL_LEVEL_CONNECT) {
07422          ast_log(LOG_WARNING,
07423             "Span %d: Digit '%c' may be ignored by peer. (Call level:%d(%s))\n",
07424             pvt->pri->span, digit, pvt->call_level,
07425             sig_pri_call_level2str(pvt->call_level));
07426       }
07427    }
07428    return 1;
07429 }
07430 
07431 /*!
07432  * \brief DTMF dial string complete.
07433  * \since 1.8.11
07434  *
07435  * \param pvt sig_pri private channel structure.
07436  * \param ast Asterisk channel
07437  *
07438  * \note Channel and private lock are already held.
07439  *
07440  * \return Nothing
07441  */
07442 void sig_pri_dial_complete(struct sig_pri_chan *pvt, struct ast_channel *ast)
07443 {
07444    /* If we just completed 'w' deferred dialing digits, we need to answer now. */
07445    if (pvt->call_level == SIG_PRI_CALL_LEVEL_DEFER_DIAL) {
07446       pvt->call_level = SIG_PRI_CALL_LEVEL_CONNECT;
07447 
07448       sig_pri_open_media(pvt);
07449       {
07450          struct ast_frame f = {AST_FRAME_CONTROL, };
07451 
07452          if (pvt->calls->queue_control) {
07453             pvt->calls->queue_control(pvt->chan_pvt, AST_CONTROL_ANSWER);
07454          }
07455 
07456          f.subclass.integer = AST_CONTROL_ANSWER;
07457          ast_queue_frame(ast, &f);
07458       }
07459       sig_pri_set_dialing(pvt, 0);
07460       /* Enable echo cancellation if it's not on already */
07461       sig_pri_set_echocanceller(pvt, 1);
07462    }
07463 }
07464 
07465 #if defined(HAVE_PRI_MWI)
07466 /*!
07467  * \internal
07468  * \brief Send a MWI indication to the given span.
07469  * \since 1.8
07470  *
07471  * \param pri PRI span control structure.
07472  * \param mbox_number Mailbox number
07473  * \param mbox_context Mailbox context
07474  * \param num_messages Number of messages waiting.
07475  *
07476  * \return Nothing
07477  */
07478 static void sig_pri_send_mwi_indication(struct sig_pri_span *pri, const char *mbox_number, const char *mbox_context, int num_messages)
07479 {
07480    struct pri_party_id mailbox;
07481 
07482    ast_debug(1, "Send MWI indication for %s@%s num_messages:%d\n", mbox_number,
07483       mbox_context, num_messages);
07484 
07485    memset(&mailbox, 0, sizeof(mailbox));
07486    mailbox.number.valid = 1;
07487    mailbox.number.presentation = PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
07488    mailbox.number.plan = (PRI_TON_UNKNOWN << 4) | PRI_NPI_UNKNOWN;
07489    ast_copy_string(mailbox.number.str, mbox_number, sizeof(mailbox.number.str));
07490 
07491    ast_mutex_lock(&pri->lock);
07492    pri_mwi_indicate(pri->pri, &mailbox, 1 /* speech */, num_messages, NULL, NULL, -1, 0);
07493    ast_mutex_unlock(&pri->lock);
07494 }
07495 #endif   /* defined(HAVE_PRI_MWI) */
07496 
07497 #if defined(HAVE_PRI_MWI)
07498 /*!
07499  * \internal
07500  * \brief MWI subscription event callback.
07501  * \since 1.8
07502  *
07503  * \param event the event being passed to the subscriber
07504  * \param userdata the data provider in the call to ast_event_subscribe()
07505  *
07506  * \return Nothing
07507  */
07508 static void sig_pri_mwi_event_cb(const struct ast_event *event, void *userdata)
07509 {
07510    struct sig_pri_span *pri = userdata;
07511    const char *mbox_context;
07512    const char *mbox_number;
07513    int num_messages;
07514 
07515    mbox_number = ast_event_get_ie_str(event, AST_EVENT_IE_MAILBOX);
07516    if (ast_strlen_zero(mbox_number)) {
07517       return;
07518    }
07519    mbox_context = ast_event_get_ie_str(event, AST_EVENT_IE_CONTEXT);
07520    if (ast_strlen_zero(mbox_context)) {
07521       return;
07522    }
07523    num_messages = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
07524    sig_pri_send_mwi_indication(pri, mbox_number, mbox_context, num_messages);
07525 }
07526 #endif   /* defined(HAVE_PRI_MWI) */
07527 
07528 #if defined(HAVE_PRI_MWI)
07529 /*!
07530  * \internal
07531  * \brief Send update MWI indications from the event cache.
07532  * \since 1.8
07533  *
07534  * \param pri PRI span control structure.
07535  *
07536  * \return Nothing
07537  */
07538 static void sig_pri_mwi_cache_update(struct sig_pri_span *pri)
07539 {
07540    int idx;
07541    int num_messages;
07542    struct ast_event *event;
07543 
07544    for (idx = 0; idx < ARRAY_LEN(pri->mbox); ++idx) {
07545       if (!pri->mbox[idx].sub) {
07546          /* There are no more mailboxes on this span. */
07547          break;
07548       }
07549 
07550       event = ast_event_get_cached(AST_EVENT_MWI,
07551          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, pri->mbox[idx].number,
07552          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, pri->mbox[idx].context,
07553          AST_EVENT_IE_END);
07554       if (!event) {
07555          /* No cached event for this mailbox. */
07556          continue;
07557       }
07558       num_messages = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
07559       sig_pri_send_mwi_indication(pri, pri->mbox[idx].number, pri->mbox[idx].context,
07560          num_messages);
07561       ast_event_destroy(event);
07562    }
07563 }
07564 #endif   /* defined(HAVE_PRI_MWI) */
07565 
07566 /*!
07567  * \brief Stop PRI span.
07568  * \since 1.8
07569  *
07570  * \param pri PRI span control structure.
07571  *
07572  * \return Nothing
07573  */
07574 void sig_pri_stop_pri(struct sig_pri_span *pri)
07575 {
07576 #if defined(HAVE_PRI_MWI)
07577    int idx;
07578 #endif   /* defined(HAVE_PRI_MWI) */
07579 
07580 #if defined(HAVE_PRI_MWI)
07581    for (idx = 0; idx < ARRAY_LEN(pri->mbox); ++idx) {
07582       if (pri->mbox[idx].sub) {
07583          pri->mbox[idx].sub = ast_event_unsubscribe(pri->mbox[idx].sub);
07584       }
07585    }
07586 #endif   /* defined(HAVE_PRI_MWI) */
07587 }
07588 
07589 /*!
07590  * \internal
07591  * \brief qsort comparison function.
07592  * \since 1.8
07593  *
07594  * \param left Ptr to sig_pri_chan ptr to compare.
07595  * \param right Ptr to sig_pri_chan ptr to compare.
07596  *
07597  * \retval <0 if left < right.
07598  * \retval =0 if left == right.
07599  * \retval >0 if left > right.
07600  */
07601 static int sig_pri_cmp_pri_chans(const void *left, const void *right)
07602 {
07603    const struct sig_pri_chan *pvt_left;
07604    const struct sig_pri_chan *pvt_right;
07605 
07606    pvt_left = *(struct sig_pri_chan **) left;
07607    pvt_right = *(struct sig_pri_chan **) right;
07608    if (!pvt_left) {
07609       if (!pvt_right) {
07610          return 0;
07611       }
07612       return 1;
07613    }
07614    if (!pvt_right) {
07615       return -1;
07616    }
07617 
07618    return pvt_left->channel - pvt_right->channel;
07619 }
07620 
07621 /*!
07622  * \internal
07623  * \brief Sort the PRI B channel private pointer array.
07624  * \since 1.8
07625  *
07626  * \param pri PRI span control structure.
07627  *
07628  * \details
07629  * Since the chan_dahdi.conf file can declare channels in any order, we need to sort
07630  * the private channel pointer array.
07631  *
07632  * \return Nothing
07633  */
07634 static void sig_pri_sort_pri_chans(struct sig_pri_span *pri)
07635 {
07636    qsort(&pri->pvts, pri->numchans, sizeof(pri->pvts[0]), sig_pri_cmp_pri_chans);
07637 }
07638 
07639 int sig_pri_start_pri(struct sig_pri_span *pri)
07640 {
07641    int x;
07642    int i;
07643 #if defined(HAVE_PRI_MWI)
07644    char *saveptr;
07645    char *mbox_number;
07646    char *mbox_context;
07647    struct ast_str *mwi_description = ast_str_alloca(64);
07648 #endif   /* defined(HAVE_PRI_MWI) */
07649 
07650 #if defined(HAVE_PRI_MWI)
07651    /* Prepare the mbox[] for use. */
07652    for (i = 0; i < ARRAY_LEN(pri->mbox); ++i) {
07653       if (pri->mbox[i].sub) {
07654          pri->mbox[i].sub = ast_event_unsubscribe(pri->mbox[i].sub);
07655       }
07656    }
07657 #endif   /* defined(HAVE_PRI_MWI) */
07658 
07659    ast_mutex_init(&pri->lock);
07660    sig_pri_sort_pri_chans(pri);
07661 
07662 #if defined(HAVE_PRI_MWI)
07663    /*
07664     * Split the mwi_mailboxes configuration string into the mbox[]:
07665     * mailbox_number[@context]{,mailbox_number[@context]}
07666     */
07667    i = 0;
07668    saveptr = pri->mwi_mailboxes;
07669    while (i < ARRAY_LEN(pri->mbox)) {
07670       mbox_number = strsep(&saveptr, ",");
07671       if (!mbox_number) {
07672          break;
07673       }
07674       /* Split the mailbox_number and context */
07675       mbox_context = strchr(mbox_number, '@');
07676       if (mbox_context) {
07677          *mbox_context++ = '\0';
07678          mbox_context = ast_strip(mbox_context);
07679       }
07680       mbox_number = ast_strip(mbox_number);
07681       if (ast_strlen_zero(mbox_number)) {
07682          /* There is no mailbox number.  Skip it. */
07683          continue;
07684       }
07685       if (ast_strlen_zero(mbox_context)) {
07686          /* There was no context so use the default. */
07687          mbox_context = "default";
07688       }
07689 
07690       /* Fill the mbox[] element. */
07691       ast_str_set(&mwi_description, -1, "%s span %d[%d] MWI mailbox %s@%s",
07692          sig_pri_cc_type_name, pri->span, i, mbox_number, mbox_context);
07693       pri->mbox[i].sub = ast_event_subscribe(AST_EVENT_MWI, sig_pri_mwi_event_cb,
07694          ast_str_buffer(mwi_description), pri,
07695          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mbox_number,
07696          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, mbox_context,
07697          AST_EVENT_IE_END);
07698       if (!pri->mbox[i].sub) {
07699          ast_log(LOG_ERROR, "%s span %d could not subscribe to MWI events for %s@%s.",
07700             sig_pri_cc_type_name, pri->span, mbox_number, mbox_context);
07701          continue;
07702       }
07703       pri->mbox[i].number = mbox_number;
07704       pri->mbox[i].context = mbox_context;
07705       ++i;
07706    }
07707 #endif   /* defined(HAVE_PRI_MWI) */
07708 
07709    for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
07710       if (pri->fds[i] == -1) {
07711          break;
07712       }
07713 
07714       switch (pri->sig) {
07715       case SIG_BRI:
07716          pri->dchans[i] = pri_new_bri(pri->fds[i], 1, pri->nodetype, pri->switchtype);
07717          break;
07718       case SIG_BRI_PTMP:
07719          pri->dchans[i] = pri_new_bri(pri->fds[i], 0, pri->nodetype, pri->switchtype);
07720          break;
07721       default:
07722          pri->dchans[i] = pri_new(pri->fds[i], pri->nodetype, pri->switchtype);
07723 #if defined(HAVE_PRI_SERVICE_MESSAGES)
07724          if (pri->enable_service_message_support) {
07725             pri_set_service_message_support(pri->dchans[i], 1);
07726          }
07727 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
07728          break;
07729       }
07730 
07731       pri_set_overlapdial(pri->dchans[i], (pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING) ? 1 : 0);
07732 #ifdef HAVE_PRI_PROG_W_CAUSE
07733       pri_set_chan_mapping_logical(pri->dchans[i], pri->qsigchannelmapping == DAHDI_CHAN_MAPPING_LOGICAL);
07734 #endif
07735 #ifdef HAVE_PRI_INBANDDISCONNECT
07736       pri_set_inbanddisconnect(pri->dchans[i], pri->inbanddisconnect);
07737 #endif
07738       /* Enslave to master if appropriate */
07739       if (i)
07740          pri_enslave(pri->dchans[0], pri->dchans[i]);
07741       if (!pri->dchans[i]) {
07742          if (pri->fds[i] > 0)
07743             close(pri->fds[i]);
07744          pri->fds[i] = -1;
07745          ast_log(LOG_ERROR, "Unable to create PRI structure\n");
07746          return -1;
07747       }
07748       pri_set_debug(pri->dchans[i], SIG_PRI_DEBUG_DEFAULT);
07749       pri_set_nsf(pri->dchans[i], pri->nsf);
07750 #ifdef PRI_GETSET_TIMERS
07751       for (x = 0; x < PRI_MAX_TIMERS; x++) {
07752          if (pri->pritimers[x] != 0)
07753             pri_set_timer(pri->dchans[i], x, pri->pritimers[x]);
07754       }
07755 #endif
07756    }
07757 
07758    /* Assume primary is the one we use */
07759    pri->pri = pri->dchans[0];
07760 
07761 #if defined(HAVE_PRI_CALL_HOLD)
07762    pri_hold_enable(pri->pri, 1);
07763 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
07764 #if defined(HAVE_PRI_CALL_REROUTING)
07765    pri_reroute_enable(pri->pri, 1);
07766 #endif   /* defined(HAVE_PRI_CALL_REROUTING) */
07767 #if defined(HAVE_PRI_HANGUP_FIX)
07768    pri_hangup_fix_enable(pri->pri, 1);
07769 #endif   /* defined(HAVE_PRI_HANGUP_FIX) */
07770 #if defined(HAVE_PRI_CCSS)
07771    pri_cc_enable(pri->pri, 1);
07772    pri_cc_recall_mode(pri->pri, pri->cc_ptmp_recall_mode);
07773    pri_cc_retain_signaling_req(pri->pri, pri->cc_qsig_signaling_link_req);
07774    pri_cc_retain_signaling_rsp(pri->pri, pri->cc_qsig_signaling_link_rsp);
07775 #endif   /* defined(HAVE_PRI_CCSS) */
07776 #if defined(HAVE_PRI_TRANSFER)
07777    pri_transfer_enable(pri->pri, 1);
07778 #endif   /* defined(HAVE_PRI_TRANSFER) */
07779 #if defined(HAVE_PRI_AOC_EVENTS)
07780    pri_aoc_events_enable(pri->pri, 1);
07781 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
07782 #if defined(HAVE_PRI_CALL_WAITING)
07783    pri_connect_ack_enable(pri->pri, 1);
07784 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
07785 #if defined(HAVE_PRI_MCID)
07786    pri_mcid_enable(pri->pri, 1);
07787 #endif   /* defined(HAVE_PRI_MCID) */
07788 #if defined(HAVE_PRI_L2_PERSISTENCE)
07789    pri_persistent_layer2_option(pri->pri, pri->l2_persistence);
07790 #endif   /* defined(HAVE_PRI_L2_PERSISTENCE) */
07791 
07792    pri->resetpos = -1;
07793    if (ast_pthread_create_background(&pri->master, NULL, pri_dchannel, pri)) {
07794       for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
07795          if (!pri->dchans[i])
07796             break;
07797          if (pri->fds[i] > 0)
07798             close(pri->fds[i]);
07799          pri->fds[i] = -1;
07800       }
07801       ast_log(LOG_ERROR, "Unable to spawn D-channel: %s\n", strerror(errno));
07802       return -1;
07803    }
07804 
07805 #if defined(HAVE_PRI_MWI)
07806    /*
07807     * Send the initial MWI indications from the event cache for this span.
07808     *
07809     * If we were loaded after app_voicemail the event would already be in
07810     * the cache.  If we were loaded before app_voicemail the event would not
07811     * be in the cache yet and app_voicemail will send the event when it
07812     * gets loaded.
07813     */
07814    sig_pri_mwi_cache_update(pri);
07815 #endif   /* defined(HAVE_PRI_MWI) */
07816 
07817    return 0;
07818 }
07819 
07820 /*!
07821  * \brief Notify new alarm status.
07822  *
07823  * \param p Channel private pointer.
07824  * \param noalarm Non-zero if not in alarm mode.
07825  * 
07826  * \note Assumes the sig_pri_lock_private(p) is already obtained.
07827  *
07828  * \return Nothing
07829  */
07830 void sig_pri_chan_alarm_notify(struct sig_pri_chan *p, int noalarm)
07831 {
07832    pri_grab(p, p->pri);
07833    sig_pri_set_alarm(p, !noalarm);
07834    if (!noalarm) {
07835       if (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
07836          /* T309 is not enabled : destroy calls when alarm occurs */
07837          if (p->call) {
07838             pri_destroycall(p->pri->pri, p->call);
07839             p->call = NULL;
07840          }
07841          if (p->owner)
07842             p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
07843       }
07844    }
07845    sig_pri_span_devstate_changed(p->pri);
07846    pri_rel(p->pri);
07847 }
07848 
07849 /*!
07850  * \brief Determine if layer 1 alarms are ignored.
07851  *
07852  * \param p Channel private pointer.
07853  *
07854  * \return TRUE if the alarm is ignored.
07855  */
07856 int sig_pri_is_alarm_ignored(struct sig_pri_span *pri)
07857 {
07858    return pri->layer1_ignored;
07859 }
07860 
07861 struct sig_pri_chan *sig_pri_chan_new(void *pvt_data, struct sig_pri_callback *callback, struct sig_pri_span *pri, int logicalspan, int channo, int trunkgroup)
07862 {
07863    struct sig_pri_chan *p;
07864 
07865    p = ast_calloc(1, sizeof(*p));
07866    if (!p)
07867       return p;
07868 
07869    p->logicalspan = logicalspan;
07870    p->prioffset = channo;
07871    p->mastertrunkgroup = trunkgroup;
07872 
07873    p->calls = callback;
07874    p->chan_pvt = pvt_data;
07875 
07876    p->pri = pri;
07877 
07878    return p;
07879 }
07880 
07881 /*!
07882  * \brief Delete the sig_pri private channel structure.
07883  * \since 1.8
07884  *
07885  * \param doomed sig_pri private channel structure to delete.
07886  *
07887  * \return Nothing
07888  */
07889 void sig_pri_chan_delete(struct sig_pri_chan *doomed)
07890 {
07891    ast_free(doomed);
07892 }
07893 
07894 #define SIG_PRI_SC_HEADER  "%-4s %4s %-4s %-4s %-10s %-4s %s\n"
07895 #define SIG_PRI_SC_LINE     "%4d %4d %-4s %-4s %-10s %-4s %s"
07896 void sig_pri_cli_show_channels_header(int fd)
07897 {
07898    ast_cli(fd, SIG_PRI_SC_HEADER, "PRI",  "",     "B",    "Chan", "Call",  "PRI",  "Channel");
07899    ast_cli(fd, SIG_PRI_SC_HEADER, "Span", "Chan", "Chan", "Idle", "Level", "Call", "Name");
07900 }
07901 
07902 void sig_pri_cli_show_channels(int fd, struct sig_pri_span *pri)
07903 {
07904    char line[256];
07905    int idx;
07906    struct sig_pri_chan *pvt;
07907 
07908    ast_mutex_lock(&pri->lock);
07909    for (idx = 0; idx < pri->numchans; ++idx) {
07910       if (!pri->pvts[idx]) {
07911          continue;
07912       }
07913       pvt = pri->pvts[idx];
07914       sig_pri_lock_private(pvt);
07915       sig_pri_lock_owner(pri, idx);
07916       if (pvt->no_b_channel && sig_pri_is_chan_available(pvt)) {
07917          /* Don't show held/call-waiting channels if they are not in use. */
07918          sig_pri_unlock_private(pvt);
07919          continue;
07920       }
07921 
07922       snprintf(line, sizeof(line), SIG_PRI_SC_LINE,
07923          pri->span,
07924          pvt->channel,
07925          pvt->no_b_channel ? "No" : "Yes",/* Has media */
07926          sig_pri_is_chan_available(pvt) ? "Yes" : "No",
07927          sig_pri_call_level2str(pvt->call_level),
07928          pvt->call ? "Yes" : "No",
07929          pvt->owner ? pvt->owner->name : "");
07930 
07931       if (pvt->owner) {
07932          ast_channel_unlock(pvt->owner);
07933       }
07934       sig_pri_unlock_private(pvt);
07935 
07936       ast_mutex_unlock(&pri->lock);
07937       ast_cli(fd, "%s\n", line);
07938       ast_mutex_lock(&pri->lock);
07939    }
07940    ast_mutex_unlock(&pri->lock);
07941 }
07942 
07943 static void build_status(char *s, size_t len, int status, int active)
07944 {
07945    if (!s || len < 1) {
07946       return;
07947    }
07948    s[0] = '\0';
07949    if (!(status & DCHAN_NOTINALARM))
07950       strncat(s, "In Alarm, ", len - strlen(s) - 1);
07951    if (status & DCHAN_UP)
07952       strncat(s, "Up", len - strlen(s) - 1);
07953    else
07954       strncat(s, "Down", len - strlen(s) - 1);
07955    if (active)
07956       strncat(s, ", Active", len - strlen(s) - 1);
07957    else
07958       strncat(s, ", Standby", len - strlen(s) - 1);
07959    s[len - 1] = '\0';
07960 }
07961 
07962 void sig_pri_cli_show_spans(int fd, int span, struct sig_pri_span *pri)
07963 {
07964    char status[256];
07965    int x;
07966    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
07967       if (pri->dchans[x]) {
07968          build_status(status, sizeof(status), pri->dchanavail[x], pri->dchans[x] == pri->pri);
07969          ast_cli(fd, "PRI span %d/%d: %s\n", span, x, status);
07970       }
07971    }
07972 }
07973 
07974 void sig_pri_cli_show_span(int fd, int *dchannels, struct sig_pri_span *pri)
07975 {
07976    int x;
07977    char status[256];
07978 
07979    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
07980       if (pri->dchans[x]) {
07981 #ifdef PRI_DUMP_INFO_STR
07982          char *info_str = NULL;
07983 #endif
07984          ast_cli(fd, "%s D-channel: %d\n", pri_order(x), dchannels[x]);
07985          build_status(status, sizeof(status), pri->dchanavail[x], pri->dchans[x] == pri->pri);
07986          ast_cli(fd, "Status: %s\n", status);
07987          ast_mutex_lock(&pri->lock);
07988 #ifdef PRI_DUMP_INFO_STR
07989          info_str = pri_dump_info_str(pri->pri);
07990          if (info_str) {
07991             ast_cli(fd, "%s", info_str);
07992             ast_std_free(info_str);
07993          }
07994 #else
07995          pri_dump_info(pri->pri);
07996 #endif
07997          ast_mutex_unlock(&pri->lock);
07998          ast_cli(fd, "Overlap Recv: %s\n\n", (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)?"Yes":"No");
07999          ast_cli(fd, "\n");
08000       }
08001    }
08002 }
08003 
08004 int pri_send_keypad_facility_exec(struct sig_pri_chan *p, const char *digits)
08005 {
08006    sig_pri_lock_private(p);
08007 
08008    if (!p->pri || !p->call) {
08009       ast_debug(1, "Unable to find pri or call on channel!\n");
08010       sig_pri_unlock_private(p);
08011       return -1;
08012    }
08013 
08014    pri_grab(p, p->pri);
08015    pri_keypad_facility(p->pri->pri, p->call, digits);
08016    pri_rel(p->pri);
08017 
08018    sig_pri_unlock_private(p);
08019 
08020    return 0;
08021 }
08022 
08023 int pri_send_callrerouting_facility_exec(struct sig_pri_chan *p, enum ast_channel_state chanstate, const char *destination, const char *original, const char *reason)
08024 {
08025    int res;
08026 
08027    sig_pri_lock_private(p);
08028 
08029    if (!p->pri || !p->call) {
08030       ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
08031       sig_pri_unlock_private(p);
08032       return -1;
08033    }
08034 
08035    pri_grab(p, p->pri);
08036    res = pri_callrerouting_facility(p->pri->pri, p->call, destination, original, reason);
08037    pri_rel(p->pri);
08038 
08039    sig_pri_unlock_private(p);
08040 
08041    return res;
08042 }
08043 
08044 #if defined(HAVE_PRI_SERVICE_MESSAGES)
08045 int pri_maintenance_bservice(struct pri *pri, struct sig_pri_chan *p, int changestatus)
08046 {
08047    int channel = PVT_TO_CHANNEL(p);
08048    int span = PRI_SPAN(channel);
08049 
08050    return pri_maintenance_service(pri, span, channel, changestatus);
08051 }
08052 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
08053 
08054 void sig_pri_fixup(struct ast_channel *oldchan, struct ast_channel *newchan, struct sig_pri_chan *pchan)
08055 {
08056    if (pchan->owner == oldchan) {
08057       pchan->owner = newchan;
08058    }
08059 }
08060 
08061 #if defined(HAVE_PRI_CCSS)
08062 /*!
08063  * \brief PRI CC agent initialization.
08064  * \since 1.8
08065  *
08066  * \param agent CC core agent control.
08067  * \param pvt_chan Original channel the agent will attempt to recall.
08068  *
08069  * \details
08070  * This callback is called when the CC core is initialized.  Agents should allocate
08071  * any private data necessary for the call and assign it to the private_data
08072  * on the agent.  Additionally, if any ast_cc_agent_flags are pertinent to the
08073  * specific agent type, they should be set in this function as well.
08074  *
08075  * \retval 0 on success.
08076  * \retval -1 on error.
08077  */
08078 int sig_pri_cc_agent_init(struct ast_cc_agent *agent, struct sig_pri_chan *pvt_chan)
08079 {
08080    struct sig_pri_cc_agent_prv *cc_pvt;
08081 
08082    cc_pvt = ast_calloc(1, sizeof(*cc_pvt));
08083    if (!cc_pvt) {
08084       return -1;
08085    }
08086 
08087    ast_mutex_lock(&pvt_chan->pri->lock);
08088    cc_pvt->pri = pvt_chan->pri;
08089    cc_pvt->cc_id = pri_cc_available(pvt_chan->pri->pri, pvt_chan->call);
08090    ast_mutex_unlock(&pvt_chan->pri->lock);
08091    if (cc_pvt->cc_id == -1) {
08092       ast_free(cc_pvt);
08093       return -1;
08094    }
08095    agent->private_data = cc_pvt;
08096    return 0;
08097 }
08098 #endif   /* defined(HAVE_PRI_CCSS) */
08099 
08100 #if defined(HAVE_PRI_CCSS)
08101 /*!
08102  * \brief Start the offer timer.
08103  * \since 1.8
08104  *
08105  * \param agent CC core agent control.
08106  *
08107  * \details
08108  * This is called by the core when the caller hangs up after
08109  * a call for which CC may be requested. The agent should
08110  * begin the timer as configured.
08111  *
08112  * The primary reason why this functionality is left to
08113  * the specific agent implementations is due to the differing
08114  * use of schedulers throughout the code. Some channel drivers
08115  * may already have a scheduler context they wish to use, and
08116  * amongst those, some may use the ast_sched API while others
08117  * may use the ast_sched_thread API, which are incompatible.
08118  *
08119  * \retval 0 on success.
08120  * \retval -1 on error.
08121  */
08122 int sig_pri_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
08123 {
08124    /* libpri maintains it's own offer timer in the form of T_RETENTION. */
08125    return 0;
08126 }
08127 #endif   /* defined(HAVE_PRI_CCSS) */
08128 
08129 #if defined(HAVE_PRI_CCSS)
08130 /*!
08131  * \brief Stop the offer timer.
08132  * \since 1.8
08133  *
08134  * \param agent CC core agent control.
08135  *
08136  * \details
08137  * This callback is called by the CC core when the caller
08138  * has requested CC.
08139  *
08140  * \retval 0 on success.
08141  * \retval -1 on error.
08142  */
08143 int sig_pri_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
08144 {
08145    /* libpri maintains it's own offer timer in the form of T_RETENTION. */
08146    return 0;
08147 }
08148 #endif   /* defined(HAVE_PRI_CCSS) */
08149 
08150 #if defined(HAVE_PRI_CCSS)
08151 /*!
08152  * \brief Response to a CC request.
08153  * \since 1.8
08154  *
08155  * \param agent CC core agent control.
08156  * \param reason CC request response status.
08157  *
08158  * \details
08159  * When the core receives knowledge that a called
08160  * party has accepted a CC request, it will call
08161  * this callback.  The core may also call this
08162  * if there is some error when attempting to process
08163  * the incoming CC request.
08164  *
08165  * The duty of this is to issue a propper response to a
08166  * CC request from the caller by acknowledging receipt
08167  * of that request or rejecting it.
08168  *
08169  * \return Nothing
08170  */
08171 void sig_pri_cc_agent_req_rsp(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
08172 {
08173    struct sig_pri_cc_agent_prv *cc_pvt;
08174    int res;
08175    int status;
08176    const char *failed_msg;
08177    static const char *failed_to_send = "Failed to send the CC request response.";
08178    static const char *not_accepted = "The core declined the CC request.";
08179 
08180    cc_pvt = agent->private_data;
08181    ast_mutex_lock(&cc_pvt->pri->lock);
08182    if (cc_pvt->cc_request_response_pending) {
08183       cc_pvt->cc_request_response_pending = 0;
08184 
08185       /* Convert core response reason to ISDN response status. */
08186       status = 2;/* short_term_denial */
08187       switch (reason) {
08188       case AST_CC_AGENT_RESPONSE_SUCCESS:
08189          status = 0;/* success */
08190          break;
08191       case AST_CC_AGENT_RESPONSE_FAILURE_INVALID:
08192          status = 2;/* short_term_denial */
08193          break;
08194       case AST_CC_AGENT_RESPONSE_FAILURE_TOO_MANY:
08195          status = 5;/* queue_full */
08196          break;
08197       }
08198 
08199       res = pri_cc_req_rsp(cc_pvt->pri->pri, cc_pvt->cc_id, status);
08200       if (!status) {
08201          /* CC core request was accepted. */
08202          if (res) {
08203             failed_msg = failed_to_send;
08204          } else {
08205             failed_msg = NULL;
08206          }
08207       } else {
08208          /* CC core request was declined. */
08209          if (res) {
08210             failed_msg = failed_to_send;
08211          } else {
08212             failed_msg = not_accepted;
08213          }
08214       }
08215    } else {
08216       failed_msg = NULL;
08217    }
08218    ast_mutex_unlock(&cc_pvt->pri->lock);
08219    if (failed_msg) {
08220       ast_cc_failed(agent->core_id, "%s agent: %s", sig_pri_cc_type_name, failed_msg);
08221    }
08222 }
08223 #endif   /* defined(HAVE_PRI_CCSS) */
08224 
08225 #if defined(HAVE_PRI_CCSS)
08226 /*!
08227  * \brief Request the status of the agent's device.
08228  * \since 1.8
08229  *
08230  * \param agent CC core agent control.
08231  *
08232  * \details
08233  * Asynchronous request for the status of any caller
08234  * which may be a valid caller for the CC transaction.
08235  * Status responses should be made using the
08236  * ast_cc_status_response function.
08237  *
08238  * \retval 0 on success.
08239  * \retval -1 on error.
08240  */
08241 int sig_pri_cc_agent_status_req(struct ast_cc_agent *agent)
08242 {
08243    struct sig_pri_cc_agent_prv *cc_pvt;
08244 
08245    cc_pvt = agent->private_data;
08246    ast_mutex_lock(&cc_pvt->pri->lock);
08247    pri_cc_status_req(cc_pvt->pri->pri, cc_pvt->cc_id);
08248    ast_mutex_unlock(&cc_pvt->pri->lock);
08249    return 0;
08250 }
08251 #endif   /* defined(HAVE_PRI_CCSS) */
08252 
08253 #if defined(HAVE_PRI_CCSS)
08254 /*!
08255  * \brief Request for an agent's phone to stop ringing.
08256  * \since 1.8
08257  *
08258  * \param agent CC core agent control.
08259  *
08260  * \details
08261  * The usefulness of this is quite limited. The only specific
08262  * known case for this is if Asterisk requests CC over an ISDN
08263  * PTMP link as the TE side. If other phones are in the same
08264  * recall group as the Asterisk server, and one of those phones
08265  * picks up the recall notice, then Asterisk will receive a
08266  * "stop ringing" notification from the NT side of the PTMP
08267  * link. This indication needs to be passed to the phone
08268  * on the other side of the Asterisk server which originally
08269  * placed the call so that it will stop ringing. Since the
08270  * phone may be of any type, it is necessary to have a callback
08271  * that the core can know about.
08272  *
08273  * \retval 0 on success.
08274  * \retval -1 on error.
08275  */
08276 int sig_pri_cc_agent_stop_ringing(struct ast_cc_agent *agent)
08277 {
08278    struct sig_pri_cc_agent_prv *cc_pvt;
08279 
08280    cc_pvt = agent->private_data;
08281    ast_mutex_lock(&cc_pvt->pri->lock);
08282    pri_cc_stop_alerting(cc_pvt->pri->pri, cc_pvt->cc_id);
08283    ast_mutex_unlock(&cc_pvt->pri->lock);
08284    return 0;
08285 }
08286 #endif   /* defined(HAVE_PRI_CCSS) */
08287 
08288 #if defined(HAVE_PRI_CCSS)
08289 /*!
08290  * \brief Let the caller know that the callee has become free
08291  * but that the caller cannot attempt to call back because
08292  * he is either busy or there is congestion on his line.
08293  * \since 1.8
08294  *
08295  * \param agent CC core agent control.
08296  *
08297  * \details
08298  * This is something that really only affects a scenario where
08299  * a phone places a call over ISDN PTMP to Asterisk, who then
08300  * connects over PTMP again to the ISDN network. For most agent
08301  * types, there is no need to implement this callback at all
08302  * because they don't really need to actually do anything in
08303  * this situation. If you're having trouble understanding what
08304  * the purpose of this callback is, then you can be safe simply
08305  * not implementing it.
08306  *
08307  * \retval 0 on success.
08308  * \retval -1 on error.
08309  */
08310 int sig_pri_cc_agent_party_b_free(struct ast_cc_agent *agent)
08311 {
08312    struct sig_pri_cc_agent_prv *cc_pvt;
08313 
08314    cc_pvt = agent->private_data;
08315    ast_mutex_lock(&cc_pvt->pri->lock);
08316    pri_cc_b_free(cc_pvt->pri->pri, cc_pvt->cc_id);
08317    ast_mutex_unlock(&cc_pvt->pri->lock);
08318    return 0;
08319 }
08320 #endif   /* defined(HAVE_PRI_CCSS) */
08321 
08322 #if defined(HAVE_PRI_CCSS)
08323 /*!
08324  * \brief Begin monitoring a busy device.
08325  * \since 1.8
08326  *
08327  * \param agent CC core agent control.
08328  *
08329  * \details
08330  * The core will call this callback if the callee becomes
08331  * available but the caller has reported that he is busy.
08332  * The agent should begin monitoring the caller's device.
08333  * When the caller becomes available again, the agent should
08334  * call ast_cc_agent_caller_available.
08335  *
08336  * \retval 0 on success.
08337  * \retval -1 on error.
08338  */
08339 int sig_pri_cc_agent_start_monitoring(struct ast_cc_agent *agent)
08340 {
08341    /* libpri already knows when and how it needs to monitor Party A. */
08342    return 0;
08343 }
08344 #endif   /* defined(HAVE_PRI_CCSS) */
08345 
08346 #if defined(HAVE_PRI_CCSS)
08347 /*!
08348  * \brief Alert the caller that it is time to try recalling.
08349  * \since 1.8
08350  *
08351  * \param agent CC core agent control.
08352  *
08353  * \details
08354  * The core will call this function when it receives notice
08355  * that a monitored party has become available.
08356  *
08357  * The agent's job is to send a message to the caller to
08358  * notify it of such a change. If the agent is able to
08359  * discern that the caller is currently unavailable, then
08360  * the agent should react by calling the ast_cc_caller_unavailable
08361  * function.
08362  *
08363  * \retval 0 on success.
08364  * \retval -1 on error.
08365  */
08366 int sig_pri_cc_agent_callee_available(struct ast_cc_agent *agent)
08367 {
08368    struct sig_pri_cc_agent_prv *cc_pvt;
08369 
08370    cc_pvt = agent->private_data;
08371    ast_mutex_lock(&cc_pvt->pri->lock);
08372    pri_cc_remote_user_free(cc_pvt->pri->pri, cc_pvt->cc_id);
08373    ast_mutex_unlock(&cc_pvt->pri->lock);
08374    return 0;
08375 }
08376 #endif   /* defined(HAVE_PRI_CCSS) */
08377 
08378 #if defined(HAVE_PRI_CCSS)
08379 /*!
08380  * \brief Destroy private data on the agent.
08381  * \since 1.8
08382  *
08383  * \param agent CC core agent control.
08384  *
08385  * \details
08386  * The core will call this function upon completion
08387  * or failure of CC.
08388  *
08389  * \note
08390  * The agent private_data pointer may be NULL if the agent
08391  * constructor failed.
08392  *
08393  * \return Nothing
08394  */
08395 void sig_pri_cc_agent_destructor(struct ast_cc_agent *agent)
08396 {
08397    struct sig_pri_cc_agent_prv *cc_pvt;
08398    int res;
08399 
08400    cc_pvt = agent->private_data;
08401    if (!cc_pvt) {
08402       /* The agent constructor probably failed. */
08403       return;
08404    }
08405    ast_mutex_lock(&cc_pvt->pri->lock);
08406    res = -1;
08407    if (cc_pvt->cc_request_response_pending) {
08408       res = pri_cc_req_rsp(cc_pvt->pri->pri, cc_pvt->cc_id, 2/* short_term_denial */);
08409    }
08410    if (res) {
08411       pri_cc_cancel(cc_pvt->pri->pri, cc_pvt->cc_id);
08412    }
08413    ast_mutex_unlock(&cc_pvt->pri->lock);
08414    ast_free(cc_pvt);
08415 }
08416 #endif   /* defined(HAVE_PRI_CCSS) */
08417 
08418 #if defined(HAVE_PRI_CCSS)
08419 /*!
08420  * \internal
08421  * \brief Return the hash value of the given CC monitor instance object.
08422  * \since 1.8
08423  *
08424  * \param obj pointer to the (user-defined part) of an object.
08425  * \param flags flags from ao2_callback().  Ignored at the moment.
08426  *
08427  * \retval core_id
08428  */
08429 static int sig_pri_cc_monitor_instance_hash_fn(const void *obj, const int flags)
08430 {
08431    const struct sig_pri_cc_monitor_instance *monitor_instance = obj;
08432 
08433    return monitor_instance->core_id;
08434 }
08435 #endif   /* defined(HAVE_PRI_CCSS) */
08436 
08437 #if defined(HAVE_PRI_CCSS)
08438 /*!
08439  * \internal
08440  * \brief Compere the monitor instance core_id key value.
08441  * \since 1.8
08442  *
08443  * \param obj pointer to the (user-defined part) of an object.
08444  * \param arg callback argument from ao2_callback()
08445  * \param flags flags from ao2_callback()
08446  *
08447  * \return values are a combination of enum _cb_results.
08448  */
08449 static int sig_pri_cc_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
08450 {
08451    struct sig_pri_cc_monitor_instance *monitor_1 = obj;
08452    struct sig_pri_cc_monitor_instance *monitor_2 = arg;
08453 
08454    return monitor_1->core_id == monitor_2->core_id ? CMP_MATCH | CMP_STOP : 0;
08455 }
08456 #endif   /* defined(HAVE_PRI_CCSS) */
08457 
08458 #if defined(HAVE_PRI_CCSS)
08459 /*!
08460  * \brief Request CCSS.
08461  * \since 1.8
08462  *
08463  * \param monitor CC core monitor control.
08464  * \param available_timer_id Where to put the available timer scheduler id.
08465  * Will never be NULL for a device monitor.
08466  *
08467  * \details
08468  * Perform whatever steps are necessary in order to request CC.
08469  * In addition, the monitor implementation is responsible for
08470  * starting the available timer in this callback. The scheduler
08471  * ID for the callback must be stored in the parent_link's child_avail_id
08472  * field.
08473  *
08474  * \retval 0 on success
08475  * \retval -1 on failure.
08476  */
08477 int sig_pri_cc_monitor_req_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
08478 {
08479    struct sig_pri_cc_monitor_instance *instance;
08480    int cc_mode;
08481    int res;
08482 
08483    switch (monitor->service_offered) {
08484    case AST_CC_CCBS:
08485       cc_mode = 0;/* CCBS */
08486       break;
08487    case AST_CC_CCNR:
08488       cc_mode = 1;/* CCNR */
08489       break;
08490    default:
08491       /* CC service not supported by ISDN. */
08492       return -1;
08493    }
08494 
08495    instance = monitor->private_data;
08496 
08497    /* libpri handles it's own available timer. */
08498    ast_mutex_lock(&instance->pri->lock);
08499    res = pri_cc_req(instance->pri->pri, instance->cc_id, cc_mode);
08500    ast_mutex_unlock(&instance->pri->lock);
08501 
08502    return res;
08503 }
08504 #endif   /* defined(HAVE_PRI_CCSS) */
08505 
08506 #if defined(HAVE_PRI_CCSS)
08507 /*!
08508  * \brief Suspend monitoring.
08509  * \since 1.8
08510  *
08511  * \param monitor CC core monitor control.
08512  *
08513  * \details
08514  * Implementers must perform the necessary steps to suspend
08515  * monitoring.
08516  *
08517  * \retval 0 on success
08518  * \retval -1 on failure.
08519  */
08520 int sig_pri_cc_monitor_suspend(struct ast_cc_monitor *monitor)
08521 {
08522    struct sig_pri_cc_monitor_instance *instance;
08523 
08524    instance = monitor->private_data;
08525    ast_mutex_lock(&instance->pri->lock);
08526    pri_cc_status(instance->pri->pri, instance->cc_id, 1/* busy */);
08527    ast_mutex_unlock(&instance->pri->lock);
08528 
08529    return 0;
08530 }
08531 #endif   /* defined(HAVE_PRI_CCSS) */
08532 
08533 #if defined(HAVE_PRI_CCSS)
08534 /*!
08535  * \brief Unsuspend monitoring.
08536  * \since 1.8
08537  *
08538  * \param monitor CC core monitor control.
08539  *
08540  * \details
08541  * Perform the necessary steps to unsuspend monitoring.
08542  *
08543  * \retval 0 on success
08544  * \retval -1 on failure.
08545  */
08546 int sig_pri_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
08547 {
08548    struct sig_pri_cc_monitor_instance *instance;
08549 
08550    instance = monitor->private_data;
08551    ast_mutex_lock(&instance->pri->lock);
08552    pri_cc_status(instance->pri->pri, instance->cc_id, 0/* free */);
08553    ast_mutex_unlock(&instance->pri->lock);
08554 
08555    return 0;
08556 }
08557 #endif   /* defined(HAVE_PRI_CCSS) */
08558 
08559 #if defined(HAVE_PRI_CCSS)
08560 /*!
08561  * \brief Status response to an ast_cc_monitor_status_request().
08562  * \since 1.8
08563  *
08564  * \param monitor CC core monitor control.
08565  * \param devstate Current status of a Party A device.
08566  *
08567  * \details
08568  * Alert a monitor as to the status of the agent for which
08569  * the monitor had previously requested a status request.
08570  *
08571  * \note Zero or more responses may come as a result.
08572  *
08573  * \retval 0 on success
08574  * \retval -1 on failure.
08575  */
08576 int sig_pri_cc_monitor_status_rsp(struct ast_cc_monitor *monitor, enum ast_device_state devstate)
08577 {
08578    struct sig_pri_cc_monitor_instance *instance;
08579    int cc_status;
08580 
08581    switch (devstate) {
08582    case AST_DEVICE_UNKNOWN:
08583    case AST_DEVICE_NOT_INUSE:
08584       cc_status = 0;/* free */
08585       break;
08586    case AST_DEVICE_BUSY:
08587    case AST_DEVICE_INUSE:
08588       cc_status = 1;/* busy */
08589       break;
08590    default:
08591       /* Don't know how to interpret this device state into free/busy status. */
08592       return 0;
08593    }
08594    instance = monitor->private_data;
08595    ast_mutex_lock(&instance->pri->lock);
08596    pri_cc_status_req_rsp(instance->pri->pri, instance->cc_id, cc_status);
08597    ast_mutex_unlock(&instance->pri->lock);
08598 
08599    return 0;
08600 }
08601 #endif   /* defined(HAVE_PRI_CCSS) */
08602 
08603 #if defined(HAVE_PRI_CCSS)
08604 /*!
08605  * \brief Cancel the running available timer.
08606  * \since 1.8
08607  *
08608  * \param monitor CC core monitor control.
08609  * \param sched_id Available timer scheduler id to cancel.
08610  * Will never be NULL for a device monitor.
08611  *
08612  * \details
08613  * In most cases, this function will likely consist of just a
08614  * call to AST_SCHED_DEL. It might have been possible to do this
08615  * within the core, but unfortunately the mixture of sched_thread
08616  * and sched usage in Asterisk prevents such usage.
08617  *
08618  * \retval 0 on success
08619  * \retval -1 on failure.
08620  */
08621 int sig_pri_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
08622 {
08623    /*
08624     * libpri maintains it's own available timer as one of:
08625     * T_CCBS2/T_CCBS5/T_CCBS6/QSIG_CCBS_T2
08626     * T_CCNR2/T_CCNR5/T_CCNR6/QSIG_CCNR_T2
08627     */
08628    return 0;
08629 }
08630 #endif   /* defined(HAVE_PRI_CCSS) */
08631 
08632 #if defined(HAVE_PRI_CCSS)
08633 /*!
08634  * \brief Destroy PRI private data on the monitor.
08635  * \since 1.8
08636  *
08637  * \param monitor_pvt CC device monitor private data pointer.
08638  *
08639  * \details
08640  * Implementers of this callback are responsible for destroying
08641  * all heap-allocated data in the monitor's private_data pointer, including
08642  * the private_data itself.
08643  */
08644 void sig_pri_cc_monitor_destructor(void *monitor_pvt)
08645 {
08646    struct sig_pri_cc_monitor_instance *instance;
08647 
08648    instance = monitor_pvt;
08649    if (!instance) {
08650       return;
08651    }
08652    ao2_unlink(sig_pri_cc_monitors, instance);
08653    ao2_ref(instance, -1);
08654 }
08655 #endif   /* defined(HAVE_PRI_CCSS) */
08656 
08657 /*!
08658  * \brief Load the sig_pri submodule.
08659  * \since 1.8
08660  *
08661  * \param cc_type_name CC type name to use when looking up agent/monitor.
08662  *
08663  * \retval 0 on success.
08664  * \retval -1 on error.
08665  */
08666 int sig_pri_load(const char *cc_type_name)
08667 {
08668 #if defined(HAVE_PRI_CCSS)
08669    sig_pri_cc_type_name = cc_type_name;
08670    sig_pri_cc_monitors = ao2_container_alloc(37, sig_pri_cc_monitor_instance_hash_fn,
08671       sig_pri_cc_monitor_instance_cmp_fn);
08672    if (!sig_pri_cc_monitors) {
08673       return -1;
08674    }
08675 #endif   /* defined(HAVE_PRI_CCSS) */
08676    return 0;
08677 }
08678 
08679 /*!
08680  * \brief Unload the sig_pri submodule.
08681  * \since 1.8
08682  *
08683  * \return Nothing
08684  */
08685 void sig_pri_unload(void)
08686 {
08687 #if defined(HAVE_PRI_CCSS)
08688    if (sig_pri_cc_monitors) {
08689       ao2_ref(sig_pri_cc_monitors, -1);
08690       sig_pri_cc_monitors = NULL;
08691    }
08692 #endif   /* defined(HAVE_PRI_CCSS) */
08693 }
08694 
08695 #endif /* HAVE_PRI */

Generated on 3 Apr 2014 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1