Mon May 14 2012 03:42:51

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