Asterisk.org: Developer Documentation (28 Oct 2009)

Wed Oct 28 15:47:51 2009

## Asterisk developer's documentation

# chan_sip.c

Go to the documentation of this file.

    00001 /*
    00002  * Asterisk -- An open source telephony toolkit.
    00003  *
    00004  * Copyright (C) 1999 - 2006, 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 /*!
    00020  * \file
    00021  * \brief Implementation of Session Initiation Protocol
    00022  *
    00023  * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
    00024  * Configuration file \link Config_sip sip.conf \endlink
    00025  *
    00026  * \todo SIP over TCP
    00027  * \todo SIP over TLS
    00028  * \todo Better support of forking
    00029  */
    00030
    00031
    00032 #include <stdio.h>
    00033 #include <ctype.h>
    00034 #include <string.h>
    00035 #include <unistd.h>
    00036 #include <sys/socket.h>
    00037 #include <sys/ioctl.h>
    00038 #include <net/if.h>
    00039 #include <errno.h>
    00040 #include <stdlib.h>
    00041 #include <fcntl.h>
    00042 #include <netdb.h>
    00043 #include <signal.h>
    00044 #include <sys/signal.h>
    00045 #include <netinet/in.h>
    00046 #include <netinet/in_systm.h>
    00047 #include <arpa/inet.h>
    00048 #include <netinet/ip.h>
    00049 #include <regex.h>
    00050
    00051 #include "asterisk.h"
    00052
    00053 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 211526 $")
    00054
    00055 #include "asterisk/lock.h"
    00056 #include "asterisk/channel.h"
    00057 #include "asterisk/config.h"
    00058 #include "asterisk/logger.h"
    00059 #include "asterisk/module.h"
    00060 #include "asterisk/pbx.h"
    00061 #include "asterisk/options.h"
    00062 #include "asterisk/lock.h"
    00063 #include "asterisk/sched.h"
    00064 #include "asterisk/io.h"
    00065 #include "asterisk/rtp.h"
    00066 #include "asterisk/acl.h"
    00067 #include "asterisk/manager.h"
    00068 #include "asterisk/callerid.h"
    00069 #include "asterisk/cli.h"
    00070 #include "asterisk/app.h"
    00071 #include "asterisk/musiconhold.h"
    00072 #include "asterisk/dsp.h"
    00073 #include "asterisk/features.h"
    00074 #include "asterisk/acl.h"
    00075 #include "asterisk/srv.h"
    00076 #include "asterisk/astdb.h"
    00077 #include "asterisk/causes.h"
    00078 #include "asterisk/utils.h"
    00079 #include "asterisk/file.h"
    00080 #include "asterisk/astobj.h"
    00081 #include "asterisk/devicestate.h"
    00082 #include "asterisk/linkedlists.h"
    00083
    00084 #ifdef OSP_SUPPORT
    00085 #include "asterisk/astosp.h"
    00086 #endif
    00087
    00088 #ifndef DEFAULT_USERAGENT
    00089 #define DEFAULT_USERAGENT "Asterisk PBX"
    00090 #endif
    00091
    00092 #define VIDEO_CODEC_MASK   0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
    00093 #ifndef IPTOS_MINCOST
    00094 #define IPTOS_MINCOST      0x02
    00095 #endif
    00096
    00097 /* #define VOCAL_DATA_HACK */
    00098
    00099 #define SIPDUMPER
    00100 #define DEFAULT_DEFAULT_EXPIRY  120
    00101 #define DEFAULT_MAX_EXPIRY 3600
    00102 #define DEFAULT_REGISTRATION_TIMEOUT   20
    00103 #define DEFAULT_MAX_FORWARDS  "70"
    00104
    00105 /* guard limit must be larger than guard secs */
    00106 /* guard min must be < 1000, and should be >= 250 */
    00107 #define EXPIRY_GUARD_SECS  15 /* How long before expiry do we reregister */
    00108 #define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of
    00109                   EXPIRY_GUARD_SECS */
    00110 #define EXPIRY_GUARD_MIN   500   /* This is the minimum guard time applied. If
    00111                   GUARD_PCT turns out to be lower than this, it
    00112                   will use this time instead.
    00113                   This is in milliseconds. */
    00114 #define EXPIRY_GUARD_PCT   0.20  /* Percentage of expires timeout to use when
    00115                   below EXPIRY_GUARD_LIMIT */
    00116
    00117 #define SIP_LEN_CONTACT    256
    00118
    00119 static int max_expiry = DEFAULT_MAX_EXPIRY;
    00120 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
    00121
    00122 #ifndef MAX
    00123 #define MAX(a,b) ((a) > (b) ? (a) : (b))
    00124 #endif
    00125
    00126 #define CALLERID_UNKNOWN   "Unknown"
    00127
    00128
    00129
    00130 #define DEFAULT_MAXMS      2000     /* Must be faster than 2 seconds by default */
    00131 #define DEFAULT_FREQ_OK    60 * 1000   /* How often to check for the host to be up */
    00132 #define DEFAULT_FREQ_NOTOK 10 * 1000   /* How often to check, if the host is down... */
    00133
    00134 #define DEFAULT_RETRANS    1000     /* How frequently to retransmit */
    00135                   /* 2 * 500 ms in RFC 3261 */
    00136 #define MAX_RETRANS     6     /* Try only 6 times for retransmissions, a total of 7 transmissions */
    00137 #define MAX_AUTHTRIES      3     /* Try authentication three times, then fail */
    00138
    00139
    00140 #define DEBUG_READ   0        /* Recieved data  */
    00141 #define DEBUG_SEND   1        /* Transmit data  */
    00142
    00143 static const char desc[] = "Session Initiation Protocol (SIP)";
    00144 static const char channeltype[] = "SIP";
    00145 static const char config[] = "sip.conf";
    00146 static const char notify_config[] = "sip_notify.conf";
    00147
    00148 #define RTP    1
    00149 #define NO_RTP 0
    00150
    00151 /* Do _NOT_ make any changes to this enum, or the array following it;
    00152    if you think you are doing the right thing, you are probably
    00153    not doing the right thing. If you think there are changes
    00154    needed, get someone else to review them first _before_
    00155    submitting a patch. If these two lists do not match properly
    00156    bad things will happen.
    00157 */
    00158
    00159 enum subscriptiontype {
    00160    NONE = 0,
    00161    XPIDF_XML,
    00162    DIALOG_INFO_XML,
    00163    CPIM_PIDF_XML,
    00164    PIDF_XML
    00165 };
    00166
    00167 static const struct cfsubscription_types {
    00168    enum subscriptiontype type;
    00169    const char * const event;
    00170    const char * const mediatype;
    00171    const char * const text;
    00172 } subscription_types[] = {
    00173    { NONE,            "-",        "unknown",                   "unknown" },
    00174    /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
    00175    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
    00176    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
    00177    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
    00178    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" }       /* Pre-RFC 3863 with MS additions */
    00179 };
    00180
    00181 enum sipmethod {
    00182    SIP_UNKNOWN,
    00183    SIP_RESPONSE,
    00184    SIP_REGISTER,
    00185    SIP_OPTIONS,
    00186    SIP_NOTIFY,
    00187    SIP_INVITE,
    00188    SIP_ACK,
    00189    SIP_PRACK,
    00190    SIP_BYE,
    00191    SIP_REFER,
    00192    SIP_SUBSCRIBE,
    00193    SIP_MESSAGE,
    00194    SIP_UPDATE,
    00195    SIP_INFO,
    00196    SIP_CANCEL,
    00197    SIP_PUBLISH,
    00198 } sip_method_list;
    00199
    00200 enum sip_auth_type {
    00201    PROXY_AUTH,
    00202    WWW_AUTH,
    00203 };
    00204
    00205 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
    00206 static const struct  cfsip_methods {
    00207    enum sipmethod id;
    00208    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
    00209    char * const text;
    00210    int can_create;   /*!< 0=can't create, 1 can create, 2 can create, but not supported */
    00211 } sip_methods[] = {
    00212    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-", 2 },
    00213    { SIP_RESPONSE,    NO_RTP, "SIP/2.0", 0 },
    00214    { SIP_REGISTER,    NO_RTP, "REGISTER", 1 },
    00215    { SIP_OPTIONS,  NO_RTP, "OPTIONS", 1 },
    00216    { SIP_NOTIFY,   NO_RTP, "NOTIFY", 2 },
    00217    { SIP_INVITE,   RTP,    "INVITE", 1 },
    00218    { SIP_ACK,   NO_RTP, "ACK", 0 },
    00219    { SIP_PRACK,    NO_RTP, "PRACK", 2 },
    00220    { SIP_BYE,   NO_RTP, "BYE", 0 },
    00221    { SIP_REFER,    NO_RTP, "REFER", 2 },
    00222    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", 1 },
    00223    { SIP_MESSAGE,  NO_RTP, "MESSAGE", 1 },
    00224    { SIP_UPDATE,   NO_RTP, "UPDATE", 0 },
    00225    { SIP_INFO,  NO_RTP, "INFO", 0 },
    00226    { SIP_CANCEL,   NO_RTP, "CANCEL", 0 },
    00227    { SIP_PUBLISH,  NO_RTP, "PUBLISH", 1 }
    00228 };
    00229
    00230 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
    00231 static const struct cfalias {
    00232    char * const fullname;
    00233    char * const shortname;
    00234 } aliases[] = {
    00235    { "Content-Type", "c" },
    00236    { "Content-Encoding", "e" },
    00237    { "From", "f" },
    00238    { "Call-ID", "i" },
    00239    { "Contact", "m" },
    00240    { "Content-Length", "l" },
    00241    { "Subject", "s" },
    00242    { "To", "t" },
    00243    { "Supported", "k" },
    00244    { "Refer-To", "r" },
    00245    { "Referred-By", "b" },
    00246    { "Allow-Events", "u" },
    00247    { "Event", "o" },
    00248    { "Via", "v" },
    00249    { "Accept-Contact",      "a" },
    00250    { "Reject-Contact",      "j" },
    00251    { "Request-Disposition", "d" },
    00252    { "Session-Expires",     "x" },
    00253 };
    00254
    00255 /*!  Define SIP option tags, used in Require: and Supported: headers
    00256    We need to be aware of these properties in the phones to use
    00257    the replace: header. We should not do that without knowing
    00258    that the other end supports it...
    00259    This is nothing we can configure, we learn by the dialog
    00260    Supported: header on the REGISTER (peer) or the INVITE
    00261    (other devices)
    00262    We are not using many of these today, but will in the future.
    00263    This is documented in RFC 3261
    00264 */
    00265 #define SUPPORTED    1
    00266 #define NOT_SUPPORTED      0
    00267
    00268 #define SIP_OPT_REPLACES   (1 << 0)
    00269 #define SIP_OPT_100REL     (1 << 1)
    00270 #define SIP_OPT_TIMER      (1 << 2)
    00271 #define SIP_OPT_EARLY_SESSION (1 << 3)
    00272 #define SIP_OPT_JOIN    (1 << 4)
    00273 #define SIP_OPT_PATH    (1 << 5)
    00274 #define SIP_OPT_PREF    (1 << 6)
    00275 #define SIP_OPT_PRECONDITION  (1 << 7)
    00276 #define SIP_OPT_PRIVACY    (1 << 8)
    00277 #define SIP_OPT_SDP_ANAT   (1 << 9)
    00278 #define SIP_OPT_SEC_AGREE  (1 << 10)
    00279 #define SIP_OPT_EVENTLIST  (1 << 11)
    00280 #define SIP_OPT_GRUU    (1 << 12)
    00281 #define SIP_OPT_TARGET_DIALOG (1 << 13)
    00282
    00283 /*! \brief List of well-known SIP options. If we get this in a require,
    00284    we should check the list and answer accordingly. */
    00285 static const struct cfsip_options {
    00286    int id;        /*!< Bitmap ID */
    00287    int supported;    /*!< Supported by Asterisk ? */
    00288    char * const text;   /*!< Text id, as in standard */
    00289 } sip_options[] = {
    00290    /* Replaces: header for transfer */
    00291    { SIP_OPT_REPLACES,  SUPPORTED,  "replaces" },
    00292    /* RFC3262: PRACK 100% reliability */
    00293    { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
    00294    /* SIP Session Timers */
    00295    { SIP_OPT_TIMER,  NOT_SUPPORTED, "timer" },
    00296    /* RFC3959: SIP Early session support */
    00297    { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,   "early-session" },
    00298    /* SIP Join header support */
    00299    { SIP_OPT_JOIN,      NOT_SUPPORTED, "join" },
    00300    /* RFC3327: Path support */
    00301    { SIP_OPT_PATH,      NOT_SUPPORTED, "path" },
    00302    /* RFC3840: Callee preferences */
    00303    { SIP_OPT_PREF,      NOT_SUPPORTED, "pref" },
    00304    /* RFC3312: Precondition support */
    00305    { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
    00306    /* RFC3323: Privacy with proxies*/
    00307    { SIP_OPT_PRIVACY,   NOT_SUPPORTED, "privacy" },
    00308    /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
    00309    { SIP_OPT_SDP_ANAT,  NOT_SUPPORTED, "sdp-anat" },
    00310    /* RFC3329: Security agreement mechanism */
    00311    { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
    00312    /* SIMPLE events:  draft-ietf-simple-event-list-07.txt */
    00313    { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
    00314    /* GRUU: Globally Routable User Agent URI's */
    00315    { SIP_OPT_GRUU,      NOT_SUPPORTED, "gruu" },
    00316    /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
    00317    { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
    00318 };
    00319
    00320
    00321 /*! \brief SIP Methods we support */
    00322 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
    00323
    00324 /*! \brief SIP Extensions we support */
    00325 #define SUPPORTED_EXTENSIONS "replaces"
    00326
    00327 #define DEFAULT_SIP_PORT   5060  /*!< From RFC 3261 (former 2543) */
    00328 #define SIP_MAX_PACKET     4096  /*!< Also from RFC 3261 (2543), should sub headers tho */
    00329
    00330 static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
    00331
    00332 #define DEFAULT_CONTEXT "default"
    00333 static char default_context[AST_MAX_CONTEXT] = DEFAULT_CONTEXT;
    00334 static char default_subscribecontext[AST_MAX_CONTEXT];
    00335
    00336 #define DEFAULT_VMEXTEN "asterisk"
    00337 static char global_vmexten[AST_MAX_EXTENSION] = DEFAULT_VMEXTEN;
    00338
    00339 static char default_language[MAX_LANGUAGE] = "";
    00340
    00341 #define DEFAULT_CALLERID "asterisk"
    00342 static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
    00343
    00344 static char default_fromdomain[AST_MAX_EXTENSION] = "";
    00345
    00346 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
    00347 static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
    00348
    00349 static int global_notifyringing = 1;   /*!< Send notifications on ringing */
    00350
    00351 static int global_alwaysauthreject = 0;   /*!< Send 401 Unauthorized for all failing requests */
    00352
    00353 static int default_qualify = 0;     /*!< Default Qualify= setting */
    00354
    00355 static struct ast_flags global_flags = {0};     /*!< global SIP_ flags */
    00356 static struct ast_flags global_flags_page2 = {0};  /*!< more global SIP_ flags */
    00357
    00358 static int srvlookup = 0;     /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
    00359
    00360 static int pedanticsipchecking = 0; /*!< Extra checking ?  Default off */
    00361
    00362 static int autocreatepeer = 0;      /*!< Auto creation of peers at registration? Default off. */
    00363
    00364 static int relaxdtmf = 0;
    00365
    00366 static int global_rtptimeout = 0;
    00367
    00368 static int global_rtpholdtimeout = 0;
    00369
    00370 static int global_rtpkeepalive = 0;
    00371
    00372 static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
    00373 static int global_regattempts_max = 0;
    00374
    00375 /* Object counters */
    00376 static int suserobjs = 0;
    00377 static int ruserobjs = 0;
    00378 static int speerobjs = 0;
    00379 static int rpeerobjs = 0;
    00380 static int apeerobjs = 0;
    00381 static int regobjs = 0;
    00382
    00383 static int global_allowguest = 1;    /*!< allow unauthenticated users/peers to connect? */
    00384
    00385 #define DEFAULT_MWITIME 10
    00386 static int global_mwitime = DEFAULT_MWITIME; /*!< Time between MWI checks for peers */
    00387
    00388 static int usecnt =0;
    00389 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
    00390
    00391 AST_MUTEX_DEFINE_STATIC(rand_lock);
    00392
    00393 /*! \brief Protect the interface list (of sip_pvt's) */
    00394 AST_MUTEX_DEFINE_STATIC(iflock);
    00395
    00396 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
    00397    when it's doing something critical. */
    00398 AST_MUTEX_DEFINE_STATIC(netlock);
    00399
    00400 AST_MUTEX_DEFINE_STATIC(monlock);
    00401
    00402 /*! \brief This is the thread for the monitor which checks for input on the channels
    00403    which are not currently in use.  */
    00404 static pthread_t monitor_thread = AST_PTHREADT_NULL;
    00405
    00406 static int restart_monitor(void);
    00407
    00408 /*! \brief Codecs that we support by default: */
    00409 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
    00410
    00411 static struct in_addr __ourip;
    00412 static struct sockaddr_in outboundproxyip;
    00413 static int ourport;
    00414
    00415 #define SIP_DEBUG_CONFIG 1 << 0
    00416 #define SIP_DEBUG_CONSOLE 1 << 1
    00417 static int sipdebug = 0;
    00418 static struct sockaddr_in debugaddr;
    00419
    00420 static int tos = 0;
    00421
    00422 static int videosupport = 0;
    00423
    00424 static int compactheaders = 0;            /*!< send compact sip headers */
    00425
    00426 static int recordhistory = 0;          /*!< Record SIP history. Off by default */
    00427 static int dumphistory = 0;            /*!< Dump history to verbose before destroying SIP dialog */
    00428
    00429 static char global_musicclass[MAX_MUSICCLASS] = "";   /*!< Global music on hold class */
    00430 #define DEFAULT_REALM   "asterisk"
    00431 static char global_realm[MAXHOSTNAMELEN] = DEFAULT_REALM;   /*!< Default realm */
    00432 static char regcontext[AST_MAX_CONTEXT] = "";      /*!< Context for auto-extensions */
    00433
    00434 #define DEFAULT_EXPIRY 900          /*!< Expire slowly */
    00435 static int expiry = DEFAULT_EXPIRY;
    00436
    00437 #define DEFAULT_T1MIN   100            /*!< Minimial T1 roundtrip time - ms */
    00438
    00439 static struct sched_context *sched;
    00440 static struct io_context *io;
    00441 static int *sipsock_read_id;
    00442
    00443 #define SIP_MAX_HEADERS    64       /*!< Max amount of SIP headers to read */
    00444 #define SIP_MAX_LINES      64       /*!< Max amount of lines in SIP attachment (like SDP) */
    00445
    00446 #define DEC_CALL_LIMIT  0
    00447 #define INC_CALL_LIMIT  1
    00448
    00449 static struct ast_codec_pref prefs;
    00450
    00451
    00452 /*! \brief sip_request: The data grabbed from the UDP socket */
    00453 struct sip_request {
    00454    char *rlPart1;       /*!< SIP Method Name or "SIP/2.0" protocol version */
    00455    char *rlPart2;       /*!< The Request URI or Response Status */
    00456    int len;    /*!< Length */
    00457    int headers;      /*!< # of SIP Headers */
    00458    int method;    /*!< Method of this request */
    00459    char *header[SIP_MAX_HEADERS];
    00460    int lines;     /*!< Body Content */
    00461    char *line[SIP_MAX_LINES];
    00462    char data[SIP_MAX_PACKET];
    00463    int debug;     /*!< Debug flag for this packet */
    00464    unsigned int flags;  /*!< SIP_PKT Flags for this packet */
    00465    unsigned int sdp_start; /*!< the line number where the SDP begins */
    00466    unsigned int sdp_end;   /*!< the line number where the SDP ends */
    00467 };
    00468
    00469 struct sip_pkt;
    00470
    00471 /*! \brief Parameters to the transmit_invite function */
    00472 struct sip_invite_param {
    00473    char *distinctive_ring; /*!< Distinctive ring header */
    00474    char *osptoken;      /*!< OSP token for this call */
    00475    int addsipheaders;   /*!< Add extra SIP headers */
    00476    char *uri_options;   /*!< URI options to add to the URI */
    00477    char *vxml_url;      /*!< VXML url for Cisco phones */
    00478    char *auth;    /*!< Authentication */
    00479    char *authheader; /*!< Auth header */
    00480    enum sip_auth_type auth_type; /*!< Authentication type */
    00481 };
    00482
    00483 struct sip_route {
    00484    struct sip_route *next;
    00485    char hop[0];
    00486 };
    00487
    00488 enum domain_mode {
    00489    SIP_DOMAIN_AUTO,  /*!< This domain is auto-configured */
    00490    SIP_DOMAIN_CONFIG,   /*!< This domain is from configuration */
    00491 };
    00492
    00493 struct domain {
    00494    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
    00495    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
    00496    enum domain_mode mode;        /*!< How did we find this domain? */
    00497    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
    00498 };
    00499
    00500 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
    00501
    00502 int allow_external_domains;      /*!< Accept calls to external SIP domains? */
    00503
    00504 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
    00505 struct sip_history {
    00506    char event[80];
    00507    struct sip_history *next;
    00508 };
    00509
    00510 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
    00511 struct sip_auth {
    00512    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
    00513    char username[256];             /*!< Username */
    00514    char secret[256];               /*!< Secret */
    00515    char md5secret[256];            /*!< MD5Secret */
    00516    struct sip_auth *next;          /*!< Next auth structure in list */
    00517 };
    00518
    00519 #define SIP_ALREADYGONE    (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
    00520 #define SIP_NEEDDESTROY    (1 << 1) /*!< if we need to be destroyed */
    00521 #define SIP_NOVIDEO     (1 << 2) /*!< Didn't get video in invite, don't offer */
    00522 #define SIP_RINGING     (1 << 3) /*!< Have sent 180 ringing */
    00523 #define SIP_PROGRESS_SENT  (1 << 4) /*!< Have sent 183 message progress */
    00524 #define SIP_NEEDREINVITE   (1 << 5) /*!< Do we need to send another reinvite? */
    00525 #define SIP_PENDINGBYE     (1 << 6) /*!< Need to send bye after we ack? */
    00526 #define SIP_GOTREFER    (1 << 7) /*!< Got a refer? */
    00527 #define SIP_PROMISCREDIR   (1 << 8) /*!< Promiscuous redirection */
    00528 #define SIP_TRUSTRPID      (1 << 9) /*!< Trust RPID headers? */
    00529 #define SIP_USEREQPHONE    (1 << 10)   /*!< Add user=phone to numeric URI. Default off */
    00530 #define SIP_REALTIME    (1 << 11)   /*!< Flag for realtime users */
    00531 #define SIP_USECLIENTCODE  (1 << 12)   /*!< Trust X-ClientCode info message */
    00532 #define SIP_OUTGOING    (1 << 13)   /*!< Is this an outgoing call? */
    00533 #define SIP_SELFDESTRUCT   (1 << 14)   /*!< This is an autocreated peer */
    00534 #define SIP_CAN_BYE     (1 << 15)   /*!< Can we send BYE for this dialog? */
    00535 /* --- Choices for DTMF support in SIP channel */
    00536 #define SIP_DTMF     (3 << 16)   /*!< three settings, uses two bits */
    00537 #define SIP_DTMF_RFC2833   (0 << 16)   /*!< RTP DTMF */
    00538 #define SIP_DTMF_INBAND    (1 << 16)   /*!< Inband audio, only for ULAW/ALAW */
    00539 #define SIP_DTMF_INFO      (2 << 16)   /*!< SIP Info messages */
    00540 #define SIP_DTMF_AUTO      (3 << 16)   /*!< AUTO switch between rfc2833 and in-band DTMF */
    00541 /* NAT settings */
    00542 #define SIP_NAT         (3 << 18)   /*!< four settings, uses two bits */
    00543 #define SIP_NAT_NEVER      (0 << 18)   /*!< No nat support */
    00544 #define SIP_NAT_RFC3581    (1 << 18)
    00545 #define SIP_NAT_ROUTE      (2 << 18)
    00546 #define SIP_NAT_ALWAYS     (3 << 18)
    00547 /* re-INVITE related settings */
    00548 #define SIP_REINVITE    (3 << 20)   /*!< two bits used */
    00549 #define SIP_CAN_REINVITE   (1 << 20)   /*!< allow peers to be reinvited to send media directly p2p */
    00550 #define SIP_REINVITE_UPDATE   (2 << 20)   /*!< use UPDATE (RFC3311) when reinviting this peer */
    00551 /* "insecure" settings */
    00552 #define SIP_INSECURE_PORT  (1 << 22)   /*!< don't require matching port for incoming requests */
    00553 #define SIP_INSECURE_INVITE   (1 << 23)   /*!< don't require authentication for incoming INVITEs */
    00554 /* Sending PROGRESS in-band settings */
    00555 #define SIP_PROG_INBAND    (3 << 24)   /*!< three settings, uses two bits */
    00556 #define SIP_PROG_INBAND_NEVER (0 << 24)
    00557 #define SIP_PROG_INBAND_NO (1 << 24)
    00558 #define SIP_PROG_INBAND_YES   (2 << 24)
    00559 /* Open Settlement Protocol authentication */
    00560 #define SIP_OSPAUTH     (3 << 26)   /*!< four settings, uses two bits */
    00561 #define SIP_OSPAUTH_NO     (0 << 26)
    00562 #define SIP_OSPAUTH_GATEWAY   (1 << 26)
    00563 #define SIP_OSPAUTH_PROXY  (2 << 26)
    00564 #define SIP_OSPAUTH_EXCLUSIVE (3 << 26)
    00565 /* Call states */
    00566 #define SIP_CALL_ONHOLD    (1 << 28)
    00567 #define SIP_CALL_LIMIT     (1 << 29)
    00568 /* Remote Party-ID Support */
    00569 #define SIP_SENDRPID    (1 << 30)
    00570 #define SIP_INC_COUNT      (1 << 31)   /* Did this connection increment the counter of in-use calls? */
    00571
    00572 #define SIP_FLAGS_TO_COPY \
    00573    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
    00574     SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
    00575     SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
    00576
    00577 /* a new page of flags for peer */
    00578 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
    00579 #define SIP_PAGE2_RTUPDATE    (1 << 1)
    00580 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2)
    00581 #define SIP_PAGE2_IGNOREREGEXPIRE   (1 << 3)
    00582 #define SIP_PAGE2_RT_FROMCONTACT    (1 << 4)
    00583 #define SIP_PAGE2_DYNAMIC     (1 << 5) /*!< Is this a dynamic peer? */
    00584
    00585 /* SIP packet flags */
    00586 #define SIP_PKT_DEBUG      (1 << 0) /*!< Debug this packet */
    00587 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */
    00588
    00589 static int global_rtautoclear;
    00590
    00591 /*! \brief sip_pvt: PVT structures are used for each SIP conversation, ie. a call  */
    00592 static struct sip_pvt {
    00593    ast_mutex_t lock;       /*!< Channel private lock */
    00594    int method;          /*!< SIP method of this packet */
    00595    char callid[128];       /*!< Global CallID */
    00596    char randdata[80];         /*!< Random data */
    00597    struct ast_codec_pref prefs;     /*!< codec prefs */
    00598    unsigned int ocseq;        /*!< Current outgoing seqno */
    00599    unsigned int icseq;        /*!< Current incoming seqno */
    00600    ast_group_t callgroup;        /*!< Call group */
    00601    ast_group_t pickupgroup;      /*!< Pickup group */
    00602    int lastinvite;            /*!< Last Cseq of invite */
    00603    unsigned int flags;        /*!< SIP_ flags */
    00604    int timer_t1;           /*!< SIP timer T1, ms rtt */
    00605    unsigned int sipoptions;      /*!< Supported SIP sipoptions on the other end */
    00606    int capability;            /*!< Special capability (codec) */
    00607    int jointcapability;       /*!< Supported capability at both ends (codecs ) */
    00608    int peercapability;        /*!< Supported peer capability */
    00609    int prefcodec;          /*!< Preferred codec (outbound only) */
    00610    int noncodeccapability;
    00611    int jointnoncodeccapability;
    00612    int callingpres;        /*!< Calling presentation */
    00613    int authtries;          /*!< Times we've tried to authenticate */
    00614    int expiry;          /*!< How long we take to expire */
    00615    int branch;          /*!< One random number */
    00616    char tag[11];           /*!< Another random number */
    00617    int sessionid;          /*!< SDP Session ID */
    00618    int sessionversion;        /*!< SDP Session Version */
    00619    struct sockaddr_in sa;        /*!< Our peer */
    00620    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
    00621    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
    00622    int redircodecs;        /*!< Redirect codecs */
    00623    struct sockaddr_in recv;      /*!< Received as */
    00624    struct in_addr ourip;         /*!< Our IP */
    00625    struct ast_channel *owner;    /*!< Who owns us */
    00626    char exten[AST_MAX_EXTENSION];      /*!< Extension where to start */
    00627    char refer_to[AST_MAX_EXTENSION];   /*!< Place to store REFER-TO extension */
    00628    char referred_by[AST_MAX_EXTENSION];   /*!< Place to store REFERRED-BY extension */
    00629    char refer_contact[SIP_LEN_CONTACT];   /*!< Place to store Contact info from a REFER extension */
    00630    struct sip_pvt *refer_call;      /*!< Call we are referring */
    00631    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
    00632    int route_persistant;         /*!< Is this the "real" route? */
    00633    char from[256];            /*!< The From: header */
    00634    char useragent[256];       /*!< User agent in SIP request */
    00635    char context[AST_MAX_CONTEXT];      /*!< Context for this call */
    00636    char subscribecontext[AST_MAX_CONTEXT];   /*!< Subscribecontext */
    00637    char fromdomain[MAXHOSTNAMELEN]; /*!< Domain to show in the from field */
    00638    char fromuser[AST_MAX_EXTENSION];   /*!< User to show in the user field */
    00639    char fromname[AST_MAX_EXTENSION];   /*!< Name to show in the user field */
    00640    char tohost[MAXHOSTNAMELEN];     /*!< Host we should put in the "to" field */
    00641    char language[MAX_LANGUAGE];     /*!< Default language for this call */
    00642    char musicclass[MAX_MUSICCLASS]; /*!< Music on Hold class */
    00643    char rdnis[256];        /*!< Referring DNIS */
    00644    char theirtag[256];        /*!< Their tag */
    00645    char username[256];        /*!< [user] name */
    00646    char peername[256];        /*!< [peer] name, not set if [user] */
    00647    char authname[256];        /*!< Who we use for authentication */
    00648    char uri[256];          /*!< Original requested URI */
    00649    char okcontacturi[SIP_LEN_CONTACT]; /*!< URI from the 200 OK on INVITE */
    00650    char peersecret[256];         /*!< Password */
    00651    char peermd5secret[256];
    00652    struct sip_auth *peerauth;    /*!< Realm authentication */
    00653    char cid_num[256];         /*!< Caller*ID */
    00654    char cid_name[256];        /*!< Caller*ID */
    00655    char via[256];          /*!< Via: header */
    00656    char fullcontact[SIP_LEN_CONTACT];  /*!< The Contact: that the UA registers with us */
    00657    char accountcode[AST_MAX_ACCOUNT_CODE];   /*!< Account code */
    00658    char our_contact[SIP_LEN_CONTACT];  /*!< Our contact header */
    00659    char *rpid;          /*!< Our RPID header */
    00660    char *rpid_from;        /*!< Our RPID From header */
    00661    char realm[MAXHOSTNAMELEN];      /*!< Authorization realm */
    00662    char nonce[256];        /*!< Authorization nonce */
    00663    int noncecount;            /*!< Nonce-count */
    00664    char opaque[256];       /*!< Opaque nonsense */
    00665    char qop[80];           /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
    00666    char domain[MAXHOSTNAMELEN];     /*!< Authorization domain */
    00667    char lastmsg[256];         /*!< Last Message sent/received */
    00668    int amaflags;           /*!< AMA Flags */
    00669    int pendinginvite;         /*!< Any pending invite */
    00670 #ifdef OSP_SUPPORT
    00671    int osphandle;          /*!< OSP Handle for call */
    00672    time_t ospstart;        /*!< OSP Start time */
    00673    unsigned int osptimelimit;    /*!< OSP call duration limit */
    00674 #endif
    00675    struct sip_request initreq;      /*!< Initial request */
    00676
    00677    int maxtime;            /*!< Max time for first response */
    00678    int initid;          /*!< Auto-congest ID if appropriate */
    00679    int autokillid;            /*!< Auto-kill ID */
    00680    time_t lastrtprx;       /*!< Last RTP received */
    00681    time_t lastrtptx;       /*!< Last RTP sent */
    00682    int rtptimeout;            /*!< RTP timeout time */
    00683    int rtpholdtimeout;        /*!< RTP timeout when on hold */
    00684    int rtpkeepalive;       /*!< Send RTP packets for keepalive */
    00685    enum subscriptiontype subscribed;   /*!< Is this call a subscription?  */
    00686    int stateid;
    00687    int laststate;                          /*!< Last known extension state */
    00688    int dialogver;
    00689
    00690    struct ast_dsp *vad;       /*!< Voice Activation Detection dsp */
    00691
    00692    struct sip_peer *peerpoke;    /*!< If this calls is to poke a peer, which one */
    00693    struct sip_registry *registry;      /*!< If this is a REGISTER call, to which registry */
    00694    struct ast_rtp *rtp;       /*!< RTP Session */
    00695    struct ast_rtp *vrtp;         /*!< Video RTP session */
    00696    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
    00697    struct sip_history *history;     /*!< History of this SIP dialog */
    00698    struct ast_variable *chanvars;      /*!< Channel variables to set for call */
    00699    struct sip_pvt *next;         /*!< Next call in chain */
    00700    struct sip_invite_param *options;   /*!< Options for INVITE */
    00701 } *iflist = NULL;
    00702
    00703 #define FLAG_RESPONSE (1 << 0)
    00704 #define FLAG_FATAL (1 << 1)
    00705
    00706 /*! \brief sip packet - read in sipsock_read, transmitted in send_request */
    00707 struct sip_pkt {
    00708    struct sip_pkt *next;         /*!< Next packet */
    00709    int retrans;            /*!< Retransmission number */
    00710    int method;          /*!< SIP method for this packet */
    00711    int seqno;           /*!< Sequence number */
    00712    unsigned int flags;        /*!< non-zero if this is a response packet (e.g. 200 OK) */
    00713    struct sip_pvt *owner;        /*!< Owner call */
    00714    int retransid;          /*!< Retransmission ID */
    00715    int timer_a;            /*!< SIP timer A, retransmission timer */
    00716    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
    00717    int packetlen;          /*!< Length of packet */
    00718    char data[0];
    00719 };
    00720
    00721 /*! \brief Structure for SIP user data. User's place calls to us */
    00722 struct sip_user {
    00723    /* Users who can access various contexts */
    00724    ASTOBJ_COMPONENTS(struct sip_user);
    00725    char secret[80];     /*!< Password */
    00726    char md5secret[80];     /*!< Password in md5 */
    00727    char context[AST_MAX_CONTEXT];   /*!< Default context for incoming calls */
    00728    char subscribecontext[AST_MAX_CONTEXT];   /* Default context for subscriptions */
    00729    char cid_num[80];    /*!< Caller ID num */
    00730    char cid_name[80];      /*!< Caller ID name */
    00731    char accountcode[AST_MAX_ACCOUNT_CODE];   /* Account code */
    00732    char language[MAX_LANGUAGE];  /*!< Default language for this user */
    00733    char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
    00734    char useragent[256];    /*!< User agent in SIP request */
    00735    struct ast_codec_pref prefs;  /*!< codec prefs */
    00736    ast_group_t callgroup;     /*!< Call group */
    00737    ast_group_t pickupgroup;   /*!< Pickup Group */
    00738    unsigned int flags;     /*!< SIP flags */
    00739    unsigned int sipoptions;   /*!< Supported SIP options */
    00740    struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */
    00741    int amaflags;        /*!< AMA flags for billing */
    00742    int callingpres;     /*!< Calling id presentation */
    00743    int capability;         /*!< Codec capability */
    00744    int inUse;        /*!< Number of calls in use */
    00745    int call_limit;         /*!< Limit of concurrent calls */
    00746    struct ast_ha *ha;      /*!< ACL setting */
    00747    struct ast_variable *chanvars;   /*!< Variables to set for channel created by user */
    00748 };
    00749
    00750 /* Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
    00751 struct sip_peer {
    00752    ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags,  object pointers */
    00753                /*!< peer->name is the unique name of this object */
    00754    char secret[80];     /*!< Password */
    00755    char md5secret[80];     /*!< Password in MD5 */
    00756    struct sip_auth *auth;     /*!< Realm authentication list */
    00757    char context[AST_MAX_CONTEXT];   /*!< Default context for incoming calls */
    00758    char subscribecontext[AST_MAX_CONTEXT];   /*!< Default context for subscriptions */
    00759    char username[80];      /*!< Temporary username until registration */
    00760    char accountcode[AST_MAX_ACCOUNT_CODE];   /*!< Account code */
    00761    int amaflags;        /*!< AMA Flags (for billing) */
    00762    char tohost[MAXHOSTNAMELEN];  /*!< If not dynamic, IP address */
    00763    char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
    00764    char fromuser[80];      /*!< From: user when calling this peer */
    00765    char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
    00766    char fullcontact[SIP_LEN_CONTACT];  /*!< Contact registered with us (not in sip.conf) */
    00767    char cid_num[80];    /*!< Caller ID num */
    00768    char cid_name[80];      /*!< Caller ID name */
    00769    int callingpres;     /*!< Calling id presentation */
    00770    int inUse;        /*!< Number of calls in use */
    00771    int call_limit;         /*!< Limit of concurrent calls */
    00772    char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
    00773    char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
    00774    char language[MAX_LANGUAGE];  /*!<  Default language for prompts */
    00775    char musicclass[MAX_MUSICCLASS];/*!<  Music on Hold class */
    00776    char useragent[256];    /*!<  User agent in SIP request (saved from registration) */
    00777    struct ast_codec_pref prefs;  /*!<  codec prefs */
    00778    int lastmsgssent;
    00779    time_t   lastmsgcheck;     /*!<  Last time we checked for MWI */
    00780    unsigned int flags;     /*!<  SIP flags */
    00781    unsigned int sipoptions;   /*!<  Supported SIP options */
    00782    struct ast_flags flags_page2; /*!<  SIP_PAGE2 flags */
    00783    int expire;       /*!<  When to expire this peer registration */
    00784    int capability;         /*!<  Codec capability */
    00785    int rtptimeout;         /*!<  RTP timeout */
    00786    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
    00787    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
    00788    ast_group_t callgroup;     /*!<  Call group */
    00789    ast_group_t pickupgroup;   /*!<  Pickup group */
    00790    struct sockaddr_in addr;   /*!<  IP address of peer */
    00791
    00792    /* Qualification */
    00793    struct sip_pvt *call;      /*!<  Call pointer */
    00794    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
    00795    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
    00796    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
    00797    struct timeval ps;      /*!<  Ping send time */
    00798
    00799    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
    00800    struct ast_ha *ha;      /*!<  Access control list */
    00801    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
    00802    int lastmsg;
    00803 };
    00804
    00805 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
    00806 static int sip_reloading = 0;
    00807
    00808 /* States for outbound registrations (with register= lines in sip.conf */
    00809 #define REG_STATE_UNREGISTERED      0
    00810 #define REG_STATE_REGSENT     1
    00811 #define REG_STATE_AUTHSENT    2
    00812 #define REG_STATE_REGISTERED        3
    00813 #define REG_STATE_REJECTED       4
    00814 #define REG_STATE_TIMEOUT        5
    00815 #define REG_STATE_NOAUTH         6
    00816 #define REG_STATE_FAILED      7
    00817
    00818
    00819 /*! \brief sip_registry: Registrations with other SIP proxies */
    00820 struct sip_registry {
    00821    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
    00822    int portno;       /*!<  Optional port override */
    00823    char username[80];      /*!<  Who we are registering as */
    00824    char authuser[80];      /*!< Who we *authenticate* as */
    00825    char hostname[MAXHOSTNAMELEN];   /*!< Domain or host we register to */
    00826    char secret[80];     /*!< Password in clear text */
    00827    char md5secret[80];     /*!< Password in md5 */
    00828    char contact[SIP_LEN_CONTACT];   /*!< Contact extension */
    00829    char random[80];
    00830    int expire;       /*!< Sched ID of expiration */
    00831    int regattempts;     /*!< Number of attempts (since the last success) */
    00832    int timeout;         /*!< sched id of sip_reg_timeout */
    00833    int refresh;         /*!< How often to refresh */
    00834    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration call" in progress */
    00835    int regstate;        /*!< Registration state (see above) */
    00836    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
    00837    char callid[128];    /*!< Global CallID for this registry */
    00838    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
    00839    struct sockaddr_in us;     /*!< Who the server thinks we are */
    00840
    00841                /* Saved headers */
    00842    char realm[MAXHOSTNAMELEN];   /*!< Authorization realm */
    00843    char nonce[256];     /*!< Authorization nonce */
    00844    char domain[MAXHOSTNAMELEN];  /*!< Authorization domain */
    00845    char opaque[256];    /*!< Opaque nonsense */
    00846    char qop[80];        /*!< Quality of Protection. */
    00847    int noncecount;         /*!< Nonce-count */
    00848
    00849    char lastmsg[256];      /*!< Last Message sent/received */
    00850 };
    00851
    00852 /*! \brief  The user list: Users and friends ---*/
    00853 static struct ast_user_list {
    00854    ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
    00855 } userl;
    00856
    00857 /*! \brief  The peer list: Peers and Friends ---*/
    00858 static struct ast_peer_list {
    00859    ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
    00860 } peerl;
    00861
    00862 /*! \brief  The register list: Other SIP proxys we register with and call ---*/
    00863 static struct ast_register_list {
    00864    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
    00865    int recheck;
    00866 } regl;
    00867
    00868
    00869 static int __sip_do_register(struct sip_registry *r);
    00870
    00871 static int sipsock  = -1;
    00872
    00873
    00874 static struct sockaddr_in bindaddr = { 0, };
    00875 static struct sockaddr_in externip;
    00876 static char externhost[MAXHOSTNAMELEN] = "";
    00877 static time_t externexpire = 0;
    00878 static int externrefresh = 10;
    00879 static struct ast_ha *localaddr;
    00880
    00881 /* The list of manual NOTIFY types we know how to send */
    00882 struct ast_config *notify_types;
    00883
    00884 static struct sip_auth *authl;          /*!< Authentication list */
    00885
    00886 static int transmit_response_using_temp(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, struct sip_request *req, char *msg);
    00887 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
    00888 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
    00889 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
    00890 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header, int stale);
    00891 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
    00892 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
    00893 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
    00894 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
    00895 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
    00896 static int transmit_info_with_vidupdate(struct sip_pvt *p);
    00897 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
    00898 static int transmit_refer(struct sip_pvt *p, const char *dest);
    00899 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
    00900 static struct sip_peer *temp_peer(const char *name);
    00901 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
    00902 static void free_old_route(struct sip_route *route);
    00903 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
    00904 static int update_call_counter(struct sip_pvt *fup, int event);
    00905 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
    00906 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
    00907 static int sip_do_reload(void);
    00908 static int expire_register(void *data);
    00909 static int callevents = 0;
    00910
    00911 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
    00912 static int sip_devicestate(void *data);
    00913 static int sip_sendtext(struct ast_channel *ast, const char *text);
    00914 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
    00915 static int sip_hangup(struct ast_channel *ast);
    00916 static int sip_answer(struct ast_channel *ast);
    00917 static struct ast_frame *sip_read(struct ast_channel *ast);
    00918 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
    00919 static int sip_indicate(struct ast_channel *ast, int condition);
    00920 static int sip_transfer(struct ast_channel *ast, const char *dest);
    00921 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
    00922 static int sip_senddigit(struct ast_channel *ast, char digit);
    00923 static int clear_realm_authentication(struct sip_auth *authlist);                            /* Clear realm authentication list (at reload) */
    00924 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);   /* Add realm authentication in list */
    00925 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm);         /* Find authentication for a specific realm */
    00926 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
    00927 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
    00928 static int determine_firstline_parts(struct sip_request *req);
    00929 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
    00930 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
    00931 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate, int timeout);
    00932 static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
    00933
    00934 /*! \brief Definition of this channel for PBX channel registration */
    00935 static const struct ast_channel_tech sip_tech = {
    00936    .type = channeltype,
    00937    .description = "Session Initiation Protocol (SIP)",
    00938    .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
    00939    .properties = AST_CHAN_TP_WANTSJITTER,
    00940    .requester = sip_request_call,
    00941    .devicestate = sip_devicestate,
    00942    .call = sip_call,
    00943    .hangup = sip_hangup,
    00944    .answer = sip_answer,
    00945    .read = sip_read,
    00946    .write = sip_write,
    00947    .write_video = sip_write,
    00948    .indicate = sip_indicate,
    00949    .transfer = sip_transfer,
    00950    .fixup = sip_fixup,
    00951    .send_digit = sip_senddigit,
    00952    .bridge = ast_rtp_bridge,
    00953    .send_text = sip_sendtext,
    00954 };
    00955
    00956 #ifdef __AST_DEBUG_MALLOC
    00957 static void FREE(void *ptr)
    00958 {
    00959    free(ptr);
    00960 }
    00961 #else
    00962 #define FREE free
    00963 #endif
    00964
    00965 /*!
    00966   \brief Thread-safe random number generator
    00967   \return a random number
    00968
    00969   This function uses a mutex lock to guarantee that no
    00970   two threads will receive the same random number.
    00971  */
    00972 static force_inline int thread_safe_rand(void)
    00973 {
    00974    int val;
    00975
    00976    ast_mutex_lock(&rand_lock);
    00977    val = rand();
    00978    ast_mutex_unlock(&rand_lock);
    00979
    00980    return val;
    00981 }
    00982
    00983 /*! \brief  find_sip_method: Find SIP method from header
    00984  * Strictly speaking, SIP methods are case SENSITIVE, but we don't check
    00985  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
    00986 static int find_sip_method(char *msg)
    00987 {
    00988    int i, res = 0;
    00989
    00990    if (ast_strlen_zero(msg))
    00991       return 0;
    00992
    00993    for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
    00994       if (!strcasecmp(sip_methods[i].text, msg))
    00995          res = sip_methods[i].id;
    00996    }
    00997    return res;
    00998 }
    00999
    01000 /*! \brief  parse_sip_options: Parse supported header in incoming packet */
    01001 static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
    01002 {
    01003    char *next = NULL;
    01004    char *sep = NULL;
    01005    char *temp = ast_strdupa(supported);
    01006    int i;
    01007    unsigned int profile = 0;
    01008
    01009    if (ast_strlen_zero(supported) )
    01010       return 0;
    01011
    01012    if (option_debug > 2 && sipdebug)
    01013       ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
    01014
    01015    next = temp;
    01016    while (next) {
    01017       char res=0;
    01018       if ( (sep = strchr(next, ',')) != NULL) {
    01019          *sep = '\0';
    01020          sep++;
    01021       }
    01022       while (*next == ' ') /* Skip spaces */
    01023          next++;
    01024       if (option_debug > 2 && sipdebug)
    01025          ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
    01026       for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
    01027          if (!strcasecmp(next, sip_options[i].text)) {
    01028             profile |= sip_options[i].id;
    01029             res = 1;
    01030             if (option_debug > 2 && sipdebug)
    01031                ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
    01032          }
    01033       }
    01034       if (!res)
    01035          if (option_debug > 2 && sipdebug)
    01036             ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
    01037       next = sep;
    01038    }
    01039    if (pvt) {
    01040       pvt->sipoptions = profile;
    01041       if (option_debug)
    01042          ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
    01043    }
    01044    return profile;
    01045 }
    01046
    01047 /*! \brief  sip_debug_test_addr: See if we pass debug IP filter */
    01048 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
    01049 {
    01050    if (sipdebug == 0)
    01051       return 0;
    01052    if (debugaddr.sin_addr.s_addr) {
    01053       if (((ntohs(debugaddr.sin_port) != 0)
    01054          && (debugaddr.sin_port != addr->sin_port))
    01055          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
    01056          return 0;
    01057    }
    01058    return 1;
    01059 }
    01060
    01061 /*! \brief  sip_debug_test_pvt: Test PVT for debugging output */
    01062 static inline int sip_debug_test_pvt(struct sip_pvt *p)
    01063 {
    01064    if (sipdebug == 0)
    01065       return 0;
    01066    return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
    01067 }
    01068
    01069
    01070 /*! \brief  __sip_xmit: Transmit SIP message ---*/
    01071 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
    01072 {
    01073    int res;
    01074    char iabuf[INET_ADDRSTRLEN];
    01075
    01076    if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
    01077       res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
    01078    else
    01079       res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
    01080
    01081    if (res != len) {
    01082       ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), res, strerror(errno));
    01083    }
    01084    return res;
    01085 }
    01086
    01087 static void sip_destroy(struct sip_pvt *p);
    01088
    01089 /*! \brief  build_via: Build a Via header for a request ---*/
    01090 static void build_via(struct sip_pvt *p, char *buf, int len)
    01091 {
    01092    char iabuf[INET_ADDRSTRLEN];
    01093
    01094    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
    01095    if (ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581)
    01096       snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
    01097    else /* Work around buggy UNIDEN UIP200 firmware */
    01098       snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
    01099 }
    01100
    01101 /*! \brief  ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
    01102 /* Only used for outbound registrations */
    01103 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
    01104 {
    01105    /*
    01106     * Using the localaddr structure built up with localnet statements
    01107     * apply it to their address to see if we need to substitute our
    01108     * externip or can get away with our internal bindaddr
    01109     */
    01110    struct sockaddr_in theirs;
    01111    theirs.sin_addr = *them;
    01112    if (localaddr && externip.sin_addr.s_addr &&
    01113       ast_apply_ha(localaddr, &theirs)) {
    01114       char iabuf[INET_ADDRSTRLEN];
    01115       if (externexpire && (time(NULL) >= externexpire)) {
    01116          struct ast_hostent ahp;
    01117          struct hostent *hp;
    01118          time(&externexpire);
    01119          externexpire += externrefresh;
    01120          if ((hp = ast_gethostbyname(externhost, &ahp))) {
    01121             memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
    01122          } else
    01123             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
    01124       }
    01125       memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
    01126       ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
    01127       ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
    01128    }
    01129    else if (bindaddr.sin_addr.s_addr)
    01130       memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
    01131    else
    01132       return ast_ouraddrfor(them, us);
    01133    return 0;
    01134 }
    01135
    01136 /*! \brief  append_history: Append to SIP dialog history */
    01137 /* Always returns 0 */
    01138 static int append_history(struct sip_pvt *p, const char *event, const char *data)
    01139 {
    01140    struct sip_history *hist, *prev;
    01141    char *c;
    01142
    01143    if (!recordhistory || !p)
    01144       return 0;
    01145    if(!(hist = malloc(sizeof(struct sip_history)))) {
    01146       ast_log(LOG_WARNING, "Can't allocate memory for history\n");
    01147       return 0;
    01148    }
    01149    memset(hist, 0, sizeof(struct sip_history));
    01150    snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
    01151    /* Trim up nicely */
    01152    c = hist->event;
    01153    while(*c) {
    01154       if ((*c == '\r') || (*c == '\n')) {
    01155          *c = '\0';
    01156          break;
    01157       }
    01158       c++;
    01159    }
    01160    /* Enqueue into history */
    01161    prev = p->history;
    01162    if (prev) {
    01163       while(prev->next)
    01164          prev = prev->next;
    01165       prev->next = hist;
    01166    } else {
    01167       p->history = hist;
    01168    }
    01169    return 0;
    01170 }
    01171
    01172 /*! \brief  retrans_pkt: Retransmit SIP message if no answer ---*/
    01173 static int retrans_pkt(void *data)
    01174 {
    01175    struct sip_pkt *pkt=data, *prev, *cur = NULL;
    01176    char iabuf[INET_ADDRSTRLEN];
    01177    int reschedule = DEFAULT_RETRANS;
    01178
    01179    /* Lock channel */
    01180    ast_mutex_lock(&pkt->owner->lock);
    01181
    01182    if (pkt->retrans < MAX_RETRANS) {
    01183       char buf[80];
    01184
    01185       pkt->retrans++;
    01186       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
    01187          if (sipdebug && option_debug > 3)
    01188             ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
    01189       } else {
    01190          int siptimer_a;
    01191
    01192          if (sipdebug && option_debug > 3)
    01193             ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
    01194          if (!pkt->timer_a)
    01195             pkt->timer_a = 2 ;
    01196          else
    01197             pkt->timer_a = 2 * pkt->timer_a;
    01198
    01199          /* For non-invites, a maximum of 4 secs */
    01200          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
    01201          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
    01202             siptimer_a = 4000;
    01203
    01204          /* Reschedule re-transmit */
    01205          reschedule = siptimer_a;
    01206          if (option_debug > 3)
    01207             ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
    01208       }
    01209
    01210       if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
    01211          if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
    01212             ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
    01213          else
    01214             ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
    01215       }
    01216       snprintf(buf, sizeof(buf), "ReTx %d", reschedule);
    01217
    01218       append_history(pkt->owner, buf, pkt->data);
    01219       __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
    01220       ast_mutex_unlock(&pkt->owner->lock);
    01221       return  reschedule;
    01222    }
    01223    /* Too many retries */
    01224    if (pkt->owner && pkt->method != SIP_OPTIONS) {
    01225       if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
    01226          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
    01227    } else {
    01228       if (pkt->method == SIP_OPTIONS && sipdebug)
    01229          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
    01230    }
    01231    append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
    01232
    01233    pkt->retransid = -1;
    01234
    01235    if (ast_test_flag(pkt, FLAG_FATAL)) {
    01236       while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
    01237          ast_mutex_unlock(&pkt->owner->lock);
    01238          usleep(1);
    01239          ast_mutex_lock(&pkt->owner->lock);
    01240       }
    01241       if (pkt->owner->owner) {
    01242          ast_set_flag(pkt->owner, SIP_ALREADYGONE);
    01243          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
    01244          ast_queue_hangup(pkt->owner->owner);
    01245          ast_mutex_unlock(&pkt->owner->owner->lock);
    01246       } else {
    01247          /* If no channel owner, destroy now */
    01248          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
    01249          if (pkt->method != SIP_OPTIONS)
    01250             ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
    01251       }
    01252    }
    01253    /* In any case, go ahead and remove the packet */
    01254    prev = NULL;
    01255    cur = pkt->owner->packets;
    01256    while(cur) {
    01257       if (cur == pkt)
    01258          break;
    01259       prev = cur;
    01260       cur = cur->next;
    01261    }
    01262    if (cur) {
    01263       if (prev)
    01264          prev->next = cur->next;
    01265       else
    01266          pkt->owner->packets = cur->next;
    01267       ast_mutex_unlock(&pkt->owner->lock);
    01268       free(cur);
    01269       pkt = NULL;
    01270    } else
    01271       ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
    01272    if (pkt)
    01273       ast_mutex_unlock(&pkt->owner->lock);
    01274    return 0;
    01275 }
    01276
    01277 /*! \brief  __sip_reliable_xmit: transmit packet with retransmits ---*/
    01278 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
    01279 {
    01280    struct sip_pkt *pkt;
    01281    int siptimer_a = DEFAULT_RETRANS;
    01282
    01283    pkt = malloc(sizeof(struct sip_pkt) + len + 1);
    01284    if (!pkt)
    01285       return -1;
    01286    memset(pkt, 0, sizeof(struct sip_pkt));
    01287    memcpy(pkt->data, data, len);
    01288    pkt->method = sipmethod;
    01289    pkt->packetlen = len;
    01290    pkt->next = p->packets;
    01291    pkt->owner = p;
    01292    pkt->seqno = seqno;
    01293    if (resp)
    01294       ast_set_flag(pkt, FLAG_RESPONSE);
    01295    pkt->data[len] = '\0';
    01296    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
    01297    if (fatal)
    01298       ast_set_flag(pkt, FLAG_FATAL);
    01299    if (pkt->timer_t1)
    01300       siptimer_a = pkt->timer_t1 * 2;
    01301
    01302    /* Schedule retransmission */
    01303    pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
    01304    if (option_debug > 3 && sipdebug)
    01305       ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id  #%d\n", pkt->retransid);
    01306    pkt->next = p->packets;
    01307    p->packets = pkt;
    01308
    01309    __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
    01310    if (sipmethod == SIP_INVITE) {
    01311       /* Note this is a pending invite */
    01312       p->pendinginvite = seqno;
    01313    }
    01314    return 0;
    01315 }
    01316
    01317 /*! \brief  __sip_autodestruct: Kill a call (called by scheduler) ---*/
    01318 static int __sip_autodestruct(void *data)
    01319 {
    01320    struct sip_pvt *p = data;
    01321
    01322
    01323    /* If this is a subscription, tell the phone that we got a timeout */
    01324    if (p->subscribed) {
    01325       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, 1, 1);  /* Send first notification */
    01326       p->subscribed = NONE;
    01327       append_history(p, "Subscribestatus", "timeout");
    01328       return 10000;  /* Reschedule this destruction so that we know that it's gone */
    01329    }
    01330
    01331    /* This scheduled event is now considered done. */
    01332    p->autokillid = -1;
    01333
    01334    ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
    01335    append_history(p, "AutoDestroy", "");
    01336    if (p->owner) {
    01337       ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
    01338       ast_queue_hangup(p->owner);
    01339    } else {
    01340       sip_destroy(p);
    01341    }
    01342    return 0;
    01343 }
    01344
    01345 /*! \brief  sip_scheddestroy: Schedule destruction of SIP call ---*/
    01346 static int sip_scheddestroy(struct sip_pvt *p, int ms)
    01347 {
    01348    char tmp[80];
    01349    if (sip_debug_test_pvt(p))
    01350       ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
    01351    if (recordhistory) {
    01352       snprintf(tmp, sizeof(tmp), "%d ms", ms);
    01353       append_history(p, "SchedDestroy", tmp);
    01354    }
    01355
    01356    if (p->autokillid > -1)
    01357       ast_sched_del(sched, p->autokillid);
    01358    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
    01359    return 0;
    01360 }
    01361
    01362 /*! \brief  sip_cancel_destroy: Cancel destruction of SIP call ---*/
    01363 static int sip_cancel_destroy(struct sip_pvt *p)
    01364 {
    01365    if (p->autokillid > -1)
    01366       ast_sched_del(sched, p->autokillid);
    01367    append_history(p, "CancelDestroy", "");
    01368    p->autokillid = -1;
    01369    return 0;
    01370 }
    01371
    01372 /*! \brief  __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
    01373 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
    01374 {
    01375    struct sip_pkt *cur, *prev = NULL;
    01376    int res = -1;
    01377    int resetinvite = 0;
    01378    /* Just in case... */
    01379    char *msg;
    01380
    01381    msg = sip_methods[sipmethod].text;
    01382
    01383    ast_mutex_lock(&p->lock);
    01384    cur = p->packets;
    01385    while(cur) {
    01386       if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
    01387          ((ast_test_flag(cur, FLAG_RESPONSE)) ||
    01388           (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
    01389          if (!resp && (seqno == p->pendinginvite)) {
    01390             ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
    01391             p->pendinginvite = 0;
    01392             resetinvite = 1;
    01393          }
    01394          /* this is our baby */
    01395          if (prev)
    01396             prev->next = cur->next;
    01397          else
    01398             p->packets = cur->next;
    01399          if (cur->retransid > -1) {
    01400             if (sipdebug && option_debug > 3)
    01401                ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
    01402             ast_sched_del(sched, cur->retransid);
    01403             cur->retransid = -1;
    01404          }
    01405          free(cur);
    01406          res = 0;
    01407          break;
    01408       }
    01409       prev = cur;
    01410       cur = cur->next;
    01411    }
    01412    ast_mutex_unlock(&p->lock);
    01413    ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
    01414    return res;
    01415 }
    01416
    01417 /* Pretend to ack all packets */
    01418 static int __sip_pretend_ack(struct sip_pvt *p)
    01419 {
    01420    struct sip_pkt *cur=NULL;
    01421
    01422    while(p->packets) {
    01423       if (cur == p->packets) {
    01424          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
    01425          return -1;
    01426       }
    01427       cur = p->packets;
    01428       if (cur->method)
    01429          __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
    01430       else {   /* Unknown packet type */
    01431          char *c;
    01432          char method[128];
    01433          ast_copy_string(method, p->packets->data, sizeof(method));
    01434          c = ast_skip_blanks(method); /* XXX what ? */
    01435          *c = '\0';
    01436          __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
    01437       }
    01438    }
    01439    return 0;
    01440 }
    01441
    01442 /*! \brief  __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
    01443 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
    01444 {
    01445    struct sip_pkt *cur;
    01446    int res = -1;
    01447    char *msg = sip_methods[sipmethod].text;
    01448
    01449    cur = p->packets;
    01450    while(cur) {
    01451       if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
    01452          ((ast_test_flag(cur, FLAG_RESPONSE)) ||
    01453           (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
    01454          /* this is our baby */
    01455          if (cur->retransid > -1) {
    01456             if (option_debug > 3 && sipdebug)
    01457                ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
    01458             ast_sched_del(sched, cur->retransid);
    01459             cur->retransid = -1;
    01460          }
    01461          res = 0;
    01462          break;
    01463       }
    01464       cur = cur->next;
    01465    }
    01466    ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
    01467    return res;
    01468 }
    01469
    01470 static void parse_request(struct sip_request *req);
    01471 static char *get_header(struct sip_request *req, char *name);
    01472 static void copy_request(struct sip_request *dst,struct sip_request *src);
    01473
    01474 /*! \brief  parse_copy: Copy SIP request, parse it */
    01475 static void parse_copy(struct sip_request *dst, struct sip_request *src)
    01476 {
    01477    memset(dst, 0, sizeof(*dst));
    01478    memcpy(dst->data, src->data, sizeof(dst->data));
    01479    dst->len = src->len;
    01480    parse_request(dst);
    01481 }
    01482
    01483 /*! \brief  send_response: Transmit response on SIP request---*/
    01484 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
    01485 {
    01486    int res;
    01487    char iabuf[INET_ADDRSTRLEN];
    01488    struct sip_request tmp;
    01489    char tmpmsg[80];
    01490
    01491    if (sip_debug_test_pvt(p)) {
    01492       if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
    01493          ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
    01494       else
    01495          ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
    01496    }
    01497    if (reliable) {
    01498       if (recordhistory) {
    01499          parse_copy(&tmp, req);
    01500          snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
    01501          append_history(p, "TxRespRel", tmpmsg);
    01502       }
    01503       res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1), req->method);
    01504    } else {
    01505       if (recordhistory) {
    01506          parse_copy(&tmp, req);
    01507          snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
    01508          append_history(p, "TxResp", tmpmsg);
    01509       }
    01510       res = __sip_xmit(p, req->data, req->len);
    01511    }
    01512    if (res > 0)
    01513       return 0;
    01514    return res;
    01515 }
    01516
    01517 /*! \brief  send_request: Send SIP Request to the other part of the dialogue ---*/
    01518 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
    01519 {
    01520    int res;
    01521    char iabuf[INET_ADDRSTRLEN];
    01522    struct sip_request tmp;
    01523    char tmpmsg[80];
    01524
    01525    if (sip_debug_test_pvt(p)) {
    01526       if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
    01527          ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
    01528       else
    01529          ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
    01530    }
    01531    if (reliable) {
    01532       if (recordhistory) {
    01533          parse_copy(&tmp, req);
    01534          snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
    01535          append_history(p, "TxReqRel", tmpmsg);
    01536       }
    01537       res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method);
    01538    } else {
    01539       if (recordhistory) {
    01540          parse_copy(&tmp, req);
    01541          snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
    01542          append_history(p, "TxReq", tmpmsg);
    01543       }
    01544       res = __sip_xmit(p, req->data, req->len);
    01545    }
    01546    return res;
    01547 }
    01548
    01549 /*! \brief  get_in_brackets: Pick out text in brackets from character string ---*/
    01550 /* returns pointer to terminated stripped string. modifies input string. */
    01551 static char *get_in_brackets(char *tmp)
    01552 {
    01553    char *parse;
    01554    char *first_quote;
    01555    char *first_bracket;
    01556    char *second_bracket;
    01557    char last_char;
    01558
    01559    parse = tmp;
    01560    while (1) {
    01561       first_quote = strchr(parse, '"');
    01562       first_bracket = strchr(parse, '<');
    01563       if (first_quote && first_bracket && (first_quote < first_bracket)) {
    01564          last_char = '\0';
    01565          for (parse = first_quote + 1; *parse; parse++) {
    01566             if ((*parse == '"') && (last_char != '\\'))
    01567                break;
    01568             last_char = *parse;
    01569          }
    01570          if (!*parse) {
    01571             ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
    01572             return tmp;
    01573          }
    01574          parse++;
    01575          continue;
    01576       }
    01577       if (first_bracket) {
    01578          second_bracket = strchr(first_bracket + 1, '>');
    01579          if (second_bracket) {
    01580             *second_bracket = '\0';
    01581             return first_bracket + 1;
    01582          } else {
    01583             ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
    01584             return tmp;
    01585          }
    01586       }
    01587       return tmp;
    01588    }
    01589 }
    01590
    01591 /*! \brief  sip_sendtext: Send SIP MESSAGE text within a call ---*/
    01592 /*      Called from PBX core text message functions */
    01593 static int sip_sendtext(struct ast_channel *ast, const char *text)
    01594 {
    01595    struct sip_pvt *p = ast->tech_pvt;
    01596    int debug=sip_debug_test_pvt(p);
    01597
    01598    if (debug)
    01599       ast_verbose("Sending text %s on %s\n", text, ast->name);
    01600    if (!p)
    01601       return -1;
    01602    if (ast_strlen_zero(text))
    01603       return 0;
    01604    if (debug)
    01605       ast_verbose("Really sending text %s on %s\n", text, ast->name);
    01606    transmit_message_with_text(p, text);
    01607    return 0;
    01608 }
    01609
    01610 /*! \brief  realtime_update_peer: Update peer object in realtime storage ---*/
    01611 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
    01612 {
    01613    char port[10];
    01614    char ipaddr[20];
    01615    char regseconds[20];
    01616    time_t nowtime;
    01617
    01618    time(&nowtime);
    01619    nowtime += expirey;
    01620    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
    01621    ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
    01622    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
    01623
    01624    if (fullcontact)
    01625       ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL);
    01626    else
    01627       ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
    01628 }
    01629
    01630 /*! \brief  register_peer_exten: Automatically add peer extension to dial plan ---*/
    01631 static void register_peer_exten(struct sip_peer *peer, int onoff)
    01632 {
    01633    char multi[256];
    01634    char *stringp, *ext;
    01635    if (!ast_strlen_zero(regcontext)) {
    01636       ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
    01637       stringp = multi;
    01638       while((ext = strsep(&stringp, "&"))) {
    01639          if (onoff)
    01640             ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), FREE, channeltype);
    01641          else
    01642             ast_context_remove_extension(regcontext, ext, 1, NULL);
    01643       }
    01644    }
    01645 }
    01646
    01647 /*! \brief  sip_destroy_peer: Destroy peer object from memory */
    01648 static void sip_destroy_peer(struct sip_peer *peer)
    01649 {
    01650    /* Delete it, it needs to disappear */
    01651    if (peer->call)
    01652       sip_destroy(peer->call);
    01653    if (peer->chanvars) {
    01654       ast_variables_destroy(peer->chanvars);
    01655       peer->chanvars = NULL;
    01656    }
    01657    if (peer->expire > -1)
    01658       ast_sched_del(sched, peer->expire);
    01659
    01660    if (peer->pokeexpire > -1)
    01661       ast_sched_del(sched, peer->pokeexpire);
    01662    register_peer_exten(peer, 0);
    01663    ast_free_ha(peer->ha);
    01664    if (ast_test_flag(peer, SIP_SELFDESTRUCT))
    01665       apeerobjs--;
    01666    else if (ast_test_flag(peer, SIP_REALTIME))
    01667       rpeerobjs--;
    01668    else
    01669       speerobjs--;
    01670    clear_realm_authentication(peer->auth);
    01671    peer->auth = (struct sip_auth *) NULL;
    01672    free(peer);
    01673 }
    01674
    01675 /*! \brief  update_peer: Update peer data in database (if used) ---*/
    01676 static void update_peer(struct sip_peer *p, int expiry)
    01677 {
    01678    int rtcachefriends = ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
    01679    if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) &&
    01680       (ast_test_flag(p, SIP_REALTIME) || rtcachefriends)) {
    01681       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
    01682    }
    01683 }
    01684
    01685
    01686 /*! \brief  realtime_peer: Get peer from realtime storage
    01687  * Checks the "sippeers" realtime family from extconfig.conf */
    01688 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
    01689 {
    01690    struct sip_peer *peer=NULL;
    01691    struct ast_variable *var = NULL;
    01692    struct ast_variable *tmp;
    01693    char *newpeername = (char *) peername;
    01694    char iabuf[80];
    01695
    01696    /* First check on peer name */
    01697    if (newpeername) {
    01698       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
    01699       if (!var && sin)
    01700          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), NULL);
    01701       if (!var) {
    01702          var = ast_load_realtime("sippeers", "name", newpeername, NULL);
    01703          /*!\note
    01704           * If this one loaded something, then we need to ensure that the host
    01705           * field matched.  The only reason why we can't have this as a criteria
    01706           * is because we only have the IP address and the host field might be
    01707           * set as a name (and the reverse PTR might not match).
    01708           */
    01709          if (var) {
    01710             for (tmp = var; tmp; tmp = tmp->next) {
    01711                if (!strcasecmp(var->name, "host")) {
    01712                   struct hostent *hp;
    01713                   struct ast_hostent ahp;
    01714                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
    01715                      /* No match */
    01716                      ast_variables_destroy(var);
    01717                      var = NULL;
    01718                   }
    01719                   break;
    01720                }
    01721             }
    01722          }
    01723       }
    01724    }
    01725
    01726    if (!var && sin) {   /* Then check on IP address */
    01727       ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
    01728       var = ast_load_realtime("sippeers", "host", iabuf, NULL);   /* First check for fixed IP hosts */
    01729       if (!var)
    01730          var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL); /* Then check for registred hosts */
    01731    }
    01732
    01733    if (!var)
    01734       return NULL;
    01735
    01736    tmp = var;
    01737    /* If this is type=user, then skip this object. */
    01738    while(tmp) {
    01739       if (!strcasecmp(tmp->name, "type") &&
    01740           !strcasecmp(tmp->value, "user")) {
    01741          ast_variables_destroy(var);
    01742          return NULL;
    01743       } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
    01744          newpeername = tmp->value;
    01745       }
    01746       tmp = tmp->next;
    01747    }
    01748
    01749    if (!newpeername) {  /* Did not find peer in realtime */
    01750       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
    01751       ast_variables_destroy(var);
    01752       return (struct sip_peer *) NULL;
    01753    }
    01754
    01755    /* Peer found in realtime, now build it in memory */
    01756    peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
    01757    if (!peer) {
    01758       ast_variables_destroy(var);
    01759       return (struct sip_peer *) NULL;
    01760    }
    01761
    01762    if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
    01763       /* Cache peer */
    01764       ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
    01765       if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
    01766          if (peer->expire > -1) {
    01767             ast_sched_del(sched, peer->expire);
    01768          }
    01769          peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
    01770       }
    01771       ASTOBJ_CONTAINER_LINK(&peerl,peer);
    01772    } else {
    01773       ast_set_flag(peer, SIP_REALTIME);
    01774    }
    01775    ast_variables_destroy(var);
    01776
    01777    return peer;
    01778 }
    01779
    01780 /*! \brief  sip_addrcmp: Support routine for find_peer ---*/
    01781 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
    01782 {
    01783    /* We know name is the first field, so we can cast */
    01784    struct sip_peer *p = (struct sip_peer *)name;
    01785    return   !(!inaddrcmp(&p->addr, sin) ||
    01786                (ast_test_flag(p, SIP_INSECURE_PORT) &&
    01787                (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
    01788 }
    01789
    01790 /*! \brief  find_peer: Locate peer by name or ip address
    01791  * This is used on incoming SIP message to find matching peer on ip
    01792    or outgoing message to find matching peer on name */
    01793 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
    01794 {
    01795    struct sip_peer *p = NULL;
    01796
    01797    if (peer)
    01798       p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
    01799    else
    01800       p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
    01801
    01802    if (!p && realtime) {
    01803       p = realtime_peer(peer, sin);
    01804    }
    01805
    01806    return p;
    01807 }
    01808
    01809 /*! \brief  sip_destroy_user: Remove user object from in-memory storage ---*/
    01810 static void sip_destroy_user(struct sip_user *user)
    01811 {
    01812    ast_free_ha(user->ha);
    01813    if (user->chanvars) {
    01814       ast_variables_destroy(user->chanvars);
    01815       user->chanvars = NULL;
    01816    }
    01817    if (ast_test_flag(user, SIP_REALTIME))
    01818       ruserobjs--;
    01819    else
    01820       suserobjs--;
    01821    free(user);
    01822 }
    01823
    01824 /*! \brief  realtime_user: Load user from realtime storage
    01825  * Loads user from "sipusers" category in realtime (extconfig.conf)
    01826  * Users are matched on From: user name (the domain in skipped) */
    01827 static struct sip_user *realtime_user(const char *username)
    01828 {
    01829    struct ast_variable *var;
    01830    struct ast_variable *tmp;
    01831    struct sip_user *user = NULL;
    01832
    01833    var = ast_load_realtime("sipusers", "name", username, NULL);
    01834
    01835    if (!var)
    01836       return NULL;
    01837
    01838    tmp = var;
    01839    while (tmp) {
    01840       if (!strcasecmp(tmp->name, "type") &&
    01841          !strcasecmp(tmp->value, "peer")) {
    01842          ast_variables_destroy(var);
    01843          return NULL;
    01844       }
    01845       tmp = tmp->next;
    01846    }
    01847
    01848
    01849
    01850    user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
    01851
    01852    if (!user) {   /* No user found */
    01853       ast_variables_destroy(var);
    01854       return NULL;
    01855    }
    01856
    01857    if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
    01858       ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
    01859       suserobjs++;
    01860       ASTOBJ_CONTAINER_LINK(&userl,user);
    01861    } else {
    01862       /* Move counter from s to r... */
    01863       suserobjs--;
    01864       ruserobjs++;
    01865       ast_set_flag(user, SIP_REALTIME);
    01866    }
    01867    ast_variables_destroy(var);
    01868    return user;
    01869 }
    01870
    01871 /*! \brief  find_user: Locate user by name
    01872  * Locates user by name (From: sip uri user name part) first
    01873  * from in-memory list (static configuration) then from
    01874  * realtime storage (defined in extconfig.conf) */
    01875 static struct sip_user *find_user(const char *name, int realtime)
    01876 {
    01877    struct sip_user *u = NULL;
    01878    u = ASTOBJ_CONTAINER_FIND(&userl,name);
    01879    if (!u && realtime) {
    01880       u = realtime_user(name);
    01881    }
    01882    return u;
    01883 }
    01884
    01885 /*! \brief  create_addr_from_peer: create address structure from peer reference ---*/
    01886 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
    01887 {
    01888    char *callhost;
    01889
    01890    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
    01891        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
    01892       if (peer->addr.sin_addr.s_addr) {
    01893          r->sa.sin_family = peer->addr.sin_family;
    01894          r->sa.sin_addr = peer->addr.sin_addr;
    01895          r->sa.sin_port = peer->addr.sin_port;
    01896       } else {
    01897          r->sa.sin_family = peer->defaddr.sin_family;
    01898          r->sa.sin_addr = peer->defaddr.sin_addr;
    01899          r->sa.sin_port = peer->defaddr.sin_port;
    01900       }
    01901       memcpy(&r->recv, &r->sa, sizeof(r->recv));
    01902    } else {
    01903       return -1;
    01904    }
    01905
    01906    ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY);
    01907    r->capability = peer->capability;
    01908    r->prefs = peer->prefs;
    01909    if (r->rtp) {
    01910       ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
    01911       ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
    01912    }
    01913    if (r->vrtp) {
    01914       ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
    01915       ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
    01916    }
    01917    ast_copy_string(r->peername, peer->name, sizeof(r->peername));
    01918    ast_copy_string(r->authname, peer->username, sizeof(r->authname));
    01919    ast_copy_string(r->username, peer->username, sizeof(r->username));
    01920    ast_copy_string(r->peersecret, peer->secret, sizeof(r->peersecret));
    01921    ast_copy_string(r->peermd5secret, peer->md5secret, sizeof(r->peermd5secret));
    01922    ast_copy_string(r->tohost, peer->tohost, sizeof(r->tohost));
    01923    ast_copy_string(r->fullcontact, peer->fullcontact, sizeof(r->fullcontact));
    01924    if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
    01925       if ((callhost = strchr(r->callid, '@'))) {
    01926          strncpy(callhost + 1, peer->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
    01927       }
    01928    }
    01929    if (ast_strlen_zero(r->tohost)) {
    01930       if (peer->addr.sin_addr.s_addr)
    01931          ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->addr.sin_addr);
    01932       else
    01933          ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->defaddr.sin_addr);
    01934    }
    01935    if (!ast_strlen_zero(peer->fromdomain))
    01936       ast_copy_string(r->fromdomain, peer->fromdomain, sizeof(r->fromdomain));
    01937    if (!ast_strlen_zero(peer->fromuser))
    01938       ast_copy_string(r->fromuser, peer->fromuser, sizeof(r->fromuser));
    01939    if (!ast_strlen_zero(peer->language))
    01940       ast_copy_string(r->language, peer->language, sizeof(r->language));
    01941    r->maxtime = peer->maxms;
    01942    r->callgroup = peer->callgroup;
    01943    r->pickupgroup = peer->pickupgroup;
    01944    /* Set timer T1 to RTT for this peer (if known by qualify=) */
    01945    if (peer->maxms && peer->lastms)
    01946       r->timer_t1 = peer->lastms < DEFAULT_T1MIN ? DEFAULT_T1MIN : peer->lastms;
    01947    if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO))
    01948       r->noncodeccapability |= AST_RTP_DTMF;
    01949    else
    01950       r->noncodeccapability &= ~AST_RTP_DTMF;
    01951    ast_copy_string(r->context, peer->context,sizeof(r->context));
    01952    r->rtptimeout = peer->rtptimeout;
    01953    r->rtpholdtimeout = peer->rtpholdtimeout;
    01954    r->rtpkeepalive = peer->rtpkeepalive;
    01955    if (peer->call_limit)
    01956       ast_set_flag(r, SIP_CALL_LIMIT);
    01957
    01958    return 0;
    01959 }
    01960
    01961 /*! \brief  create_addr: create address structure from peer name
    01962  *      Or, if peer not found, find it in the global DNS
    01963  *      returns TRUE (-1) on failure, FALSE on success */
    01964 static int create_addr(struct sip_pvt *dialog, char *opeer)
    01965 {
    01966    struct hostent *hp;
    01967    struct ast_hostent ahp;
    01968    struct sip_peer *p;
    01969    int found=0;
    01970    char *port;
    01971    int portno;
    01972    char host[MAXHOSTNAMELEN], *hostn;
    01973    char peer[256];
    01974
    01975    ast_copy_string(peer, opeer, sizeof(peer));
    01976    port = strchr(peer, ':');
    01977    if (port) {
    01978       *port = '\0';
    01979       port++;
    01980    }
    01981    dialog->sa.sin_family = AF_INET;
    01982    dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
    01983    p = find_peer(peer, NULL, 1);
    01984
    01985    if (p) {
    01986       found++;
    01987       if (create_addr_from_peer(dialog, p))
    01988          ASTOBJ_UNREF(p, sip_destroy_peer);
    01989    }
    01990    if (!p) {
    01991       if (found)
    01992          return -1;
    01993
    01994       hostn = peer;
    01995       if (port)
    01996          portno = atoi(port);
    01997       else
    01998          portno = DEFAULT_SIP_PORT;
    01999       if (srvlookup) {
    02000          char service[MAXHOSTNAMELEN];
    02001          int tportno;
    02002          int ret;
    02003          snprintf(service, sizeof(service), "_sip._udp.%s", peer);
    02004          ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
    02005          if (ret > 0) {
    02006             hostn = host;
    02007             portno = tportno;
    02008          }
    02009       }
    02010       hp = ast_gethostbyname(hostn, &ahp);
    02011       if (hp) {
    02012          ast_copy_string(dialog->tohost, peer, sizeof(dialog->tohost));
    02013          memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
    02014          dialog->sa.sin_port = htons(portno);
    02015          memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
    02016          return 0;
    02017       } else {
    02018          ast_log(LOG_WARNING, "No such host: %s\n", peer);
    02019          return -1;
    02020       }
    02021    } else {
    02022       ASTOBJ_UNREF(p, sip_destroy_peer);
    02023       return 0;
    02024    }
    02025 }
    02026
    02027 /*! \brief  auto_congest: Scheduled congestion on a call ---*/
    02028 static int auto_congest(void *nothing)
    02029 {
    02030    struct sip_pvt *p = nothing;
    02031    ast_mutex_lock(&p->lock);
    02032    p->initid = -1;
    02033    if (p->owner) {
    02034       if (!ast_mutex_trylock(&p->owner->lock)) {
    02035          ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
    02036          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
    02037          ast_mutex_unlock(&p->owner->lock);
    02038       }
    02039    }
    02040    ast_mutex_unlock(&p->lock);
    02041    return 0;
    02042 }
    02043
    02044
    02045
    02046
    02047 /*! \brief  sip_call: Initiate SIP call from PBX
    02048  *      used from the dial() application      */
    02049 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
    02050 {
    02051    int res;
    02052    struct sip_pvt *p;
    02053 #ifdef OSP_SUPPORT
    02054    char *osphandle = NULL;
    02055 #endif
    02056    struct varshead *headp;
    02057    struct ast_var_t *current;
    02058
    02059
    02060
    02061    p = ast->tech_pvt;
    02062    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
    02063       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
    02064       return -1;
    02065    }
    02066
    02067
    02068    /* Check whether there is vxml_url, distinctive ring variables */
    02069
    02070    headp=&ast->varshead;
    02071    AST_LIST_TRAVERSE(headp,current,entries) {
    02072       /* Check whether there is a VXML_URL variable */
    02073       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
    02074          p->options->vxml_url = ast_var_value(current);
    02075                } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
    02076                        p->options->uri_options = ast_var_value(current);
    02077       } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
    02078          /* Check whether there is a ALERT_INFO variable */
    02079          p->options->distinctive_ring = ast_var_value(current);
    02080       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
    02081          /* Check whether there is a variable with a name starting with SIPADDHEADER */
    02082          p->options->addsipheaders = 1;
    02083       }
    02084
    02085
    02086 #ifdef OSP_SUPPORT
    02087       else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
    02088          p->options->osptoken = ast_var_value(current);
    02089       } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
    02090          osphandle = ast_var_value(current);
    02091       }
    02092 #endif
    02093    }
    02094
    02095    res = 0;
    02096    ast_set_flag(p, SIP_OUTGOING);
    02097 #ifdef OSP_SUPPORT
    02098    if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%30d", &p->osphandle) != 1)) {
    02099       /* Force Disable OSP support */
    02100       ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
    02101       p->options->osptoken = NULL;
    02102       osphandle = NULL;
    02103       p->osphandle = -1;
    02104    }
    02105 #endif
    02106    ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
    02107    res = update_call_counter(p, INC_CALL_LIMIT);
    02108    if ( res != -1 ) {
    02109       p->callingpres = ast->cid.cid_pres;
    02110       p->jointcapability = p->capability;
    02111       p->jointnoncodeccapability = p->noncodeccapability;
    02112       transmit_invite(p, SIP_INVITE, 1, 2);
    02113       if (p->maxtime) {
    02114          /* Initialize auto-congest time */
    02115          p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
    02116       }
    02117    }
    02118    return res;
    02119 }
    02120
    02121 /*! \brief  sip_registry_destroy: Destroy registry object ---*/
    02122 /* Objects created with the register= statement in static configuration */
    02123 static void sip_registry_destroy(struct sip_registry *reg)
    02124 {
    02125    /* Really delete */
    02126    if (reg->call) {
    02127       /* Clear registry before destroying to ensure
    02128          we don't get reentered trying to grab the registry lock */
    02129       reg->call->registry = NULL;
    02130       sip_destroy(reg->call);
    02131    }
    02132    if (reg->expire > -1)
    02133       ast_sched_del(sched, reg->expire);
    02134    if (reg->timeout > -1)
    02135       ast_sched_del(sched, reg->timeout);
    02136    regobjs--;
    02137    free(reg);
    02138
    02139 }
    02140
    02141 /*! \brief   __sip_destroy: Execute destrucion of call structure, release memory---*/
    02142 static void __sip_destroy(struct sip_pvt *p, int lockowner)
    02143 {
    02144    struct sip_pvt *cur, *prev = NULL;
    02145    struct sip_pkt *cp;
    02146    struct sip_history *hist;
    02147
    02148    if (sip_debug_test_pvt(p))
    02149       ast_verbose("Destroying call '%s'\n", p->callid);
    02150
    02151    if (ast_test_flag(p, SIP_INC_COUNT)) {
    02152       update_call_counter(p, DEC_CALL_LIMIT);
    02153       if (option_debug)
    02154          ast_log(LOG_DEBUG, "Call did not properly clean up call counter. Call ID %s\n", p->callid);
    02155    }
    02156
    02157    if (dumphistory)
    02158       sip_dump_history(p);
    02159
    02160    if (p->options)
    02161       free(p->options);
    02162
    02163    if (p->stateid > -1)
    02164       ast_extension_state_del(p->stateid, NULL);
    02165    if (p->initid > -1)
    02166       ast_sched_del(sched, p->initid);
    02167    if (p->autokillid > -1)
    02168       ast_sched_del(sched, p->autokillid);
    02169
    02170    if (p->rtp) {
    02171       ast_rtp_destroy(p->rtp);
    02172    }
    02173    if (p->vrtp) {
    02174       ast_rtp_destroy(p->vrtp);
    02175    }
    02176    if (p->route) {
    02177       free_old_route(p->route);
    02178       p->route = NULL;
    02179    }
    02180    if (p->registry) {
    02181       if (p->registry->call == p)
    02182          p->registry->call = NULL;
    02183       ASTOBJ_UNREF(p->registry,sip_registry_destroy);
    02184    }
    02185
    02186    if (p->rpid)
    02187       free(p->rpid);
    02188
    02189    if (p->rpid_from)
    02190       free(p->rpid_from);
    02191
    02192    /* Unlink us from the owner if we have one */
    02193    if (p->owner) {
    02194       if (lockowner)
    02195          ast_mutex_lock(&p->owner->lock);
    02196       ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
    02197       p->owner->tech_pvt = NULL;
    02198       if (lockowner)
    02199          ast_mutex_unlock(&p->owner->lock);
    02200    }
    02201    /* Clear history */
    02202    while(p->history) {
    02203       hist = p->history;
    02204       p->history = p->history->next;
    02205       free(hist);
    02206    }
    02207
    02208    cur = iflist;
    02209    while(cur) {
    02210       if (cur == p) {
    02211          if (prev)
    02212             prev->next = cur->next;
    02213          else
    02214             iflist = cur->next;
    02215          break;
    02216       }
    02217       prev = cur;
    02218       cur = cur->next;
    02219    }
    02220    if (!cur) {
    02221       ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
    02222       return;
    02223    }
    02224    while((cp = p->packets)) {
    02225       p->packets = p->packets->next;
    02226       if (cp->retransid > -1) {
    02227          ast_sched_del(sched, cp->retransid);
    02228       }
    02229       free(cp);
    02230    }
    02231    if (p->chanvars) {
    02232       ast_variables_destroy(p->chanvars);
    02233       p->chanvars = NULL;
    02234    }
    02235    ast_mutex_destroy(&p->lock);
    02236    free(p);
    02237 }
    02238
    02239 /*! \brief  update_call_counter: Handle call_limit for SIP users
    02240  * Note: This is going to be replaced by app_groupcount
    02241  * Thought: For realtime, we should propably update storage with inuse counter... */
    02242 static int update_call_counter(struct sip_pvt *fup, int event)
    02243 {
    02244    char name[256];
    02245    int *inuse, *call_limit;
    02246    int outgoing = ast_test_flag(fup, SIP_OUTGOING);
    02247    struct sip_user *u = NULL;
    02248    struct sip_peer *p = NULL;
    02249
    02250    if (option_debug > 2)
    02251       ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
    02252    /* Test if we need to check call limits, in order to avoid
    02253       realtime lookups if we do not need it */
    02254    if (!ast_test_flag(fup, SIP_CALL_LIMIT))
    02255       return 0;
    02256
    02257    ast_copy_string(name, fup->username, sizeof(name));
    02258
    02259    /* Check the list of users */
    02260    if (!outgoing && (u = find_user(name, 1))) {
    02261       inuse = &u->inUse;
    02262       call_limit = &u->call_limit;
    02263       p = NULL;
    02264    } else {
    02265       /* Try to find peer */
    02266       if (!p)
    02267          p = find_peer(fup->peername, NULL, 1);
    02268       if (p) {
    02269          inuse = &p->inUse;
    02270          call_limit = &p->call_limit;
    02271          ast_copy_string(name, fup->peername, sizeof(name));
    02272       } else {
    02273          if (option_debug > 1)
    02274             ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
    02275          return 0;
    02276       }
    02277    }
    02278    switch(event) {
    02279       /* incoming and outgoing affects the inUse counter */
    02280       case DEC_CALL_LIMIT:
    02281          if ( *inuse > 0 ) {
    02282             if (ast_test_flag(fup, SIP_INC_COUNT)) {
    02283                      (*inuse)--;
    02284                ast_clear_flag(fup, SIP_INC_COUNT);
    02285             }
    02286          } else {
    02287             *inuse = 0;
    02288          }
    02289          if (option_debug > 1 || sipdebug) {
    02290             ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
    02291          }
    02292          break;
    02293       case INC_CALL_LIMIT:
    02294          if (*call_limit > 0 ) {
    02295             if (*inuse >= *call_limit) {
    02296                ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
    02297                if (u)
    02298                   ASTOBJ_UNREF(u,sip_destroy_user);
    02299                else
    02300                   ASTOBJ_UNREF(p,sip_destroy_peer);
    02301                return -1;
    02302             }
    02303          }
    02304          (*inuse)++;
    02305                    ast_set_flag(fup,SIP_INC_COUNT);
    02306          if (option_debug > 1 || sipdebug) {
    02307             ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
    02308          }
    02309          break;
    02310       default:
    02311          ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
    02312    }
    02313    if (u)
    02314       ASTOBJ_UNREF(u,sip_destroy_user);
    02315    else
    02316       ASTOBJ_UNREF(p,sip_destroy_peer);
    02317    return 0;
    02318 }
    02319
    02320 /*! \brief  sip_destroy: Destroy SIP call structure ---*/
    02321 static void sip_destroy(struct sip_pvt *p)
    02322 {
    02323    ast_mutex_lock(&iflock);
    02324    __sip_destroy(p, 1);
    02325    ast_mutex_unlock(&iflock);
    02326 }
    02327
    02328
    02329 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
    02330
    02331 /*! \brief  hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes ---*/
    02332 static int hangup_sip2cause(int cause)
    02333 {
    02334 /* Possible values taken from causes.h */
    02335
    02336    switch(cause) {
    02337       case 603:   /* Declined */
    02338       case 403:   /* Not found */
    02339       case 487:   /* Call cancelled */
    02340          return AST_CAUSE_CALL_REJECTED;
    02341       case 404:   /* Not found */
    02342          return AST_CAUSE_UNALLOCATED;
    02343       case 408:   /* No reaction */
    02344          return AST_CAUSE_NO_USER_RESPONSE;
    02345       case 480:   /* No answer */
    02346          return AST_CAUSE_NO_ANSWER;
    02347       case 483:   /* Too many hops */
    02348          return AST_CAUSE_NO_ANSWER;
    02349       case 486:   /* Busy everywhere */
    02350          return AST_CAUSE_BUSY;
    02351       case 488:   /* No codecs approved */
    02352          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
    02353       case 500:   /* Server internal failure */
    02354          return AST_CAUSE_FAILURE;
    02355       case 501:   /* Call rejected */
    02356          return AST_CAUSE_FACILITY_REJECTED;
    02357       case 502:
    02358          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
    02359       case 503:   /* Service unavailable */
    02360       case 504:   /* Server timeout */
    02361          return AST_CAUSE_CONGESTION;
    02362       default:
    02363          return AST_CAUSE_NORMAL;
    02364    }
    02365    /* Never reached */
    02366    return 0;
    02367 }
    02368
    02369
    02370 /*! \brief  hangup_cause2sip: Convert Asterisk hangup causes to SIP codes
    02371 \verbatim
    02372  Possible values from causes.h
    02373         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
    02374         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
    02375
    02376    In addition to these, a lot of PRI codes is defined in causes.h
    02377    ...should we take care of them too ?
    02378
    02379    Quote RFC 3398
    02380
    02381    ISUP Cause value                        SIP response
    02382    ----------------                        ------------
    02383    1  unallocated number                   404 Not Found
    02384    2  no route to network                  404 Not found
    02385    3  no route to destination              404 Not found
    02386    16 normal call clearing                 --- (*)
    02387    17 user busy                            486 Busy here
    02388    18 no user responding                   408 Request Timeout
    02389    19 no answer from the user              480 Temporarily unavailable
    02390    20 subscriber absent                    480 Temporarily unavailable
    02391    21 call rejected                        403 Forbidden (+)
    02392    22 number changed (w/o diagnostic)      410 Gone
    02393    22 number changed (w/ diagnostic)       301 Moved Permanently
    02394    23 redirection to new destination       410 Gone
    02395    26 non-selected user clearing           404 Not Found (=)
    02396    27 destination out of order             502 Bad Gateway
    02397    28 address incomplete                   484 Address incomplete
    02398    29 facility rejected                    501 Not implemented
    02399    31 normal unspecified                   480 Temporarily unavailable
    02400 \endverbatim
    02401 */
    02402 static char *hangup_cause2sip(int cause)
    02403 {
    02404    switch(cause)
    02405    {
    02406       case AST_CAUSE_UNALLOCATED:      /* 1 */
    02407       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
    02408       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
    02409          return "404 Not Found";
    02410                 case AST_CAUSE_CONGESTION:      /* 34 */
    02411                 case AST_CAUSE_SWITCH_CONGESTION:  /* 42 */
    02412                         return "503 Service Unavailable";
    02413       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
    02414          return "408 Request Timeout";
    02415       case AST_CAUSE_NO_ANSWER:     /* 19 */
    02416          return "480 Temporarily unavailable";
    02417       case AST_CAUSE_CALL_REJECTED:    /* 21 */
    02418          return "403 Forbidden";
    02419       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
    02420          return "410 Gone";
    02421       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
    02422          return "480 Temporarily unavailable";
    02423       case AST_CAUSE_INVALID_NUMBER_FORMAT:
    02424          return "484 Address incomplete";
    02425       case AST_CAUSE_USER_BUSY:
    02426          return "486 Busy here";
    02427       case AST_CAUSE_FAILURE:
    02428                   return "500 Server internal failure";
    02429       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
    02430          return "501 Not Implemented";
    02431       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
    02432          return "503 Service Unavailable";
    02433       /* Used in chan_iax2 */
    02434       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
    02435          return "502 Bad Gateway";
    02436       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
    02437          return "488 Not Acceptable Here";
    02438
    02439       case AST_CAUSE_NOTDEFINED:
    02440       default:
    02441          ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
    02442          return NULL;
    02443    }
    02444
    02445    /* Never reached */
    02446    return 0;
    02447 }
    02448
    02449
    02450 /*! \brief  sip_hangup: Hangup SIP call
    02451  * Part of PBX interface, called from ast_hangup */
    02452 static int sip_hangup(struct ast_channel *ast)
    02453 {
    02454    struct sip_pvt *p = ast->tech_pvt;
    02455    int needcancel = 0;
    02456    int needdestroy = 0;
    02457
    02458    if (!p) {
    02459       ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
    02460       return 0;
    02461    }
    02462    if (option_debug)
    02463       ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
    02464
    02465    ast_mutex_lock(&p->lock);
    02466 #ifdef OSP_SUPPORT
    02467    if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
    02468       ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
    02469    }
    02470 #endif
    02471    ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter\n", p->username);
    02472    update_call_counter(p, DEC_CALL_LIMIT);
    02473    /* Determine how to disconnect */
    02474    if (p->owner != ast) {
    02475       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
    02476       ast_mutex_unlock(&p->lock);
    02477       return 0;
    02478    }
    02479    /* If the call is not UP, we need to send CANCEL instead of BYE */
    02480    if (ast->_state != AST_STATE_UP)
    02481       needcancel = 1;
    02482
    02483    /* Disconnect */
    02484    if (p->vad) {
    02485       ast_dsp_free(p->vad);
    02486    }
    02487    p->owner = NULL;
    02488    ast->tech_pvt = NULL;
    02489
    02490    ast_mutex_lock(&usecnt_lock);
    02491    usecnt--;
    02492    ast_mutex_unlock(&usecnt_lock);
    02493    ast_update_use_count();
    02494
    02495    /* Do not destroy this pvt until we have timeout or
    02496       get an answer to the BYE or INVITE/CANCEL
    02497       If we get no answer during retransmit period, drop the call anyway.
    02498       (Sorry, mother-in-law, you can't deny a hangup by sending
    02499       603 declined to BYE...)
    02500    */
    02501    if (ast_test_flag(p, SIP_ALREADYGONE))
    02502       needdestroy = 1;  /* Set destroy flag at end of this function */
    02503    else
    02504       sip_scheddestroy(p, 32000);
    02505
    02506    /* Start the process if it's not already started */
    02507    if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
    02508       if (needcancel) { /* Outgoing call, not up */
    02509          if (ast_test_flag(p, SIP_OUTGOING)) {
    02510             /* stop retransmitting an INVITE that has not received a response */
    02511             __sip_pretend_ack(p);
    02512
    02513             /* are we allowed to send CANCEL yet? if not, mark
    02514                it pending */
    02515             if (!ast_test_flag(p, SIP_CAN_BYE)) {
    02516                ast_set_flag(p, SIP_PENDINGBYE);
    02517                /* Do we need a timer here if we don't hear from them at all? */
    02518             } else {
    02519                /* Send a new request: CANCEL */
    02520                transmit_request(p, SIP_CANCEL, p->ocseq, 1, 0);
    02521                /* Actually don't destroy us yet, wait for the 487 on our original
    02522                   INVITE, but do set an autodestruct just in case we never get it. */
    02523             }
    02524             if ( p->initid != -1 ) {
    02525                /* channel still up - reverse dec of inUse counter
    02526                   only if the channel is not auto-congested */
    02527                update_call_counter(p, INC_CALL_LIMIT);
    02528             }
    02529          } else { /* Incoming call, not up */
    02530             char *res;
    02531             if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
    02532                transmit_response_reliable(p, res, &p->initreq, 1);
    02533             } else
    02534                transmit_response_reliable(p, "603 Declined", &p->initreq, 1);
    02535          }
    02536       } else { /* Call is in UP state, send BYE */
    02537          if (!p->pendinginvite) {
    02538             /* Send a hangup */
    02539             transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
    02540          } else {
    02541             /* Note we will need a BYE when this all settles out
    02542                but we can't send one while we have "INVITE" outstanding. */
    02543             ast_set_flag(p, SIP_PENDINGBYE);
    02544             ast_clear_flag(p, SIP_NEEDREINVITE);
    02545          }
    02546       }
    02547    }
    02548    if (needdestroy)
    02549       ast_set_flag(p, SIP_NEEDDESTROY);
    02550    ast_mutex_unlock(&p->lock);
    02551    return 0;
    02552 }
    02553
    02554 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
    02555 static void try_suggested_sip_codec(struct sip_pvt *p)
    02556 {
    02557    int fmt;
    02558    char *codec;
    02559
    02560    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
    02561    if (!codec)
    02562       return;
    02563
    02564    fmt = ast_getformatbyname(codec);
    02565    if (fmt) {
    02566       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
    02567       if (p->jointcapability & fmt) {
    02568          p->jointcapability &= fmt;
    02569          p->capability &= fmt;
    02570       } else
    02571          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
    02572    } else
    02573       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
    02574    return;
    02575 }
    02576
    02577 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
    02578  * Part of PBX interface */
    02579 static int sip_answer(struct ast_channel *ast)
    02580 {
    02581    int res = 0;
    02582    struct sip_pvt *p = ast->tech_pvt;
    02583
    02584    ast_mutex_lock(&p->lock);
    02585    if (ast->_state != AST_STATE_UP) {
    02586 #ifdef OSP_SUPPORT
    02587       time(&p->ospstart);
    02588 #endif
    02589       try_suggested_sip_codec(p);
    02590
    02591       ast_setstate(ast, AST_STATE_UP);
    02592       if (option_debug)
    02593          ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
    02594       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 2);
    02595    }
    02596    ast_mutex_unlock(&p->lock);
    02597    return res;
    02598 }
    02599
    02600 /*! \brief  sip_write: Send frame to media channel (rtp) ---*/
    02601 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
    02602 {
    02603    struct sip_pvt *p = ast->tech_pvt;
    02604    int res = 0;
    02605    switch (frame->frametype) {
    02606    case AST_FRAME_VOICE:
    02607       if (!(frame->subclass & ast->nativeformats)) {
    02608          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
    02609             frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
    02610          return 0;
    02611       }
    02612       if (p) {
    02613          ast_mutex_lock(&p->lock);
    02614          if (p->rtp) {
    02615             /* If channel is not up, activate early media session */
    02616             if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
    02617                transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
    02618                ast_set_flag(p, SIP_PROGRESS_SENT);
    02619             }
    02620             time(&p->lastrtptx);
    02621             res =  ast_rtp_write(p->rtp, frame);
    02622          }
    02623          ast_mutex_unlock(&p->lock);
    02624       }
    02625       break;
    02626    case AST_FRAME_VIDEO:
    02627       if (p) {
    02628          ast_mutex_lock(&p->lock);
    02629          if (p->vrtp) {
    02630             /* Activate video early media */
    02631             if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
    02632                transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
    02633                ast_set_flag(p, SIP_PROGRESS_SENT);
    02634             }
    02635             time(&p->lastrtptx);
    02636             res =  ast_rtp_write(p->vrtp, frame);
    02637          }
    02638          ast_mutex_unlock(&p->lock);
    02639       }
    02640       break;
    02641    case AST_FRAME_IMAGE:
    02642       return 0;
    02643       break;
    02644    default:
    02645       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
    02646       return 0;
    02647    }
    02648
    02649    return res;
    02650 }
    02651
    02652 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
    02653         Basically update any ->owner links ----*/
    02654 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
    02655 {
    02656    struct sip_pvt *p = newchan->tech_pvt;
    02657    if (!p) {
    02658       ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
    02659       return -1;
    02660    }
    02661
    02662    ast_mutex_lock(&p->lock);
    02663    if (p->owner != oldchan) {
    02664       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
    02665       ast_mutex_unlock(&p->lock);
    02666       return -1;
    02667    }
    02668    p->owner = newchan;
    02669    ast_mutex_unlock(&p->lock);
    02670    return 0;
    02671 }
    02672
    02673 /*! \brief  sip_senddigit: Send DTMF character on SIP channel */
    02674 /*    within one call, we're able to transmit in many methods simultaneously */
    02675 static int sip_senddigit(struct ast_channel *ast, char digit)
    02676 {
    02677    struct sip_pvt *p = ast->tech_pvt;
    02678    int res = 0;
    02679    ast_mutex_lock(&p->lock);
    02680    switch (ast_test_flag(p, SIP_DTMF)) {
    02681    case SIP_DTMF_INFO:
    02682       transmit_info_with_digit(p, digit);
    02683       break;
    02684    case SIP_DTMF_RFC2833:
    02685       if (p->rtp)
    02686          ast_rtp_senddigit(p->rtp, digit);
    02687       break;
    02688    case SIP_DTMF_INBAND:
    02689       res = -1;
    02690       break;
    02691    }
    02692    ast_mutex_unlock(&p->lock);
    02693    return res;
    02694 }
    02695
    02696
    02697
    02698 /*! \brief  sip_transfer: Transfer SIP call */
    02699 static int sip_transfer(struct ast_channel *ast, const char *dest)
    02700 {
    02701    struct sip_pvt *p = ast->tech_pvt;
    02702    int res;
    02703
    02704    ast_mutex_lock(&p->lock);
    02705    if (ast->_state == AST_STATE_RING)
    02706       res = sip_sipredirect(p, dest);
    02707    else
    02708       res = transmit_refer(p, dest);
    02709    ast_mutex_unlock(&p->lock);
    02710    return res;
    02711 }
    02712
    02713 /*! \brief  sip_indicate: Play indication to user
    02714  * With SIP a lot of indications is sent as messages, letting the device play
    02715    the indication - busy signal, congestion etc */
    02716 static int sip_indicate(struct ast_channel *ast, int condition)
    02717 {
    02718    struct sip_pvt *p = ast->tech_pvt;
    02719    int res = 0;
    02720
    02721    ast_mutex_lock(&p->lock);
    02722    switch(condition) {
    02723    case AST_CONTROL_RINGING:
    02724       if (ast->_state == AST_STATE_RING) {
    02725          if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
    02726              (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
    02727             /* Send 180 ringing if out-of-band seems reasonable */
    02728             transmit_response(p, "180 Ringing", &p->initreq);
    02729             ast_set_flag(p, SIP_RINGING);
    02730             if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
    02731                break;
    02732          } else {
    02733             /* Well, if it's not reasonable, just send in-band */
    02734          }
    02735       }
    02736       res = -1;
    02737       break;
    02738    case AST_CONTROL_BUSY:
    02739       if (ast->_state != AST_STATE_UP) {
    02740          transmit_response(p, "486 Busy Here", &p->initreq);
    02741          ast_set_flag(p, SIP_ALREADYGONE);
    02742          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
    02743          break;
    02744       }
    02745       res = -1;
    02746       break;
    02747    case AST_CONTROL_CONGESTION:
    02748       if (ast->_state != AST_STATE_UP) {
    02749          transmit_response(p, "503 Service Unavailable", &p->initreq);
    02750          ast_set_flag(p, SIP_ALREADYGONE);
    02751          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
    02752          break;
    02753       }
    02754       res = -1;
    02755       break;
    02756    case AST_CONTROL_PROCEEDING:
    02757       if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
    02758          transmit_response(p, "100 Trying", &p->initreq);
    02759          break;
    02760       }
    02761       res = -1;
    02762       break;
    02763    case AST_CONTROL_PROGRESS:
    02764       if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
    02765          transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
    02766          ast_set_flag(p, SIP_PROGRESS_SENT);
    02767          break;
    02768       }
    02769       res = -1;
    02770       break;
    02771    case AST_CONTROL_HOLD:  /* The other part of the bridge are put on hold */
    02772       if (sipdebug)
    02773          ast_log(LOG_DEBUG, "Bridged channel now on hold%s\n", p->callid);
    02774       res = -1;
    02775       break;
    02776    case AST_CONTROL_UNHOLD:   /* The other part of the bridge are back from hold */
    02777       if (sipdebug)
    02778          ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
    02779       res = -1;
    02780       break;
    02781    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
    02782       if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) {
    02783          transmit_info_with_vidupdate(p);
    02784          res = 0;
    02785       } else
    02786          res = -1;
    02787       break;
    02788    case -1:
    02789       res = -1;
    02790       break;
    02791    default:
    02792       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
    02793       res = -1;
    02794       break;
    02795    }
    02796    ast_mutex_unlock(&p->lock);
    02797    return res;
    02798 }
    02799
    02800
    02801
    02802 /*! \brief  sip_new: Initiate a call in the SIP channel */
    02803 /*      called from sip_request_call (calls from the pbx ) */
    02804 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
    02805 {
    02806    struct ast_channel *tmp;
    02807    struct ast_variable *v = NULL;
    02808    int fmt;
    02809 #ifdef OSP_SUPPORT
    02810    char iabuf[INET_ADDRSTRLEN];
    02811    char peer[MAXHOSTNAMELEN];
    02812 #endif
    02813
    02814    ast_mutex_unlock(&i->lock);
    02815    /* Don't hold a sip pvt lock while we allocate a channel */
    02816    tmp = ast_channel_alloc(1);
    02817    if (!tmp) {
    02818       ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
    02819       return NULL;
    02820    }
    02821    ast_mutex_lock(&i->lock);
    02822    tmp->tech = &sip_tech;
    02823    /* Select our native format based on codec preference until we receive
    02824       something from another device to the contrary. */
    02825    if (i->jointcapability)
    02826       tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
    02827    else if (i->capability)
    02828       tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
    02829    else
    02830       tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
    02831    fmt = ast_best_codec(tmp->nativeformats);
    02832
    02833    if (title)
    02834       snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", title, (int)(long) i);
    02835    else if (strchr(i->fromdomain,':'))
    02836       snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':') + 1, (int)(long) i);
    02837    else
    02838       snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long) i);
    02839
    02840    tmp->type = channeltype;
    02841    if (ast_test_flag(i, SIP_DTMF) ==  SIP_DTMF_INBAND) {
    02842       i->vad = ast_dsp_new();
    02843       ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
    02844       if (relaxdtmf)
    02845          ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
    02846    }
    02847    if (i->rtp) {
    02848       tmp->fds[0] = ast_rtp_fd(i->rtp);
    02849       tmp->fds[1] = ast_rtcp_fd(i->rtp);
    02850    }
    02851    if (i->vrtp) {
    02852       tmp->fds[2] = ast_rtp_fd(i->vrtp);
    02853       tmp->fds[3] = ast_rtcp_fd(i->vrtp);
    02854    }
    02855    if (state == AST_STATE_RING)
    02856       tmp->rings = 1;
    02857    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
    02858    tmp->writeformat = fmt;
    02859    tmp->rawwriteformat = fmt;
    02860    tmp->readformat = fmt;
    02861    tmp->rawreadformat = fmt;
    02862    tmp->tech_pvt = i;
    02863
    02864    tmp->callgroup = i->callgroup;
    02865    tmp->pickupgroup = i->pickupgroup;
    02866    tmp->cid.cid_pres = i->callingpres;
    02867    if (!ast_strlen_zero(i->accountcode))
    02868       ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
    02869    if (i->amaflags)
    02870       tmp->amaflags = i->amaflags;
    02871    if (!ast_strlen_zero(i->language))
    02872       ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
    02873    if (!ast_strlen_zero(i->musicclass))
    02874       ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
    02875    i->owner = tmp;
    02876    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
    02877    ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
    02878
    02879    if (!ast_strlen_zero(i->cid_num))
    02880       tmp->cid.cid_num = strdup(i->cid_num);
    02881    if (!ast_strlen_zero(i->cid_name))
    02882       tmp->cid.cid_name = strdup(i->cid_name);
    02883    if (!ast_strlen_zero(i->rdnis))
    02884       tmp->cid.cid_rdnis = strdup(i->rdnis);
    02885    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
    02886       tmp->cid.cid_dnid = strdup(i->exten);
    02887
    02888    tmp->priority = 1;
    02889    if (!ast_strlen_zero(i->uri)) {
    02890       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
    02891    }
    02892    if (!ast_strlen_zero(i->domain)) {
    02893       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
    02894    }
    02895    if (!ast_strlen_zero(i->useragent)) {
    02896       pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
    02897    }
    02898    if (!ast_strlen_zero(i->callid)) {
    02899       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
    02900    }
    02901 #ifdef OSP_SUPPORT
    02902    snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
    02903    pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
    02904 #endif
    02905    ast_setstate(tmp, state);
    02906
    02907    /* Set channel variables for this call from configuration */
    02908    for (v = i->chanvars ; v ; v = v->next)
    02909       pbx_builtin_setvar_helper(tmp, v->name, v->value);
    02910
    02911    if (state != AST_STATE_DOWN) {
    02912       if (ast_pbx_start(tmp)) {
    02913          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
    02914          ast_hangup(tmp);
    02915          tmp = NULL;
    02916       }
    02917    }
    02918
    02919    ast_mutex_lock(&usecnt_lock);
    02920    usecnt++;
    02921    ast_mutex_unlock(&usecnt_lock);
    02922    ast_update_use_count();
    02923
    02924    return tmp;
    02925 }
    02926
    02927 /*! \brief  get_body_by_line: Reads one line of message body */
    02928 static char *get_body_by_line(char *line, char *name, int nameLen)
    02929 {
    02930    if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
    02931       return ast_skip_blanks(line + nameLen + 1);
    02932    }
    02933    return "";
    02934 }
    02935
    02936 /*! \brief  get_sdp: get a specific line from the SDP */
    02937 static char *get_sdp(struct sip_request *req, char *name)
    02938 {
    02939    int x;
    02940    int len = strlen(name);
    02941    char *r;
    02942
    02943    for (x = req->sdp_start; x < req->sdp_end; x++) {
    02944       r = get_body_by_line(req->line[x], name, len);
    02945       if (r[0] != '\0')
    02946          return r;
    02947    }
    02948    return "";
    02949 }
    02950
    02951 static void sdpLineNum_iterator_init(int *iterator, struct sip_request *req)
    02952 {
    02953    *iterator = req->sdp_start;
    02954 }
    02955
    02956 static char *get_sdp_iterate(int *iterator,
    02957               struct sip_request *req, char *name)
    02958 {
    02959    int len = strlen(name);
    02960    char *r;
    02961
    02962    while (*iterator < req->sdp_end) {
    02963       r = get_body_by_line(req->line[(*iterator)++], name, len);
    02964       if (r[0] != '\0')
    02965          return r;
    02966    }
    02967    return "";
    02968 }
    02969
    02970 /*! \brief  get_body: get a specific line from the message body */
    02971 static char *get_body(struct sip_request *req, char *name)
    02972 {
    02973    int x;
    02974    int len = strlen(name);
    02975    char *r;
    02976
    02977    for (x = 0; x < req->lines; x++) {
    02978       r = get_body_by_line(req->line[x], name, len);
    02979       if (r[0] != '\0')
    02980          return r;
    02981    }
    02982    return "";
    02983 }
    02984
    02985 static char *find_alias(const char *name, char *_default)
    02986 {
    02987    int x;
    02988    for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
    02989       if (!strcasecmp(aliases[x].fullname, name))
    02990          return aliases[x].shortname;
    02991    return _default;
    02992 }
    02993
    02994 static char *__get_header(struct sip_request *req, char *name, int *start)
    02995 {
    02996    int pass;
    02997
    02998    /*
    02999     * Technically you can place arbitrary whitespace both before and after the ':' in
    03000     * a header, although RFC3261 clearly says you shouldn't before, and place just
    03001     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
    03002     * a good idea to say you can do it, and if you can do it, why in the hell would.
    03003     * you say you shouldn't.
    03004     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
    03005     * and we always allow spaces after that for compatibility.
    03006     */
    03007    for (pass = 0; name && pass < 2;pass++) {
    03008       int x, len = strlen(name);
    03009       for (x=*start; x<req->headers; x++) {
    03010          if (!strncasecmp(req->header[x], name, len)) {
    03011             char *r = req->header[x] + len;  /* skip name */
    03012             if (pedanticsipchecking)
    03013                r = ast_skip_blanks(r);
    03014
    03015             if (*r == ':') {
    03016                *start = x+1;
    03017                return ast_skip_blanks(r+1);
    03018             }
    03019          }
    03020       }
    03021       if (pass == 0) /* Try aliases */
    03022          name = find_alias(name, NULL);
    03023    }
    03024
    03025    /* Don't return NULL, so get_header is always a valid pointer */
    03026    return "";
    03027 }
    03028
    03029 /*! \brief  get_header: Get header from SIP request ---*/
    03030 static char *get_header(struct sip_request *req, char *name)
    03031 {
    03032    int start = 0;
    03033    return __get_header(req, name, &start);
    03034 }
    03035
    03036 /*! \brief  sip_rtp_read: Read RTP from network ---*/
    03037 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
    03038 {
    03039    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
    03040    struct ast_frame *f;
    03041    static struct ast_frame null_frame = { AST_FRAME_NULL, };
    03042
    03043    if (!p->rtp) {
    03044       /* We have no RTP allocated for this channel */
    03045       return &null_frame;
    03046    }
    03047
    03048    switch(ast->fdno) {
    03049    case 0:
    03050       f = ast_rtp_read(p->rtp);  /* RTP Audio */
    03051       break;
    03052    case 1:
    03053       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
    03054       break;
    03055    case 2:
    03056       f = ast_rtp_read(p->vrtp); /* RTP Video */
    03057       break;
    03058    case 3:
    03059       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
    03060       break;
    03061    default:
    03062       f = &null_frame;
    03063    }
    03064    /* Don't forward RFC2833 if we're not supposed to */
    03065    if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
    03066       return &null_frame;
    03067    if (p->owner) {
    03068       /* We already hold the channel lock */
    03069       if (f && f->frametype == AST_FRAME_VOICE) {
    03070          if (f->subclass != p->owner->nativeformats) {
    03071             if (!(f->subclass & p->jointcapability)) {
    03072                ast_log(LOG_DEBUG, "Bogus frame of format '%s' received from '%s'!\n",
    03073                   ast_getformatname(f->subclass), p->owner->name);
    03074                return &null_frame;
    03075             }
    03076             ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
    03077             p->owner->nativeformats = f->subclass;
    03078             ast_set_read_format(p->owner, p->owner->readformat);
    03079             ast_set_write_format(p->owner, p->owner->writeformat);
    03080          }
    03081          if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
    03082             f = ast_dsp_process(p->owner, p->vad, f);
    03083             if (f && (f->frametype == AST_FRAME_DTMF))
    03084                ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
    03085          }
    03086       }
    03087    }
    03088    return f;
    03089 }
    03090
    03091 /*! \brief  sip_read: Read SIP RTP from channel */
    03092 static struct ast_frame *sip_read(struct ast_channel *ast)
    03093 {
    03094    struct ast_frame *fr;
    03095    struct sip_pvt *p = ast->tech_pvt;
    03096    ast_mutex_lock(&p->lock);
    03097    fr = sip_rtp_read(ast, p);
    03098    time(&p->lastrtprx);
    03099    ast_mutex_unlock(&p->lock);
    03100    return fr;
    03101 }
    03102
    03103 /*! \brief  build_callid: Build SIP CALLID header ---*/
    03104 static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
    03105 {
    03106    int res;
    03107    int val;
    03108    int x;
    03109    char iabuf[INET_ADDRSTRLEN];
    03110    for (x=0; x<4; x++) {
    03111       val = thread_safe_rand();
    03112       res = snprintf(callid, len, "%08x", val);
    03113       len -= res;
    03114       callid += res;
    03115    }
    03116    if (!ast_strlen_zero(fromdomain))
    03117       snprintf(callid, len, "@%s", fromdomain);
    03118    else
    03119    /* It's not important that we really use our right IP here... */
    03120       snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
    03121 }
    03122
    03123 static void make_our_tag(char *tagbuf, size_t len)
    03124 {
    03125    snprintf(tagbuf, len, "as%08x", thread_safe_rand());
    03126 }
    03127
    03128 /*! \brief  sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
    03129 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method)
    03130 {
    03131    struct sip_pvt *p;
    03132
    03133    if (!(p = calloc(1, sizeof(*p))))
    03134       return NULL;
    03135
    03136    ast_mutex_init(&p->lock);
    03137
    03138    p->method = intended_method;
    03139    p->initid = -1;
    03140    p->autokillid = -1;
    03141    p->subscribed = NONE;
    03142    p->stateid = -1;
    03143    p->prefs = prefs;
    03144    if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
    03145       p->timer_t1 = 500;   /* Default SIP retransmission timer T1 (RFC 3261) */
    03146 #ifdef OSP_SUPPORT
    03147    p->osphandle = -1;
    03148    p->osptimelimit = 0;
    03149 #endif
    03150    if (sin) {
    03151       memcpy(&p->sa, sin, sizeof(p->sa));
    03152       if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
    03153          memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
    03154    } else {
    03155       memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
    03156    }
    03157
    03158    p->branch = thread_safe_rand();
    03159    make_our_tag(p->tag, sizeof(p->tag));
    03160    /* Start with 101 instead of 1 */
    03161    p->ocseq = 101;
    03162
    03163    if (sip_methods[intended_method].need_rtp) {
    03164       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
    03165       if (videosupport)
    03166          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
    03167       if (!p->rtp || (videosupport && !p->vrtp)) {
    03168          ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n", videosupport ? "and video" : "", strerror(errno));
    03169          ast_mutex_destroy(&p->lock);
    03170          if (p->chanvars) {
    03171             ast_variables_destroy(p->chanvars);
    03172             p->chanvars = NULL;
    03173          }
    03174          free(p);
    03175          return NULL;
    03176       }
    03177       ast_rtp_settos(p->rtp, tos);
    03178       if (p->vrtp)
    03179          ast_rtp_settos(p->vrtp, tos);
    03180       p->rtptimeout = global_rtptimeout;
    03181       p->rtpholdtimeout = global_rtpholdtimeout;
    03182       p->rtpkeepalive = global_rtpkeepalive;
    03183    }
    03184
    03185    if (useglobal_nat && sin) {
    03186       /* Setup NAT structure according to global settings if we have an address */
    03187       ast_copy_flags(p, &global_flags, SIP_NAT);
    03188       memcpy(&p->recv, sin, sizeof(p->recv));
    03189       if (p->rtp)
    03190          ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    03191       if (p->vrtp)
    03192          ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    03193    }
    03194
    03195    if (p->method != SIP_REGISTER)
    03196       ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
    03197    build_via(p, p->via, sizeof(p->via));
    03198    if (!callid)
    03199       build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
    03200    else
    03201       ast_copy_string(p->callid, callid, sizeof(p->callid));
    03202    ast_copy_flags(p, &global_flags, SIP_FLAGS_TO_COPY);
    03203    /* Assign default music on hold class */
    03204    strcpy(p->musicclass, global_musicclass);
    03205    p->capability = global_capability;
    03206    if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
    03207       p->noncodeccapability |= AST_RTP_DTMF;
    03208    p->jointnoncodeccapability = p->noncodeccapability;
    03209    strcpy(p->context, default_context);
    03210
    03211    /* Add to active dialog list */
    03212    ast_mutex_lock(&iflock);
    03213    p->next = iflist;
    03214    iflist = p;
    03215    ast_mutex_unlock(&iflock);
    03216    if (option_debug)
    03217       ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
    03218    return p;
    03219 }
    03220
    03221 /*! \brief  find_call: Connect incoming SIP message to current dialog or create new dialog structure */
    03222 /*               Called by handle_request, sipsock_read */
    03223 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
    03224 {
    03225    struct sip_pvt *p = NULL;
    03226    char *callid;
    03227    char *tag = "";
    03228    char totag[128];
    03229    char fromtag[128];
    03230
    03231    callid = get_header(req, "Call-ID");
    03232
    03233    if (pedanticsipchecking) {
    03234       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
    03235          we need more to identify a branch - so we have to check branch, from
    03236          and to tags to identify a call leg.
    03237          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
    03238          in sip.conf
    03239          */
    03240       if (gettag(req, "To", totag, sizeof(totag)))
    03241          ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */
    03242       gettag(req, "From", fromtag, sizeof(fromtag));
    03243
    03244       if (req->method == SIP_RESPONSE)
    03245          tag = totag;
    03246       else
    03247          tag = fromtag;
    03248
    03249
    03250       if (option_debug > 4 )
    03251          ast_log(LOG_DEBUG, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
    03252    }
    03253
    03254    ast_mutex_lock(&iflock);
    03255    p = iflist;
    03256    while(p) {  /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
    03257       int found = 0;
    03258       if (req->method == SIP_REGISTER)
    03259          found = (!strcmp(p->callid, callid));
    03260       else
    03261          found = (!strcmp(p->callid, callid) &&
    03262          (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
    03263
    03264       if (option_debug > 4)
    03265          ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
    03266
    03267       /* If we get a new request within an existing to-tag - check the to tag as well */
    03268       if (pedanticsipchecking && found  && req->method != SIP_RESPONSE) {  /* SIP Request */
    03269          if (p->tag[0] == '\0' && totag[0]) {
    03270             /* We have no to tag, but they have. Wrong dialog */
    03271             found = 0;
    03272          } else if (totag[0]) {        /* Both have tags, compare them */
    03273             if (strcmp(totag, p->tag)) {
    03274                found = 0;     /* This is not our packet */
    03275             }
    03276          }
    03277          if (!found && option_debug > 4)
    03278             ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
    03279       }
    03280
    03281
    03282       if (found) {
    03283          /* Found the call */
    03284          ast_mutex_lock(&p->lock);
    03285          ast_mutex_unlock(&iflock);
    03286          return p;
    03287       }
    03288       p = p->next;
    03289    }
    03290    ast_mutex_unlock(&iflock);
    03291
    03292    /* If this is a response and we have ignoring of out of dialog responses turned on, then drop it */
    03293    /* ...and never respond to a SIP ACK message */
    03294    if (!sip_methods[intended_method].can_create) {
    03295       /* Can't create dialog */
    03296       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK)
    03297          transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
    03298    } else if (sip_methods[intended_method].can_create == 2) {
    03299       char *response = "481 Call leg/transaction does not exist";
    03300       /* In theory, can create dialog. We don't support it */
    03301       if (intended_method == SIP_PRACK || intended_method == SIP_UNKNOWN)
    03302          response = "501 Method not implemented";
    03303       else if(intended_method == SIP_REFER)
    03304          response = "603 Declined (no dialog)";
    03305       else if(intended_method == SIP_NOTIFY)
    03306          response = "489 Bad event";
    03307
    03308       transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
    03309
    03310    } else {
    03311       p = sip_alloc(callid, sin, 1, intended_method);
    03312       if (p)
    03313          ast_mutex_lock(&p->lock);
    03314       else {
    03315          /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
    03316             getting a dialog from sip_alloc.
    03317
    03318             Without a dialog we can't retransmit and handle ACKs and all that, but at least
    03319             send an error message.
    03320
    03321             Sorry, we apologize for the inconvienience
    03322          */
    03323          transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
    03324          if (option_debug > 3)
    03325             ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
    03326       }
    03327    }
    03328
    03329    return p;
    03330 }
    03331
    03332 /*! \brief  sip_register: Parse register=> line in sip.conf and add to registry */
    03333 static int sip_register(char *value, int lineno)
    03334 {
    03335    struct sip_registry *reg;
    03336    char copy[256];
    03337    char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
    03338    char *porta=NULL;
    03339    char *contact=NULL;
    03340    char *stringp=NULL;
    03341
    03342    if (!value)
    03343       return -1;
    03344    ast_copy_string(copy, value, sizeof(copy));
    03345    stringp=copy;
    03346    username = stringp;
    03347    hostname = strrchr(stringp, '@');
    03348    if (hostname) {
    03349       *hostname = '\0';
    03350       hostname++;
    03351    }
    03352    if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
    03353       ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
    03354       return -1;
    03355    }
    03356    stringp=username;
    03357    username = strsep(&stringp, ":");
    03358    if (username) {
    03359       secret = strsep(&stringp, ":");
    03360       if (secret)
    03361          authuser = strsep(&stringp, ":");
    03362    }
    03363    stringp = hostname;
    03364    hostname = strsep(&stringp, "/");
    03365    if (hostname)
    03366       contact = strsep(&stringp, "/");
    03367    if (ast_strlen_zero(contact))
    03368       contact = "s";
    03369    stringp=hostname;
    03370    hostname = strsep(&stringp, ":");
    03371    porta = strsep(&stringp, ":");
    03372
    03373    if (porta && !atoi(porta)) {
    03374       ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
    03375       return -1;
    03376    }
    03377    reg = malloc(sizeof(struct sip_registry));
    03378    if (!reg) {
    03379       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
    03380       return -1;
    03381    }
    03382    memset(reg, 0, sizeof(struct sip_registry));
    03383    regobjs++;
    03384    ASTOBJ_INIT(reg);
    03385    ast_copy_string(reg->contact, contact, sizeof(reg->contact));
    03386    if (username)
    03387       ast_copy_string(reg->username, username, sizeof(reg->username));
    03388    if (hostname)
    03389       ast_copy_string(reg->hostname, hostname, sizeof(reg->hostname));
    03390    if (authuser)
    03391       ast_copy_string(reg->authuser, authuser, sizeof(reg->authuser));
    03392    if (secret)
    03393       ast_copy_string(reg->secret, secret, sizeof(reg->secret));
    03394    reg->expire = -1;
    03395    reg->timeout =  -1;
    03396    reg->refresh = default_expiry;
    03397    reg->portno = porta ? atoi(porta) : 0;
    03398    reg->callid_valid = 0;
    03399    reg->ocseq = 101;
    03400    ASTOBJ_CONTAINER_LINK(&regl, reg);
    03401    ASTOBJ_UNREF(reg,sip_registry_destroy);
    03402    return 0;
    03403 }
    03404
    03405 /*! \brief  lws2sws: Parse multiline SIP headers into one header */
    03406 /* This is enabled if pedanticsipchecking is enabled */
    03407 static int lws2sws(char *msgbuf, int len)
    03408 {
    03409    int h = 0, t = 0;
    03410    int lws = 0;
    03411
    03412    for (; h < len;) {
    03413       /* Eliminate all CRs */
    03414       if (msgbuf[h] == '\r') {
    03415          h++;
    03416          continue;
    03417       }
    03418       /* Check for end-of-line */
    03419       if (msgbuf[h] == '\n') {
    03420          /* Check for end-of-message */
    03421          if (h + 1 == len)
    03422             break;
    03423          /* Check for a continuation line */
    03424          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
    03425             /* Merge continuation line */
    03426             h++;
    03427             continue;
    03428          }
    03429          /* Propagate LF and start new line */
    03430          msgbuf[t++] = msgbuf[h++];
    03431          lws = 0;
    03432          continue;
    03433       }
    03434       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
    03435          if (lws) {
    03436             h++;
    03437             continue;
    03438          }
    03439          msgbuf[t++] = msgbuf[h++];
    03440          lws = 1;
    03441          continue;
    03442       }
    03443       msgbuf[t++] = msgbuf[h++];
    03444       if (lws)
    03445          lws = 0;
    03446    }
    03447    msgbuf[t] = '\0';
    03448    return t;
    03449 }
    03450
    03451 /*! \brief  parse_request: Parse a SIP message ----*/
    03452 static void parse_request(struct sip_request *req)
    03453 {
    03454    /* Divide fields by NULL's */
    03455    char *c;
    03456    int f = 0;
    03457
    03458    c = req->data;
    03459
    03460    /* First header starts immediately */
    03461    req->header[f] = c;
    03462    while(*c) {
    03463       if (*c == '\n') {
    03464          /* We've got a new header */
    03465          *c = 0;
    03466
    03467          if (sipdebug && option_debug > 3)
    03468             ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
    03469          if (ast_strlen_zero(req->header[f])) {
    03470             /* Line by itself means we're now in content */
    03471             c++;
    03472             break;
    03473          }
    03474          if (f >= SIP_MAX_HEADERS - 1) {
    03475             ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
    03476          } else
    03477             f++;
    03478          req->header[f] = c + 1;
    03479       } else if (*c == '\r') {
    03480          /* Ignore but eliminate \r's */
    03481          *c = 0;
    03482       }
    03483       c++;
    03484    }
    03485    /* Check for last header */
    03486    if (!ast_strlen_zero(req->header[f])) {
    03487       if (sipdebug && option_debug > 3)
    03488          ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
    03489       f++;
    03490    }
    03491    req->headers = f;
    03492    /* Now we process any mime content */
    03493    f = 0;
    03494    req->line[f] = c;
    03495    while(*c) {
    03496       if (*c == '\n') {
    03497          /* We've got a new line */
    03498          *c = 0;
    03499          if (sipdebug && option_debug > 3)
    03500             ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
    03501          if (f >= SIP_MAX_LINES - 1) {
    03502             ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
    03503          } else
    03504             f++;
    03505          req->line[f] = c + 1;
    03506       } else if (*c == '\r') {
    03507          /* Ignore and eliminate \r's */
    03508          *c = 0;
    03509       }
    03510       c++;
    03511    }
    03512    /* Check for last line */
    03513    if (!ast_strlen_zero(req->line[f]))
    03514       f++;
    03515    req->lines = f;
    03516    if (*c)
    03517       ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
    03518    /* Split up the first line parts */
    03519    determine_firstline_parts(req);
    03520 }
    03521
    03522 /*!
    03523   \brief Determine whether a SIP message contains an SDP in its body
    03524   \param req the SIP request to process
    03525   \return 1 if SDP found, 0 if not found
    03526
    03527   Also updates req->sdp_start and req->sdp_end to indicate where the SDP
    03528   lives in the message body.
    03529 */
    03530 static int find_sdp(struct sip_request *req)
    03531 {
    03532    char *content_type;
    03533    char *search;
    03534    char *boundary;
    03535    unsigned int x;
    03536
    03537    content_type = get_header(req, "Content-Type");
    03538
    03539    /* if the body contains only SDP, this is easy */
    03540    if (!strcasecmp(content_type, "application/sdp")) {
    03541       req->sdp_start = 0;
    03542       req->sdp_end = req->lines;
    03543       return 1;
    03544    }
    03545
    03546    /* if it's not multipart/mixed, there cannot be an SDP */
    03547    if (strncasecmp(content_type, "multipart/mixed", 15))
    03548       return 0;
    03549
    03550    /* if there is no boundary marker, it's invalid */
    03551    if (!(search = strcasestr(content_type, ";boundary=")))
    03552       return 0;
    03553
    03554    search += 10;
    03555
    03556    if (ast_strlen_zero(search))
    03557       return 0;
    03558
    03559    /* make a duplicate of the string, with two extra characters
    03560       at the beginning */
    03561    boundary = ast_strdupa(search - 2);
    03562    boundary[0] = boundary[1] = '-';
    03563
    03564    /* search for the boundary marker, but stop when there are not enough
    03565       lines left for it, the Content-Type header and at least one line of
    03566       body */
    03567    for (x = 0; x < (req->lines - 2); x++) {
    03568       if (!strncasecmp(req->line[x], boundary, strlen(boundary)) &&
    03569           !strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) {
    03570          x += 2;
    03571          req->sdp_start = x;
    03572
    03573          /* search for the end of the body part */
    03574          for ( ; x < req->lines; x++) {
    03575             if (!strncasecmp(req->line[x], boundary, strlen(boundary)))
    03576                break;
    03577          }
    03578          req->sdp_end = x;
    03579          return 1;
    03580       }
    03581    }
    03582
    03583    return 0;
    03584 }
    03585
    03586 /*! \brief  process_sdp: Process SIP SDP and activate RTP channels---*/
    03587 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
    03588 {
    03589    char *m;
    03590    char *c;
    03591    char *a;
    03592    char host[258];
    03593    char iabuf[INET_ADDRSTRLEN];
    03594    int len = -1;
    03595    int portno = -1;
    03596    int vportno = -1;
    03597    int peercapability, peernoncodeccapability;
    03598    int vpeercapability=0, vpeernoncodeccapability=0;
    03599    struct sockaddr_in sin;
    03600    char *codecs;
    03601    struct hostent *hp;
    03602    struct ast_hostent ahp;
    03603    int codec;
    03604    int destiterator = 0;
    03605    int iterator;
    03606    int sendonly = 0;
    03607    int x,y;
    03608    int debug=sip_debug_test_pvt(p);
    03609    struct ast_channel *bridgepeer = NULL;
    03610
    03611    if (!p->rtp) {
    03612       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
    03613       return -1;
    03614    }
    03615
    03616    /* Update our last rtprx when we receive an SDP, too */
    03617    time(&p->lastrtprx);
    03618    time(&p->lastrtptx);
    03619
    03620    m = get_sdp(req, "m");
    03621    sdpLineNum_iterator_init(&destiterator, req);
    03622    c = get_sdp_iterate(&destiterator, req, "c");
    03623    if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
    03624       ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
    03625       return -1;
    03626    }
    03627    if (sscanf(c, "IN IP4 %256s", host) != 1) {
    03628       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
    03629       return -1;
    03630    }
    03631    /* XXX This could block for a long time, and block the main thread! XXX */
    03632    hp = ast_gethostbyname(host, &ahp);
    03633    if (!hp) {
    03634       ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
    03635       return -1;
    03636    }
    03637    sdpLineNum_iterator_init(&iterator, req);
    03638    ast_set_flag(p, SIP_NOVIDEO);
    03639    while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
    03640       int found = 0;
    03641       if ((sscanf(m, "audio %30d/%30d RTP/AVP %n", &x, &y, &len) == 2) ||
    03642           (sscanf(m, "audio %30d RTP/AVP %n", &x, &len) == 1)) {
    03643          found = 1;
    03644          portno = x;
    03645          /* Scan through the RTP payload types specified in a "m=" line: */
    03646          ast_rtp_pt_clear(p->rtp);
    03647          codecs = m + len;
    03648          while(!ast_strlen_zero(codecs)) {
    03649             if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
    03650                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
    03651                return -1;
    03652             }
    03653             if (debug)
    03654                ast_verbose("Found RTP audio format %d\n", codec);
    03655             ast_rtp_set_m_type(p->rtp, codec);
    03656             codecs = ast_skip_blanks(codecs + len);
    03657          }
    03658       }
    03659       if (p->vrtp)
    03660          ast_rtp_pt_clear(p->vrtp);  /* Must be cleared in case no m=video line exists */
    03661
    03662       if (p->vrtp && (sscanf(m, "video %30d RTP/AVP %n", &x, &len) == 1)) {
    03663          found = 1;
    03664          ast_clear_flag(p, SIP_NOVIDEO);
    03665          vportno = x;
    03666          /* Scan through the RTP payload types specified in a "m=" line: */
    03667          codecs = m + len;
    03668          while(!ast_strlen_zero(codecs)) {
    03669             if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
    03670                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
    03671                return -1;
    03672             }
    03673             if (debug)
    03674                ast_verbose("Found RTP video format %d\n", codec);
    03675             ast_rtp_set_m_type(p->vrtp, codec);
    03676             codecs = ast_skip_blanks(codecs + len);
    03677          }
    03678       }
    03679       if (!found )
    03680          ast_log(LOG_WARNING, "Unknown SDP media type in offer: %s\n", m);
    03681    }
    03682    if (portno == -1 && vportno == -1) {
    03683       /* No acceptable offer found in SDP */
    03684       return -2;
    03685    }
    03686    /* Check for Media-description-level-address for audio */
    03687    c = get_sdp_iterate(&destiterator, req, "c");
    03688    if (!ast_strlen_zero(c)) {
    03689       if (sscanf(c, "IN IP4 %256s", host) != 1) {
    03690          ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
    03691       } else {
    03692          /* XXX This could block for a long time, and block the main thread! XXX */
    03693          hp = ast_gethostbyname(host, &ahp);
    03694          if (!hp) {
    03695             ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
    03696             return -1;
    03697          }
    03698       }
    03699    }
    03700    /* RTP addresses and ports for audio and video */
    03701    sin.sin_family = AF_INET;
    03702    memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
    03703
    03704    /* Setup audio port number */
    03705    sin.sin_port = htons(portno);
    03706    if (p->rtp && sin.sin_port) {
    03707       ast_rtp_set_peer(p->rtp, &sin);
    03708       if (debug) {
    03709          ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
    03710          ast_log(LOG_DEBUG,"Peer audio RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
    03711       }
    03712    }
    03713    /* Check for Media-description-level-address for video */
    03714    c = get_sdp_iterate(&destiterator, req, "c");
    03715    if (!ast_strlen_zero(c)) {
    03716       if (sscanf(c, "IN IP4 %256s", host) != 1) {
    03717          ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
    03718       } else {
    03719          /* XXX This could block for a long time, and block the main thread! XXX */
    03720          hp = ast_gethostbyname(host, &ahp);
    03721          if (!hp) {
    03722             ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
    03723             return -1;
    03724          }
    03725       }
    03726    }
    03727    /* Setup video port number */
    03728    sin.sin_port = htons(vportno);
    03729    if (p->vrtp && sin.sin_port) {
    03730       ast_rtp_set_peer(p->vrtp, &sin);
    03731       if (debug) {
    03732          ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
    03733          ast_log(LOG_DEBUG,"Peer video RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
    03734       }
    03735    }
    03736
    03737    /* Next, scan through each "a=rtpmap:" line, noting each
    03738     * specified RTP payload type (with corresponding MIME subtype):
    03739     */
    03740    sdpLineNum_iterator_init(&iterator, req);
    03741    while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
    03742       char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
    03743       if (!strcasecmp(a, "sendonly") || !strcasecmp(a, "inactive")) {
    03744          sendonly = 1;
    03745          continue;
    03746       }
    03747       if (!strcasecmp(a, "sendrecv")) {
    03748          sendonly = 0;
    03749       }
    03750       if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) != 2) continue;
    03751       if (debug)
    03752          ast_verbose("Found description format %s\n", mimeSubtype);
    03753       /* Note: should really look at the 'freq' and '#chans' params too */
    03754       ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
    03755       if (p->vrtp)
    03756          ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
    03757    }
    03758
    03759    /* Now gather all of the codecs that were asked for: */
    03760    ast_rtp_get_current_formats(p->rtp,
    03761             &peercapability, &peernoncodeccapability);
    03762    if (p->vrtp)
    03763       ast_rtp_get_current_formats(p->vrtp,
    03764             &vpeercapability, &vpeernoncodeccapability);
    03765    p->jointcapability = p->capability & (peercapability | vpeercapability);
    03766    p->peercapability = (peercapability | vpeercapability);
    03767    p->jointnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
    03768
    03769    if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO) {
    03770       ast_clear_flag(p, SIP_DTMF);
    03771       if (p->jointnoncodeccapability & AST_RTP_DTMF) {
    03772          /* XXX Would it be reasonable to drop the DSP at this point? XXX */
    03773          ast_set_flag(p, SIP_DTMF_RFC2833);
    03774       } else {
    03775          ast_set_flag(p, SIP_DTMF_INBAND);
    03776       }
    03777    }
    03778
    03779    if (debug) {
    03780       /* shame on whoever coded this.... */
    03781       const unsigned slen=512;
    03782       char s1[slen], s2[slen], s3[slen], s4[slen];
    03783
    03784       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
    03785          ast_getformatname_multiple(s1, slen, p->capability),
    03786          ast_getformatname_multiple(s2, slen, peercapability),
    03787          ast_getformatname_multiple(s3, slen, vpeercapability),
    03788          ast_getformatname_multiple(s4, slen, p->jointcapability));
    03789
    03790       ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
    03791          ast_rtp_lookup_mime_multiple(s1, slen, p->noncodeccapability, 0),
    03792          ast_rtp_lookup_mime_multiple(s2, slen, peernoncodeccapability, 0),
    03793          ast_rtp_lookup_mime_multiple(s3, slen, p->jointnoncodeccapability, 0));
    03794    }
    03795    if (!p->jointcapability) {
    03796       ast_log(LOG_NOTICE, "No compatible codecs!\n");
    03797       return -1;
    03798    }
    03799
    03800    if (!p->owner)    /* There's no open channel owning us */
    03801       return 0;
    03802
    03803    if (!(p->owner->nativeformats & p->jointcapability)) {
    03804       const unsigned slen=512;
    03805       char s1[slen], s2[slen];
    03806       ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n",
    03807             ast_getformatname_multiple(s1, slen, p->jointcapability),
    03808             ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
    03809       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1);
    03810       ast_set_read_format(p->owner, p->owner->readformat);
    03811       ast_set_write_format(p->owner, p->owner->writeformat);
    03812    }
    03813    if ((bridgepeer=ast_bridged_channel(p->owner))) {
    03814       /* We have a bridge */
    03815       /* Turn on/off music on hold if we are holding/unholding */
    03816       struct ast_frame af = { AST_FRAME_NULL, };
    03817       if (sin.sin_addr.s_addr && !sendonly) {
    03818          ast_moh_stop(bridgepeer);
    03819
    03820          /* Activate a re-invite */
    03821          ast_queue_frame(p->owner, &af);
    03822       } else {
    03823          /* No address for RTP, we're on hold */
    03824
    03825          ast_moh_start(bridgepeer, NULL);
    03826          if (sendonly)
    03827             ast_rtp_stop(p->rtp);
    03828          /* Activate a re-invite */
    03829          ast_queue_frame(p->owner, &af);
    03830       }
    03831    }
    03832
    03833    /* Manager Hold and Unhold events must be generated, if necessary */
    03834    if (sin.sin_addr.s_addr && !sendonly) {
    03835            append_history(p, "Unhold", req->data);
    03836
    03837       if (callevents && ast_test_flag(p, SIP_CALL_ONHOLD)) {
    03838          manager_event(EVENT_FLAG_CALL, "Unhold",
    03839             "Channel: %s\r\n"
    03840             "Uniqueid: %s\r\n",
    03841             p->owner->name,
    03842             p->owner->uniqueid);
    03843
    03844             }
    03845       ast_clear_flag(p, SIP_CALL_ONHOLD);
    03846    } else {
    03847       /* No address for RTP, we're on hold */
    03848            append_history(p, "Hold", req->data);
    03849
    03850            if (callevents && !ast_test_flag(p, SIP_CALL_ONHOLD)) {
    03851          manager_event(EVENT_FLAG_CALL, "Hold",
    03852             "Channel: %s\r\n"
    03853                   "Uniqueid: %s\r\n",
    03854             p->owner->name,
    03855             p->owner->uniqueid);
    03856       }
    03857       ast_set_flag(p, SIP_CALL_ONHOLD);
    03858    }
    03859
    03860    return 0;
    03861 }
    03862
    03863 /*! \brief  add_header: Add header to SIP message */
    03864 static int add_header(struct sip_request *req, const char *var, const char *value)
    03865 {
    03866    int x = 0;
    03867
    03868    if (req->headers == SIP_MAX_HEADERS) {
    03869       ast_log(LOG_WARNING, "Out of SIP header space\n");
    03870       return -1;
    03871    }
    03872
    03873    if (req->lines) {
    03874       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
    03875       return -1;
    03876    }
    03877
    03878    if (req->len >= sizeof(req->data) - 4) {
    03879       ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
    03880       return -1;
    03881    }
    03882
    03883    req->header[req->headers] = req->data + req->len;
    03884
    03885    if (compactheaders) {
    03886       for (x = 0; x < (sizeof(aliases) / sizeof(aliases[0])); x++)
    03887          if (!strcasecmp(aliases[x].fullname, var))
    03888             var = aliases[x].shortname;
    03889    }
    03890
    03891    snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
    03892    req->len += strlen(req->header[req->headers]);
    03893    req->headers++;
    03894
    03895    return 0;
    03896 }
    03897
    03898 /*! \brief  add_header_contentLen: Add 'Content-Length' header to SIP message */
    03899 static int add_header_contentLength(struct sip_request *req, int len)
    03900 {
    03901    char clen[10];
    03902
    03903    snprintf(clen, sizeof(clen), "%d", len);
    03904    return add_header(req, "Content-Length", clen);
    03905 }
    03906
    03907 /*! \brief  add_blank_header: Add blank header to SIP message */
    03908 static int add_blank_header(struct sip_request *req)
    03909 {
    03910    if (req->headers == SIP_MAX_HEADERS)  {
    03911       ast_log(LOG_WARNING, "Out of SIP header space\n");
    03912       return -1;
    03913    }
    03914    if (req->lines) {
    03915       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
    03916       return -1;
    03917    }
    03918    if (req->len >= sizeof(req->data) - 4) {
    03919       ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
    03920       return -1;
    03921    }
    03922    req->header[req->headers] = req->data + req->len;
    03923    snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
    03924    req->len += strlen(req->header[req->headers]);
    03925    req->headers++;
    03926    return 0;
    03927 }
    03928
    03929 /*! \brief  add_line: Add content (not header) to SIP message */
    03930 static int add_line(struct sip_request *req, const char *line)
    03931 {
    03932    if (req->lines == SIP_MAX_LINES)  {
    03933       ast_log(LOG_WARNING, "Out of SIP line space\n");
    03934       return -1;
    03935    }
    03936    if (!req->lines) {
    03937       /* Add extra empty return */
    03938       snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
    03939       req->len += strlen(req->data + req->len);
    03940    }
    03941    if (req->len >= sizeof(req->data) - 4) {
    03942       ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
    03943       return -1;
    03944    }
    03945    req->line[req->lines] = req->data + req->len;
    03946    snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
    03947    req->len += strlen(req->line[req->lines]);
    03948    req->lines++;
    03949    return 0;
    03950 }
    03951
    03952 /*! \brief  copy_header: Copy one header field from one request to another */
    03953 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
    03954 {
    03955    char *tmp;
    03956    tmp = get_header(orig, field);
    03957    if (!ast_strlen_zero(tmp)) {
    03958       /* Add what we're responding to */
    03959       return add_header(req, field, tmp);
    03960    }
    03961    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
    03962    return -1;
    03963 }
    03964
    03965 /*! \brief  copy_all_header: Copy all headers from one request to another ---*/
    03966 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
    03967 {
    03968    char *tmp;
    03969    int start = 0;
    03970    int copied = 0;
    03971    for (;;) {
    03972       tmp = __get_header(orig, field, &start);
    03973       if (!ast_strlen_zero(tmp)) {
    03974          /* Add what we're responding to */
    03975          add_header(req, field, tmp);
    03976          copied++;
    03977       } else
    03978          break;
    03979    }
    03980    return copied ? 0 : -1;
    03981 }
    03982
    03983 /*! \brief  copy_via_headers: Copy SIP VIA Headers from the request to the response ---*/
    03984 /* If the client indicates that it wishes to know the port we received from,
    03985    it adds ;rport without an argument to the topmost via header. We need to
    03986    add the port number (from our point of view) to that parameter.
    03987    We always add ;received=<ip address> to the topmost via header.
    03988    Received: RFC 3261, rport RFC 3581 */
    03989 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
    03990 {
    03991    char tmp[256], *oh, *end;
    03992    int start = 0;
    03993    int copied = 0;
    03994    char iabuf[INET_ADDRSTRLEN];
    03995
    03996    for (;;) {
    03997       oh = __get_header(orig, field, &start);
    03998       if (!ast_strlen_zero(oh)) {
    03999          if (!copied) { /* Only check for empty rport in topmost via header */
    04000             char *rport;
    04001             char new[256];
    04002
    04003             /* Find ;rport;  (empty request) */
    04004             rport = strstr(oh, ";rport");
    04005             if (rport && *(rport+6) == '=')
    04006                rport = NULL;     /* We already have a parameter to rport */
    04007
    04008             if (rport && ((ast_test_flag(p, SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(p, SIP_NAT) == SIP_NAT_RFC3581))) {
    04009                /* We need to add received port - rport */
    04010                ast_copy_string(tmp, oh, sizeof(tmp));
    04011
    04012                rport = strstr(tmp, ";rport");
    04013
    04014                if (rport) {
    04015                   end = strchr(rport + 1, ';');
    04016                   if (end)
    04017                      memmove(rport, end, strlen(end) + 1);
    04018                   else
    04019                      *rport = '\0';
    04020                }
    04021
    04022                /* Add rport to first VIA header if requested */
    04023                /* Whoo hoo!  Now we can indicate port address translation too!  Just
    04024                      another RFC (RFC3581). I'll leave the original comments in for
    04025                      posterity.  */
    04026                snprintf(new, sizeof(new), "%s;received=%s;rport=%d", tmp, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
    04027             } else {
    04028                /* We should *always* add a received to the topmost via */
    04029                snprintf(new, sizeof(new), "%s;received=%s", oh, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
    04030             }
    04031             add_header(req, field, new);
    04032          } else {
    04033             /* Add the following via headers untouched */
    04034             add_header(req, field, oh);
    04035          }
    04036          copied++;
    04037       } else
    04038          break;
    04039    }
    04040    if (!copied) {
    04041       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
    04042       return -1;
    04043    }
    04044    return 0;
    04045 }
    04046
    04047 /*! \brief  add_route: Add route header into request per learned route ---*/
    04048 static void add_route(struct sip_request *req, struct sip_route *route)
    04049 {
    04050    char r[BUFSIZ*2], *p;
    04051    int n, rem = sizeof(r);
    04052
    04053    if (!route) return;
    04054
    04055    p = r;
    04056    while (route) {
    04057       n = strlen(route->hop);
    04058       if ((n+3)>rem) break;
    04059       if (p != r) {
    04060          *p++ = ',';
    04061          --rem;
    04062       }
    04063       *p++ = '<';
    04064       ast_copy_string(p, route->hop, rem);  p += n;
    04065       *p++ = '>';
    04066       rem -= (n+2);
    04067       route = route->next;
    04068    }
    04069    *p = '\0';
    04070    add_header(req, "Route", r);
    04071 }
    04072
    04073 /*! \brief  set_destination: Set destination from SIP URI ---*/
    04074 static void set_destination(struct sip_pvt *p, char *uri)
    04075 {
    04076    char *h, *maddr, hostname[256];
    04077    char iabuf[INET_ADDRSTRLEN];
    04078    int port, hn;
    04079    struct hostent *hp;
    04080    struct ast_hostent ahp;
    04081    int debug=sip_debug_test_pvt(p);
    04082
    04083    /* Parse uri to h (host) and port - uri is already just the part inside the <> */
    04084    /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
    04085
    04086    if (debug)
    04087       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
    04088
    04089    /* Find and parse hostname */
    04090    h = strchr(uri, '@');
    04091    if (h)
    04092       ++h;
    04093    else {
    04094       h = uri;
    04095       if (strncasecmp(h, "sip:", 4) == 0)
    04096          h += 4;
    04097       else if (strncasecmp(h, "sips:", 5) == 0)
    04098          h += 5;
    04099    }
    04100    hn = strcspn(h, ":;>") + 1;
    04101    if (hn > sizeof(hostname))
    04102       hn = sizeof(hostname);
    04103    ast_copy_string(hostname, h, hn);
    04104    h += hn - 1;
    04105
    04106    /* Is "port" present? if not default to DEFAULT_SIP_PORT */
    04107    if (*h == ':') {
    04108       /* Parse port */
    04109       ++h;
    04110       port = strtol(h, &h, 10);
    04111    }
    04112    else
    04113       port = DEFAULT_SIP_PORT;
    04114
    04115    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
    04116    maddr = strstr(h, "maddr=");
    04117    if (maddr) {
    04118       maddr += 6;
    04119       hn = strspn(maddr, "0123456789.") + 1;
    04120       if (hn > sizeof(hostname)) hn = sizeof(hostname);
    04121       ast_copy_string(hostname, maddr, hn);
    04122    }
    04123
    04124    hp = ast_gethostbyname(hostname, &ahp);
    04125    if (hp == NULL)  {
    04126       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
    04127       return;
    04128    }
    04129    p->sa.sin_family = AF_INET;
    04130    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
    04131    p->sa.sin_port = htons(port);
    04132    if (debug)
    04133       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), port);
    04134 }
    04135
    04136 /*! \brief  init_resp: Initialize SIP response, based on SIP request ---*/
    04137 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
    04138 {
    04139    /* Initialize a response */
    04140    if (req->headers || req->len) {
    04141       ast_log(LOG_WARNING, "Request already initialized?!?\n");
    04142       return -1;
    04143    }
    04144    req->method = SIP_RESPONSE;
    04145    req->header[req->headers] = req->data + req->len;
    04146    snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
    04147    req->len += strlen(req->header[req->headers]);
    04148    req->headers++;
    04149    return 0;
    04150 }
    04151
    04152 /*! \brief  init_req: Initialize SIP request ---*/
    04153 static int init_req(struct sip_request *req, int sipmethod, char *recip)
    04154 {
    04155    /* Initialize a response */
    04156    if (req->headers || req->len) {
    04157       ast_log(LOG_WARNING, "Request already initialized?!?\n");
    04158       return -1;
    04159    }
    04160    req->header[req->headers] = req->data + req->len;
    04161    snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
    04162    req->len += strlen(req->header[req->headers]);
    04163    req->headers++;
    04164    req->method = sipmethod;
    04165    return 0;
    04166 }
    04167
    04168
    04169 /*! \brief  respprep: Prepare SIP response packet ---*/
    04170 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
    04171 {
    04172    char newto[256], *ot;
    04173
    04174    memset(resp, 0, sizeof(*resp));
    04175    init_resp(resp, msg, req);
    04176    copy_via_headers(p, resp, req, "Via");
    04177    if (msg[0] == '2')
    04178       copy_all_header(resp, req, "Record-Route");
    04179    copy_header(resp, req, "From");
    04180    ot = get_header(req, "To");
    04181    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
    04182       /* Add the proper tag if we don't have it already.  If they have specified
    04183          their tag, use it.  Otherwise, use our own tag */
    04184       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(p, SIP_OUTGOING))
    04185          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
    04186       else if (p->tag && !ast_test_flag(p, SIP_OUTGOING))
    04187          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
    04188       else {
    04189          ast_copy_string(newto, ot, sizeof(newto));
    04190          newto[sizeof(newto) - 1] = '\0';
    04191       }
    04192       ot = newto;
    04193    }
    04194    add_header(resp, "To", ot);
    04195    copy_header(resp, req, "Call-ID");
    04196    copy_header(resp, req, "CSeq");
    04197    if (!ast_strlen_zero(default_useragent))
    04198       add_header(resp, "User-Agent", default_useragent);
    04199    add_header(resp, "Allow", ALLOWED_METHODS);
    04200    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
    04201       /* For registration responses, we also need expiry and
    04202          contact info */
    04203       char tmp[256];
    04204
    04205       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
    04206       add_header(resp, "Expires", tmp);
    04207       if (p->expiry) {  /* Only add contact if we have an expiry time */
    04208          char contact[SIP_LEN_CONTACT];
    04209          snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
    04210          add_header(resp, "Contact", contact);  /* Not when we unregister */
    04211       }
    04212    } else if (msg[0] != '4' && p->our_contact[0]) {
    04213       add_header(resp, "Contact", p->our_contact);
    04214    }
    04215    return 0;
    04216 }
    04217
    04218 /*! \brief  reqprep: Initialize a SIP request response packet ---*/
    04219 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
    04220 {
    04221    struct sip_request *orig = &p->initreq;
    04222    char stripped[80];
    04223    char tmp[80];
    04224    char newto[256];
    04225    char *c, *n;
    04226    char *ot, *of;
    04227    int is_strict = 0;   /* Strict routing flag */
    04228
    04229    memset(req, 0, sizeof(struct sip_request));
    04230
    04231    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
    04232
    04233    if (!seqno) {
    04234       p->ocseq++;
    04235       seqno = p->ocseq;
    04236    }
    04237
    04238    if (newbranch) {
    04239       p->branch ^= thread_safe_rand();
    04240       build_via(p, p->via, sizeof(p->via));
    04241    }
    04242
    04243    /* Check for strict or loose router */
    04244    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL)
    04245       is_strict = 1;
    04246
    04247    if (sipmethod == SIP_CANCEL) {
    04248       c = p->initreq.rlPart2; /* Use original URI */
    04249    } else if (sipmethod == SIP_ACK) {
    04250       /* Use URI from Contact: in 200 OK (if INVITE)
    04251       (we only have the contacturi on INVITEs) */
    04252       if (!ast_strlen_zero(p->okcontacturi))
    04253          c = is_strict ? p->route->hop : p->okcontacturi;
    04254       else
    04255          c = p->initreq.rlPart2;
    04256    } else if (!ast_strlen_zero(p->okcontacturi)) {
    04257          c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
    04258    } else if (!ast_strlen_zero(p->uri)) {
    04259       c = p->uri;
    04260    } else {
    04261       /* We have no URI, use To: or From:  header as URI (depending on direction) */
    04262       c = get_header(orig, (ast_test_flag(p, SIP_OUTGOING)) ? "To" : "From");
    04263       ast_copy_string(stripped, c, sizeof(stripped));
    04264       c = get_in_brackets(stripped);
    04265       n = strchr(c, ';');
    04266       if (n)
    04267          *n = '\0';
    04268    }
    04269    init_req(req, sipmethod, c);
    04270
    04271    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
    04272
    04273    add_header(req, "Via", p->via);
    04274    if (p->route) {
    04275       set_destination(p, p->route->hop);
    04276       if (is_strict)
    04277          add_route(req, p->route->next);
    04278       else
    04279          add_route(req, p->route);
    04280    }
    04281
    04282    ot = get_header(orig, "To");
    04283    of = get_header(orig, "From");
    04284
    04285    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
    04286       as our original request, including tag (or presumably lack thereof) */
    04287    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
    04288       /* Add the proper tag if we don't have it already.  If they have specified
    04289          their tag, use it.  Otherwise, use our own tag */
    04290       if (ast_test_flag(p, SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
    04291          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
    04292       else if (!ast_test_flag(p, SIP_OUTGOING))
    04293          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
    04294       else
    04295          snprintf(newto, sizeof(newto), "%s", ot);
    04296       ot = newto;
    04297    }
    04298
    04299    if (ast_test_flag(p, SIP_OUTGOING)) {
    04300       add_header(req, "From", of);
    04301       add_header(req, "To", ot);
    04302    } else {
    04303       add_header(req, "From", ot);
    04304       add_header(req, "To", of);
    04305    }
    04306    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
    04307       add_header(req, "Contact", p->our_contact);
    04308    copy_header(req, orig, "Call-ID");
    04309    add_header(req, "CSeq", tmp);
    04310
    04311    if (!ast_strlen_zero(default_useragent))
    04312       add_header(req, "User-Agent", default_useragent);
    04313    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
    04314
    04315    if (p->rpid)
    04316       add_header(req, "Remote-Party-ID", p->rpid);
    04317
    04318    return 0;
    04319 }
    04320
    04321 /*! \brief  __transmit_response: Base transmit response function */
    04322 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
    04323 {
    04324    struct sip_request resp;
    04325    int seqno = 0;
    04326
    04327    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
    04328       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
    04329       return -1;
    04330    }
    04331    respprep(&resp, p, msg, req);
    04332    add_header_contentLength(&resp, 0);
    04333    /* If we are cancelling an incoming invite for some reason, add information
    04334       about the reason why we are doing this in clear text */
    04335    if (msg[0] != '1' && p->owner && p->owner->hangupcause) {
    04336       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
    04337    }
    04338    add_blank_header(&resp);
    04339    return send_response(p, &resp, reliable, seqno);
    04340 }
    04341
    04342 /*! \brief  transmit_response_using_temp: Transmit response, no retransmits, using temporary pvt */
    04343 static int transmit_response_using_temp(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, struct sip_request *req, char *msg)
    04344 {
    04345    struct sip_pvt *p = alloca(sizeof(*p));
    04346    struct sip_history *hist = NULL;
    04347
    04348    memset(p, 0, sizeof(*p));
    04349
    04350    p->method = intended_method;
    04351    if (sin) {
    04352       p->sa = *sin;
    04353       if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
    04354          p->ourip = __ourip;
    04355    } else
    04356       p->ourip = __ourip;
    04357    p->branch = thread_safe_rand();
    04358    make_our_tag(p->tag, sizeof(p->tag));
    04359    p->ocseq = 101;
    04360
    04361    if (useglobal_nat && sin) {
    04362       ast_copy_flags(p, &global_flags, SIP_NAT);
    04363       memcpy(&p->recv, sin, sizeof(p->recv));
    04364    }
    04365
    04366    ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
    04367    build_via(p, p->via, sizeof(p->via));
    04368    ast_copy_string(p->callid, callid, sizeof(p->callid));
    04369
    04370    __transmit_response(p, msg, req, 0);
    04371
    04372    while ((hist = p->history)) {
    04373       p->history = p->history->next;
    04374       free(hist);
    04375    }
    04376
    04377    return 0;
    04378 }
    04379
    04380 /*! \brief  transmit_response: Transmit response, no retransmits */
    04381 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
    04382 {
    04383    return __transmit_response(p, msg, req, 0);
    04384 }
    04385
    04386 /*! \brief  transmit_response_with_unsupported: Transmit response, no retransmits */
    04387 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported)
    04388 {
    04389    struct sip_request resp;
    04390    respprep(&resp, p, msg, req);
    04391    append_date(&resp);
    04392    add_header(&resp, "Unsupported", unsupported);
    04393    add_header_contentLength(&resp, 0);
    04394    add_blank_header(&resp);
    04395    return send_response(p, &resp, 0, 0);
    04396 }
    04397
    04398 /*! \brief  transmit_response_reliable: Transmit response, Make sure you get a reply */
    04399 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
    04400 {
    04401    return __transmit_response(p, msg, req, fatal ? 2 : 1);
    04402 }
    04403
    04404 /*! \brief  append_date: Append date to SIP message ---*/
    04405 static void append_date(struct sip_request *req)
    04406 {
    04407    char tmpdat[256];
    04408    struct tm tm;
    04409    time_t t;
    04410
    04411    time(&t);
    04412    gmtime_r(&t, &tm);
    04413    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
    04414    add_header(req, "Date", tmpdat);
    04415 }
    04416
    04417 /*! \brief  transmit_response_with_date: Append date and content length before transmitting response ---*/
    04418 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
    04419 {
    04420    struct sip_request resp;
    04421    respprep(&resp, p, msg, req);
    04422    append_date(&resp);
    04423    add_header_contentLength(&resp, 0);
    04424    add_blank_header(&resp);
    04425    return send_response(p, &resp, 0, 0);
    04426 }
    04427
    04428 /*! \brief  transmit_response_with_allow: Append Accept header, content length before transmitting response ---*/
    04429 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
    04430 {
    04431    struct sip_request resp;
    04432    respprep(&resp, p, msg, req);
    04433    add_header(&resp, "Accept", "application/sdp");
    04434    add_header_contentLength(&resp, 0);
    04435    add_blank_header(&resp);
    04436    return send_response(p, &resp, reliable, 0);
    04437 }
    04438
    04439 /* transmit_response_with_auth: Respond with authorization request */
    04440 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable, char *header, int stale)
    04441 {
    04442    struct sip_request resp;
    04443    char tmp[512];
    04444    int seqno = 0;
    04445
    04446    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
    04447       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
    04448       return -1;
    04449    }
    04450    /* Stale means that they sent us correct authentication, but
    04451       based it on an old challenge (nonce) */
    04452    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
    04453    respprep(&resp, p, msg, req);
    04454    add_header(&resp, header, tmp);
    04455    add_header_contentLength(&resp, 0);
    04456    add_blank_header(&resp);
    04457    return send_response(p, &resp, reliable, seqno);
    04458 }
    04459
    04460 /*! \brief  add_text: Add text body to SIP message ---*/
    04461 static int add_text(struct sip_request *req, const char *text)
    04462 {
    04463    /* XXX Convert \n's to \r\n's XXX */
    04464    add_header(req, "Content-Type", "text/plain");
    04465    add_header_contentLength(req, strlen(text));
    04466    add_line(req, text);
    04467    return 0;
    04468 }
    04469
    04470 /*! \brief  add_digit: add DTMF INFO tone to sip message ---*/
    04471 /* Always adds default duration 250 ms, regardless of what came in over the line */
    04472 static int add_digit(struct sip_request *req, char digit)
    04473 {
    04474    char tmp[256];
    04475
    04476    snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
    04477    add_header(req, "Content-Type", "application/dtmf-relay");
    04478    add_header_contentLength(req, strlen(tmp));
    04479    add_line(req, tmp);
    04480    return 0;
    04481 }
    04482
    04483 /*! \brief  add_vidupdate: add XML encoded media control with update ---*/
    04484 /* XML: The only way to turn 0 bits of information into a few hundred. */
    04485 static int add_vidupdate(struct sip_request *req)
    04486 {
    04487    const char *xml_is_a_huge_waste_of_space =
    04488       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
    04489       " <media_control>\r\n"
    04490       "  <vc_primitive>\r\n"
    04491       "   <to_encoder>\r\n"
    04492       "    <picture_fast_update>\r\n"
    04493       "    </picture_fast_update>\r\n"
    04494       "   </to_encoder>\r\n"
    04495       "  </vc_primitive>\r\n"
    04496       " </media_control>\r\n";
    04497    add_header(req, "Content-Type", "application/media_control+xml");
    04498    add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
    04499    add_line(req, xml_is_a_huge_waste_of_space);
    04500    return 0;
    04501 }
    04502
    04503 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
    04504               char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
    04505               int debug)
    04506 {
    04507    int rtp_code;
    04508
    04509    if (debug)
    04510       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
    04511    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
    04512       return;
    04513
    04514    ast_build_string(m_buf, m_size, " %d", rtp_code);
    04515    ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
    04516           ast_rtp_lookup_mime_subtype(1, codec),
    04517           sample_rate);
    04518    if (codec == AST_FORMAT_G729A)
    04519       /* Indicate that we don't support VAD (G.729 annex B) */
    04520       ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
    04521    else if (codec == AST_FORMAT_G723_1)
    04522       /* Indicate that we don't support VAD (G.723.1 annex A) */
    04523       ast_build_string(a_buf, a_size, "a=fmtp:%d annexa=no\r\n", rtp_code);
    04524 }
    04525
    04526 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
    04527             char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
    04528             int debug)
    04529 {
    04530    int rtp_code;
    04531
    04532    if (debug)
    04533       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format));
    04534    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
    04535       return;
    04536
    04537    ast_build_string(m_buf, m_size, " %d", rtp_code);
    04538    ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
    04539           ast_rtp_lookup_mime_subtype(0, format),
    04540           sample_rate);
    04541    if (format == AST_RTP_DTMF)
    04542       /* Indicate we support DTMF and FLASH... */
    04543       ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
    04544 }
    04545
    04546 /*! \brief  add_sdp: Add Session Description Protocol message ---*/
    04547 static int add_sdp(struct sip_request *resp, struct sip_pvt *p)
    04548 {
    04549    int len = 0;
    04550    int pref_codec;
    04551    int alreadysent = 0;
    04552    struct sockaddr_in sin;
    04553    struct sockaddr_in vsin;
    04554    char v[256];
    04555    char s[256];
    04556    char o[256];
    04557    char c[256];
    04558    char t[256];
    04559    char m_audio[256];
    04560    char m_video[256];
    04561    char a_audio[1024];
    04562    char a_video[1024];
    04563    char *m_audio_next = m_audio;
    04564    char *m_video_next = m_video;
    04565    size_t m_audio_left = sizeof(m_audio);
    04566    size_t m_video_left = sizeof(m_video);
    04567    char *a_audio_next = a_audio;
    04568    char *a_video_next = a_video;
    04569    size_t a_audio_left = sizeof(a_audio);
    04570    size_t a_video_left = sizeof(a_video);
    04571    char iabuf[INET_ADDRSTRLEN];
    04572    int x;
    04573    int capability;
    04574    struct sockaddr_in dest;
    04575    struct sockaddr_in vdest = { 0, };
    04576    int debug;
    04577
    04578    debug = sip_debug_test_pvt(p);
    04579
    04580    len = 0;
    04581    if (!p->rtp) {
    04582       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
    04583       return -1;
    04584    }
    04585    capability = p->jointcapability;
    04586
    04587    if (!p->sessionid) {
    04588       p->sessionid = getpid();
    04589       p->sessionversion = p->sessionid;
    04590    } else
    04591       p->sessionversion++;
    04592    ast_rtp_get_us(p->rtp, &sin);
    04593    if (p->vrtp)
    04594       ast_rtp_get_us(p->vrtp, &vsin);
    04595
    04596    if (p->redirip.sin_addr.s_addr) {
    04597       dest.sin_port = p->redirip.sin_port;
    04598       dest.sin_addr = p->redirip.sin_addr;
    04599       if (p->redircodecs)
    04600          capability = p->redircodecs;
    04601    } else {
    04602       dest.sin_addr = p->ourip;
    04603       dest.sin_port = sin.sin_port;
    04604    }
    04605
    04606    /* Determine video destination */
    04607    if (p->vrtp) {
    04608       if (p->vredirip.sin_addr.s_addr) {
    04609          vdest.sin_port = p->vredirip.sin_port;
    04610          vdest.sin_addr = p->vredirip.sin_addr;
    04611       } else {
    04612          vdest.sin_addr = p->ourip;
    04613          vdest.sin_port = vsin.sin_port;
    04614       }
    04615    }
    04616    if (debug){
    04617       ast_verbose("We're at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(sin.sin_port));
    04618       if (p->vrtp)
    04619          ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(vsin.sin_port));
    04620    }
    04621
    04622    /* We break with the "recommendation" and send our IP, in order that our
    04623       peer doesn't have to ast_gethostbyname() us */
    04624
    04625    snprintf(v, sizeof(v), "v=0\r\n");
    04626    snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
    04627    snprintf(s, sizeof(s), "s=session\r\n");
    04628    snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
    04629    snprintf(t, sizeof(t), "t=0 0\r\n");
    04630
    04631    ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
    04632    ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
    04633
    04634    /* Prefer the codec we were requested to use, first, no matter what */
    04635    if (capability & p->prefcodec) {
    04636       if (p->prefcodec <= AST_FORMAT_MAX_AUDIO)
    04637          add_codec_to_sdp(p, p->prefcodec, 8000,
    04638                 &m_audio_next, &m_audio_left,
    04639                 &a_audio_next, &a_audio_left,
    04640                 debug);
    04641       else
    04642          add_codec_to_sdp(p, p->prefcodec, 90000,
    04643                 &m_video_next, &m_video_left,
    04644                 &a_video_next, &a_video_left,
    04645                 debug);
    04646       alreadysent |= p->prefcodec;
    04647    }
    04648
    04649    /* Start by sending our preferred codecs */
    04650    for (x = 0; x < 32; x++) {
    04651       if (!(pref_codec = ast_codec_pref_index(&p->prefs, x)))
    04652          break;
    04653
    04654       if (!(capability & pref_codec))
    04655          continue;
    04656
    04657       if (alreadysent & pref_codec)
    04658          continue;
    04659
    04660       if (pref_codec <= AST_FORMAT_MAX_AUDIO)
    04661          add_codec_to_sdp(p, pref_codec, 8000,
    04662                 &m_audio_next, &m_audio_left,
    04663                 &a_audio_next, &a_audio_left,
    04664                 debug);
    04665       else
    04666          add_codec_to_sdp(p, pref_codec, 90000,
    04667                 &m_video_next, &m_video_left,
    04668                 &a_video_next, &a_video_left,
    04669                 debug);
    04670       alreadysent |= pref_codec;
    04671    }
    04672
    04673    /* Now send any other common codecs, and non-codec formats: */
    04674    for (x = 1; x <= ((videosupport && p->vrtp) ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
    04675       if (!(capability & x))
    04676          continue;
    04677
    04678       if (alreadysent & x)
    04679          continue;
    04680
    04681       if (x <= AST_FORMAT_MAX_AUDIO)
    04682          add_codec_to_sdp(p, x, 8000,
    04683                 &m_audio_next, &m_audio_left,
    04684                 &a_audio_next, &a_audio_left,
    04685                 debug);
    04686       else
    04687          add_codec_to_sdp(p, x, 90000,
    04688                 &m_video_next, &m_video_left,
    04689                 &a_video_next, &a_video_left,
    04690                 debug);
    04691    }
    04692
    04693    for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
    04694       if (!(p->jointnoncodeccapability & x))
    04695          continue;
    04696
    04697       add_noncodec_to_sdp(p, x, 8000,
    04698                 &m_audio_next, &m_audio_left,
    04699                 &a_audio_next, &a_audio_left,
    04700                 debug);
    04701    }
    04702
    04703    ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");
    04704
    04705    if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
    04706       ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
    04707
    04708    ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
    04709    ast_build_string(&m_video_next, &m_video_left, "\r\n");
    04710
    04711    len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_audio) + strlen(a_audio);
    04712    if ((p->vrtp) && (!ast_test_flag(p, SIP_NOVIDEO)) && (capability & VIDEO_CODEC_MASK)) /* only if video response is appropriate */
    04713       len += strlen(m_video) + strlen(a_video);
    04714
    04715    add_header(resp, "Content-Type", "application/sdp");
    04716    add_header_contentLength(resp, len);
    04717    add_line(resp, v);
    04718    add_line(resp, o);
    04719    add_line(resp, s);
    04720    add_line(resp, c);
    04721    add_line(resp, t);
    04722    add_line(resp, m_audio);
    04723    add_line(resp, a_audio);
    04724    if ((p->vrtp) && (!ast_test_flag(p, SIP_NOVIDEO)) && (capability & VIDEO_CODEC_MASK)) { /* only if video response is appropriate */
    04725       add_line(resp, m_video);
    04726       add_line(resp, a_video);
    04727    }
    04728
    04729    /* Update lastrtprx when we send our SDP */
    04730    time(&p->lastrtprx);
    04731    time(&p->lastrtptx);
    04732
    04733    return 0;
    04734 }
    04735
    04736 /*! \brief  copy_request: copy SIP request (mostly used to save request for responses) ---*/
    04737 static void copy_request(struct sip_request *dst, struct sip_request *src)
    04738 {
    04739    long offset;
    04740    int x;
    04741    offset = ((void *)dst) - ((void *)src);
    04742    /* First copy stuff */
    04743    memcpy(dst, src, sizeof(*dst));
    04744    /* Now fix pointer arithmetic */
    04745    for (x=0; x < src->headers; x++)
    04746       dst->header[x] += offset;
    04747    for (x=0; x < src->lines; x++)
    04748       dst->line[x] += offset;
    04749    dst->rlPart1 += offset;
    04750    dst->rlPart2 += offset;
    04751 }
    04752
    04753 /*! \brief  transmit_response_with_sdp: Used for 200 OK and 183 early media ---*/
    04754 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
    04755 {
    04756    struct sip_request resp;
    04757    int seqno;
    04758    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
    04759       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
    04760       return -1;
    04761    }
    04762    respprep(&resp, p, msg, req);
    04763    if (p->rtp) {
    04764       ast_rtp_offered_from_local(p->rtp, 0);
    04765       try_suggested_sip_codec(p);
    04766       add_sdp(&resp, p);
    04767    } else {
    04768       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
    04769    }
    04770    return send_response(p, &resp, retrans, seqno);
    04771 }
    04772
    04773 /*! \brief  determine_firstline_parts: parse first line of incoming SIP request */
    04774 static int determine_firstline_parts( struct sip_request *req )
    04775 {
    04776    char *e, *cmd;
    04777    int len;
    04778
    04779    cmd = ast_skip_blanks(req->header[0]);
    04780    if (!*cmd)
    04781       return -1;
    04782    req->rlPart1 = cmd;
    04783    e = ast_skip_nonblanks(cmd);
    04784    /* Get the command */
    04785    if (*e)
    04786       *e++ = '\0';
    04787    e = ast_skip_blanks(e);
    04788    if ( !*e )
    04789       return -1;
    04790
    04791    if ( !strcasecmp(cmd, "SIP/2.0") ) {
    04792       /* We have a response */
    04793       req->rlPart2 = e;
    04794       len = strlen( req->rlPart2 );
    04795       if ( len < 2 ) {
    04796          return -1;
    04797       }
    04798       ast_trim_blanks(e);
    04799    } else {
    04800       /* We have a request */
    04801       if ( *e == '<' ) {
    04802          e++;
    04803          if ( !*e ) {
    04804             return -1;
    04805          }
    04806       }
    04807       req->rlPart2 = e; /* URI */
    04808       if ( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
    04809          return -1;
    04810       }
    04811       /* XXX maybe trim_blanks() ? */
    04812       while( isspace( *(--e) ) ) {}
    04813       if ( *e == '>' ) {
    04814          *e = '\0';
    04815       } else {
    04816          *(++e)= '\0';
    04817       }
    04818    }
    04819    return 1;
    04820 }
    04821
    04822 /*! \brief  transmit_reinvite_with_sdp: Transmit reinvite with SDP :-) ---*/
    04823 /*    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
    04824    INVITE that opened the SIP dialogue
    04825    We reinvite so that the audio stream (RTP) go directly between
    04826    the SIP UAs. SIP Signalling stays with * in the path.
    04827 */
    04828 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
    04829 {
    04830    struct sip_request req;
    04831    if (ast_test_flag(p, SIP_REINVITE_UPDATE))
    04832       reqprep(&req, p, SIP_UPDATE, 0, 1);
    04833    else
    04834       reqprep(&req, p, SIP_INVITE, 0, 1);
    04835
    04836    add_header(&req, "Allow", ALLOWED_METHODS);
    04837    if (sipdebug)
    04838       add_header(&req, "X-asterisk-info", "SIP re-invite (RTP bridge)");
    04839    ast_rtp_offered_from_local(p->rtp, 1);
    04840    add_sdp(&req, p);
    04841    /* Use this as the basis */
    04842    copy_request(&p->initreq, &req);
    04843    parse_request(&p->initreq);
    04844    if (sip_debug_test_pvt(p))
    04845       ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
    04846    p->lastinvite = p->ocseq;
    04847    ast_set_flag(p, SIP_OUTGOING);
    04848    return send_request(p, &req, 1, p->ocseq);
    04849 }
    04850
    04851 /*! \brief  extract_uri: Check Contact: URI of SIP message ---*/
    04852 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
    04853 {
    04854    char stripped[256];
    04855    char *c, *n;
    04856    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
    04857    c = get_in_brackets(stripped);
    04858    n = strchr(c, ';');
    04859    if (n)
    04860       *n = '\0';
    04861    if (!ast_strlen_zero(c))
    04862       ast_copy_string(p->uri, c, sizeof(p->uri));
    04863 }
    04864
    04865 /*! \brief  build_contact: Build contact header - the contact header we send out ---*/
    04866 static void build_contact(struct sip_pvt *p)
    04867 {
    04868    char iabuf[INET_ADDRSTRLEN];
    04869
    04870    /* Construct Contact: header */
    04871    if (ourport != 5060) /* Needs to be 5060, according to the RFC */
    04872       snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport);
    04873    else
    04874       snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip));
    04875 }
    04876
    04877 /*! \brief  build_rpid: Build the Remote Party-ID & From using callingpres options ---*/
    04878 static void build_rpid(struct sip_pvt *p)
    04879 {
    04880    int send_pres_tags = 1;
    04881    const char *privacy = NULL;
    04882    const char *screen = NULL;
    04883    char buf[256];
    04884    const char *clid = default_callerid;
    04885    const char *clin = NULL;
    04886    char iabuf[INET_ADDRSTRLEN];
    04887    const char *fromdomain;
    04888
    04889    if (p->rpid || p->rpid_from)
    04890       return;
    04891
    04892    if (p->owner && p->owner->cid.cid_num)
    04893       clid = p->owner->cid.cid_num;
    04894    if (p->owner && p->owner->cid.cid_name)
    04895       clin = p->owner->cid.cid_name;
    04896    if (ast_strlen_zero(clin))
    04897       clin = clid;
    04898
    04899    switch (p->callingpres) {
    04900    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
    04901       privacy = "off";
    04902       screen = "no";
    04903       break;
    04904    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
    04905       privacy = "off";
    04906       screen = "yes";
    04907       break;
    04908    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
    04909       privacy = "off";
    04910       screen = "no";
    04911       break;
    04912    case AST_PRES_ALLOWED_NETWORK_NUMBER:
    04913       privacy = "off";
    04914       screen = "yes";
    04915       break;
    04916    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
    04917       privacy = "full";
    04918       screen = "no";
    04919       break;
    04920    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
    04921       privacy = "full";
    04922       screen = "yes";
    04923       break;
    04924    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
    04925       privacy = "full";
    04926       screen = "no";
    04927       break;
    04928    case AST_PRES_PROHIB_NETWORK_NUMBER:
    04929       privacy = "full";
    04930       screen = "yes";
    04931       break;
    04932    case AST_PRES_NUMBER_NOT_AVAILABLE:
    04933       send_pres_tags = 0;
    04934       break;
    04935    default:
    04936       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
    04937       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
    04938          privacy = "full";
    04939       else
    04940          privacy = "off";
    04941       screen = "no";
    04942       break;
    04943    }
    04944
    04945    fromdomain = ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain;
    04946
    04947    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
    04948    if (send_pres_tags)
    04949       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
    04950    p->rpid = strdup(buf);
    04951
    04952    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>;tag=%s", clin,
    04953        ast_strlen_zero(p->fromuser) ? clid : p->fromuser,
    04954        fromdomain, p->tag);
    04955    p->rpid_from = strdup(buf);
    04956 }
    04957
    04958 /*! \brief  initreqprep: Initiate new SIP request to peer/user ---*/
    04959 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
    04960 {
    04961    char invite_buf[256] = "";
    04962    char *invite = invite_buf;
    04963    size_t invite_max = sizeof(invite_buf);
    04964    char from[256];
    04965    char to[256];
    04966    char tmp[BUFSIZ/2];
    04967    char tmp2[BUFSIZ/2];
    04968    char iabuf[INET_ADDRSTRLEN];
    04969    char *l = NULL, *n = NULL;
    04970    int x;
    04971    char urioptions[256]="";
    04972
    04973    if (ast_test_flag(p, SIP_USEREQPHONE)) {
    04974       char onlydigits = 1;
    04975       x=0;
    04976
    04977       /* Test p->username against allowed characters in AST_DIGIT_ANY
    04978       If it matches the allowed characters list, then sipuser = ";user=phone"
    04979       If not, then sipuser = ""
    04980          */
    04981          /* + is allowed in first position in a tel: uri */
    04982          if (p->username && p->username[0] == '+')
    04983          x=1;
    04984
    04985       for (; x < strlen(p->username); x++) {
    04986          if (!strchr(AST_DIGIT_ANYNUM, p->username[x])) {
    04987                      onlydigits = 0;
    04988             break;
    04989          }
    04990       }
    04991
    04992       /* If we have only digits, add ;user=phone to the uri */
    04993       if (onlydigits)
    04994          strcpy(urioptions, ";user=phone");
    04995    }
    04996
    04997
    04998    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
    04999
    05000    if (p->owner) {
    05001       l = p->owner->cid.cid_num;
    05002       n = p->owner->cid.cid_name;
    05003    }
    05004    /* if we are not sending RPID and user wants his callerid restricted */
    05005    if (!ast_test_flag(p, SIP_SENDRPID) && ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
    05006       l = CALLERID_UNKNOWN;
    05007       n = l;
    05008    }
    05009    if (ast_strlen_zero(l))
    05010       l = default_callerid;
    05011    if (ast_strlen_zero(n))
    05012       n = l;
    05013    /* Allow user to be overridden */
    05014    if (!ast_strlen_zero(p->fromuser))
    05015       l = p->fromuser;
    05016    else /* Save for any further attempts */
    05017       ast_copy_string(p->fromuser, l, sizeof(p->fromuser));
    05018
    05019    /* Allow user to be overridden */
    05020    if (!ast_strlen_zero(p->fromname))
    05021       n = p->fromname;
    05022    else /* Save for any further attempts */
    05023       ast_copy_string(p->fromname, n, sizeof(p->fromname));
    05024
    05025    if (pedanticsipchecking) {
    05026       ast_uri_encode(n, tmp, sizeof(tmp), 0);
    05027       n = tmp;
    05028       ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
    05029       l = tmp2;
    05030    }
    05031
    05032    if ((ourport != 5060) && ast_strlen_zero(p->fromdomain)) /* Needs to be 5060 */
    05033       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, ourport, p->tag);
    05034    else
    05035       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, p->tag);
    05036
    05037    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
    05038    if (!ast_strlen_zero(p->fullcontact)) {
    05039       /* If we have full contact, trust it */
    05040       ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
    05041    } else {
    05042       /* Otherwise, use the username while waiting for registration */
    05043       ast_build_string(&invite, &invite_max, "sip:");
    05044       if (!ast_strlen_zero(p->username)) {
    05045          n = p->username;
    05046          if (pedanticsipchecking) {
    05047             ast_uri_encode(n, tmp, sizeof(tmp), 0);
    05048             n = tmp;
    05049          }
    05050          ast_build_string(&invite, &invite_max, "%s@", n);
    05051       }
    05052       ast_build_string(&invite, &invite_max, "%s", p->tohost);
    05053       if (ntohs(p->sa.sin_port) != 5060)     /* Needs to be 5060 */
    05054          ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
    05055       ast_build_string(&invite, &invite_max, "%s", urioptions);
    05056    }
    05057
    05058    /* If custom URI options have been provided, append them */
    05059    if (p->options && p->options->uri_options)
    05060       ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
    05061
    05062    ast_copy_string(p->uri, invite_buf, sizeof(p->uri));
    05063
    05064    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
    05065       /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
    05066       snprintf(to, sizeof(to), "<sip:%s>;tag=%s", p->uri, p->theirtag);
    05067    } else if (p->options && p->options->vxml_url) {
    05068       /* If there is a VXML URL append it to the SIP URL */
    05069       snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
    05070    } else {
    05071       snprintf(to, sizeof(to), "<%s>", p->uri);
    05072    }
    05073
    05074    memset(req, 0, sizeof(struct sip_request));
    05075    init_req(req, sipmethod, p->uri);
    05076    snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
    05077
    05078    add_header(req, "Via", p->via);
    05079    /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
    05080     * OTOH, then we won't have anything in p->route anyway */
    05081    /* Build Remote Party-ID and From */
    05082    if (ast_test_flag(p, SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
    05083       build_rpid(p);
    05084       add_header(req, "From", p->rpid_from);
    05085    } else {
    05086       add_header(req, "From", from);
    05087    }
    05088    add_header(req, "To", to);
    05089    ast_copy_string(p->exten, l, sizeof(p->exten));
    05090    build_contact(p);
    05091    add_header(req, "Contact", p->our_contact);
    05092    add_header(req, "Call-ID", p->callid);
    05093    add_header(req, "CSeq", tmp);
    05094    if (!ast_strlen_zero(default_useragent))
    05095       add_header(req, "User-Agent", default_useragent);
    05096    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
    05097    if (p->rpid)
    05098       add_header(req, "Remote-Party-ID", p->rpid);
    05099 }
    05100
    05101 /*! \brief  transmit_invite: Build REFER/INVITE/OPTIONS message and transmit it ---*/
    05102 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
    05103 {
    05104    struct sip_request req;
    05105
    05106    req.method = sipmethod;
    05107    if (init) {
    05108       /* Bump branch even on initial requests */
    05109       p->branch ^= thread_safe_rand();
    05110       build_via(p, p->via, sizeof(p->via));
    05111       if (init > 1)
    05112          initreqprep(&req, p, sipmethod);
    05113       else
    05114          reqprep(&req, p, sipmethod, 0, 1);
    05115    } else
    05116       reqprep(&req, p, sipmethod, 0, 1);
    05117
    05118    if (p->options && p->options->auth)
    05119       add_header(&req, p->options->authheader, p->options->auth);
    05120    append_date(&req);
    05121    if (sipmethod == SIP_REFER) { /* Call transfer */
    05122       if (!ast_strlen_zero(p->refer_to))
    05123          add_header(&req, "Refer-To", p->refer_to);
    05124       if (!ast_strlen_zero(p->referred_by))
    05125          add_header(&req, "Referred-By", p->referred_by);
    05126    }
    05127 #ifdef OSP_SUPPORT
    05128    if ((req.method != SIP_OPTIONS) && p->options && !ast_strlen_zero(p->options->osptoken)) {
    05129       ast_log(LOG_DEBUG,"Adding OSP Token: %s\n", p->options->osptoken);
    05130       add_header(&req, "P-OSP-Auth-Token", p->options->osptoken);
    05131    }
    05132 #endif
    05133    if (p->options && !ast_strlen_zero(p->options->distinctive_ring))
    05134    {
    05135       add_header(&req, "Alert-Info", p->options->distinctive_ring);
    05136    }
    05137    add_header(&req, "Allow", ALLOWED_METHODS);
    05138    if (p->options && p->options->addsipheaders ) {
    05139       struct ast_channel *ast;
    05140       char *header = (char *) NULL;
    05141       char *content = (char *) NULL;
    05142       char *end = (char *) NULL;
    05143       struct varshead *headp = (struct varshead *) NULL;
    05144       struct ast_var_t *current;
    05145
    05146       ast = p->owner;   /* The owner channel */
    05147       if (ast) {
    05148          char *headdup;
    05149          headp = &ast->varshead;
    05150          if (!headp)
    05151             ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
    05152          else {
    05153             AST_LIST_TRAVERSE(headp, current, entries) {
    05154                /* SIPADDHEADER: Add SIP header to outgoing call        */
    05155                if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
    05156                   header = ast_var_value(current);
    05157                   headdup = ast_strdupa(header);
    05158                   /* Strip of the starting " (if it's there) */
    05159                   if (*headdup == '"')
    05160                      headdup++;
    05161                   if ((content = strchr(headdup, ':'))) {
    05162                      *content = '\0';
    05163                      content++;  /* Move pointer ahead */
    05164                      /* Skip white space */
    05165                      while (*content == ' ')
    05166                         content++;
    05167                      /* Strip the ending " (if it's there) */
    05168                      end = content + strlen(content) -1;
    05169                      if (*end == '"')
    05170                         *end = '\0';
    05171
    05172                      add_header(&req, headdup, content);
    05173                      if (sipdebug)
    05174                         ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
    05175                   }
    05176                }
    05177             }
    05178          }
    05179       }
    05180    }
    05181    if (sdp && p->rtp) {
    05182       ast_rtp_offered_from_local(p->rtp, 1);
    05183       add_sdp(&req, p);
    05184    } else {
    05185       add_header_contentLength(&req, 0);
    05186       add_blank_header(&req);
    05187    }
    05188
    05189    if (!p->initreq.headers) {
    05190       /* Use this as the basis */
    05191       copy_request(&p->initreq, &req);
    05192       parse_request(&p->initreq);
    05193       if (sip_debug_test_pvt(p))
    05194          ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
    05195    }
    05196    p->lastinvite = p->ocseq;
    05197    return send_request(p, &req, init ? 2 : 1, p->ocseq);
    05198 }
    05199
    05200 /*! \brief  transmit_state_notify: Used in the SUBSCRIBE notification subsystem ----*/
    05201 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate, int timeout)
    05202 {
    05203    char tmp[4000], from[256], to[256];
    05204    char *t = tmp, *c, *a, *mfrom, *mto;
    05205    size_t maxbytes = sizeof(tmp);
    05206    struct sip_request req;
    05207    char hint[AST_MAX_EXTENSION];
    05208    char *statestring = "terminated";
    05209    const struct cfsubscription_types *subscriptiontype;
    05210    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
    05211    char *pidfstate = "--";
    05212    char *pidfnote= "Ready";
    05213
    05214    memset(from, 0, sizeof(from));
    05215    memset(to, 0, sizeof(to));
    05216    memset(tmp, 0, sizeof(tmp));
    05217
    05218    switch (state) {
    05219    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
    05220       if (global_notifyringing)
    05221          statestring = "early";
    05222       else
    05223          statestring = "confirmed";
    05224       local_state = NOTIFY_INUSE;
    05225       pidfstate = "busy";
    05226       pidfnote = "Ringing";
    05227       break;
    05228    case AST_EXTENSION_RINGING:
    05229       statestring = "early";
    05230       local_state = NOTIFY_INUSE;
    05231       pidfstate = "busy";
    05232       pidfnote = "Ringing";
    05233       break;
    05234    case AST_EXTENSION_INUSE:
    05235       statestring = "confirmed";
    05236       local_state = NOTIFY_INUSE;
    05237       pidfstate = "busy";
    05238       pidfnote = "On the phone";
    05239       break;
    05240    case AST_EXTENSION_BUSY:
    05241       statestring = "confirmed";
    05242       local_state = NOTIFY_CLOSED;
    05243       pidfstate = "busy";
    05244       pidfnote = "On the phone";
    05245       break;
    05246    case AST_EXTENSION_UNAVAILABLE:
    05247       statestring = "confirmed";
    05248       local_state = NOTIFY_CLOSED;
    05249       pidfstate = "away";
    05250       pidfnote = "Unavailable";
    05251       break;
    05252    case AST_EXTENSION_NOT_INUSE:
    05253    default:
    05254       /* Default setting */
    05255       break;
    05256    }
    05257
    05258    subscriptiontype = find_subscription_type(p->subscribed);
    05259
    05260    /* Check which device/devices we are watching  and if they are registered */
    05261    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
    05262       char *hint2 = hint, *individual_hint = NULL;
    05263       while ((individual_hint = strsep(&hint2, "&"))) {
    05264          /* If they are not registered, we will override notification and show no availability */
    05265          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE) {
    05266             local_state = NOTIFY_CLOSED;
    05267             pidfstate = "away";
    05268             pidfnote = "Not online";
    05269          }
    05270       }
    05271    }
    05272
    05273    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
    05274    c = get_in_brackets(from);
    05275    if (strncasecmp(c, "sip:", 4)) {
    05276       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
    05277       return -1;
    05278    }
    05279    if ((a = strchr(c, ';')))
    05280       *a = '\0';
    05281    mfrom = c;
    05282
    05283    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
    05284    c = get_in_brackets(to);
    05285    if (strncasecmp(c, "sip:", 4)) {
    05286       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
    05287       return -1;
    05288    }
    05289    if ((a = strchr(c, ';')))
    05290       *a = '\0';
    05291    mto = c;
    05292
    05293    reqprep(&req, p, SIP_NOTIFY, 0, 1);
    05294
    05295
    05296    add_header(&req, "Event", subscriptiontype->event);
    05297    add_header(&req, "Content-Type", subscriptiontype->mediatype);
    05298    switch(state) {
    05299    case AST_EXTENSION_DEACTIVATED:
    05300       if (timeout)
    05301          add_header(&req, "Subscription-State", "terminated;reason=timeout");
    05302       else {
    05303          add_header(&req, "Subscription-State", "terminated;reason=probation");
    05304          add_header(&req, "Retry-After", "60");
    05305       }
    05306       break;
    05307    case AST_EXTENSION_REMOVED:
    05308       add_header(&req, "Subscription-State", "terminated;reason=noresource");
    05309       break;
    05310       break;
    05311    default:
    05312       if (p->expiry)
    05313          add_header(&req, "Subscription-State", "active");
    05314       else  /* Expired */
    05315          add_header(&req, "Subscription-State", "terminated;reason=timeout");
    05316    }
    05317    switch (p->subscribed) {
    05318    case XPIDF_XML:
    05319    case CPIM_PIDF_XML:
    05320       ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
    05321       ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
    05322       ast_build_string(&t, &maxbytes, "<presence>\n");
    05323       ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
    05324       ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
    05325       ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
    05326       ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
    05327       ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
    05328       ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
    05329       break;
    05330    case PIDF_XML: /* Eyebeam supports this format */
    05331       ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
    05332       ast_build_string(&t, &maxbytes, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
    05333       ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
    05334       if (pidfstate[0] != '-')
    05335          ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
    05336       ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
    05337       ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
    05338       ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
    05339       ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
    05340       if (pidfstate[0] == 'b') /* Busy? Still open ... */
    05341          ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
    05342       else
    05343          ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
    05344       ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
    05345       break;
    05346    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
    05347       ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
    05348       ast_build_string(&t, &maxbytes, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
    05349       if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
    05350          ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
    05351       else
    05352          ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
    05353       ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
    05354       ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
    05355       break;
    05356    case NONE:
    05357    default:
    05358       break;
    05359    }
    05360
    05361    if (t > tmp + sizeof(tmp))
    05362       ast_log(LOG_WARNING, "Buffer overflow detected!!  (Please file a bug report)\n");
    05363
    05364    add_header_contentLength(&req, strlen(tmp));
    05365    add_line(&req, tmp);
    05366
    05367    return send_request(p, &req, 1, p->ocseq);
    05368 }
    05369
    05370 /*! \brief  transmit_notify_with_mwi: Notify user of messages waiting in voicemail ---*/
    05371 /*      Notification only works for registered peers with mailbox= definitions
    05372  *      in sip.conf
    05373  *      We use the SIP Event package message-summary
    05374  *      MIME type defaults to  "application/simple-message-summary";
    05375  */
    05376 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
    05377 {
    05378    struct sip_request req;
    05379    char tmp[500];
    05380    char *t = tmp;
    05381    size_t maxbytes = sizeof(tmp);
    05382    char iabuf[INET_ADDRSTRLEN];
    05383
    05384    initreqprep(&req, p, SIP_NOTIFY);
    05385    add_header(&req, "Event", "message-summary");
    05386    add_header(&req, "Content-Type", default_notifymime);
    05387
    05388    ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
    05389    ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n", !ast_strlen_zero(vmexten) ? vmexten : global_vmexten, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain);
    05390    ast_build_string(&t, &maxbytes, "Voice-Message: %d/%d (0/0)\r\n", newmsgs, oldmsgs);
    05391
    05392    if (t > tmp + sizeof(tmp))
    05393       ast_log(LOG_WARNING, "Buffer overflow detected!!  (Please file a bug report)\n");
    05394
    05395    add_header_contentLength(&req, strlen(tmp));
    05396    add_line(&req, tmp);
    05397
    05398    if (!p->initreq.headers) { /* Use this as the basis */
    05399       copy_request(&p->initreq, &req);
    05400       parse_request(&p->initreq);
    05401       if (sip_debug_test_pvt(p))
    05402          ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
    05403       determine_firstline_parts(&p->initreq);
    05404    }
    05405
    05406    return send_request(p, &req, 1, p->ocseq);
    05407 }
    05408
    05409 /*! \brief  transmit_sip_request: Transmit SIP request */
    05410 static int transmit_sip_request(struct sip_pvt *p,struct sip_request *req)
    05411 {
    05412    if (!p->initreq.headers) {
    05413       /* Use this as the basis */
    05414       copy_request(&p->initreq, req);
    05415       parse_request(&p->initreq);
    05416       if (sip_debug_test_pvt(p))
    05417          ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
    05418       determine_firstline_parts(&p->initreq);
    05419    }
    05420
    05421    return send_request(p, req, 0, p->ocseq);
    05422 }
    05423
    05424 /*! \brief  transmit_notify_with_sipfrag: Notify a transferring party of the status of trasnfer ---*/
    05425 /*      Apparently the draft SIP REFER structure was too simple, so it was decided that the
    05426  *      status of transfers also needed to be sent via NOTIFY instead of just the 202 Accepted
    05427  *      that had worked heretofore.
    05428  */
    05429 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq)
    05430 {
    05431    struct sip_request req;
    05432    char tmp[20];
    05433    reqprep(&req, p, SIP_NOTIFY, 0, 1);
    05434    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
    05435    add_header(&req, "Event", tmp);
    05436    add_header(&req, "Subscription-state", "terminated;reason=noresource");
    05437    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
    05438
    05439    strcpy(tmp, "SIP/2.0 200 OK\r\n");
    05440    add_header_contentLength(&req, strlen(tmp));
    05441    add_line(&req, tmp);
    05442
    05443    if (!p->initreq.headers) {
    05444       /* Use this as the basis */
    05445       copy_request(&p->initreq, &req);
    05446       parse_request(&p->initreq);
    05447       if (sip_debug_test_pvt(p))
    05448          ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
    05449       determine_firstline_parts(&p->initreq);
    05450    }
    05451
    05452    return send_request(p, &req, 1, p->ocseq);
    05453 }
    05454
    05455 static char *regstate2str(int regstate)
    05456 {
    05457    switch(regstate) {
    05458    case REG_STATE_FAILED:
    05459       return "Failed";
    05460    case REG_STATE_UNREGISTERED:
    05461       return "Unregistered";
    05462    case REG_STATE_REGSENT:
    05463       return "Request Sent";
    05464    case REG_STATE_AUTHSENT:
    05465       return "Auth. Sent";
    05466    case REG_STATE_REGISTERED:
    05467       return "Registered";
    05468    case REG_STATE_REJECTED:
    05469       return "Rejected";
    05470    case REG_STATE_TIMEOUT:
    05471       return "Timeout";
    05472    case REG_STATE_NOAUTH:
    05473       return "No Authentication";
    05474    default:
    05475       return "Unknown";
    05476    }
    05477 }
    05478
    05479 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
    05480
    05481 /*! \brief  sip_reregister: Update registration with SIP Proxy---*/
    05482 static int sip_reregister(void *data)
    05483 {
    05484    /* if we are here, we know that we need to reregister. */
    05485    struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);
    05486
    05487    /* if we couldn't get a reference to the registry object, punt */
    05488    if (!r)
    05489       return 0;
    05490
    05491    if (r->call && recordhistory) {
    05492       char tmp[80];
    05493       snprintf(tmp, sizeof(tmp), "Account: %s@%s", r->username, r->hostname);
    05494       append_history(r->call, "RegistryRenew", tmp);
    05495    }
    05496    /* Since registry's are only added/removed by the the monitor thread, this
    05497       may be overkill to reference/dereference at all here */
    05498    if (sipdebug)
    05499       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
    05500
    05501    r->expire = -1;
    05502    __sip_do_register(r);
    05503    ASTOBJ_UNREF(r, sip_registry_destroy);
    05504    return 0;
    05505 }
    05506
    05507 /*! \brief  __sip_do_register: Register with SIP proxy ---*/
    05508 static int __sip_do_register(struct sip_registry *r)
    05509 {
    05510    int res;
    05511
    05512    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
    05513    return res;
    05514 }
    05515
    05516 /*! \brief  sip_reg_timeout: Registration timeout, register again */
    05517 static int sip_reg_timeout(void *data)
    05518 {
    05519
    05520    /* if we are here, our registration timed out, so we'll just do it over */
    05521    struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
    05522    struct sip_pvt *p;
    05523    int res;
    05524
    05525    /* if we couldn't get a reference to the registry object, punt */
    05526    if (!r)
    05527       return 0;
    05528
    05529    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
    05530    if (r->call) {
    05531       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
    05532          in the single SIP manager thread. */
    05533       p = r->call;
    05534       if (p->registry)
    05535          ASTOBJ_UNREF(p->registry, sip_registry_destroy);
    05536       r->call = NULL;
    05537       ast_set_flag(p, SIP_NEEDDESTROY);
    05538       /* Pretend to ACK anything just in case */
    05539       __sip_pretend_ack(p);
    05540    }
    05541    /* If we have a limit, stop registration and give up */
    05542    if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
    05543       /* Ok, enough is enough. Don't try any more */
    05544       /* We could add an external notification here...
    05545          steal it from app_voicemail :-) */
    05546       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
    05547       r->regstate=REG_STATE_FAILED;
    05548    } else {
    05549       r->regstate=REG_STATE_UNREGISTERED;
    05550       r->timeout = -1;
    05551       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
    05552    }
    05553    manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
    05554    ASTOBJ_UNREF(r,sip_registry_destroy);
    05555    return 0;
    05556 }
    05557
    05558 /*! \brief  transmit_register: Transmit register to SIP proxy or UA ---*/
    05559 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader)
    05560 {
    05561    struct sip_request req;
    05562    char from[256];
    05563    char to[256];
    05564    char tmp[80];
    05565    char via[80];
    05566    char addr[80];
    05567    struct sip_pvt *p;
    05568
    05569    /* exit if we are already in process with this registrar ?*/
    05570    if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
    05571       ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
    05572       return 0;
    05573    }
    05574
    05575    if (r->call) { /* We have a registration */
    05576       if (!auth) {
    05577          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
    05578          return 0;
    05579       } else {
    05580          p = r->call;
    05581          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
    05582          p->theirtag[0]='\0'; /* forget their old tag, so we don't match tags when getting response */
    05583       }
    05584    } else {
    05585       /* Build callid for registration if we haven't registered before */
    05586       if (!r->callid_valid) {
    05587          build_callid(r->callid, sizeof(r->callid), __ourip, default_fromdomain);
    05588          r->callid_valid = 1;
    05589       }
    05590       /* Allocate SIP packet for registration */
    05591       p=sip_alloc( r->callid, NULL, 0, SIP_REGISTER);
    05592       if (!p) {
    05593          ast_log(LOG_WARNING, "Unable to allocate registration call\n");
    05594          return 0;
    05595       }
    05596       if (recordhistory) {
    05597          char tmp[80];
    05598          snprintf(tmp, sizeof(tmp), "Account: %s@%s", r->username, r->hostname);
    05599          append_history(p, "RegistryInit", tmp);
    05600       }
    05601       /* Find address to hostname */
    05602       if (create_addr(p, r->hostname)) {
    05603          /* we have what we hope is a temporary network error,
    05604           * probably DNS.  We need to reschedule a registration try */
    05605          sip_destroy(p);
    05606          if (r->timeout > -1) {
    05607             ast_sched_del(sched, r->timeout);
    05608             r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
    05609             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
    05610          } else {
    05611             r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
    05612             ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
    05613          }
    05614          r->regattempts++;
    05615          return 0;
    05616       }
    05617       /* Copy back Call-ID in case create_addr changed it */
    05618       ast_copy_string(r->callid, p->callid, sizeof(r->callid));
    05619       if (r->portno)
    05620          p->sa.sin_port = htons(r->portno);
    05621       else  /* Set registry port to the port set from the peer definition/srv or default */
    05622          r->portno = ntohs(p->sa.sin_port);
    05623       ast_set_flag(p, SIP_OUTGOING);   /* Registration is outgoing call */
    05624       r->call=p;        /* Save pointer to SIP packet */
    05625       p->registry=ASTOBJ_REF(r); /* Add pointer to registry in packet */
    05626       if (!ast_strlen_zero(r->secret)) /* Secret (password) */
    05627          ast_copy_string(p->peersecret, r->secret, sizeof(p->peersecret));
    05628       if (!ast_strlen_zero(r->md5secret))
    05629          ast_copy_string(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret));
    05630       /* User name in this realm
    05631       - if authuser is set, use that, otherwise use username */
    05632       if (!ast_strlen_zero(r->authuser)) {
    05633          ast_copy_string(p->peername, r->authuser, sizeof(p->peername));
    05634          ast_copy_string(p->authname, r->authuser, sizeof(p->authname));
    05635       } else {
    05636          if (!ast_strlen_zero(r->username)) {
    05637             ast_copy_string(p->peername, r->username, sizeof(p->peername));
    05638             ast_copy_string(p->authname, r->username, sizeof(p->authname));
    05639             ast_copy_string(p->fromuser, r->username, sizeof(p->fromuser));
    05640          }
    05641       }
    05642       if (!ast_strlen_zero(r->username))
    05643          ast_copy_string(p->username, r->username, sizeof(p->username));
    05644       /* Save extension in packet */
    05645       ast_copy_string(p->exten, r->contact, sizeof(p->exten));
    05646
    05647       /*
    05648         check which address we should use in our contact header
    05649         based on whether the remote host is on the external or
    05650         internal network so we can register through nat
    05651        */
    05652       if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
    05653          memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
    05654       build_contact(p);
    05655    }
    05656
    05657    /* set up a timeout */
    05658    if (auth == NULL)  {
    05659       if (r->timeout > -1) {
    05660          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
    05661          ast_sched_del(sched, r->timeout);
    05662       }
    05663       r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
    05664       ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
    05665    }
    05666
    05667    if (strchr(r->username, '@')) {
    05668       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
    05669       if (!ast_strlen_zero(p->theirtag))
    05670          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
    05671       else
    05672          snprintf(to, sizeof(to), "<sip:%s>", r->username);
    05673    } else {
    05674       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
    05675       if (!ast_strlen_zero(p->theirtag))
    05676          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
    05677       else
    05678          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
    05679    }
    05680
    05681    /* Fromdomain is what we are registering to, regardless of actual
    05682       host name from SRV */
    05683    if (!ast_strlen_zero(p->fromdomain)) {
    05684       if (r->portno && r->portno != DEFAULT_SIP_PORT)
    05685          snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
    05686       else
    05687          snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
    05688    } else {
    05689       if (r->portno && r->portno != DEFAULT_SIP_PORT)
    05690          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
    05691       else
    05692          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
    05693    }
    05694    ast_copy_string(p->uri, addr, sizeof(p->uri));
    05695
    05696    p->branch ^= thread_safe_rand();
    05697
    05698    memset(&req, 0, sizeof(req));
    05699    init_req(&req, sipmethod, addr);
    05700
    05701    /* Add to CSEQ */
    05702    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
    05703    p->ocseq = r->ocseq;
    05704
    05705    build_via(p, via, sizeof(via));
    05706    add_header(&req, "Via", via);
    05707    add_header(&req, "From", from);
    05708    add_header(&req, "To", to);
    05709    add_header(&req, "Call-ID", p->callid);
    05710    add_header(&req, "CSeq", tmp);
    05711    if (!ast_strlen_zero(default_useragent))
    05712       add_header(&req, "User-Agent", default_useragent);
    05713    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
    05714
    05715
    05716    if (auth)   /* Add auth header */
    05717       add_header(&req, authheader, auth);
    05718    else if (!ast_strlen_zero(r->nonce)) {
    05719       char digest[1024];
    05720
    05721       /* We have auth data to reuse, build a digest header! */
    05722       if (sipdebug)
    05723          ast_log(LOG_DEBUG, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
    05724       ast_copy_string(p->realm, r->realm, sizeof(p->realm));
    05725       ast_copy_string(p->nonce, r->nonce, sizeof(p->nonce));
    05726       ast_copy_string(p->domain, r->domain, sizeof(p->domain));
    05727       ast_copy_string(p->opaque, r->opaque, sizeof(p->opaque));
    05728       ast_copy_string(p->qop, r->qop, sizeof(p->qop));
    05729       r->noncecount++;
    05730       p->noncecount = r->noncecount;
    05731
    05732       memset(digest,0,sizeof(digest));
    05733       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
    05734          add_header(&req, "Authorization", digest);
    05735       else
    05736          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
    05737
    05738    }
    05739
    05740    snprintf(tmp, sizeof(tmp), "%d", default_expiry);
    05741    add_header(&req, "Expires", tmp);
    05742    add_header(&req, "Contact", p->our_contact);
    05743    add_header(&req, "Event", "registration");
    05744    add_header_contentLength(&req, 0);
    05745    add_blank_header(&req);
    05746    copy_request(&p->initreq, &req);
    05747    parse_request(&p->initreq);
    05748    if (sip_debug_test_pvt(p)) {
    05749       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
    05750    }
    05751    determine_firstline_parts(&p->initreq);
    05752    r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
    05753    r->regattempts++; /* Another attempt */
    05754    if (option_debug > 3)
    05755       ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
    05756    return send_request(p, &req, 2, p->ocseq);
    05757 }
    05758
    05759 /*! \brief  transmit_message_with_text: Transmit text with SIP MESSAGE method ---*/
    05760 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
    05761 {
    05762    struct sip_request req;
    05763    reqprep(&req, p, SIP_MESSAGE, 0, 1);
    05764    add_text(&req, text);
    05765    return send_request(p, &req, 1, p->ocseq);
    05766 }
    05767
    05768 /*! \brief  transmit_refer: Transmit SIP REFER message ---*/
    05769 static int transmit_refer(struct sip_pvt *p, const char *dest)
    05770 {
    05771    struct sip_request req;
    05772    char from[256];
    05773    char *of, *c;
    05774    char referto[256];
    05775
    05776    if (ast_test_flag(p, SIP_OUTGOING))
    05777       of = get_header(&p->initreq, "To");
    05778    else
    05779       of = get_header(&p->initreq, "From");
    05780    ast_copy_string(from, of, sizeof(from));
    05781    of = get_in_brackets(from);
    05782    ast_copy_string(p->from,of,sizeof(p->from));
    05783    if (strncasecmp(of, "sip:", 4)) {
    05784       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
    05785    } else
    05786       of += 4;
    05787    /* Get just the username part */
    05788    if ((c = strchr(dest, '@'))) {
    05789       c = NULL;
    05790    } else if ((c = strchr(of, '@'))) {
    05791       *c = '\0';
    05792       c++;
    05793    }
    05794    if (c) {
    05795       snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
    05796    } else {
    05797       snprintf(referto, sizeof(referto), "<sip:%s>", dest);
    05798    }
    05799
    05800    /* save in case we get 407 challenge */
    05801    ast_copy_string(p->refer_to, referto, sizeof(p->refer_to));
    05802    ast_copy_string(p->referred_by, p->our_contact, sizeof(p->referred_by));
    05803
    05804    reqprep(&req, p, SIP_REFER, 0, 1);
    05805    add_header(&req, "Refer-To", referto);
    05806    if (!ast_strlen_zero(p->our_contact))
    05807       add_header(&req, "Referred-By", p->our_contact);
    05808    add_blank_header(&req);
    05809    return send_request(p, &req, 1, p->ocseq);
    05810 }
    05811
    05812 /*! \brief  transmit_info_with_digit: Send SIP INFO dtmf message, see Cisco documentation on cisco.co
    05813 m ---*/
    05814 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
    05815 {
    05816    struct sip_request req;
    05817    reqprep(&req, p, SIP_INFO, 0, 1);
    05818    add_digit(&req, digit);
    05819    return send_request(p, &req, 1, p->ocseq);
    05820 }
    05821
    05822 /*! \brief  transmit_info_with_vidupdate: Send SIP INFO with video update request ---*/
    05823 static int transmit_info_with_vidupdate(struct sip_pvt *p)
    05824 {
    05825    struct sip_request req;
    05826    reqprep(&req, p, SIP_INFO, 0, 1);
    05827    add_vidupdate(&req);
    05828    return send_request(p, &req, 1, p->ocseq);
    05829 }
    05830
    05831 /*! \brief  transmit_request: transmit generic SIP request ---*/
    05832 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, int reliable, int newbranch)
    05833 {
    05834    struct sip_request resp;
    05835    reqprep(&resp, p, sipmethod, seqno, newbranch);
    05836    add_header_contentLength(&resp, 0);
    05837    add_blank_header(&resp);
    05838    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
    05839 }
    05840
    05841 /*! \brief  transmit_request_with_auth: Transmit SIP request, auth added ---*/
    05842 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, int reliable, int newbranch)
    05843 {
    05844    struct sip_request resp;
    05845
    05846    reqprep(&resp, p, sipmethod, seqno, newbranch);
    05847    if (*p->realm) {
    05848       char digest[1024];
    05849
    05850       memset(digest, 0, sizeof(digest));
    05851       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
    05852          if (p->options && p->options->auth_type == PROXY_AUTH)
    05853             add_header(&resp, "Proxy-Authorization", digest);
    05854          else if (p->options && p->options->auth_type == WWW_AUTH)
    05855             add_header(&resp, "Authorization", digest);
    05856          else  /* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
    05857             add_header(&resp, "Proxy-Authorization", digest);
    05858       } else
    05859          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
    05860    }
    05861    /* If we are hanging up and know a cause for that, send it in clear text to make
    05862       debugging easier. */
    05863    if (sipmethod == SIP_BYE) {
    05864       if (p->owner && p->owner->hangupcause) {
    05865          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
    05866       }
    05867    }
    05868
    05869    add_header_contentLength(&resp, 0);
    05870    add_blank_header(&resp);
    05871    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
    05872 }
    05873
    05874 static void destroy_association(struct sip_peer *peer)
    05875 {
    05876    if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_IGNOREREGEXPIRE)) {
    05877       if (ast_test_flag(&(peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT)) {
    05878          ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", NULL);
    05879       } else {
    05880          ast_db_del("SIP/Registry", peer->name);
    05881       }
    05882    }
    05883 }
    05884
    05885 /*! \brief  expire_register: Expire registration of SIP peer ---*/
    05886 static int expire_register(void *data)
    05887 {
    05888    struct sip_peer *peer = data;
    05889
    05890    if (!peer)     /* Hmmm. We have no peer. Weird. */
    05891       return 0;
    05892
    05893    memset(&peer->addr, 0, sizeof(peer->addr));
    05894
    05895    destroy_association(peer);
    05896
    05897    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
    05898    register_peer_exten(peer, 0); /* Remove regexten */
    05899    peer->expire = -1;
    05900    ast_device_state_changed("SIP/%s", peer->name);
    05901
    05902    /* Do we need to release this peer from memory?
    05903       Only for realtime peers and autocreated peers
    05904    */
    05905    if (ast_test_flag(peer, SIP_SELFDESTRUCT) || ast_test_flag((&peer->flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
    05906       peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);   /* Remove from peer list */
    05907       ASTOBJ_UNREF(peer, sip_destroy_peer);
    05908    }
    05909
    05910    return 0;
    05911 }
    05912
    05913 static int sip_poke_peer(struct sip_peer *peer);
    05914
    05915 static int sip_poke_peer_s(void *data)
    05916 {
    05917    struct sip_peer *peer = data;
    05918    peer->pokeexpire = -1;
    05919    sip_poke_peer(peer);
    05920    return 0;
    05921 }
    05922
    05923 /*! \brief  reg_source_db: Get registration details from Asterisk DB ---*/
    05924 static void reg_source_db(struct sip_peer *peer)
    05925 {
    05926    char data[256];
    05927    char iabuf[INET_ADDRSTRLEN];
    05928    struct in_addr in;
    05929    int expiry;
    05930    int port;
    05931    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
    05932
    05933    if (ast_test_flag(&(peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT))
    05934       return;
    05935    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
    05936       return;
    05937
    05938    scan = data;
    05939    addr = strsep(&scan, ":");
    05940    port_str = strsep(&scan, ":");
    05941    expiry_str = strsep(&scan, ":");
    05942    username = strsep(&scan, ":");
    05943    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
    05944
    05945    if (!inet_aton(addr, &in))
    05946       return;
    05947
    05948    if (port_str)
    05949       port = atoi(port_str);
    05950    else
    05951       return;
    05952
    05953    if (expiry_str)
    05954       expiry = atoi(expiry_str);
    05955    else
    05956       return;
    05957
    05958    if (username)
    05959       ast_copy_string(peer->username, username, sizeof(peer->username));
    05960    if (contact)
    05961       ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
    05962
    05963    if (option_verbose > 2)
    05964       ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
    05965              peer->name, peer->username, ast_inet_ntoa(iabuf, sizeof(iabuf), in), port, expiry);
    05966
    05967    memset(&peer->addr, 0, sizeof(peer->addr));
    05968    peer->addr.sin_family = AF_INET;
    05969    peer->addr.sin_addr = in;
    05970    peer->addr.sin_port = htons(port);
    05971    if (sipsock < 0) {
    05972       /* SIP isn't up yet, so schedule a poke only, pretty soon */
    05973       if (peer->pokeexpire > -1)
    05974          ast_sched_del(sched, peer->pokeexpire);
    05975       peer->pokeexpire = ast_sched_add(sched, thread_safe_rand() % 5000 + 1, sip_poke_peer_s, peer);
    05976    } else
    05977       sip_poke_peer(peer);
    05978    if (peer->expire > -1)
    05979       ast_sched_del(sched, peer->expire);
    05980    peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
    05981    register_peer_exten(peer, 1);
    05982 }
    05983
    05984 /*! \brief  parse_ok_contact: Parse contact header for 200 OK on INVITE ---*/
    05985 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
    05986 {
    05987    char contact[SIP_LEN_CONTACT];
    05988    char *c, *n, *pt;
    05989    int port;
    05990    struct hostent *hp;
    05991    struct ast_hostent ahp;
    05992    struct sockaddr_in oldsin;
    05993
    05994    /* Look for brackets */
    05995    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
    05996    c = get_in_brackets(contact);
    05997
    05998    /* Save full contact to call pvt for later bye or re-invite */
    05999    ast_copy_string(pvt->fullcontact, c, sizeof(pvt->fullcontact));
    06000
    06001    /* Save URI for later ACKs, BYE or RE-invites */
    06002    ast_copy_string(pvt->okcontacturi, c, sizeof(pvt->okcontacturi));
    06003
    06004    /* Make sure it's a SIP URL */
    06005    if (strncasecmp(c, "sip:", 4)) {
    06006       ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
    06007    } else
    06008       c += 4;
    06009
    06010    /* Ditch arguments */
    06011    n = strchr(c, ';');
    06012    if (n)
    06013       *n = '\0';
    06014
    06015    /* Grab host */
    06016    n = strchr(c, '@');
    06017    if (!n) {
    06018       n = c;
    06019       c = NULL;
    06020    } else {
    06021       *n = '\0';
    06022       n++;
    06023    }
    06024    pt = strchr(n, ':');
    06025    if (pt) {
    06026       *pt = '\0';
    06027       pt++;
    06028       port = atoi(pt);
    06029    } else
    06030       port = DEFAULT_SIP_PORT;
    06031
    06032    memcpy(&oldsin, &pvt->sa, sizeof(oldsin));
    06033
    06034    if (!(ast_test_flag(pvt, SIP_NAT) & SIP_NAT_ROUTE)) {
    06035       /* XXX This could block for a long time XXX */
    06036       /* We should only do this if it's a name, not an IP */
    06037       hp = ast_gethostbyname(n, &ahp);
    06038       if (!hp)  {
    06039          ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
    06040          return -1;
    06041       }
    06042       pvt->sa.sin_family = AF_INET;
    06043       memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
    06044       pvt->sa.sin_port = htons(port);
    06045    } else {
    06046       /* Don't trust the contact field.  Just use what they came to us
    06047          with. */
    06048       memcpy(&pvt->sa, &pvt->recv, sizeof(pvt->sa));
    06049    }
    06050    return 0;
    06051 }
    06052
    06053
    06054 enum parse_register_result {
    06055    PARSE_REGISTER_FAILED,
    06056    PARSE_REGISTER_UPDATE,
    06057    PARSE_REGISTER_QUERY,
    06058 };
    06059
    06060 /*! \brief  parse_register_contact: Parse contact header and save registration ---*/
    06061 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
    06062 {
    06063    char contact[BUFSIZ];
    06064    char data[BUFSIZ];
    06065    char iabuf[INET_ADDRSTRLEN];
    06066    char *expires = get_header(req, "Expires");
    06067    int expiry = atoi(expires);
    06068    char *c, *n, *pt;
    06069    int port;
    06070    char *useragent;
    06071    struct hostent *hp;
    06072    struct ast_hostent ahp;
    06073    struct sockaddr_in oldsin;
    06074
    06075    if (ast_strlen_zero(expires)) {  /* No expires header */
    06076       expires = strcasestr(get_header(req, "Contact"), ";expires=");
    06077       if (expires) {
    06078          char *ptr;
    06079          if ((ptr = strchr(expires, ';')))
    06080             *ptr = '\0';
    06081          if (sscanf(expires + 9, "%30d", &expiry) != 1)
    06082             expiry = default_expiry;
    06083       } else {
    06084          /* Nothing has been specified */
    06085          expiry = default_expiry;
    06086       }
    06087    }
    06088    /* Look for brackets */
    06089    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
    06090    if (strchr(contact, '<') == NULL) { /* No <, check for ; and strip it */
    06091       char *ptr = strchr(contact, ';');   /* This is Header options, not URI options */
    06092       if (ptr)
    06093          *ptr = '\0';
    06094    }
    06095    c = get_in_brackets(contact);
    06096
    06097    /* if they did not specify Contact: or Expires:, they are querying
    06098       what we currently have stored as their contact address, so return
    06099       it
    06100    */
    06101    if (ast_strlen_zero(c) && ast_strlen_zero(expires)) {
    06102       /* If we have an active registration, tell them when the registration is going to expire */
    06103       if ((p->expire > -1) && !ast_strlen_zero(p->fullcontact)) {
    06104          pvt->expiry = ast_sched_when(sched, p->expire);
    06105       }
    06106       return PARSE_REGISTER_QUERY;
    06107    } else if (!strcasecmp(c, "*") || !expiry) { /* Unregister this peer */
    06108       /* This means remove all registrations and return OK */
    06109       memset(&p->addr, 0, sizeof(p->addr));
    06110       if (p->expire > -1)
    06111          ast_sched_del(sched, p->expire);
    06112       p->expire = -1;
    06113
    06114       destroy_association(p);
    06115
    06116       register_peer_exten(p, 0);
    06117       p->fullcontact[0] = '\0';
    06118       p->useragent[0] = '\0';
    06119       p->sipoptions = 0;
    06120       p->lastms = 0;
    06121
    06122       if (option_verbose > 2)
    06123          ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->name);
    06124          manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", p->name);
    06125       return PARSE_REGISTER_UPDATE;
    06126    }
    06127    ast_copy_string(p->fullcontact, c, sizeof(p->fullcontact));
    06128    /* For the 200 OK, we should use the received contact */
    06129    snprintf(pvt->our_contact, sizeof(pvt->our_contact) - 1, "<%s>", c);
    06130    /* Make sure it's a SIP URL */
    06131    if (strncasecmp(c, "sip:", 4)) {
    06132       ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
    06133    } else
    06134       c += 4;
    06135    /* Ditch q */
    06136    n = strchr(c, ';');
    06137    if (n) {
    06138       *n = '\0';
    06139    }
    06140    /* Grab host */
    06141    n = strchr(c, '@');
    06142    if (!n) {
    06143       n = c;
    06144       c = NULL;
    06145    } else {
    06146       *n = '\0';
    06147       n++;
    06148    }
    06149    pt = strchr(n, ':');
    06150    if (pt) {
    06151       *pt = '\0';
    06152       pt++;
    06153       port = atoi(pt);
    06154    } else
    06155       port = DEFAULT_SIP_PORT;
    06156    memcpy(&oldsin, &p->addr, sizeof(oldsin));
    06157    if (!(ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)) {
    06158       /* XXX This could block for a long time XXX */
    06159       hp = ast_gethostbyname(n, &ahp);
    06160       if (!hp)  {
    06161          ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
    06162          return PARSE_REGISTER_FAILED;
    06163       }
    06164       p->addr.sin_family = AF_INET;
    06165       memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
    06166       p->addr.sin_port = htons(port);
    06167    } else {
    06168       /* Don't trust the contact field.  Just use what they came to us
    06169          with */
    06170       memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
    06171    }
    06172
    06173    if (c && ast_strlen_zero(p->username))
    06174       ast_copy_string(p->username, c, sizeof(p->username));
    06175
    06176    if (p->expire > -1) {
    06177       ast_sched_del(sched, p->expire);
    06178       p->expire = -1;
    06179    }
    06180    if ((expiry < 1) || (expiry > max_expiry))
    06181       expiry = max_expiry;
    06182    if (!ast_test_flag(p, SIP_REALTIME))
    06183       p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
    06184    else
    06185       p->expire = -1;
    06186    pvt->expiry = expiry;
    06187    snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry, p->username, p->fullcontact);
    06188    if (!ast_test_flag((&p->flags_page2), SIP_PAGE2_RT_FROMCONTACT))
    06189       ast_db_put("SIP/Registry", p->name, data);
    06190    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", p->name);
    06191    if (inaddrcmp(&p->addr, &oldsin)) {
    06192       sip_poke_peer(p);
    06193       if (option_verbose > 2)
    06194          ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->name, ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry);
    06195       register_peer_exten(p, 1);
    06196    }
    06197
    06198    /* Save SIP options profile */
    06199    p->sipoptions = pvt->sipoptions;
    06200
    06201    /* Save User agent */
    06202    useragent = get_header(req, "User-Agent");
    06203    if (useragent && strcasecmp(useragent, p->useragent)) {
    06204       ast_copy_string(p->useragent, useragent, sizeof(p->useragent));
    06205       if (option_verbose > 3) {
    06206          ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n",p->useragent,p->name);
    06207       }
    06208    }
    06209    return PARSE_REGISTER_UPDATE;
    06210 }
    06211
    06212 /*! \brief  free_old_route: Remove route from route list ---*/
    06213 static void free_old_route(struct sip_route *route)
    06214 {
    06215    struct sip_route *next;
    06216    while (route) {
    06217       next = route->next;
    06218       free(route);
    06219       route = next;
    06220    }
    06221 }
    06222
    06223 /*! \brief  list_route: List all routes - mostly for debugging ---*/
    06224 static void list_route(struct sip_route *route)
    06225 {
    06226    if (!route) {
    06227       ast_verbose("list_route: no route\n");
    06228       return;
    06229    }
    06230    while (route) {
    06231       ast_verbose("list_route: hop: <%s>\n", route->hop);
    06232       route = route->next;
    06233    }
    06234 }
    06235
    06236 /*! \brief  build_route: Build route list from Record-Route header ---*/
    06237 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
    06238 {
    06239    struct sip_route *thishop, *head, *tail;
    06240    int start = 0;
    06241    int len;
    06242    char *rr, *contact, *c;
    06243
    06244    /* Once a persistant route is set, don't fool with it */
    06245    if (p->route && p->route_persistant) {
    06246       ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
    06247       return;
    06248    }
    06249
    06250    if (p->route) {
    06251       free_old_route(p->route);
    06252       p->route = NULL;
    06253    }
    06254
    06255    p->route_persistant = backwards;
    06256
    06257    /* We build up head, then assign it to p->route when we're done */
    06258    head = NULL;  tail = head;
    06259    /* 1st we pass through all the hops in any Record-Route headers */
    06260    for (;;) {
    06261       /* Each Record-Route header */
    06262       rr = __get_header(req, "Record-Route", &start);
    06263       if (*rr == '\0') break;
    06264       for (;;) {
    06265          /* Each route entry */
    06266          /* Find < */
    06267          rr = strchr(rr, '<');
    06268          if (!rr) break; /* No more hops */
    06269          ++rr;
    06270          len = strcspn(rr, ">") + 1;
    06271          /* Make a struct route */
    06272          thishop = malloc(sizeof(*thishop) + len);
    06273          if (thishop) {
    06274             ast_copy_string(thishop->hop, rr, len);
    06275             ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
    06276             /* Link in */
    06277             if (backwards) {
    06278                /* Link in at head so they end up in reverse order */
    06279                thishop->next = head;
    06280                head = thishop;
    06281                /* If this was the first then it'll be the tail */
    06282                if (!tail) tail = thishop;
    06283             } else {
    06284                thishop->next = NULL;
    06285                /* Link in at the end */
    06286                if (tail)
    06287                   tail->next = thishop;
    06288                else
    06289                   head = thishop;
    06290                tail = thishop;
    06291             }
    06292          }
    06293          rr += len;
    06294       }
    06295    }
    06296
    06297    /* Only append the contact if we are dealing with a strict router */
    06298    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
    06299       /* 2nd append the Contact: if there is one */
    06300       /* Can be multiple Contact headers, comma separated values - we just take the first */
    06301       contact = get_header(req, "Contact");
    06302       if (!ast_strlen_zero(contact)) {
    06303          ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
    06304          /* Look for <: delimited address */
    06305          c = strchr(contact, '<');
    06306          if (c) {
    06307             /* Take to > */
    06308             ++c;
    06309             len = strcspn(c, ">") + 1;
    06310          } else {
    06311             /* No <> - just take the lot */
    06312             c = contact;
    06313             len = strlen(contact) + 1;
    06314          }
    06315          thishop = malloc(sizeof(*thishop) + len);
    06316          if (thishop) {
    06317             ast_copy_string(thishop->hop, c, len);
    06318             thishop->next = NULL;
    06319             /* Goes at the end */
    06320             if (tail)
    06321                tail->next = thishop;
    06322             else
    06323                head = thishop;
    06324          }
    06325       }
    06326    }
    06327
    06328    /* Store as new route */
    06329    p->route = head;
    06330
    06331    /* For debugging dump what we ended up with */
    06332    if (sip_debug_test_pvt(p))
    06333       list_route(p->route);
    06334 }
    06335
    06336 #ifdef OSP_SUPPORT
    06337 /*! \brief  check_osptoken: Validate OSP token for user authrroization ---*/
    06338 static int check_osptoken (struct sip_pvt *p, char *token)
    06339 {
    06340    char tmp[80];
    06341
    06342    if (ast_osp_validate (NULL, token, &p->osphandle, &p->osptimelimit, p->cid_num, p->sa.sin_addr, p->exten) < 1) {
    06343       return (-1);
    06344    } else {
    06345       snprintf (tmp, sizeof (tmp), "%d", p->osphandle);
    06346       pbx_builtin_setvar_helper (p->owner, "_OSPHANDLE", tmp);
    06347       return (0);
    06348    }
    06349 }
    06350 #endif
    06351
    06352 /*! \brief  check_auth: Check user authorization from peer definition ---*/
    06353 /*      Some actions, like REGISTER and INVITEs from peers require
    06354         authentication (if peer have secret set) */
    06355 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *md5secret, int sipmethod, char *uri, int reliable, int ignore)
    06356 {
    06357    int res = -1;
    06358    char *response = "407 Proxy Authentication Required";
    06359    char *reqheader = "Proxy-Authorization";
    06360    char *respheader = "Proxy-Authenticate";
    06361    char *authtoken;
    06362 #ifdef OSP_SUPPORT
    06363    char *osptoken;
    06364 #endif
    06365    /* Always OK if no secret */
    06366    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)
    06367 #ifdef OSP_SUPPORT
    06368        && !ast_test_flag(p, SIP_OSPAUTH)
    06369        && global_allowguest != 2
    06370 #endif
    06371       )
    06372       return 0;
    06373    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
    06374       /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
    06375          of headers -- GO SIP!  Whoo hoo!  Two things that do the same thing but are used in
    06376          different circumstances! What a surprise. */
    06377       response = "401 Unauthorized";
    06378       reqheader = "Authorization";
    06379       respheader = "WWW-Authenticate";
    06380    }
    06381 #ifdef OSP_SUPPORT
    06382    else {
    06383       ast_log (LOG_DEBUG, "Checking OSP Authentication!\n");
    06384       osptoken = get_header (req, "P-OSP-Auth-Token");
    06385       switch (ast_test_flag (p, SIP_OSPAUTH)) {
    06386          case SIP_OSPAUTH_NO:
    06387             break;
    06388          case SIP_OSPAUTH_GATEWAY:
    06389             if (ast_strlen_zero (osptoken)) {
    06390                if (ast_strlen_zero (secret) && ast_strlen_zero (md5secret)) {
    06391                   return (0);
    06392                }
    06393             }
    06394             else {
    06395                return (check_osptoken (p, osptoken));
    06396             }
    06397             break;
    06398          case SIP_OSPAUTH_PROXY:
    06399             if (ast_strlen_zero (osptoken)) {
    06400                return (0);
    06401             }
    06402             else {
    06403                return (check_osptoken (p, osptoken));
    06404             }
    06405             break;
    06406          case SIP_OSPAUTH_EXCLUSIVE:
    06407             if (ast_strlen_zero (osptoken)) {
    06408                return (-1);
    06409             }
    06410             else {
    06411                return (check_osptoken (p, osptoken));
    06412             }
    06413             break;
    06414          default:
    06415             return (-1);
    06416       }
    06417    }
    06418 #endif
    06419    authtoken =  get_header(req, reqheader);
    06420    if (ignore && !ast_strlen_zero(randdata) && ast_strlen_zero(authtoken)) {
    06421       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
    06422          information */
    06423       if (!ast_strlen_zero(randdata)) {
    06424          if (!reliable) {
    06425             /* Resend message if this was NOT a reliable delivery.   Otherwise the
    06426                retransmission should get it */
    06427             transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
    06428             /* Schedule auto destroy in 15 seconds */
    06429             sip_scheddestroy(p, 15000);
    06430          }
    06431          res = 1;
    06432       }
    06433    } else if (ast_strlen_zero(randdata) || ast_strlen_zero(authtoken)) {
    06434       snprintf(randdata, randlen, "%08x", thread_safe_rand());
    06435       transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
    06436       /* Schedule auto destroy in 15 seconds */
    06437       sip_scheddestroy(p, 15000);
    06438       res = 1;
    06439    } else {
    06440       /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
    06441          an example in the spec of just what it is you're doing a hash on. */
    06442       char a1[256];
    06443       char a2[256];
    06444       char a1_hash[256];
    06445       char a2_hash[256];
    06446       char resp[256];
    06447       char resp_hash[256]="";
    06448       char tmp[256];
    06449       char *c;
    06450       char *z;
    06451       char *ua_hash ="";
    06452       char *resp_uri ="";
    06453       char *nonce = "";
    06454       char *digestusername = "";
    06455       int  wrongnonce = 0;
    06456       char *usednonce = randdata;
    06457
    06458       /* Find their response among the mess that we'r sent for comparison */
    06459       ast_copy_string(tmp, authtoken, sizeof(tmp));
    06460       c = tmp;
    06461
    06462       while(c) {
    06463          c = ast_skip_blanks(c);
    06464          if (!*c)
    06465             break;
    06466          if (!strncasecmp(c, "response=", strlen("response="))) {
    06467             c+= strlen("response=");
    06468             if ((*c == '\"')) {
    06469                ua_hash=++c;
    06470                if ((c = strchr(c,'\"')))
    06471                   *c = '\0';
    06472
    06473             } else {
    06474                ua_hash=c;
    06475                if ((c = strchr(c,',')))
    06476                   *c = '\0';
    06477             }
    06478
    06479          } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
    06480             c+= strlen("uri=");
    06481             if ((*c == '\"')) {
    06482                resp_uri=++c;
    06483                if ((c = strchr(c,'\"')))
    06484                   *c = '\0';
    06485             } else {
    06486                resp_uri=c;
    06487                if ((c = strchr(c,',')))
    06488                   *c = '\0';
    06489             }
    06490
    06491          } else if (!strncasecmp(c, "username=", strlen("username="))) {
    06492             c+= strlen("username=");
    06493             if ((*c == '\"')) {
    06494                digestusername=++c;
    06495                if((c = strchr(c,'\"')))
    06496                   *c = '\0';
    06497             } else {
    06498                digestusername=c;
    06499                if((c = strchr(c,',')))
    06500                   *c = '\0';
    06501             }
    06502          } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
    06503             c+= strlen("nonce=");
    06504             if ((*c == '\"')) {
    06505                nonce=++c;
    06506                if ((c = strchr(c,'\"')))
    06507                   *c = '\0';
    06508             } else {
    06509                nonce=c;
    06510                if ((c = strchr(c,',')))
    06511                   *c = '\0';
    06512             }
    06513
    06514          } else
    06515             if ((z = strchr(c,' ')) || (z = strchr(c,','))) c=z;
    06516          if (c)
    06517             c++;
    06518       }
    06519       /* Verify that digest username matches  the username we auth as */
    06520       if (strcmp(username, digestusername)) {
    06521          /* Oops, we're trying something here */
    06522          return -2;
    06523       }
    06524
    06525       /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
    06526       if (strncasecmp(randdata, nonce, randlen)) {
    06527          wrongnonce = 1;
    06528          usednonce = nonce;
    06529       }
    06530
    06531       snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
    06532
    06533       if (!ast_strlen_zero(resp_uri))
    06534          snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text, resp_uri);
    06535       else
    06536          snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text, uri);
    06537
    06538       if (!ast_strlen_zero(md5secret))
    06539          snprintf(a1_hash, sizeof(a1_hash), "%s", md5secret);
    06540       else
    06541          ast_md5_hash(a1_hash, a1);
    06542
    06543       ast_md5_hash(a2_hash, a2);
    06544
    06545       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
    06546       ast_md5_hash(resp_hash, resp);
    06547
    06548       if (wrongnonce) {
    06549
    06550          snprintf(randdata, randlen, "%08x", thread_safe_rand());
    06551          if (ua_hash && !strncasecmp(ua_hash, resp_hash, strlen(resp_hash))) {
    06552             if (sipdebug)
    06553                ast_log(LOG_NOTICE, "stale nonce received from '%s'\n", get_header(req, "To"));
    06554             /* We got working auth token, based on stale nonce . */
    06555             transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 1);
    06556          } else {
    06557             /* Everything was wrong, so give the device one more try with a new challenge */
    06558             if (sipdebug)
    06559                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
    06560             transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
    06561          }
    06562
    06563          /* Schedule auto destroy in 15 seconds */
    06564          sip_scheddestroy(p, 15000);
    06565          return 1;
    06566       }
    06567       /* resp_hash now has the expected response, compare the two */
    06568       if (ua_hash && !strncasecmp(ua_hash, resp_hash, strlen(resp_hash))) {
    06569          /* Auth is OK */
    06570          res = 0;
    06571       }
    06572    }
    06573    /* Failure */
    06574    return res;
    06575 }
    06576
    06577 /*! \brief  cb_extensionstate: Callback for the devicestate notification (SUBSCRIBE) support subsystem ---*/
    06578 /*    If you add an "hint" priority to the extension in the dial plan,
    06579       you will get notifications on device state changes */
    06580 static int cb_extensionstate(char *context, char* exten, int state, void *data)
    06581 {
    06582    struct sip_pvt *p = data;
    06583
    06584    ast_mutex_lock(&p->lock);
    06585
    06586    switch(state) {
    06587    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
    06588    case AST_EXTENSION_REMOVED:   /* Extension is gone */
    06589       if (p->autokillid > -1)
    06590          sip_cancel_destroy(p);  /* Remove subscription expiry for renewals */
    06591       sip_scheddestroy(p, 15000);   /* Delete subscription in 15 secs */
    06592       ast_verbose(VERBOSE_PREFIX_2 "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
    06593       p->stateid = -1;
    06594       p->subscribed = NONE;
    06595       append_history(p, "Subscribestatus", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
    06596       break;
    06597    default: /* Tell user */
    06598       p->laststate = state;
    06599       break;
    06600    }
    06601    transmit_state_notify(p, state, 1, 1, 0);
    06602
    06603    if (option_verbose > 1)
    06604       ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->username);
    06605
    06606    ast_mutex_unlock(&p->lock);
    06607
    06608    return 0;
    06609 }
    06610
    06611 /*! \brief Send a fake 401 Unauthorized response when the administrator
    06612   wants to hide the names of local users/peers from fishers
    06613 */
    06614 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, char *randdata, int randlen, int reliable, int ignore)
    06615 {
    06616    /* We have to emulate EXACTLY what we'd get with a good peer
    06617     * and a bad password, or else we leak information. */
    06618    char *response = "407 Proxy Authentication Required";
    06619    char *reqheader = "Proxy-Authorization";
    06620    char *respheader = "Proxy-Authenticate";
    06621    const char *authtoken;
    06622
    06623    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
    06624       response = "401 Unauthorized";
    06625       reqheader = "Authorization";
    06626       respheader = "WWW-Authenticate";
    06627    }
    06628
    06629    authtoken = get_header(req, reqheader);
    06630    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
    06631       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
    06632        * information */
    06633       if (!reliable) {
    06634          /* Resend message if this was NOT a reliable delivery.   Otherwise the
    06635             retransmission should get it */
    06636          transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
    06637          /* Schedule auto destroy in 15 seconds */
    06638          sip_scheddestroy(p, 15000);
    06639       }
    06640    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
    06641       /* We have no auth, so issue challenge and request authentication */
    06642       snprintf(p->randdata, sizeof(p->randdata), "%08x", thread_safe_rand());
    06643       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
    06644       sip_scheddestroy(p, 15000);
    06645    } else {
    06646       char tmp[256], *c = tmp, *z, *nonce = "";
    06647
    06648       /* Find their response among the mess that we'r sent for comparison */
    06649       ast_copy_string(tmp, authtoken, sizeof(tmp));
    06650
    06651       while (c) {
    06652          c = ast_skip_blanks(c);
    06653          if (!*c) {
    06654             break;
    06655          }
    06656          if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
    06657             c += strlen("nonce=");
    06658             if ((*c == '\"')) {
    06659                nonce = ++c;
    06660                if ((c = strchr(c,'\"'))) {
    06661                   *c = '\0';
    06662                }
    06663             } else {
    06664                nonce = c;
    06665                if ((c = strchr(c,','))) {
    06666                   *c = '\0';
    06667                }
    06668             }
    06669             /* Don't need anything beyond the nonce sent. */
    06670             break;
    06671          } else if ((z = strchr(c, ' ')) || (z = strchr(c, ','))) {
    06672             c = z;
    06673          }
    06674          if (c) {
    06675             c++;
    06676          }
    06677       }
    06678       /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
    06679       if (strncasecmp(randdata, nonce, randlen)) {
    06680          snprintf(randdata, randlen, "%08x", thread_safe_rand());
    06681          transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
    06682
    06683          /* Schedule auto destroy in 15 seconds */
    06684          sip_scheddestroy(p, 15000);
    06685       } else {
    06686          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
    06687       }
    06688    }
    06689 }
    06690
    06691 /*! \brief  register_verify: Verify registration of user */
    06692 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri, int ignore)
    06693 {
    06694    int res = -3;
    06695    struct sip_peer *peer;
    06696    char tmp[256];
    06697    char iabuf[INET_ADDRSTRLEN];
    06698    char *name, *c;
    06699    char *t;
    06700    char *domain;
    06701
    06702    /* Terminate URI */
    06703    t = uri;
    06704    while(*t && (*t > 32) && (*t != ';'))
    06705       t++;
    06706    *t = '\0';
    06707
    06708    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
    06709    if (pedanticsipchecking)
    06710       ast_uri_decode(tmp);
    06711
    06712    c = get_in_brackets(tmp);
    06713    /* Ditch ;user=phone */
    06714    name = strchr(c, ';');
    06715    if (name)
    06716       *name = '\0';
    06717
    06718    if (!strncasecmp(c, "sip:", 4)) {
    06719       name = c + 4;
    06720    } else {
    06721       name = c;
    06722       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
    06723    }
    06724
    06725    /* Strip off the domain name */
    06726    if ((c = strchr(name, '@'))) {
    06727       *c++ = '\0';
    06728       domain = c;
    06729       if ((c = strchr(domain, ':')))   /* Remove :port */
    06730          *c = '\0';
    06731       if (!AST_LIST_EMPTY(&domain_list)) {
    06732          if (!check_sip_domain(domain, NULL, 0)) {
    06733             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
    06734             return -3;
    06735          }
    06736       }
    06737    }
    06738
    06739    ast_copy_string(p->exten, name, sizeof(p->exten));
    06740    build_contact(p);
    06741    peer = find_peer(name, NULL, 1);
    06742    if (!(peer && ast_apply_ha(peer->ha, sin))) {
    06743       /* Peer fails ACL check */
    06744       if (peer)
    06745          ASTOBJ_UNREF(peer,sip_destroy_peer);
    06746       peer = NULL;
    06747       res = -4;
    06748    }
    06749    if (peer) {
    06750       if (!ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC)) {
    06751          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
    06752          res = -5;
    06753       } else {
    06754          ast_copy_flags(p, peer, SIP_NAT);
    06755          transmit_response(p, "100 Trying", req);
    06756          if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, 0, ignore))) {
    06757             sip_cancel_destroy(p);
    06758
    06759             switch (parse_register_contact(p, peer, req)) {
    06760             case PARSE_REGISTER_FAILED:
    06761                ast_log(LOG_WARNING, "Failed to parse contact info\n");
    06762                transmit_response_with_date(p, "400 Bad Request", req);
    06763                peer->lastmsgssent = -1;
    06764                res = 0;
    06765                break;
    06766             case PARSE_REGISTER_QUERY:
    06767                transmit_response_with_date(p, "200 OK", req);
    06768                peer->lastmsgssent = -1;
    06769                res = 0;
    06770                break;
    06771             case PARSE_REGISTER_UPDATE:
    06772                update_peer(peer, p->expiry);
    06773                /* Say OK and ask subsystem to retransmit msg counter */
    06774                transmit_response_with_date(p, "200 OK", req);
    06775                peer->lastmsgssent = -1;
    06776                res = 0;
    06777                break;
    06778             }
    06779          }
    06780       }
    06781    }
    06782    if (!peer && autocreatepeer) {
    06783       /* Create peer if we have autocreate mode enabled */
    06784       peer = temp_peer(name);
    06785       if (peer) {
    06786          ASTOBJ_CONTAINER_LINK(&peerl, peer);
    06787          sip_cancel_destroy(p);
    06788          switch (parse_register_contact(p, peer, req)) {
    06789          case PARSE_REGISTER_FAILED:
    06790             ast_log(LOG_WARNING, "Failed to parse contact info\n");
    06791             transmit_response_with_date(p, "400 Bad Request", req);
    06792             peer->lastmsgssent = -1;
    06793             res = 0;
    06794             break;
    06795          case PARSE_REGISTER_QUERY:
    06796             transmit_response_with_date(p, "200 OK", req);
    06797             peer->lastmsgssent = -1;
    06798             res = 0;
    06799             break;
    06800          case PARSE_REGISTER_UPDATE:
    06801             /* Say OK and ask subsystem to retransmit msg counter */
    06802             transmit_response_with_date(p, "200 OK", req);
    06803             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
    06804             peer->lastmsgssent = -1;
    06805             res = 0;
    06806             break;
    06807          }
    06808       }
    06809    }
    06810    if (!peer && global_alwaysauthreject) {
    06811       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
    06812        * trying to avoid leaking information, we MUST also transmit the same
    06813        * response when we DON'T find a peer. */
    06814       transmit_response(p, "100 Trying", req);
    06815       /* Insert a fake delay between the 100 and the subsequent failure. */
    06816       sched_yield();
    06817    }
    06818    if (!res) {
    06819       ast_device_state_changed("SIP/%s", peer->name);
    06820    }
    06821    if (res < 0) {
    06822       switch (res) {
    06823       case -1:
    06824          /* Wrong password in authentication. Go away, don't try again until you fixed it */
    06825          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
    06826          break;
    06827       case -2:
    06828          /* Username and digest username does not match.
    06829             Asterisk uses the From: username for authentication. We need the
    06830             users to use the same authentication user name until we support
    06831             proper authentication by digest auth name */
    06832          transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
    06833          break;
    06834       case -3: /* Unknown domain */
    06835       case -4: /* ACL error */
    06836       case -5: /* Peer is not supposed to register with us at all */
    06837          if (global_alwaysauthreject) {
    06838             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, p->randdata, sizeof(p->randdata), 1, ignore);
    06839          } else {
    06840             /* URI not found */
    06841             if (res == -5)
    06842                transmit_response(p, "403 Forbidden", &p->initreq);
    06843             else
    06844                transmit_response(p, "404 Not found", &p->initreq);
    06845          }
    06846          break;
    06847       }
    06848    }
    06849    if (peer)
    06850       ASTOBJ_UNREF(peer,sip_destroy_peer);
    06851
    06852    return res;
    06853 }
    06854
    06855 /*! \brief  get_rdnis: get referring dnis ---*/
    06856 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
    06857 {
    06858    char tmp[256], *c, *a;
    06859    struct sip_request *req;
    06860
    06861    req = oreq;
    06862    if (!req)
    06863       req = &p->initreq;
    06864    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
    06865    if (ast_strlen_zero(tmp))
    06866       return 0;
    06867    c = get_in_brackets(tmp);
    06868    if (strncasecmp(c, "sip:", 4)) {
    06869       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", c);
    06870       return -1;
    06871    }
    06872    c += 4;
    06873    if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
    06874       *a = '\0';
    06875    }
    06876    if (sip_debug_test_pvt(p))
    06877       ast_verbose("RDNIS is %s\n", c);
    06878    ast_copy_string(p->rdnis, c, sizeof(p->rdnis));
    06879
    06880    return 0;
    06881 }
    06882
    06883 /*! \brief  get_destination: Find out who the call is for --*/
    06884 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
    06885 {
    06886    char tmp[256] = "", *uri, *a, *user, *domain, *opts;
    06887    char tmpf[256], *from;
    06888    struct sip_request *req;
    06889    char *colon;
    06890
    06891    req = oreq;
    06892    if (!req)
    06893       req = &p->initreq;
    06894    if (req->rlPart2)
    06895       ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
    06896    uri = get_in_brackets(tmp);
    06897
    06898    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
    06899
    06900    from = get_in_brackets(tmpf);
    06901
    06902    if (strncasecmp(uri, "sip:", 4)) {
    06903       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
    06904       return -1;
    06905    }
    06906    uri += 4;
    06907    if (!ast_strlen_zero(from)) {
    06908       if (strncasecmp(from, "sip:", 4)) {
    06909          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
    06910          return -1;
    06911       }
    06912       from += 4;
    06913       if (pedanticsipchecking) {
    06914          ast_uri_decode(from);
    06915       }
    06916    } else
    06917       from = NULL;
    06918
    06919    if (pedanticsipchecking) {
    06920       ast_uri_decode(uri);
    06921    }
    06922
    06923    /* Get the target domain first and user */
    06924    if ((domain = strchr(uri, '@'))) {
    06925       *domain++ = '\0';
    06926       user = uri;
    06927    } else {
    06928       /* No user portion present */
    06929       domain = uri;
    06930       user = "s";
    06931    }
    06932
    06933    /* Strip port from domain if present */
    06934    if ((colon = strchr(domain, ':'))) {
    06935       *colon = '\0';
    06936    }
    06937
    06938    /* Strip any params or options from user */
    06939    if ((opts = strchr(user, ';'))) {
    06940       *opts = '\0';
    06941    }
    06942
    06943    ast_copy_string(p->domain, domain, sizeof(p->domain));
    06944
    06945    if (!AST_LIST_EMPTY(&domain_list)) {
    06946       char domain_context[AST_MAX_EXTENSION];
    06947
    06948       domain_context[0] = '\0';
    06949       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
    06950          if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
    06951             ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
    06952             return -2;
    06953          }
    06954       }
    06955       /* If we have a context defined, overwrite the original context */
    06956       if (!ast_strlen_zero(domain_context))
    06957          ast_copy_string(p->context, domain_context, sizeof(p->context));
    06958    }
    06959
    06960    if (from) {
    06961       if ((a = strchr(from, ';')))
    06962          *a = '\0';
    06963       if ((a = strchr(from, '@'))) {
    06964          *a = '\0';
    06965          ast_copy_string(p->fromdomain, a + 1, sizeof(p->fromdomain));
    06966       } else
    06967          ast_copy_string(p->fromdomain, from, sizeof(p->fromdomain));
    06968    }
    06969    if (sip_debug_test_pvt(p))
    06970       ast_verbose("Looking for %s in %s (domain %s)\n", user, p->context, p->domain);
    06971
    06972    /* Return 0 if we have a matching extension */
    06973    if (ast_exists_extension(NULL, p->context, user, 1, from) ||
    06974       !strcmp(uri, ast_pickup_ext())) {
    06975       if (!oreq)
    06976          ast_copy_string(p->exten, user, sizeof(p->exten));
    06977       return 0;
    06978    }
    06979
    06980    /* Return 1 for overlap dialling support */
    06981    if (ast_canmatch_extension(NULL, p->context, user, 1, from) ||
    06982        !strncmp(user, ast_pickup_ext(),strlen(user))) {
    06983       return 1;
    06984    }
    06985
    06986    return -1;
    06987 }
    06988
    06989 /*! \brief  get_sip_pvt_byid_locked: Lock interface lock and find matching pvt lock  ---*/
    06990 static struct sip_pvt *get_sip_pvt_byid_locked(char *callid)
    06991 {
    06992    struct sip_pvt *sip_pvt_ptr = NULL;
    06993
    06994    /* Search interfaces and find the match */
    06995    ast_mutex_lock(&iflock);
    06996    sip_pvt_ptr = iflist;
    06997    while(sip_pvt_ptr) {
    06998       if (!strcmp(sip_pvt_ptr->callid, callid)) {
    06999          /* Go ahead and lock it (and its owner) before returning */
    07000          ast_mutex_lock(&sip_pvt_ptr->lock);
    07001          if (sip_pvt_ptr->owner) {
    07002             while(ast_mutex_trylock(&sip_pvt_ptr->owner->lock)) {
    07003                ast_mutex_unlock(&sip_pvt_ptr->lock);
    07004                usleep(1);
    07005                ast_mutex_lock(&sip_pvt_ptr->lock);
    07006                if (!sip_pvt_ptr->owner)
    07007                   break;
    07008             }
    07009          }
    07010          break;
    07011       }
    07012       sip_pvt_ptr = sip_pvt_ptr->next;
    07013    }
    07014    ast_mutex_unlock(&iflock);
    07015    return sip_pvt_ptr;
    07016 }
    07017
    07018 /*! \brief  get_refer_info: Call transfer support (the REFER method) ---*/
    07019 static int get_refer_info(struct sip_pvt *sip_pvt, struct sip_request *outgoing_req, char **transfercontext)
    07020 {
    07021
    07022    char *p_refer_to = NULL, *p_referred_by = NULL, *h_refer_to = NULL, *h_referred_by = NULL, *h_contact = NULL;
    07023    char *replace_callid = "", *refer_to = NULL, *referred_by = NULL, *ptr = NULL;
    07024    struct sip_request *req = NULL;
    07025    struct sip_pvt *sip_pvt_ptr = NULL;
    07026    struct ast_channel *chan = NULL, *peer = NULL;
    07027
    07028    req = outgoing_req;
    07029
    07030    if (!req) {
    07031       req = &sip_pvt->initreq;
    07032    }
    07033
    07034    if (!( (p_refer_to = get_header(req, "Refer-To")) && (h_refer_to = ast_strdupa(p_refer_to)) )) {
    07035       ast_log(LOG_WARNING, "No Refer-To Header That's illegal\n");
    07036       return -1;
    07037    }
    07038
    07039    refer_to = get_in_brackets(h_refer_to);
    07040
    07041    if (!( (p_referred_by = get_header(req, "Referred-By")) && (h_referred_by = ast_strdupa(p_referred_by)) )) {
    07042       ast_log(LOG_WARNING, "No Referrred-By Header That's not illegal\n");
    07043       return -1;
    07044    } else {
    07045       if (pedanticsipchecking) {
    07046          ast_uri_decode(h_referred_by);
    07047       }
    07048       referred_by = get_in_brackets(h_referred_by);
    07049    }
    07050    h_contact = get_header(req, "Contact");
    07051
    07052    if (strncasecmp(refer_to, "sip:", 4)) {
    07053       ast_log(LOG_WARNING, "Refer-to: Huh?  Not a SIP header (%s)?\n", refer_to);
    07054       return -1;
    07055    }
    07056
    07057    if (strncasecmp(referred_by, "sip:", 4)) {
    07058       ast_log(LOG_WARNING, "Referred-by: Huh?  Not a SIP header (%s) Ignoring?\n", referred_by);
    07059       referred_by = NULL;
    07060    }
    07061
    07062    if (refer_to)
    07063       refer_to += 4;
    07064
    07065    if (referred_by)
    07066       referred_by += 4;
    07067
    07068    if ((ptr = strchr(refer_to, '?'))) {
    07069       /* Search for arguments */
    07070       *ptr = '\0';
    07071       ptr++;
    07072       if (!strncasecmp(ptr, "REPLACES=", 9)) {
    07073          char *p;
    07074          replace_callid = ast_strdupa(ptr + 9);
    07075          /* someday soon to support invite/replaces properly!
    07076             replaces_header = ast_strdupa(replace_callid);
    07077             -anthm
    07078          */
    07079          ast_uri_decode(replace_callid);
    07080          if ((ptr = strchr(replace_callid, '%')))
    07081             *ptr = '\0';
    07082          if ((ptr = strchr(replace_callid, ';')))
    07083             *ptr = '\0';
    07084          /* Skip leading whitespace XXX memmove behaviour with overlaps ? */
    07085          p = ast_skip_blanks(replace_callid);
    07086          if (p != replace_callid)
    07087             memmove(replace_callid, p, strlen(p));
    07088       }
    07089    }
    07090
    07091    if ((ptr = strchr(refer_to, '@')))  /* Skip domain (should be saved in SIPDOMAIN) */
    07092       *ptr = '\0';
    07093    if ((ptr = strchr(refer_to, ';')))
    07094       *ptr = '\0';
    07095
    07096    if (referred_by) {
    07097       if ((ptr = strchr(referred_by, '@')))
    07098          *ptr = '\0';
    07099       if ((ptr = strchr(referred_by, ';')))
    07100          *ptr = '\0';
    07101    }
    07102
    07103    *transfercontext = pbx_builtin_getvar_helper(sip_pvt->owner, "TRANSFER_CONTEXT");
    07104    if (ast_strlen_zero(*transfercontext))
    07105       *transfercontext = sip_pvt->context;
    07106
    07107    if (sip_debug_test_pvt(sip_pvt)) {
    07108       ast_verbose("Transfer to %s in %s\n", refer_to, *transfercontext);
    07109       if (referred_by)
    07110          ast_verbose("Transfer from %s in %s\n", referred_by, sip_pvt->context);
    07111    }
    07112    if (!ast_strlen_zero(replace_callid)) {
    07113       /* This is a supervised transfer */
    07114       ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",replace_callid);
    07115
    07116       ast_copy_string(sip_pvt->refer_to, "", sizeof(sip_pvt->refer_to));
    07117       ast_copy_string(sip_pvt->referred_by, "", sizeof(sip_pvt->referred_by));
    07118       ast_copy_string(sip_pvt->refer_contact, "", sizeof(sip_pvt->refer_contact));
    07119       sip_pvt->refer_call = NULL;
    07120       if ((sip_pvt_ptr = get_sip_pvt_byid_locked(replace_callid))) {
    07121          sip_pvt->refer_call = sip_pvt_ptr;
    07122          if (sip_pvt->refer_call == sip_pvt) {
    07123             ast_log(LOG_NOTICE, "Supervised transfer attempted to transfer into same call id (%s == %s)!\n", replace_callid, sip_pvt->callid);
    07124             sip_pvt->refer_call = NULL;
    07125          } else
    07126             return 0;
    07127       } else {
    07128          ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'.  Both legs must reside on Asterisk box to transfer at this time.\n", replace_callid);
    07129          /* XXX The refer_to could contain a call on an entirely different machine, requiring an
    07130               INVITE with a replaces header -anthm XXX */
    07131          /* The only way to find out is to use the dialplan - oej */
    07132       }
    07133    } else if (ast_exists_extension(NULL, *transfercontext, refer_to, 1, NULL) || !strcmp(refer_to, ast_parking_ext())) {
    07134       /* This is an unsupervised transfer (blind transfer) */
    07135
    07136       ast_log(LOG_DEBUG,"Unsupervised transfer to (Refer-To): %s\n", refer_to);
    07137       if (referred_by)
    07138          ast_log(LOG_DEBUG,"Transferred by  (Referred-by: ) %s \n", referred_by);
    07139       ast_log(LOG_DEBUG,"Transfer Contact Info %s (REFER_CONTACT)\n", h_contact);
    07140       ast_copy_string(sip_pvt->refer_to, refer_to, sizeof(sip_pvt->refer_to));
    07141       if (referred_by)
    07142          ast_copy_string(sip_pvt->referred_by, referred_by, sizeof(sip_pvt->referred_by));
    07143       if (h_contact) {
    07144          ast_copy_string(sip_pvt->refer_contact, h_contact, sizeof(sip_pvt->refer_contact));
    07145       }
    07146       sip_pvt->refer_call = NULL;
    07147       if ((chan = sip_pvt->owner) && (peer = ast_bridged_channel(sip_pvt->owner))) {
    07148          pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", peer->name);
    07149          pbx_builtin_setvar_helper(peer, "BLINDTRANSFER", chan->name);
    07150       }
    07151       return 0;
    07152    } else if (ast_canmatch_extension(NULL, *transfercontext, refer_to, 1, NULL)) {
    07153       return 1;
    07154    }
    07155
    07156    return -1;
    07157 }
    07158
    07159 /*! \brief  get_also_info: Call transfer support (old way, depreciated)--*/
    07160 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
    07161 {
    07162    char tmp[256], *c, *a;
    07163    struct sip_request *req;
    07164
    07165    req = oreq;
    07166    if (!req)
    07167       req = &p->initreq;
    07168    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
    07169
    07170    c = get_in_brackets(tmp);
    07171
    07172
    07173    if (strncasecmp(c, "sip:", 4)) {
    07174       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
    07175       return -1;
    07176    }
    07177    c += 4;
    07178    if ((a = strchr(c, '@')))
    07179       *a = '\0';
    07180    if ((a = strchr(c, ';')))
    07181       *a = '\0';
    07182
    07183    if (sip_debug_test_pvt(p)) {
    07184       ast_verbose("Looking for %s in %s\n", c, p->context);
    07185    }
    07186    if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
    07187       /* This is an unsupervised transfer */
    07188       ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
    07189       ast_copy_string(p->refer_to, c, sizeof(p->refer_to));
    07190       ast_copy_string(p->referred_by, "", sizeof(p->referred_by));
    07191       ast_copy_string(p->refer_contact, "", sizeof(p->refer_contact));
    07192       p->refer_call = NULL;
    07193       return 0;
    07194    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
    07195       return 1;
    07196    }
    07197
    07198    return -1;
    07199 }
    07200
    07201 /*! \brief check Via: header for hostname, port and rport request/answer */
    07202 static int check_via(struct sip_pvt *p, struct sip_request *req)
    07203 {
    07204    char via[256];
    07205    char iabuf[INET_ADDRSTRLEN];
    07206    char *c, *pt;
    07207    struct hostent *hp;
    07208    struct ast_hostent ahp;
    07209
    07210    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
    07211
    07212    /* Check for rport */
    07213    c = strstr(via, ";rport");
    07214    if (c && (c[6] != '=')) /* rport query, not answer */
    07215       ast_set_flag(p, SIP_NAT_ROUTE);
    07216
    07217    c = strchr(via, ';');
    07218    if (c)
    07219       *c = '\0';
    07220
    07221    c = strchr(via, ' ');
    07222    if (c) {
    07223       *c = '\0';
    07224       c = ast_skip_blanks(c+1);
    07225       if (strcasecmp(via, "SIP/2.0/UDP")) {
    07226          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
    07227          return -1;
    07228       }
    07229       pt = strchr(c, ':');
    07230       if (pt)
    07231          *pt++ = '\0';  /* remember port pointer */
    07232       hp = ast_gethostbyname(c, &ahp);
    07233       if (!hp) {
    07234          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
    07235          return -1;
    07236       }
    07237       memset(&p->sa, 0, sizeof(p->sa));
    07238       p->sa.sin_family = AF_INET;
    07239       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
    07240       p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
    07241
    07242       if (sip_debug_test_pvt(p)) {
    07243          c = (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? "NAT" : "non-NAT";
    07244          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), c);
    07245       }
    07246    }
    07247    return 0;
    07248 }
    07249
    07250 /*! \brief  get_calleridname: Get caller id name from SIP headers ---*/
    07251 static char *get_calleridname(char *input, char *output, size_t outputsize)
    07252 {
    07253    char *end = strchr(input,'<');
    07254    char *tmp = strchr(input,'\"');
    07255    int bytes = 0;
    07256    int maxbytes = outputsize - 1;
    07257
    07258    if (!end || (end == input)) return NULL;
    07259    /* move away from "<" */
    07260    end--;
    07261    /* we found "name" */
    07262    if (tmp && tmp < end) {
    07263       end = strchr(tmp+1, '\"');
    07264       if (!end) return NULL;
    07265       bytes = (int) (end - tmp);
    07266       /* protect the output buffer */
    07267       if (bytes > maxbytes)
    07268          bytes = maxbytes;
    07269       ast_copy_string(output, tmp + 1, bytes);
    07270    } else {
    07271       /* we didn't find "name" */
    07272       /* clear the empty characters in the begining*/
    07273       input = ast_skip_blanks(input);
    07274       /* clear the empty characters in the end */
    07275       while(*end && (*end < 33) && end > input)
    07276          end--;
    07277       if (end >= input) {
    07278          bytes = (int) (end - input) + 2;
    07279          /* protect the output buffer */
    07280          if (bytes > maxbytes) {
    07281             bytes = maxbytes;
    07282          }
    07283          ast_copy_string(output, input, bytes);
    07284       }
    07285       else
    07286          return NULL;
    07287    }
    07288    return output;
    07289 }
    07290
    07291 /*! \brief  get_rpid_num: Get caller id number from Remote-Party-ID header field
    07292  * Returns true if number should be restricted (privacy setting found)
    07293  * output is set to NULL if no number found
    07294  */
    07295 static int get_rpid_num(char *input,char *output, int maxlen)
    07296 {
    07297    char *start;
    07298    char *end;
    07299
    07300    start = strchr(input,':');
    07301    if (!start) {
    07302       output[0] = '\0';
    07303       return 0;
    07304    }
    07305    start++;
    07306
    07307    /* we found "number" */
    07308    ast_copy_string(output,start,maxlen);
    07309    output[maxlen-1] = '\0';
    07310
    07311    end = strchr(output,'@');
    07312    if (end)
    07313       *end = '\0';
    07314    else
    07315       output[0] = '\0';
    07316    if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
    07317       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
    07318
    07319    return 0;
    07320 }
    07321
    07322
    07323 /*! \brief  check_user_full: Check if matching user or peer is defined ---*/
    07324 /*    Match user on From: user name and peer on IP/port */
    07325 /* This is used on first invite (not re-invites) and subscribe requests */
    07326 static int check_user_full(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, int reliable, struct sockaddr_in *sin, int ignore, char *mailbox, int mailboxlen)
    07327 {
    07328    struct sip_user *user = NULL;
    07329    struct sip_peer *peer;
    07330    char *of, from[256], *c;
    07331    char *rpid,rpid_num[50];
    07332    char iabuf[INET_ADDRSTRLEN];
    07333    int res = 0;
    07334    char *t;
    07335    char calleridname[50];
    07336    int debug=sip_debug_test_addr(sin);
    07337    struct ast_variable *tmpvar = NULL, *v = NULL;
    07338    char *uri2 = ast_strdupa(uri);
    07339
    07340    /* Terminate URI */
    07341    t = uri2;
    07342    while(*t && (*t > 32) && (*t != ';'))
    07343       t++;
    07344    *t = '\0';
    07345
    07346    ast_copy_string(from, get_header(req, "From"), sizeof(from));
    07347    if (pedanticsipchecking)
    07348       ast_uri_decode(from);
    07349
    07350    memset(calleridname,0,sizeof(calleridname));
    07351    get_calleridname(from, calleridname, sizeof(calleridname));
    07352    if (calleridname[0])
    07353       ast_copy_string(p->cid_name, calleridname, sizeof(p->cid_name));
    07354
    07355    rpid = get_header(req, "Remote-Party-ID");
    07356    memset(rpid_num, 0, sizeof(rpid_num));
    07357    if (!ast_strlen_zero(rpid))
    07358       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
    07359
    07360    of = get_in_brackets(from);
    07361    if (ast_strlen_zero(p->exten)) {
    07362       t = uri2;
    07363       if (!strncasecmp(t, "sip:", 4))
    07364          t+= 4;
    07365       ast_copy_string(p->exten, t, sizeof(p->exten));
    07366       t = strchr(p->exten, '@');
    07367       if (t)
    07368          *t = '\0';
    07369       if (ast_strlen_zero(p->our_contact))
    07370          build_contact(p);
    07371    }
    07372    /* save the URI part of the From header */
    07373    ast_copy_string(p->from, of, sizeof(p->from));
    07374    if (strncasecmp(of, "sip:", 4)) {
    07375       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
    07376    } else
    07377       of += 4;
    07378    /* Get just the username part */
    07379    if ((c = strchr(of, '@'))) {
    07380       *c = '\0';
    07381       if ((c = strchr(of, ':')))
    07382          *c = '\0';
    07383       ast_copy_string(p->cid_num, of, sizeof(p->cid_num));
    07384       ast_shrink_phone_number(p->cid_num);
    07385    }
    07386
    07387    if (!mailbox)  /* If it's a mailbox SUBSCRIBE, don't check users */
    07388       user = find_user(of, 1);
    07389
    07390    /* Find user based on user name in the from header */
    07391    if (user && ast_apply_ha(user->ha, sin)) {
    07392       ast_copy_flags(p, user, SIP_FLAGS_TO_COPY);
    07393       /* copy channel vars */
    07394       for (v = user->chanvars ; v ; v = v->next) {
    07395          if ((tmpvar = ast_variable_new(v->name, v->value))) {
    07396             tmpvar->next = p->chanvars;
    07397             p->chanvars = tmpvar;
    07398          }
    07399       }
    07400       p->prefs = user->prefs;
    07401       /* replace callerid if rpid found, and not restricted */
    07402       if (!ast_strlen_zero(rpid_num) && ast_test_flag(p, SIP_TRUSTRPID)) {
    07403          if (*calleridname)
    07404             ast_copy_string(p->cid_name, calleridname, sizeof(p->cid_name));
    07405          ast_copy_string(p->cid_num, rpid_num, sizeof(p->cid_num));
    07406          ast_shrink_phone_number(p->cid_num);
    07407       }
    07408
    07409       if (p->rtp) {
    07410          ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    07411          ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    07412       }
    07413       if (p->vrtp) {
    07414          ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    07415          ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    07416       }
    07417       if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ignore))) {
    07418          sip_cancel_destroy(p);
    07419          ast_copy_flags(p, user, SIP_FLAGS_TO_COPY);
    07420          /* Copy SIP extensions profile from INVITE */
    07421          if (p->sipoptions)
    07422             user->sipoptions = p->sipoptions;
    07423
    07424          /* If we have a call limit, set flag */
    07425          if (user->call_limit)
    07426             ast_set_flag(p, SIP_CALL_LIMIT);
    07427          if (!ast_strlen_zero(user->context))
    07428             ast_copy_string(p->context, user->context, sizeof(p->context));
    07429          if (!ast_strlen_zero(user->cid_num) && !ast_strlen_zero(p->cid_num))  {
    07430             ast_copy_string(p->cid_num, user->cid_num, sizeof(p->cid_num));
    07431             ast_shrink_phone_number(p->cid_num);
    07432          }
    07433          if (!ast_strlen_zero(user->cid_name) && !ast_strlen_zero(p->cid_num))
    07434             ast_copy_string(p->cid_name, user->cid_name, sizeof(p->cid_name));
    07435          ast_copy_string(p->peername, user->name, sizeof(p->peername));
    07436          ast_copy_string(p->username, user->name, sizeof(p->username));
    07437          ast_copy_string(p->peersecret, user->secret, sizeof(p->peersecret));
    07438          ast_copy_string(p->subscribecontext, user->subscribecontext, sizeof(p->subscribecontext));
    07439          ast_copy_string(p->peermd5secret, user->md5secret, sizeof(p->peermd5secret));
    07440          ast_copy_string(p->accountcode, user->accountcode, sizeof(p->accountcode));
    07441          ast_copy_string(p->language, user->language, sizeof(p->language));
    07442          ast_copy_string(p->musicclass, user->musicclass, sizeof(p->musicclass));
    07443          p->amaflags = user->amaflags;
    07444          p->callgroup = user->callgroup;
    07445          p->pickupgroup = user->pickupgroup;
    07446          if (user->callingpres)
    07447             p->callingpres = user->callingpres;
    07448          p->capability = user->capability;
    07449          p->jointcapability = user->capability;
    07450          if (p->peercapability)
    07451             p->jointcapability &= p->peercapability;
    07452          if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
    07453             p->noncodeccapability |= AST_RTP_DTMF;
    07454          else
    07455             p->noncodeccapability &= ~AST_RTP_DTMF;
    07456          p->jointnoncodeccapability = p->noncodeccapability;
    07457       }
    07458       if (user && debug)
    07459          ast_verbose("Found user '%s'\n", user->name);
    07460    } else {
    07461       if (user) {
    07462          if (!mailbox && debug)
    07463             ast_verbose("Found user '%s', but fails host access\n", user->name);
    07464          ASTOBJ_UNREF(user,sip_destroy_user);
    07465       }
    07466       user = NULL;
    07467    }
    07468
    07469    if (!user) {
    07470       /* If we didn't find a user match, check for peers */
    07471       if (sipmethod == SIP_SUBSCRIBE)
    07472          /* For subscribes, match on peer name only */
    07473          peer = find_peer(of, NULL, 1);
    07474       else
    07475          /* Look for peer based on the IP address we received data from */
    07476          /* If peer is registered from this IP address or have this as a default
    07477             IP address, this call is from the peer
    07478          */
    07479          peer = find_peer(NULL, &p->recv, 1);
    07480
    07481       if (peer) {
    07482          if (debug)
    07483             ast_verbose("Found peer '%s'\n", peer->name);
    07484          /* Take the peer */
    07485          ast_copy_flags(p, peer, SIP_FLAGS_TO_COPY);
    07486
    07487          /* Copy SIP extensions profile to peer */
    07488          if (p->sipoptions)
    07489             peer->sipoptions = p->sipoptions;
    07490
    07491          /* replace callerid if rpid found, and not restricted */
    07492          if (!ast_strlen_zero(rpid_num) && ast_test_flag(p, SIP_TRUSTRPID)) {
    07493             if (*calleridname)
    07494                ast_copy_string(p->cid_name, calleridname, sizeof(p->cid_name));
    07495             ast_copy_string(p->cid_num, rpid_num, sizeof(p->cid_num));
    07496             ast_shrink_phone_number(p->cid_num);
    07497          }
    07498          if (p->rtp) {
    07499             ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    07500             ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    07501          }
    07502          if (p->vrtp) {
    07503             ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    07504             ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
    07505          }
    07506          ast_copy_string(p->peersecret, peer->secret, sizeof(p->peersecret));
    07507          p->peersecret[sizeof(p->peersecret)-1] = '\0';
    07508          ast_copy_string(p->subscribecontext, peer->subscribecontext, sizeof(p->subscribecontext));
    07509          ast_copy_string(p->peermd5secret, peer->md5secret, sizeof(p->peermd5secret));
    07510          p->peermd5secret[sizeof(p->peermd5secret)-1] = '\0';
    07511          if (peer->callingpres)
    07512             p->callingpres = peer->callingpres;
    07513          if (peer->maxms && peer->lastms)
    07514             p->timer_t1 = peer->lastms;
    07515          if (ast_test_flag(peer, SIP_INSECURE_INVITE)) {
    07516             /* Pretend there is no required authentication */
    07517             p->peersecret[0] = '\0';
    07518             p->peermd5secret[0] = '\0';
    07519          }
    07520          if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ignore))) {
    07521             ast_copy_flags(p, peer, SIP_FLAGS_TO_COPY);
    07522             /* If we have a call limit, set flag */
    07523             if (peer->call_limit)
    07524                ast_set_flag(p, SIP_CALL_LIMIT);
    07525             ast_copy_string(p->peername, peer->name, sizeof(p->peername));
    07526             ast_copy_string(p->authname, peer->name, sizeof(p->authname));
    07527             /* copy channel vars */
    07528             for (v = peer->chanvars ; v ; v = v->next) {
    07529                if ((tmpvar = ast_variable_new(v->name, v->value))) {
    07530                   tmpvar->next = p->chanvars;
    07531                   p->chanvars = tmpvar;
    07532                }
    07533             }
    07534             if (mailbox)
    07535                snprintf(mailbox, mailboxlen, ",%s,", peer->mailbox);
    07536             if (!ast_strlen_zero(peer->username)) {
    07537                ast_copy_string(p->username, peer->username, sizeof(p->username));
    07538                /* Use the default username for authentication on outbound calls */
    07539                ast_copy_string(p->authname, peer->username, sizeof(p->authname));
    07540             }
    07541             if (!ast_strlen_zero(peer->cid_num) && !ast_strlen_zero(p->cid_num))  {
    07542                ast_copy_string(p->cid_num, peer->cid_num, sizeof(p->cid_num));
    07543                ast_shrink_phone_number(p->cid_num);
    07544             }
    07545             if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name))
    07546                ast_copy_string(p->cid_name, peer->cid_name, sizeof(p->cid_name));
    07547             ast_copy_string(p->fullcontact, peer->fullcontact, sizeof(p->fullcontact));
    07548             if (!ast_strlen_zero(peer->context))
    07549                ast_copy_string(p->context, peer->context, sizeof(p->context));
    07550             ast_copy_string(p->peersecret, peer->secret, sizeof(p->peersecret));
    07551             ast_copy_string(p->peermd5secret, peer->md5secret, sizeof(p->peermd5secret));
    07552             ast_copy_string(p->language, peer->language, sizeof(p->language));
    07553             ast_copy_string(p->accountcode, peer->accountcode, sizeof(p->accountcode));
    07554             p->amaflags = peer->amaflags;
    07555             p->callgroup = peer->callgroup;
    07556             p->pickupgroup = peer->pickupgroup;
    07557             p->capability = peer->capability;
    07558             p->prefs = peer->prefs;
    07559             p->jointcapability = peer->capability;
    07560             if (p->peercapability)
    07561                p->jointcapability &= p->peercapability;
    07562             if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
    07563                p->noncodeccapability |= AST_RTP_DTMF;
    07564             else
    07565                p->noncodeccapability &= ~AST_RTP_DTMF;
    07566             p->jointnoncodeccapability = p->noncodeccapability;
    07567          }
    07568          ASTOBJ_UNREF(peer,sip_destroy_peer);
    07569       } else {
    07570          if (debug)
    07571             ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
    07572
    07573          /* do we allow guests? */
    07574          if (!global_allowguest) {
    07575             if (global_alwaysauthreject)
    07576                res = -4; /* reject with fake authorization request */
    07577             else
    07578                res = -1; /* we don't want any guests, authentication will fail */
    07579 #ifdef OSP_SUPPORT
    07580          } else if (global_allowguest == 2) {
    07581             ast_copy_flags(p, &global_flags, SIP_OSPAUTH);
    07582             res = check_auth(p, req, p->randdata, sizeof(p->randdata), "", "", "", sipmethod, uri2, reliable, ignore);
    07583 #endif
    07584          } else if (!ast_strlen_zero(rpid_num) && ast_test_flag(p, SIP_TRUSTRPID)) {
    07585             if (*calleridname)
    07586                ast_copy_string(p->cid_name, calleridname, sizeof(p->cid_name));
    07587             ast_copy_string(p->cid_num, rpid_num, sizeof(p->cid_num));
    07588             ast_shrink_phone_number(p->cid_num);
    07589          }
    07590       }
    07591
    07592    }
    07593
    07594    if (user)
    07595       ASTOBJ_UNREF(user,sip_destroy_user);
    07596    return res;
    07597 }
    07598
    07599 /*! \brief  check_user: Find user ---*/
    07600 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, int reliable, struct sockaddr_in *sin, int ignore)
    07601 {
    07602    return check_user_full(p, req, sipmethod, uri, reliable, sin, ignore, NULL, 0);
    07603 }
    07604
    07605 /*! \brief  get_msg_text: Get text out of a SIP MESSAGE packet ---*/
    07606 static int get_msg_text(char *buf, int len, struct sip_request *req)
    07607 {
    07608    int x;
    07609    int y;
    07610
    07611    buf[0] = '\0';
    07612    y = len - strlen(buf) - 5;
    07613    if (y < 0)
    07614       y = 0;
    07615    for (x=0;x<req->lines;x++) {
    07616       strncat(buf, req->line[x], y); /* safe */
    07617       y -= strlen(req->line[x]) + 1;
    07618       if (y < 0)
    07619          y = 0;
    07620       if (y != 0)
    07621          strcat(buf, "\n"); /* safe */
    07622    }
    07623    return 0;
    07624 }
    07625
    07626
    07627 /*! \brief  receive_message: Receive SIP MESSAGE method messages ---*/
    07628 /* We only handle messages within current calls currently */
    07629 /* Reference: RFC 3428 */
    07630 static void receive_message(struct sip_pvt *p, struct sip_request *req)
    07631 {
    07632    char buf[1024];
    07633    struct ast_frame f;
    07634    char *content_type;
    07635
    07636    content_type = get_header(req, "Content-Type");
    07637    if (strcmp(content_type, "text/plain")) { /* No text/plain attachment */
    07638       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
    07639       ast_set_flag(p, SIP_NEEDDESTROY);
    07640       return;
    07641    }
    07642
    07643    if (get_msg_text(buf, sizeof(buf), req)) {
    07644       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
    07645       transmit_response(p, "202 Accepted", req);
    07646       ast_set_flag(p, SIP_NEEDDESTROY);
    07647       return;
    07648    }
    07649
    07650    if (p->owner) {
    07651       if (sip_debug_test_pvt(p))
    07652          ast_verbose("Message received: '%s'\n", buf);
    07653       memset(&f, 0, sizeof(f));
    07654       f.frametype = AST_FRAME_TEXT;
    07655       f.subclass = 0;
    07656       f.offset = 0;
    07657       f.data = buf;
    07658       f.datalen = strlen(buf);
    07659       ast_queue_frame(p->owner, &f);
    07660       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
    07661    } else { /* Message outside of a call, we do not support that */
    07662       ast_log(LOG_WARNING,"Received message to %s from %s, dropped it...\n  Content-Type:%s\n  Message: %s\n", get_header(req,"To"), get_header(req,"From"), content_type, buf);
    07663       transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
    07664    }
    07665    ast_set_flag(p, SIP_NEEDDESTROY);
    07666    return;
    07667 }
    07668
    07669 /*! \brief  sip_show_inuse: CLI Command to show calls within limits set by
    07670       call_limit ---*/
    07671 static int sip_show_inuse(int fd, int argc, char *argv[]) {
    07672 #define FORMAT  "%-25.25s %-15.15s %-15.15s \n"
    07673 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
    07674    char ilimits[40];
    07675    char iused[40];
    07676    int showall = 0;
    07677
    07678    if (argc < 3)
    07679       return RESULT_SHOWUSAGE;
    07680
    07681    if (argc == 4 && !strcmp(argv[3],"all"))
    07682          showall = 1;
    07683
    07684    ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
    07685    ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
    07686       ASTOBJ_RDLOCK(iterator);
    07687       if (iterator->call_limit)
    07688          snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
    07689       else
    07690          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
    07691       snprintf(iused, sizeof(iused), "%d", iterator->inUse);
    07692       if (showall || iterator->call_limit)
    07693          ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
    07694       ASTOBJ_UNLOCK(iterator);
    07695    } while (0) );
    07696
    07697    ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");
    07698
    07699    ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
    07700       ASTOBJ_RDLOCK(iterator);
    07701       if (iterator->call_limit)
    07702          snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
    07703       else
    07704          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
    07705       snprintf(iused, sizeof(iused), "%d", iterator->inUse);
    07706       if (showall || iterator->call_limit)
    07707          ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
    07708       ASTOBJ_UNLOCK(iterator);
    07709    } while (0) );
    07710
    07711    return RESULT_SUCCESS;
    07712 #undef FORMAT
    07713 #undef FORMAT2
    07714 }
    07715
    07716 /*! \brief  nat2str: Convert NAT setting to text string */
    07717 static char *nat2str(int nat)
    07718 {
    07719    switch(nat) {
    07720    case SIP_NAT_NEVER:
    07721       return "No";
    07722    case SIP_NAT_ROUTE:
    07723       return "Route";
    07724    case SIP_NAT_ALWAYS:
    07725       return "Always";
    07726    case SIP_NAT_RFC3581:
    07727       return "RFC3581";
    07728    default:
    07729       return "Unknown";
    07730    }
    07731 }
    07732
    07733 /*! \brief  peer_status: Report Peer status in character string */
    07734 /*    returns 1 if peer is online, -1 if unmonitored */
    07735 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
    07736 {
    07737    int res = 0;
    07738    if (peer->maxms) {
    07739       if (peer->lastms < 0) {
    07740          ast_copy_string(status, "UNREACHABLE", statuslen);
    07741       } else if (peer->lastms > peer->maxms) {
    07742          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
    07743          res = 1;
    07744       } else if (peer->lastms) {
    07745          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
    07746          res = 1;
    07747       } else {
    07748          ast_copy_string(status, "UNKNOWN", statuslen);
    07749       }
    07750    } else {
    07751       ast_copy_string(status, "Unmonitored", statuslen);
    07752       /* Checking if port is 0 */
    07753       res = -1;
    07754    }
    07755    return res;
    07756 }
    07757
    07758 /*! \brief  sip_show_users: CLI Command 'SIP Show Users' ---*/
    07759 static int sip_show_users(int fd, int argc, char *argv[])
    07760 {
    07761    regex_t regexbuf;
    07762    int havepattern = 0;
    07763
    07764 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
    07765
    07766    switch (argc) {
    07767    case 5:
    07768       if (!strcasecmp(argv[3], "like")) {
    07769          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
    07770             return RESULT_SHOWUSAGE;
    07771          havepattern = 1;
    07772       } else
    07773          return RESULT_SHOWUSAGE;
    07774    case 3:
    07775       break;
    07776    default:
    07777       return RESULT_SHOWUSAGE;
    07778    }
    07779
    07780    ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
    07781    ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
    07782       ASTOBJ_RDLOCK(iterator);
    07783
    07784       if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
    07785          ASTOBJ_UNLOCK(iterator);
    07786          continue;
    07787       }
    07788
    07789       ast_cli(fd, FORMAT, iterator->name,
    07790          iterator->secret,
    07791          iterator->accountcode,
    07792          iterator->context,
    07793          iterator->ha ? "Yes" : "No",
    07794          nat2str(ast_test_flag(iterator, SIP_NAT)));
    07795       ASTOBJ_UNLOCK(iterator);
    07796    } while (0)
    07797    );
    07798
    07799    if (havepattern)
    07800       regfree(&regexbuf);
    07801
    07802    return RESULT_SUCCESS;
    07803 #undef FORMAT
    07804 }
    07805
    07806 static char mandescr_show_peers[] =
    07807 "Description: Lists SIP peers in text format with details on current status.\n"
    07808 "Variables: \n"
    07809 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
    07810
    07811 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
    07812
    07813 /*! \brief  manager_sip_show_peers: Show SIP peers in the manager API ---*/
    07814 /*    Inspired from chan_iax2 */
    07815 static int manager_sip_show_peers( struct mansession *s, struct message *m )
    07816 {
    07817    char *id = astman_get_header(m,"ActionID");
    07818    char *a[] = { "sip", "show", "peers" };
    07819    char idtext[256] = "";
    07820    int total = 0;
    07821
    07822    if (!ast_strlen_zero(id))
    07823       snprintf(idtext,256,"ActionID: %s\r\n",id);
    07824
    07825    astman_send_ack(s, m, "Peer status list will follow");
    07826    /* List the peers in separate manager events */
    07827    _sip_show_peers(s->fd, &total, s, m, 3, a);
    07828    /* Send final confirmation */
    07829    ast_cli(s->fd,
    07830    "Event: PeerlistComplete\r\n"
    07831    "ListItems: %d\r\n"
    07832    "%s"
    07833    "\r\n", total, idtext);
    07834    return 0;
    07835 }
    07836
    07837 /*! \brief  sip_show_peers: CLI Show Peers command */
    07838 static int sip_show_peers(int fd, int argc, char *argv[])
    07839 {
    07840    return _sip_show_peers(fd, NULL, NULL, NULL, argc, argv);
    07841 }
    07842
    07843 /*! \brief  _sip_show_peers: Execute sip show peers command */
    07844 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[])
    07845 {
    07846    regex_t regexbuf;
    07847    int havepattern = 0;
    07848
    07849 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s\n"
    07850 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s\n"
    07851
    07852    char name[256];
    07853    char iabuf[INET_ADDRSTRLEN];
    07854    int total_peers = 0;
    07855    int peers_online = 0;
    07856    int peers_offline = 0;
    07857    char *id;
    07858    char idtext[256] = "";
    07859
    07860    if (s) { /* Manager - get ActionID */
    07861       id = astman_get_header(m,"ActionID");
    07862       if (!ast_strlen_zero(id))
    07863          snprintf(idtext,256,"ActionID: %s\r\n",id);
    07864    }
    07865
    07866    switch (argc) {
    07867    case 5:
    07868       if (!strcasecmp(argv[3], "like")) {
    07869          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
    07870             return RESULT_SHOWUSAGE;
    07871          havepattern = 1;
    07872       } else
    07873          return RESULT_SHOWUSAGE;
    07874    case 3:
    07875       break;
    07876    default:
    07877       return RESULT_SHOWUSAGE;
    07878    }
    07879
    07880    if (!s) { /* Normal list */
    07881       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status");
    07882    }
    07883
    07884    ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
    07885       char status[20] = "";
    07886       char srch[2000];
    07887       char pstatus;
    07888
    07889       ASTOBJ_RDLOCK(iterator);
    07890
    07891       if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
    07892          ASTOBJ_UNLOCK(iterator);
    07893          continue;
    07894       }
    07895
    07896       if (!ast_strlen_zero(iterator->username) && !s)
    07897          snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
    07898       else
    07899          ast_copy_string(name, iterator->name, sizeof(name));
    07900
    07901       pstatus = peer_status(iterator, status, sizeof(status));
    07902       if (pstatus)
    07903          peers_online++;
    07904       else  {
    07905          if (pstatus == 0)
    07906             peers_offline++;
    07907          else {   /* Unmonitored */
    07908             /* Checking if port is 0 */
    07909             if ( ntohs(iterator->addr.sin_port) == 0 ) {
    07910                peers_offline++;
    07911             } else {
    07912                peers_online++;
    07913             }
    07914          }
    07915       }
    07916
    07917       snprintf(srch, sizeof(srch), FORMAT, name,
    07918          iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), iterator->addr.sin_addr) : "(Unspecified)",
    07919          ast_test_flag(&iterator->flags_page2, SIP_PAGE2_DYNAMIC) ? " D " : "   ",  /* Dynamic or not? */
    07920          (ast_test_flag(iterator, SIP_NAT) & SIP_NAT_ROUTE) ? " N " : "   ",  /* NAT=yes? */
    07921          iterator->ha ? " A " : "   ",    /* permit/deny */
    07922          ntohs(iterator->addr.sin_port), status);
    07923
    07924       if (!s)  {/* Normal CLI list */
    07925          ast_cli(fd, FORMAT, name,
    07926          iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), iterator->addr.sin_addr) : "(Unspecified)",
    07927          ast_test_flag(&iterator->flags_page2, SIP_PAGE2_DYNAMIC) ? " D " : "   ",  /* Dynamic or not? */
    07928          (ast_test_flag(iterator, SIP_NAT) & SIP_NAT_ROUTE) ? " N " : "   ",  /* NAT=yes? */
    07929          iterator->ha ? " A " : "   ",       /* permit/deny */
    07930
    07931          ntohs(iterator->addr.sin_port), status);
    07932       } else { /* Manager format */
    07933          /* The names here need to be the same as other channels */
    07934          ast_cli(fd,
    07935          "Event: PeerEntry\r\n%s"
    07936          "Channeltype: SIP\r\n"
    07937          "ObjectName: %s\r\n"
    07938          "ChanObjectType: peer\r\n" /* "peer" or "user" */
    07939          "IPaddress: %s\r\n"
    07940          "IPport: %d\r\n"
    07941          "Dynamic: %s\r\n"
    07942          "Natsupport: %s\r\n"
    07943          "ACL: %s\r\n"
    07944          "Status: %s\r\n\r\n",
    07945          idtext,
    07946          iterator->name,
    07947          iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), iterator->addr.sin_addr) : "-none-",
    07948          ntohs(iterator->addr.sin_port),
    07949          ast_test_flag(&iterator->flags_page2, SIP_PAGE2_DYNAMIC) ? "yes" : "no",  /* Dynamic or not? */
    07950          (ast_test_flag(iterator, SIP_NAT) & SIP_NAT_ROUTE) ? "yes" : "no",   /* NAT=yes? */
    07951          iterator->ha ? "yes" : "no",       /* permit/deny */
    07952          status);
    07953       }
    07954
    07955       ASTOBJ_UNLOCK(iterator);
    07956
    07957       total_peers++;
    07958    } while(0) );
    07959
    07960    if (!s) {
    07961       ast_cli(fd,"%d sip peers [%d online , %d offline]\n",total_peers,peers_online,peers_offline);
    07962    }
    07963
    07964    if (havepattern)
    07965       regfree(&regexbuf);
    07966
    07967    if (total)
    07968       *total = total_peers;
    07969
    07970
    07971    return RESULT_SUCCESS;
    07972 #undef FORMAT
    07973 #undef FORMAT2
    07974 }
    07975
    07976 /*! \brief  sip_show_objects: List all allocated SIP Objects ---*/
    07977 static int sip_show_objects(int fd, int argc, char *argv[])
    07978 {
    07979    char tmp[256];
    07980    if (argc != 3)
    07981       return RESULT_SHOWUSAGE;
    07982    ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
    07983    ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
    07984    ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
    07985    ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
    07986    ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
    07987    ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
    07988    return RESULT_SUCCESS;
    07989 }
    07990 /*! \brief  print_group: Print call group and pickup group ---*/
    07991 static void  print_group(int fd, ast_group_t group, int crlf)
    07992 {
    07993    char buf[256];
    07994    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
    07995 }
    07996
    07997 /*! \brief  dtmfmode2str: Convert DTMF mode to printable string ---*/
    07998 static const char *dtmfmode2str(int mode)
    07999 {
    08000    switch (mode) {
    08001    case SIP_DTMF_RFC2833:
    08002       return "rfc2833";
    08003    case SIP_DTMF_INFO:
    08004       return "info";
    08005    case SIP_DTMF_INBAND:
    08006       return "inband";
    08007    case SIP_DTMF_AUTO:
    08008       return "auto";
    08009    }
    08010    return "<error>";
    08011 }
    08012
    08013 /*! \brief  insecure2str: Convert Insecure setting to printable string ---*/
    08014 static const char *insecure2str(int port, int invite)
    08015 {
    08016    if (port && invite)
    08017       return "port,invite";
    08018    else if (port)
    08019       return "port";
    08020    else if (invite)
    08021       return "invite";
    08022    else
    08023       return "no";
    08024 }
    08025
    08026 /*! \brief  sip_prune_realtime: Remove temporary realtime objects from memory (CLI) ---*/
    08027 static int sip_prune_realtime(int fd, int argc, char *argv[])
    08028 {
    08029    struct sip_peer *peer;
    08030    struct sip_user *user;
    08031    int pruneuser = 0;
    08032    int prunepeer = 0;
    08033    int multi = 0;
    08034    char *name = NULL;
    08035    regex_t regexbuf;
    08036
    08037    switch (argc) {
    08038    case 4:
    08039       if (!strcasecmp(argv[3], "user"))
    08040          return RESULT_SHOWUSAGE;
    08041       if (!strcasecmp(argv[3], "peer"))
    08042          return RESULT_SHOWUSAGE;
    08043       if (!strcasecmp(argv[3], "like"))
    08044          return RESULT_SHOWUSAGE;
    08045       if (!strcasecmp(argv[3], "all")) {
    08046          multi = 1;
    08047          pruneuser = prunepeer = 1;
    08048       } else {
    08049          pruneuser = prunepeer = 1;
    08050          name = argv[3];
    08051       }
    08052       break;
    08053    case 5:
    08054       if (!strcasecmp(argv[4], "like"))
    08055          return RESULT_SHOWUSAGE;
    08056       if (!strcasecmp(argv[3], "all"))
    08057          return RESULT_SHOWUSAGE;
    08058       if (!strcasecmp(argv[3], "like")) {
    08059          multi = 1;
    08060          name = argv[4];
    08061          pruneuser = prunepeer = 1;
    08062       } else if (!strcasecmp(argv[3], "user")) {
    08063          pruneuser = 1;
    08064          if (!strcasecmp(argv[4], "all"))
    08065             multi = 1;
    08066          else
    08067             name = argv[4];
    08068       } else if (!strcasecmp(argv[3], "peer")) {
    08069          prunepeer = 1;
    08070          if (!strcasecmp(argv[4], "all"))
    08071             multi = 1;
    08072          else
    08073             name = argv[4];
    08074       } else
    08075          return RESULT_SHOWUSAGE;
    08076       break;
    08077    case 6:
    08078       if (strcasecmp(argv[4], "like"))
    08079          return RESULT_SHOWUSAGE;
    08080       if (!strcasecmp(argv[3], "user")) {
    08081          pruneuser = 1;
    08082          name = argv[5];
    08083       } else if (!strcasecmp(argv[3], "peer")) {
    08084          prunepeer = 1;
    08085          name = argv[5];
    08086       } else
    08087          return RESULT_SHOWUSAGE;
    08088       break;
    08089    default:
    08090       return RESULT_SHOWUSAGE;
    08091    }
    08092
    08093    if (multi && name) {
    08094       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
    08095          return RESULT_SHOWUSAGE;
    08096    }
    08097
    08098    if (multi) {
    08099       if (prunepeer) {
    08100          int pruned = 0;
    08101
    08102          ASTOBJ_CONTAINER_WRLOCK(&peerl);
    08103          ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
    08104             ASTOBJ_RDLOCK(iterator);
    08105             if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
    08106                ASTOBJ_UNLOCK(iterator);
    08107                continue;
    08108             };
    08109             if (ast_test_flag((&iterator->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
    08110                ASTOBJ_MARK(iterator);
    08111                pruned++;
    08112             }
    08113             ASTOBJ_UNLOCK(iterator);
    08114          } while (0) );
    08115          if (pruned) {
    08116             ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
    08117             ast_cli(fd, "%d peers pruned.\n", pruned);
    08118          } else
    08119             ast_cli(fd, "No peers found to prune.\n");
    08120          ASTOBJ_CONTAINER_UNLOCK(&peerl);
    08121       }
    08122       if (pruneuser) {
    08123          int pruned = 0;
    08124
    08125          ASTOBJ_CONTAINER_WRLOCK(&userl);
    08126          ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
    08127             ASTOBJ_RDLOCK(iterator);
    08128             if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
    08129                ASTOBJ_UNLOCK(iterator);
    08130                continue;
    08131             };
    08132             if (ast_test_flag((&iterator->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
    08133                ASTOBJ_MARK(iterator);
    08134                pruned++;
    08135             }
    08136             ASTOBJ_UNLOCK(iterator);
    08137          } while (0) );
    08138          if (pruned) {
    08139             ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
    08140             ast_cli(fd, "%d users pruned.\n", pruned);
    08141          } else
    08142             ast_cli(fd, "No users found to prune.\n");
    08143          ASTOBJ_CONTAINER_UNLOCK(&userl);
    08144       }
    08145    } else {
    08146       if (prunepeer) {
    08147          if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
    08148             if (!ast_test_flag((&peer->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
    08149                ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
    08150                ASTOBJ_CONTAINER_LINK(&peerl, peer);
    08151             } else
    08152                ast_cli(fd, "Peer '%s' pruned.\n", name);
    08153             ASTOBJ_UNREF(peer, sip_destroy_peer);
    08154          } else
    08155             ast_cli(fd, "Peer '%s' not found.\n", name);
    08156       }
    08157       if (pruneuser) {
    08158          if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
    08159             if (!ast_test_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
    08160                ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
    08161                ASTOBJ_CONTAINER_LINK(&userl, user);
    08162             } else
    08163                ast_cli(fd, "User '%s' pruned.\n", name);
    08164             ASTOBJ_UNREF(user, sip_destroy_user);
    08165          } else
    08166             ast_cli(fd, "User '%s' not found.\n", name);
    08167       }
    08168    }
    08169
    08170    return RESULT_SUCCESS;
    08171 }
    08172
    08173 /*! \brief  print_codec_to_cli: Print codec list from preference to CLI/manager */
    08174 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
    08175 {
    08176    int x, codec;
    08177
    08178    for(x = 0; x < 32 ; x++) {
    08179       codec = ast_codec_pref_index(pref, x);
    08180       if (!codec)
    08181          break;
    08182       ast_cli(fd, "%s", ast_getformatname(codec));
    08183       if (x < 31 && ast_codec_pref_index(pref, x + 1))
    08184          ast_cli(fd, ",");
    08185    }
    08186    if (!x)
    08187       ast_cli(fd, "none");
    08188 }
    08189
    08190 static const char *domain_mode_to_text(const enum domain_mode mode)
    08191 {
    08192    switch (mode) {
    08193    case SIP_DOMAIN_AUTO:
    08194       return "[Automatic]";
    08195    case SIP_DOMAIN_CONFIG:
    08196       return "[Configured]";
    08197    }
    08198
    08199    return "";
    08200 }
    08201
    08202 /*! \brief  sip_show_domains: CLI command to list local domains */
    08203 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
    08204 static int sip_show_domains(int fd, int argc, char *argv[])
    08205 {
    08206    struct domain *d;
    08207
    08208    if (AST_LIST_EMPTY(&domain_list)) {
    08209       ast_cli(fd, "SIP Domain support not enabled.\n\n");
    08210       return RESULT_SUCCESS;
    08211    } else {
    08212       ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
    08213       AST_LIST_LOCK(&domain_list);
    08214       AST_LIST_TRAVERSE(&domain_list, d, list)
    08215          ast_cli(fd, FORMAT, d->domain, ast_strlen_zero(d->context) ? "(default)": d->context,
    08216             domain_mode_to_text(d->mode));
    08217       AST_LIST_UNLOCK(&domain_list);
    08218       ast_cli(fd, "\n");
    08219       return RESULT_SUCCESS;
    08220    }
    08221 }
    08222 #undef FORMAT
    08223
    08224 static char mandescr_show_peer[] =
    08225 "Description: Show one SIP peer with details on current status.\n"
    08226 "  The XML format is under development, feedback welcome! /oej\n"
    08227 "Variables: \n"
    08228 "  Peer: <name>           The peer name you want to check.\n"
    08229 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
    08230
    08231 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
    08232
    08233 /*! \brief  manager_sip_show_peer: Show SIP peers in the manager API  ---*/
    08234 static int manager_sip_show_peer( struct mansession *s, struct message *m )
    08235 {
    08236    char *a[4];
    08237    char *peer;
    08238    int ret;
    08239
    08240    peer = astman_get_header(m,"Peer");
    08241    if (ast_strlen_zero(peer)) {
    08242       astman_send_error(s, m, "Peer: <name> missing.\n");
    08243       return 0;
    08244    }
    08245    a[0] = "sip";
    08246    a[1] = "show";
    08247    a[2] = "peer";
    08248    a[3] = peer;
    08249
    08250    ret = _sip_show_peer(1, s->fd, s, m, 4, a );
    08251    ast_cli( s->fd, "\r\n\r\n" );
    08252    return ret;
    08253 }
    08254
    08255
    08256
    08257 /*! \brief  sip_show_peer: Show one peer in detail ---*/
    08258 static int sip_show_peer(int fd, int argc, char *argv[])
    08259 {
    08260    return _sip_show_peer(0, fd, NULL, NULL, argc, argv);
    08261 }
    08262
    08263 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[])
    08264 {
    08265    char status[30] = "";
    08266    char cbuf[256];
    08267    char iabuf[INET_ADDRSTRLEN];
    08268    struct sip_peer *peer;
    08269    char codec_buf[512];
    08270    struct ast_codec_pref *pref;
    08271    struct ast_variable *v;
    08272    struct sip_auth *auth;
    08273    int x = 0, codec = 0, load_realtime = 0;
    08274
    08275    if (argc < 4)
    08276       return RESULT_SHOWUSAGE;
    08277
    08278    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
    08279    peer = find_peer(argv[3], NULL, load_realtime);
    08280    if (s) {    /* Manager */
    08281       if (peer) {
    08282          char *id = astman_get_header(m,"ActionID");
    08283
    08284          ast_cli(s->fd, "Response: Success\r\n");
    08285          if (!ast_strlen_zero(id))
    08286             ast_cli(s->fd, "ActionID: %s\r\n",id);
    08287       } else {
    08288          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
    08289          astman_send_error(s, m, cbuf);
    08290          return 0;
    08291       }
    08292    }
    08293    if (peer && type==0 ) { /* Normal listing */
    08294       ast_cli(fd,"\n\n");
    08295       ast_cli(fd, "  * Name       : %s\n", peer->name);
    08296       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
    08297       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
    08298       auth = peer->auth;
    08299       while(auth) {
    08300          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
    08301          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
    08302          auth = auth->next;
    08303       }
    08304       ast_cli(fd, "  Context      : %s\n", peer->context);
    08305       ast_cli(fd, "  Subscr.Cont. : %s\n", ast_strlen_zero(peer->subscribecontext)?"<Not set>":peer->subscribecontext);
    08306       ast_cli(fd, "  Language     : %s\n", peer->language);
    08307       if (!ast_strlen_zero(peer->accountcode))
    08308          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
    08309       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
    08310       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
    08311       if (!ast_strlen_zero(peer->fromuser))
    08312          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
    08313       if (!ast_strlen_zero(peer->fromdomain))
    08314          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
    08315       ast_cli(fd, "  Callgroup    : ");
    08316       print_group(fd, peer->callgroup, 0);
    08317       ast_cli(fd, "  Pickupgroup  : ");
    08318       print_group(fd, peer->pickupgroup, 0);
    08319       ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
    08320       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
    08321       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
    08322       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
    08323       ast_cli(fd, "  Dynamic      : %s\n", (ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC)?"Yes":"No"));
    08324       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
    08325       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
    08326       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(peer, SIP_INSECURE_PORT), ast_test_flag(peer, SIP_INSECURE_INVITE)));
    08327       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(peer, SIP_NAT)));
    08328       ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
    08329       ast_cli(fd, "  CanReinvite  : %s\n", (ast_test_flag(peer, SIP_CAN_REINVITE)?"Yes":"No"));
    08330       ast_cli(fd, "  PromiscRedir : %s\n", (ast_test_flag(peer, SIP_PROMISCREDIR)?"Yes":"No"));
    08331       ast_cli(fd, "  User=Phone   : %s\n", (ast_test_flag(peer, SIP_USEREQPHONE)?"Yes":"No"));
    08332       ast_cli(fd, "  Trust RPID   : %s\n", (ast_test_flag(peer, SIP_TRUSTRPID) ? "Yes" : "No"));
    08333       ast_cli(fd, "  Send RPID    : %s\n", (ast_test_flag(peer, SIP_SENDRPID) ? "Yes" : "No"));
    08334
    08335       /* - is enumerated */
    08336       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(peer, SIP_DTMF)));
    08337       ast_cli(fd, "  LastMsg      : %d\n", peer->lastmsg);
    08338       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
    08339       ast_cli(fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
    08340       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
    08341       ast_cli(fd, "  Def. Username: %s\n", peer->username);
    08342       ast_cli(fd, "  SIP Options  : ");
    08343       if (peer->sipoptions) {
    08344          for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
    08345             if (peer->sipoptions & sip_options[x].id)
    08346                ast_cli(fd, "%s ", sip_options[x].text);
    08347          }
    08348       } else
    08349          ast_cli(fd, "(none)");
    08350
    08351       ast_cli(fd, "\n");
    08352       ast_cli(fd, "  Codecs       : ");
    08353       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
    08354       ast_cli(fd, "%s\n", codec_buf);
    08355       ast_cli(fd, "  Codec Order  : (");
    08356       print_codec_to_cli(fd, &peer->prefs);
    08357
    08358       ast_cli(fd, ")\n");
    08359
    08360       ast_cli(fd, "  Status       : ");
    08361       peer_status(peer, status, sizeof(status));
    08362       ast_cli(fd, "%s\n",status);
    08363       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
    08364       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
    08365       if (peer->chanvars) {
    08366          ast_cli(fd, "  Variables    :\n");
    08367          for (v = peer->chanvars ; v ; v = v->next)
    08368             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
    08369       }
    08370       ast_cli(fd,"\n");
    08371       ASTOBJ_UNREF(peer,sip_destroy_peer);
    08372    } else  if (peer && type == 1) { /* manager listing */
    08373       ast_cli(fd, "Channeltype: SIP\r\n");
    08374       ast_cli(fd, "ObjectName: %s\r\n", peer->name);
    08375       ast_cli(fd, "ChanObjectType: peer\r\n");
    08376       ast_cli(fd, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
    08377       ast_cli(fd, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
    08378       ast_cli(fd, "Context: %s\r\n", peer->context);
    08379       ast_cli(fd, "Language: %s\r\n", peer->language);
    08380       if (!ast_strlen_zero(peer->accountcode))
    08381          ast_cli(fd, "Accountcode: %s\r\n", peer->accountcode);
    08382       ast_cli(fd, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
    08383       ast_cli(fd, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
    08384       if (!ast_strlen_zero(peer->fromuser))
    08385          ast_cli(fd, "SIP-FromUser: %s\r\n", peer->fromuser);
    08386       if (!ast_strlen_zero(peer->fromdomain))
    08387          ast_cli(fd, "SIP-FromDomain: %s\r\n", peer->fromdomain);
    08388       ast_cli(fd, "Callgroup: ");
    08389       print_group(fd, peer->callgroup, 1);
    08390       ast_cli(fd, "Pickupgroup: ");
    08391       print_group(fd, peer->pickupgroup, 1);
    08392       ast_cli(fd, "VoiceMailbox: %s\r\n", peer->mailbox);
    08393       ast_cli(fd, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
    08394       ast_cli(fd, "Call-limit: %d\r\n", peer->call_limit);
    08395       ast_cli(fd, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC)?"Y":"N"));
    08396       ast_cli(fd, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
    08397       ast_cli(fd, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
    08398       ast_cli(fd, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(peer, SIP_INSECURE_PORT), ast_test_flag(peer, SIP_INSECURE_INVITE)));
    08399       ast_cli(fd, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(peer, SIP_NAT)));
    08400       ast_cli(fd, "ACL: %s\r\n", (peer->ha?"Y":"N"));
    08401       ast_cli(fd, "SIP-CanReinvite: %s\r\n", (ast_test_flag(peer, SIP_CAN_REINVITE)?"Y":"N"));
    08402       ast_cli(fd, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(peer, SIP_PROMISCREDIR)?"Y":"N"));
    08403       ast_cli(fd, "SIP-UserPhone: %s\r\n", (ast_test_flag(peer, SIP_USEREQPHONE)?"Y":"N"));
    08404
    08405       /* - is enumerated */
    08406       ast_cli(fd, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(peer, SIP_DTMF)));
    08407       ast_cli(fd, "SIPLastMsg: %d\r\n", peer->lastmsg);
    08408       ast_cli(fd, "ToHost: %s\r\n", peer->tohost);
    08409       ast_cli(fd, "Address-IP: %s\r\nAddress-Port: %d\r\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
    08410       ast_cli(fd, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
    08411       ast_cli(fd, "Default-Username: %s\r\n", peer->username);
    08412       ast_cli(fd, "Codecs: ");
    08413       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
    08414       ast_cli(fd, "%s\r\n", codec_buf);
    08415       ast_cli(fd, "CodecOrder: ");
    08416       pref = &peer->prefs;
    08417       for(x = 0; x < 32 ; x++) {
    08418          codec = ast_codec_pref_index(pref,x);
    08419          if (!codec)
    08420             break;
    08421          ast_cli(fd, "%s", ast_getformatname(codec));
    08422          if (x < 31 && ast_codec_pref_index(pref,x+1))
    08423             ast_cli(fd, ",");
    08424       }
    08425
    08426       ast_cli(fd, "\r\n");
    08427       ast_cli(fd, "Status: ");
    08428       peer_status(peer, status, sizeof(status));
    08429       ast_cli(fd, "%s\r\n", status);
    08430       ast_cli(fd, "SIP-Useragent: %s\r\n", peer->useragent);
    08431       ast_cli(fd, "Reg-Contact : %s\r\n", peer->fullcontact);
    08432       if (peer->chanvars) {
    08433          for (v = peer->chanvars ; v ; v = v->next) {
    08434             ast_cli(fd, "ChanVariable:\n");
    08435             ast_cli(fd, " %s,%s\r\n", v->name, v->value);
    08436          }
    08437       }
    08438
    08439       ASTOBJ_UNREF(peer,sip_destroy_peer);
    08440
    08441    } else {
    08442       ast_cli(fd,"Peer %s not found.\n", argv[3]);
    08443       ast_cli(fd,"\n");
    08444    }
    08445
    08446    return RESULT_SUCCESS;
    08447 }
    08448
    08449 /*! \brief  sip_show_user: Show one user in detail ---*/
    08450 static int sip_show_user(int fd, int argc, char *argv[])
    08451 {
    08452    char cbuf[256];
    08453    struct sip_user *user;
    08454    struct ast_codec_pref *pref;
    08455    struct ast_variable *v;
    08456    int x = 0, codec = 0, load_realtime = 0;
    08457
    08458    if (argc < 4)
    08459       return RESULT_SHOWUSAGE;
    08460
    08461    /* Load from realtime storage? */
    08462    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
    08463
    08464    user = find_user(argv[3], load_realtime);
    08465    if (user) {
    08466       ast_cli(fd,"\n\n");
    08467       ast_cli(fd, "  * Name       : %s\n", user->name);
    08468       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
    08469       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
    08470       ast_cli(fd, "  Context      : %s\n", user->context);
    08471       ast_cli(fd, "  Language     : %s\n", user->language);
    08472       if (!ast_strlen_zero(user->accountcode))
    08473          ast_cli(fd, "  Accountcode  : %s\n", user->accountcode);
    08474       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
    08475       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
    08476       ast_cli(fd, "  Call limit   : %d\n", user->call_limit);
    08477       ast_cli(fd, "  Callgroup    : ");
    08478       print_group(fd, user->callgroup, 0);
    08479       ast_cli(fd, "  Pickupgroup  : ");
    08480       print_group(fd, user->pickupgroup, 0);
    08481       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
    08482       ast_cli(fd, "  ACL          : %s\n", (user->ha?"Yes":"No"));
    08483       ast_cli(fd, "  Codec Order  : (");
    08484       pref = &user->prefs;
    08485       for(x = 0; x < 32 ; x++) {
    08486          codec = ast_codec_pref_index(pref,x);
    08487          if (!codec)
    08488             break;
    08489          ast_cli(fd, "%s", ast_getformatname(codec));
    08490          if (x < 31 && ast_codec_pref_index(pref,x+1))
    08491             ast_cli(fd, "|");
    08492       }
    08493
    08494       if (!x)
    08495          ast_cli(fd, "none");
    08496       ast_cli(fd, ")\n");
    08497
    08498       if (user->chanvars) {
    08499          ast_cli(fd, "  Variables    :\n");
    08500          for (v = user->chanvars ; v ; v = v->next)
    08501             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
    08502       }
    08503       ast_cli(fd,"\n");
    08504       ASTOBJ_UNREF(user,sip_destroy_user);
    08505    } else {
    08506       ast_cli(fd,"User %s not found.\n", argv[3]);
    08507       ast_cli(fd,"\n");
    08508    }
    08509
    08510    return RESULT_SUCCESS;
    08511 }
    08512
    08513 /*! \brief  sip_show_registry: Show SIP Registry (registrations with other SIP proxies ---*/
    08514 static int sip_show_registry(int fd, int argc, char *argv[])
    08515 {
    08516 #define FORMAT2 "%-30.30s  %-12.12s  %8.8s %-20.20s\n"
    08517 #define FORMAT  "%-30.30s  %-12.12s  %8d %-20.20s\n"
    08518    char host[80];
    08519
    08520    if (argc != 3)
    08521       return RESULT_SHOWUSAGE;
    08522    ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
    08523    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
    08524       ASTOBJ_RDLOCK(iterator);
    08525       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : DEFAULT_SIP_PORT);
    08526       ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate));
    08527       ASTOBJ_UNLOCK(iterator);
    08528    } while(0));
    08529    return RESULT_SUCCESS;
    08530 #undef FORMAT
    08531 #undef FORMAT2
    08532 }
    08533
    08534 /*! \brief  sip_show_settings: List global settings for the SIP channel ---*/
    08535 static int sip_show_settings(int fd, int argc, char *argv[])
    08536 {
    08537    char tmp[BUFSIZ];
    08538    int realtimepeers = 0;
    08539    int realtimeusers = 0;
    08540
    08541    realtimepeers = ast_check_realtime("sippeers");
    08542    realtimeusers = ast_check_realtime("sipusers");
    08543
    08544    if (argc != 3)
    08545       return RESULT_SHOWUSAGE;
    08546    ast_cli(fd, "\n\nGlobal Settings:\n");
    08547    ast_cli(fd, "----------------\n");
    08548    ast_cli(fd, "  SIP Port:               %d\n", ntohs(bindaddr.sin_port));
    08549    ast_cli(fd, "  Bindaddress:            %s\n", ast_inet_ntoa(tmp, sizeof(tmp), bindaddr.sin_addr));
    08550    ast_cli(fd, "  Videosupport:           %s\n", videosupport ? "Yes" : "No");
    08551    ast_cli(fd, "  AutoCreatePeer:         %s\n", autocreatepeer ? "Yes" : "No");
    08552    ast_cli(fd, "  Allow unknown access:   %s\n", global_allowguest ? "Yes" : "No");
    08553    ast_cli(fd, "  Promsic. redir:         %s\n", ast_test_flag(&global_flags, SIP_PROMISCREDIR) ? "Yes" : "No");
    08554    ast_cli(fd, "  SIP domain support:     %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
    08555    ast_cli(fd, "  Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
    08556    ast_cli(fd, "  URI user is phone no:   %s\n", ast_test_flag(&global_flags, SIP_USEREQPHONE) ? "Yes" : "No");
    08557    ast_cli(fd, "  Our auth realm          %s\n", global_realm);
    08558    ast_cli(fd, "  Realm. auth:            %s\n", authl ? "Yes": "No");
    08559    ast_cli(fd, "  Always auth rejects:    %s\n", global_alwaysauthreject ? "Yes" : "No");
    08560    ast_cli(fd, "  User Agent:             %s\n", default_useragent);
    08561    ast_cli(fd, "  MWI checking interval:  %d secs\n", global_mwitime);
    08562    ast_cli(fd, "  Reg. context:           %s\n", ast_strlen_zero(regcontext) ? "(not set)" : regcontext);
    08563    ast_cli(fd, "  Caller ID:              %s\n", default_callerid);
    08564    ast_cli(fd, "  From: Domain:           %s\n", default_fromdomain);
    08565    ast_cli(fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
    08566    ast_cli(fd, "  Call Events:            %s\n", callevents ? "On" : "Off");
    08567    ast_cli(fd, "  IP ToS:                 0x%x\n", tos);
    08568 #ifdef OSP_SUPPORT
    08569    ast_cli(fd, "  OSP Support:            Yes\n");
    08570 #else
    08571    ast_cli(fd, "  OSP Support:            No\n");
    08572 #endif
    08573    if (!realtimepeers && !realtimeusers)
    08574       ast_cli(fd, "  SIP realtime:           Disabled\n" );
    08575    else
    08576       ast_cli(fd, "  SIP realtime:           Enabled\n" );
    08577
    08578    ast_cli(fd, "\nGlobal Signalling Settings:\n");
    08579    ast_cli(fd, "---------------------------\n");
    08580    ast_cli(fd, "  Codecs:                 ");
    08581    print_codec_to_cli(fd, &prefs);
    08582    ast_cli(fd, "\n");
    08583    ast_cli(fd, "  Relax DTMF:             %s\n", relaxdtmf ? "Yes" : "No");
    08584    ast_cli(fd, "  Compact SIP headers:    %s\n", compactheaders ? "Yes" : "No");
    08585    ast_cli(fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
    08586    ast_cli(fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
    08587    ast_cli(fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
    08588    ast_cli(fd, "  DNS SRV lookup:         %s\n", srvlookup ? "Yes" : "No");
    08589    ast_cli(fd, "  Pedantic SIP support:   %s\n", pedanticsipchecking ? "Yes" : "No");
    08590    ast_cli(fd, "  Reg. max duration:      %d secs\n", max_expiry);
    08591    ast_cli(fd, "  Reg. default duration:  %d secs\n", default_expiry);
    08592    ast_cli(fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
    08593    ast_cli(fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
    08594    ast_cli(fd, "  Notify ringing state:   %s\n", global_notifyringing ? "Yes" : "No");
    08595    ast_cli(fd, "\nDefault Settings:\n");
    08596    ast_cli(fd, "-----------------\n");
    08597    ast_cli(fd, "  Context:                %s\n", default_context);
    08598    ast_cli(fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags, SIP_NAT)));
    08599    ast_cli(fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags, SIP_DTMF)));
    08600    ast_cli(fd, "  Qualify:                %d\n", default_qualify);
    08601    ast_cli(fd, "  Use ClientCode:         %s\n", ast_test_flag(&global_flags, SIP_USECLIENTCODE) ? "Yes" : "No");
    08602    ast_cli(fd, "  Progress inband:        %s\n", (ast_test_flag(&global_flags, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags, SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
    08603    ast_cli(fd, "  Language:               %s\n", ast_strlen_zero(default_language) ? "(Defaults to English)" : default_language);
    08604    ast_cli(fd, "  Musicclass:             %s\n", global_musicclass);
    08605    ast_cli(fd, "  Voice Mail Extension:   %s\n", global_vmexten);
    08606
    08607
    08608    if (realtimepeers || realtimeusers) {
    08609       ast_cli(fd, "\nRealtime SIP Settings:\n");
    08610       ast_cli(fd, "----------------------\n");
    08611       ast_cli(fd, "  Realtime Peers:         %s\n", realtimepeers ? "Yes" : "No");
    08612       ast_cli(fd, "  Realtime Users:         %s\n", realtimeusers ? "Yes" : "No");
    08613       ast_cli(fd, "  Cache Friends:          %s\n", ast_test_flag(&global_flags_page2, SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
    08614       ast_cli(fd, "  Update:                 %s\n", ast_test_flag(&global_flags_page2, SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
    08615       ast_cli(fd, "  Ignore Reg. Expire:     %s\n", ast_test_flag(&global_flags_page2, SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
    08616       ast_cli(fd, "  Auto Clear:             %d\n", global_rtautoclear);
    08617    }
    08618    ast_cli(fd, "\n----\n");
    08619    return RESULT_SUCCESS;
    08620 }
    08621
    08622 /*! \brief  subscription_type2str: Show subscription type in string format */
    08623 static const char *subscription_type2str(enum subscriptiontype subtype) {
    08624    int i;
    08625
    08626    for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
    08627       if (subscription_types[i].type == subtype) {
    08628          return subscription_types[i].text;
    08629       }
    08630    }
    08631    return subscription_types[0].text;
    08632 }
    08633
    08634 /*! \brief  find_subscription_type: Find subscription type in array */
    08635 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype) {
    08636    int i;
    08637
    08638    for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
    08639       if (subscription_types[i].type == subtype) {
    08640          return &subscription_types[i];
    08641       }
    08642    }
    08643    return &subscription_types[0];
    08644 }
    08645
    08646 /* Forward declaration */
    08647 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
    08648
    08649 /*! \brief  sip_show_channels: Show active SIP channels ---*/
    08650 static int sip_show_channels(int fd, int argc, char *argv[])
    08651 {
    08652         return __sip_show_channels(fd, argc, argv, 0);
    08653 }
    08654
    08655 /*! \brief  sip_show_subscriptions: Show active SIP subscriptions ---*/
    08656 static int sip_show_subscriptions(int fd, int argc, char *argv[])
    08657 {
    08658         return __sip_show_channels(fd, argc, argv, 1);
    08659 }
    08660
    08661 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
    08662 {
    08663 #define FORMAT3 "%-15.15s  %-10.10s  %-11.11s  %-15.15s  %-13.13s  %-15.15s\n"
    08664 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-4.4s  %-7.7s  %-15.15s\n"
    08665 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-4.4s  %-3.3s %-3.3s  %-15.15s\n"
    08666    struct sip_pvt *cur;
    08667    char iabuf[INET_ADDRSTRLEN];
    08668    int numchans = 0;
    08669    if (argc != 3)
    08670       return RESULT_SHOWUSAGE;
    08671    ast_mutex_lock(&iflock);
    08672    cur = iflist;
    08673    if (!subscriptions)
    08674       ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
    08675    else
    08676       ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type");
    08677    while (cur) {
    08678       if (cur->subscribed == NONE && !subscriptions) {
    08679          ast_cli(fd, FORMAT, ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr),
    08680             ast_strlen_zero(cur->username) ? ( ast_strlen_zero(cur->cid_num) ? "(None)" : cur->cid_num ) : cur->username,
    08681             cur->callid,
    08682             cur->ocseq, cur->icseq,
    08683             ast_getformatname(cur->owner ? cur->owner->nativeformats : 0),
    08684             ast_test_flag(cur, SIP_CALL_ONHOLD) ? "Yes" : "No",
    08685             ast_test_flag(cur, SIP_NEEDDESTROY) ? "(d)" : "",
    08686             cur->lastmsg );
    08687          numchans++;
    08688       }
    08689       if (cur->subscribed != NONE && subscriptions) {
    08690          ast_cli(fd, FORMAT3, ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr),
    08691                  ast_strlen_zero(cur->username) ? ( ast_strlen_zero(cur->cid_num) ? "(None)" : cur->cid_num ) : cur->username,
    08692                  cur->callid, cur->exten, ast_extension_state2str(cur->laststate),
    08693                  subscription_type2str(cur->subscribed));
    08694          numchans++;
    08695       }
    08696       cur = cur->next;
    08697    }
    08698    ast_mutex_unlock(&iflock);
    08699    if (!subscriptions)
    08700       ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
    08701    else
    08702       ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
    08703    return RESULT_SUCCESS;
    08704 #undef FORMAT
    08705 #undef FORMAT2
    08706 #undef FORMAT3
    08707 }
    08708
    08709 /*! \brief  complete_sipch: Support routine for 'sip show channel' CLI ---*/
    08710 static char *complete_sipch(char *line, char *word, int pos, int state)
    08711 {
    08712    int which=0;
    08713    struct sip_pvt *cur;
    08714    char *c = NULL;
    08715
    08716    ast_mutex_lock(&iflock);
    08717    cur = iflist;
    08718    while(cur) {
    08719       if (!strncasecmp(word, cur->callid, strlen(word))) {
    08720          if (++which > state) {
    08721             c = strdup(cur->callid);
    08722             break;
    08723          }
    08724       }
    08725       cur = cur->next;
    08726    }
    08727    ast_mutex_unlock(&iflock);
    08728    return c;
    08729 }
    08730
    08731 /*! \brief  complete_sip_peer: Do completion on peer name ---*/
    08732 static char *complete_sip_peer(char *word, int state, int flags2)
    08733 {
    08734    char *result = NULL;
    08735    int wordlen = strlen(word);
    08736    int which = 0;
    08737
    08738    ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
    08739       /* locking of the object is not required because only the name and flags are being compared */
    08740       if (!strncasecmp(word, iterator->name, wordlen)) {
    08741          if (flags2 && !ast_test_flag((&iterator->flags_page2), flags2))
    08742             continue;
    08743          if (++which > state) {
    08744             result = strdup(iterator->name);
    08745          }
    08746       }
    08747    } while(0) );
    08748    return result;
    08749 }
    08750
    08751 /*! \brief  complete_sip_show_peer: Support routine for 'sip show peer' CLI ---*/
    08752 static char *complete_sip_show_peer(char *line, char *word, int pos, int state)
    08753 {
    08754    if (pos == 3)
    08755       return complete_sip_peer(word, state, 0);
    08756
    08757    return NULL;
    08758 }
    08759
    08760 /*! \brief  complete_sip_debug_peer: Support routine for 'sip debug peer' CLI ---*/
    08761 static char *complete_sip_debug_peer(char *line, char *word, int pos, int state)
    08762 {
    08763    if (pos == 3)
    08764       return complete_sip_peer(word, state, 0);
    08765
    08766    return NULL;
    08767 }
    08768
    08769 /*! \brief  complete_sip_user: Do completion on user name ---*/
    08770 static char *complete_sip_user(char *word, int state, int flags2)
    08771 {
    08772    char *result = NULL;
    08773    int wordlen = strlen(word);
    08774    int which = 0;
    08775
    08776    ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
    08777       /* locking of the object is not required because only the name and flags are being compared */
    08778       if (!strncasecmp(word, iterator->name, wordlen)) {
    08779          if (flags2 && !ast_test_flag(&(iterator->flags_page2), flags2))
    08780             continue;
    08781          if (++which > state) {
    08782             result = strdup(iterator->name);
    08783          }
    08784       }
    08785    } while(0) );
    08786    return result;
    08787 }
    08788
    08789 /*! \brief  complete_sip_show_user: Support routine for 'sip show user' CLI ---*/
    08790 static char *complete_sip_show_user(char *line, char *word, int pos, int state)
    08791 {
    08792    if (pos == 3)
    08793       return complete_sip_user(word, state, 0);
    08794
    08795    return NULL;
    08796 }
    08797
    08798 /*! \brief  complete_sipnotify: Support routine for 'sip notify' CLI ---*/
    08799 static char *complete_sipnotify(char *line, char *word, int pos, int state)
    08800 {
    08801    char *c = NULL;
    08802
    08803    if (pos == 2) {
    08804       int which = 0;
    08805       char *cat;
    08806
    08807       /* do completion for notify type */
    08808
    08809       if (!notify_types)
    08810          return NULL;
    08811
    08812       cat = ast_category_browse(notify_types, NULL);
    08813       while(cat) {
    08814          if (!strncasecmp(word, cat, strlen(word))) {
    08815             if (++which > state) {
    08816                c = strdup(cat);
    08817                break;
    08818             }
    08819          }
    08820          cat = ast_category_browse(notify_types, cat);
    08821       }
    08822       return c;
    08823    }
    08824
    08825    if (pos > 2)
    08826       return complete_sip_peer(word, state, 0);
    08827
    08828    return NULL;
    08829 }
    08830
    08831 /*! \brief  complete_sip_prune_realtime_peer: Support routine for 'sip prune realtime peer' CLI ---*/
    08832 static char *complete_sip_prune_realtime_peer(char *line, char *word, int pos, int state)
    08833 {
    08834    if (pos == 4)
    08835       return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
    08836    return NULL;
    08837 }
    08838
    08839 /*! \brief  complete_sip_prune_realtime_user: Support routine for 'sip prune realtime user' CLI ---*/
    08840 static char *complete_sip_prune_realtime_user(char *line, char *word, int pos, int state)
    08841 {
    08842    if (pos == 4)
    08843       return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);
    08844
    08845    return NULL;
    08846 }
    08847
    08848 /*! \brief  sip_show_channel: Show details of one call ---*/
    08849 static int sip_show_channel(int fd, int argc, char *argv[])
    08850 {
    08851    struct sip_pvt *cur;
    08852    char iabuf[INET_ADDRSTRLEN];
    08853    size_t len;
    08854    int found = 0;
    08855
    08856    if (argc != 4)
    08857       return RESULT_SHOWUSAGE;
    08858    len = strlen(argv[3]);
    08859    ast_mutex_lock(&iflock);
    08860    cur = iflist;
    08861    while(cur) {
    08862       if (!strncasecmp(cur->callid, argv[3],len)) {
    08863          ast_cli(fd,"\n");
    08864          if (cur->subscribed != NONE)
    08865             ast_cli(fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
    08866          else
    08867             ast_cli(fd, "  * SIP Call\n");
    08868          ast_cli(fd, "  Direction:              %s\n", ast_test_flag(cur, SIP_OUTGOING)?"Outgoing":"Incoming");
    08869          ast_cli(fd, "  Call-ID:                %s\n", cur->callid);
    08870          ast_cli(fd, "  Our Codec Capability:   %d\n", cur->capability);
    08871          ast_cli(fd, "  Non-Codec Capability:   %d\n", cur->noncodeccapability);
    08872          ast_cli(fd, "  Their Codec Capability:   %d\n", cur->peercapability);
    08873          ast_cli(fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
    08874          ast_cli(fd, "  Format                  %s\n", ast_getformatname(cur->owner ? cur->owner->nativeformats : 0) );
    08875          ast_cli(fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr), ntohs(cur->sa.sin_port));
    08876          ast_cli(fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), cur->recv.sin_addr), ntohs(cur->recv.sin_port));
    08877          ast_cli(fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(cur, SIP_NAT)));
    08878          ast_cli(fd, "  Audio IP:               %s %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
    08879          ast_cli(fd, "  Our Tag:                %s\n", cur->tag);
    08880          ast_cli(fd, "  Their Tag:              %s\n", cur->theirtag);
    08881          ast_cli(fd, "  SIP User agent:         %s\n", cur->useragent);
    08882          if (!ast_strlen_zero(cur->username))
    08883             ast_cli(fd, "  Username:               %s\n", cur->username);
    08884          if (!ast_strlen_zero(cur->peername))
    08885             ast_cli(fd, "  Peername:               %s\n", cur->peername);
    08886          if (!ast_strlen_zero(cur->uri))
    08887             ast_cli(fd, "  Original uri:           %s\n", cur->uri);
    08888          if (!ast_strlen_zero(cur->cid_num))
    08889             ast_cli(fd, "  Caller-ID:              %s\n", cur->cid_num);
    08890          ast_cli(fd, "  Need Destroy:           %d\n", ast_test_flag(cur, SIP_NEEDDESTROY));
    08891          ast_cli(fd, "  Last Message:           %s\n", cur->lastmsg);
    08892          ast_cli(fd, "  Promiscuous Redir:      %s\n", ast_test_flag(cur, SIP_PROMISCREDIR) ? "Yes" : "No");
    08893          ast_cli(fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
    08894          ast_cli(fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(cur, SIP_DTMF)));
    08895          ast_cli(fd, "  SIP Options:            ");
    08896          if (cur->sipoptions) {
    08897             int x;
    08898             for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
    08899                if (cur->sipoptions & sip_options[x].id)
    08900                   ast_cli(fd, "%s ", sip_options[x].text);
    08901             }
    08902          } else
    08903             ast_cli(fd, "(none)\n");
    08904          ast_cli(fd, "\n\n");
    08905          found++;
    08906       }
    08907       cur = cur->next;
    08908    }
    08909    ast_mutex_unlock(&iflock);
    08910    if (!found)
    08911       ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
    08912    return RESULT_SUCCESS;
    08913 }
    08914
    08915 /*! \brief  sip_show_history: Show history details of one call ---*/
    08916 static int sip_show_history(int fd, int argc, char *argv[])
    08917 {
    08918    struct sip_pvt *cur;
    08919    struct sip_history *hist;
    08920    size_t len;
    08921    int x;
    08922    int found = 0;
    08923
    08924    if (argc != 4)
    08925       return RESULT_SHOWUSAGE;
    08926    if (!recordhistory)
    08927       ast_cli(fd, "\n***Note: History recording is currently DISABLED.  Use 'sip history' to ENABLE.\n");
    08928    len = strlen(argv[3]);
    08929    ast_mutex_lock(&iflock);
    08930    cur = iflist;
    08931    while(cur) {
    08932       if (!strncasecmp(cur->callid, argv[3], len)) {
    08933          ast_cli(fd,"\n");
    08934          if (cur->subscribed != NONE)
    08935             ast_cli(fd, "  * Subscription\n");
    08936          else
    08937             ast_cli(fd, "  * SIP Call\n");
    08938          x = 0;
    08939          hist = cur->history;
    08940          while(hist) {
    08941             x++;
    08942             ast_cli(fd, "%d. %s\n", x, hist->event);
    08943             hist = hist->next;
    08944          }
    08945          if (!x)
    08946             ast_cli(fd, "Call '%s' has no history\n", cur->callid);
    08947          found++;
    08948       }
    08949       cur = cur->next;
    08950    }
    08951    ast_mutex_unlock(&iflock);
    08952    if (!found)
    08953       ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
    08954    return RESULT_SUCCESS;
    08955 }
    08956
    08957 /*! \brief  dump_history: Dump SIP history to debug log file at end of
    08958   lifespan for SIP dialog */
    08959 void sip_dump_history(struct sip_pvt *dialog)
    08960 {
    08961    int x;
    08962    struct sip_history *hist;
    08963
    08964    if (!dialog)
    08965       return;
    08966
    08967    ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
    08968    if (dialog->subscribed)
    08969       ast_log(LOG_DEBUG, "  * Subscription\n");
    08970    else
    08971       ast_log(LOG_DEBUG, "  * SIP Call\n");
    08972    x = 0;
    08973    hist = dialog->history;
    08974    while(hist) {
    08975       x++;
    08976       ast_log(LOG_DEBUG, "  %d. %s\n", x, hist->event);
    08977       hist = hist->next;
    08978    }
    08979    if (!x)
    08980       ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
    08981    ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
    08982
    08983 }
    08984
    08985
    08986 /*! \brief  handle_request_info: Receive SIP INFO Message ---*/
    08987 /*    Doesn't read the duration of the DTMF signal */
    08988 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
    08989 {
    08990    char buf[1024];
    08991    unsigned int event;
    08992    char *c;
    08993
    08994    /* Need to check the media/type */
    08995    if (!strcasecmp(get_header(req, "Content-Type"), "application/dtmf-relay") ||
    08996        !strcasecmp(get_header(req, "Content-Type"), "application/vnd.nortelnetworks.digits")) {
    08997
    08998       /* Try getting the "signal=" part */
    08999       if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
    09000          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
    09001          transmit_response(p, "200 OK", req); /* Should return error */
    09002          return;
    09003       } else {
    09004          ast_copy_string(buf, c, sizeof(buf));
    09005       }
    09006
    09007       if (!p->owner) {  /* not a PBX call */
    09008          transmit_response(p, "481 Call leg/transaction does not exist", req);
    09009          ast_set_flag(p, SIP_NEEDDESTROY);
    09010          return;
    09011       }
    09012
    09013       if (ast_strlen_zero(buf)) {
    09014          transmit_response(p, "200 OK", req);
    09015          return;
    09016       }
    09017
    09018       if (buf[0] == '*')
    09019          event = 10;
    09020       else if (buf[0] == '#')
    09021          event = 11;
    09022       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
    09023          event = 12 + buf[0] - 'A';
    09024       else
    09025          event = atoi(buf);
    09026       if (event == 16) {
    09027          /* send a FLASH event */
    09028          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
    09029          ast_queue_frame(p->owner, &f);
    09030          if (sipdebug)
    09031             ast_verbose("* DTMF-relay event received: FLASH\n");
    09032       } else {
    09033          /* send a DTMF event */
    09034          struct ast_frame f = { AST_FRAME_DTMF, };
    09035          if (event < 10) {
    09036             f.subclass = '0' + event;
    09037          } else if (event < 11) {
    09038             f.subclass = '*';
    09039          } else if (event < 12) {
    09040             f.subclass = '#';
    09041          } else if (event < 16) {
    09042             f.subclass = 'A' + (event - 12);
    09043          }
    09044          ast_queue_frame(p->owner, &f);
    09045          if (sipdebug)
    09046             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
    09047       }
    09048       transmit_response(p, "200 OK", req);
    09049       return;
    09050    } else if (!strcasecmp(get_header(req, "Content-Type"), "application/media_control+xml")) {
    09051       /* Eh, we'll just assume it's a fast picture update for now */
    09052       if (p->owner)
    09053          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
    09054       transmit_response(p, "200 OK", req);
    09055       return;
    09056    } else if ((c = get_header(req, "X-ClientCode"))) {
    09057       /* Client code (from SNOM phone) */
    09058       if (ast_test_flag(p, SIP_USECLIENTCODE)) {
    09059          if (p->owner && p->owner->cdr)
    09060             ast_cdr_setuserfield(p->owner, c);
    09061          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
    09062             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
    09063          transmit_response(p, "200 OK", req);
    09064       } else {
    09065          transmit_response(p, "403 Unauthorized", req);
    09066       }
    09067       return;
    09068    }
    09069    /* Other type of INFO message, not really understood by Asterisk */
    09070    /* if (get_msg_text(buf, sizeof(buf), req)) { */
    09071
    09072    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
    09073    transmit_response(p, "415 Unsupported media type", req);
    09074    return;
    09075 }
    09076
    09077 /*! \brief  sip_do_debug: Enable SIP Debugging in CLI ---*/
    09078 static int sip_do_debug_ip(int fd, int argc, char *argv[])
    09079 {
    09080    struct hostent *hp;
    09081    struct ast_hostent ahp;
    09082    char iabuf[INET_ADDRSTRLEN];
    09083    int port = 0;
    09084    char *p, *arg;
    09085
    09086    if (argc != 4)
    09087       return RESULT_SHOWUSAGE;
    09088    arg = argv[3];
    09089    p = strstr(arg, ":");
    09090    if (p) {
    09091       *p = '\0';
    09092       p++;
    09093       port = atoi(p);
    09094    }
    09095    hp = ast_gethostbyname(arg, &ahp);
    09096    if (hp == NULL)  {
    09097       return RESULT_SHOWUSAGE;
    09098    }
    09099    debugaddr.sin_family = AF_INET;
    09100    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
    09101    debugaddr.sin_port = htons(port);
    09102    if (port == 0)
    09103       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr));
    09104    else
    09105       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr), port);
    09106    sipdebug |= SIP_DEBUG_CONSOLE;
    09107    return RESULT_SUCCESS;
    09108 }
    09109
    09110 /*! \brief  sip_do_debug_peer: Turn on SIP debugging with peer mask */
    09111 static int sip_do_debug_peer(int fd, int argc, char *argv[])
    09112 {
    09113    struct sip_peer *peer;
    09114    char iabuf[INET_ADDRSTRLEN];
    09115    if (argc != 4)
    09116       return RESULT_SHOWUSAGE;
    09117    peer = find_peer(argv[3], NULL, 1);
    09118    if (peer) {
    09119       if (peer->addr.sin_addr.s_addr) {
    09120          debugaddr.sin_family = AF_INET;
    09121          memcpy(&debugaddr.sin_addr, &peer->addr.sin_addr, sizeof(debugaddr.sin_addr));
    09122          debugaddr.sin_port = peer->addr.sin_port;
    09123          ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr), ntohs(debugaddr.sin_port));
    09124          sipdebug |= SIP_DEBUG_CONSOLE;
    09125       } else
    09126          ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[3]);
    09127       ASTOBJ_UNREF(peer,sip_destroy_peer);
    09128    } else
    09129       ast_cli(fd, "No such peer '%s'\n", argv[3]);
    09130    return RESULT_SUCCESS;
    09131 }
    09132
    09133 /*! \brief  sip_do_debug: Turn on SIP debugging (CLI command) */
    09134 static int sip_do_debug(int fd, int argc, char *argv[])
    09135 {
    09136    int oldsipdebug = sipdebug & SIP_DEBUG_CONSOLE;
    09137    if (argc != 2) {
    09138       if (argc != 4)
    09139          return RESULT_SHOWUSAGE;
    09140       else if (strncmp(argv[2], "ip\0", 3) == 0)
    09141          return sip_do_debug_ip(fd, argc, argv);
    09142       else if (strncmp(argv[2], "peer\0", 5) == 0)
    09143          return sip_do_debug_peer(fd, argc, argv);
    09144       else return RESULT_SHOWUSAGE;
    09145    }
    09146    sipdebug |= SIP_DEBUG_CONSOLE;
    09147    memset(&debugaddr, 0, sizeof(debugaddr));
    09148    if (oldsipdebug)
    09149       ast_cli(fd, "SIP Debugging re-enabled\n");
    09150    else
    09151       ast_cli(fd, "SIP Debugging enabled\n");
    09152    return RESULT_SUCCESS;
    09153 }
    09154
    09155 /*! \brief  sip_notify: Send SIP notify to peer */
    09156 static int sip_notify(int fd, int argc, char *argv[])
    09157 {
    09158    struct ast_variable *varlist;
    09159    int i;
    09160
    09161    if (argc < 4)
    09162       return RESULT_SHOWUSAGE;
    09163
    09164    if (!notify_types) {
    09165       ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
    09166       return RESULT_FAILURE;
    09167    }
    09168
    09169    varlist = ast_variable_browse(notify_types, argv[2]);
    09170
    09171    if (!varlist) {
    09172       ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
    09173       return RESULT_FAILURE;
    09174    }
    09175
    09176    for (i = 3; i < argc; i++) {
    09177       struct sip_pvt *p;
    09178       struct sip_request req;
    09179       struct ast_variable *var;
    09180
    09181       p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY);
    09182       if (!p) {
    09183          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify\n");
    09184          return RESULT_FAILURE;
    09185       }
    09186
    09187       if (create_addr(p, argv[i])) {
    09188          /* Maybe they're not registered, etc. */
    09189          sip_destroy(p);
    09190          ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
    09191          continue;
    09192       }
    09193
    09194       initreqprep(&req, p, SIP_NOTIFY);
    09195
    09196       for (var = varlist; var; var = var->next)
    09197          add_header(&req, var->name, var->value);
    09198
    09199       add_blank_header(&req);
    09200       /* Recalculate our side, and recalculate Call ID */
    09201       if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
    09202          memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
    09203       build_via(p, p->via, sizeof(p->via));
    09204       build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
    09205       ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
    09206       transmit_sip_request(p, &req);
    09207       sip_scheddestroy(p, 15000);
    09208    }
    09209
    09210    return RESULT_SUCCESS;
    09211 }
    09212 /*! \brief  sip_do_history: Enable SIP History logging (CLI) ---*/
    09213 static int sip_do_history(int fd, int argc, char *argv[])
    09214 {
    09215    if (argc != 2) {
    09216       return RESULT_SHOWUSAGE;
    09217    }
    09218    recordhistory = 1;
    09219    ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
    09220    return RESULT_SUCCESS;
    09221 }
    09222
    09223 /*! \brief  sip_no_history: Disable SIP History logging (CLI) ---*/
    09224 static int sip_no_history(int fd, int argc, char *argv[])
    09225 {
    09226    if (argc != 3) {
    09227       return RESULT_SHOWUSAGE;
    09228    }
    09229    recordhistory = 0;
    09230    ast_cli(fd, "SIP History Recording Disabled\n");
    09231    return RESULT_SUCCESS;
    09232 }
    09233
    09234 /*! \brief  sip_no_debug: Disable SIP Debugging in CLI ---*/
    09235 static int sip_no_debug(int fd, int argc, char *argv[])
    09236
    09237 {
    09238    if (argc != 3)
    09239       return RESULT_SHOWUSAGE;
    09240    sipdebug &= ~SIP_DEBUG_CONSOLE;
    09241    ast_cli(fd, "SIP Debugging Disabled\n");
    09242    return RESULT_SUCCESS;
    09243 }
    09244
    09245 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
    09246
    09247 /*! \brief  do_register_auth: Authenticate for outbound registration ---*/
    09248 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
    09249 {
    09250    char digest[1024];
    09251    p->authtries++;
    09252    memset(digest,0,sizeof(digest));
    09253    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
    09254       /* There's nothing to use for authentication */
    09255       /* No digest challenge in request */
    09256       if (sip_debug_test_pvt(p) && p->registry)
    09257          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
    09258          /* No old challenge */
    09259       return -1;
    09260    }
    09261    if (recordhistory) {
    09262       char tmp[80];
    09263       snprintf(tmp, sizeof(tmp), "Try: %d", p->authtries);
    09264       append_history(p, "RegistryAuth", tmp);
    09265    }
    09266    if (sip_debug_test_pvt(p) && p->registry)
    09267       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
    09268    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
    09269 }
    09270
    09271 /*! \brief  do_proxy_auth: Add authentication on outbound SIP packet ---*/
    09272 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
    09273 {
    09274    char digest[1024];
    09275
    09276    if (!p->options) {
    09277       p->options = calloc(1, sizeof(*p->options));
    09278       if (!p->options) {
    09279          ast_log(LOG_ERROR, "Out of memory\n");
    09280          return -2;
    09281       }
    09282    }
    09283
    09284    p->authtries++;
    09285    if (option_debug > 1)
    09286       ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
    09287    memset(digest, 0, sizeof(digest));
    09288    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
    09289       /* No way to authenticate */
    09290       return -1;
    09291    }
    09292    /* Now we have a reply digest */
    09293    p->options->auth = digest;
    09294    p->options->authheader = respheader;
    09295    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
    09296 }
    09297
    09298 /*! \brief  reply_digest: reply to authentication for outbound registrations ---*/
    09299 /*      This is used for register= servers in sip.conf, SIP proxies we register
    09300         with  for receiving calls from.  */
    09301 /* Returns -1 if we have no auth */
    09302 static int reply_digest(struct sip_pvt *p, struct sip_request *req,
    09303    char *header, int sipmethod,  char *digest, int digest_len)
    09304 {
    09305    char tmp[512];
    09306    char *c;
    09307    char oldnonce[256];
    09308
    09309    /* table of recognised keywords, and places where they should be copied */
    09310    const struct x {
    09311       const char *key;
    09312       char *dst;
    09313       int dstlen;
    09314    } *i, keys[] = {
    09315       { "realm=", p->realm, sizeof(p->realm) },
    09316       { "nonce=", p->nonce, sizeof(p->nonce) },
    09317       { "opaque=", p->opaque, sizeof(p->opaque) },
    09318       { "qop=", p->qop, sizeof(p->qop) },
    09319       { "domain=", p->domain, sizeof(p->domain) },
    09320       { NULL, NULL, 0 },
    09321    };
    09322
    09323    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
    09324    if (ast_strlen_zero(tmp))
    09325       return -1;
    09326    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
    09327       ast_log(LOG_WARNING, "missing Digest.\n");
    09328       return -1;
    09329    }
    09330    c = tmp + strlen("Digest ");
    09331    for (i = keys; i->key != NULL; i++)
    09332       i->dst[0] = '\0'; /* init all to empty strings */
    09333    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
    09334    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
    09335       for (i = keys; i->key != NULL; i++) {
    09336          char *src, *separator;
    09337          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
    09338             continue;
    09339          /* Found. Skip keyword, take text in quotes or up to the separator. */
    09340          c += strlen(i->key);
    09341          if (*c == '\"') {
    09342             src = ++c;
    09343             separator = "\"";
    09344          } else {
    09345             src = c;
    09346             separator = ",";
    09347          }
    09348          strsep(&c, separator); /* clear separator and move ptr */
    09349          ast_copy_string(i->dst, src, i->dstlen);
    09350          break;
    09351       }
    09352       if (i->key == NULL) /* not found, try ',' */
    09353          strsep(&c, ",");
    09354    }
    09355    /* Reset nonce count */
    09356    if (strcmp(p->nonce, oldnonce))
    09357       p->noncecount = 0;
    09358
    09359    /* Save auth data for following registrations */
    09360    if (p->registry) {
    09361       struct sip_registry *r = p->registry;
    09362
    09363       if (strcmp(r->nonce, p->nonce)) {
    09364          ast_copy_string(r->realm, p->realm, sizeof(r->realm));
    09365          ast_copy_string(r->nonce, p->nonce, sizeof(r->nonce));
    09366          ast_copy_string(r->domain, p->domain, sizeof(r->domain));
    09367          ast_copy_string(r->opaque, p->opaque, sizeof(r->opaque));
    09368          ast_copy_string(r->qop, p->qop, sizeof(r->qop));
    09369          r->noncecount = 0;
    09370       }
    09371    }
    09372    return build_reply_digest(p, sipmethod, digest, digest_len);
    09373 }
    09374
    09375 /*! \brief  build_reply_digest:  Build reply digest ---*/
    09376 /*      Build digest challenge for authentication of peers (for registration)
    09377    and users (for calls). Also used for authentication of CANCEL and BYE */
    09378 /* Returns -1 if we have no auth */
    09379 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
    09380 {
    09381    char a1[256];
    09382    char a2[256];
    09383    char a1_hash[256];
    09384    char a2_hash[256];
    09385    char resp[256];
    09386    char resp_hash[256];
    09387    char uri[256];
    09388    char cnonce[80];
    09389    char iabuf[INET_ADDRSTRLEN];
    09390    char *username;
    09391    char *secret;
    09392    char *md5secret;
    09393    struct sip_auth *auth = (struct sip_auth *) NULL;  /* Realm authentication */
    09394
    09395    if (!ast_strlen_zero(p->domain))
    09396       ast_copy_string(uri, p->domain, sizeof(uri));
    09397    else if (!ast_strlen_zero(p->uri))
    09398       ast_copy_string(uri, p->uri, sizeof(uri));
    09399    else
    09400       snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
    09401
    09402    snprintf(cnonce, sizeof(cnonce), "%08x", thread_safe_rand());
    09403
    09404    /* Check if we have separate auth credentials */
    09405    if ((auth = find_realm_authentication(authl, p->realm))) {
    09406       username = auth->username;
    09407       secret = auth->secret;
    09408       md5secret = auth->md5secret;
    09409       if (sipdebug)
    09410          ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
    09411    } else {
    09412       /* No authentication, use peer or register= config */
    09413       username = p->authname;
    09414       secret =  p->peersecret;
    09415       md5secret = p->peermd5secret;
    09416    }
    09417    if (ast_strlen_zero(username))   /* We have no authentication */
    09418       return -1;
    09419
    09420
    09421    /* Calculate SIP digest response */
    09422    snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
    09423    snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
    09424    if (!ast_strlen_zero(md5secret))
    09425       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
    09426    else
    09427       ast_md5_hash(a1_hash,a1);
    09428    ast_md5_hash(a2_hash,a2);
    09429
    09430    p->noncecount++;
    09431    if (!ast_strlen_zero(p->qop))
    09432       snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
    09433    else
    09434       snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
    09435    ast_md5_hash(resp_hash, resp);
    09436    /* XXX We hard code our qop to "auth" for now.  XXX */
    09437    if (!ast_strlen_zero(p->qop))
    09438       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\", qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, p->opaque, cnonce, p->noncecount);
    09439    else
    09440       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"", username, p->realm, uri, p->nonce, resp_hash, p->opaque);
    09441
    09442    return 0;
    09443 }
    09444
    09445 static char show_domains_usage[] =
    09446 "Usage: sip show domains\n"
    09447 "       Lists all configured SIP local domains.\n"
    09448 "       Asterisk only responds to SIP messages to local domains.\n";
    09449
    09450 static char notify_usage[] =
    09451 "Usage: sip notify <type> <peer> [<peer>...]\n"
    09452 "       Send a NOTIFY message to a SIP peer or peers\n"
    09453 "       Message types are defined in sip_notify.conf\n";
    09454
    09455 static char show_users_usage[] =
    09456 "Usage: sip show users [like <pattern>]\n"
    09457 "       Lists all known SIP users.\n"
    09458 "       Optional regular expression pattern is used to filter the user list.\n";
    09459
    09460 static char show_user_usage[] =
    09461 "Usage: sip show user <name> [load]\n"
    09462 "       Lists all details on one SIP user and the current status.\n"
    09463 "       Option \"load\" forces lookup of peer in realtime storage.\n";
    09464
    09465 static char show_inuse_usage[] =
    09466 "Usage: sip show inuse [all]\n"
    09467 "       List all SIP users and peers usage counters and limits.\n"
    09468 "       Add option \"all\" to show all devices, not only those with a limit.\n";
    09469
    09470 static char show_channels_usage[] =
    09471 "Usage: sip show channels\n"
    09472 "       Lists all currently active SIP channels.\n";
    09473
    09474 static char show_channel_usage[] =
    09475 "Usage: sip show channel <channel>\n"
    09476 "       Provides detailed status on a given SIP channel.\n";
    09477
    09478 static char show_history_usage[] =
    09479 "Usage: sip show history <channel>\n"
    09480 "       Provides detailed dialog history on a given SIP channel.\n";
    09481
    09482 static char show_peers_usage[] =
    09483 "Usage: sip show peers [like <pattern>]\n"
    09484 "       Lists all known SIP peers.\n"
    09485 "       Optional regular expression pattern is used to filter the peer list.\n";
    09486
    09487 static char show_peer_usage[] =
    09488 "Usage: sip show peer <name> [load]\n"
    09489 "       Lists all details on one SIP peer and the current status.\n"
    09490 "       Option \"load\" forces lookup of peer in realtime storage.\n";
    09491
    09492 static char prune_realtime_usage[] =
    09493 "Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
    09494 "       Prunes object(s) from the cache.\n"
    09495 "       Optional regular expression pattern is used to filter the objects.\n";
    09496
    09497 static char show_reg_usage[] =
    09498 "Usage: sip show registry\n"
    09499 "       Lists all registration requests and status.\n";
    09500
    09501 static char debug_usage[] =
    09502 "Usage: sip debug\n"
    09503 "       Enables dumping of SIP packets for debugging purposes\n\n"
    09504 "       sip debug ip <host[:PORT]>\n"
    09505 "       Enables dumping of SIP packets to and from host.\n\n"
    09506 "       sip debug peer <peername>\n"
    09507 "       Enables dumping of SIP packets to and from host.\n"
    09508 "       Require peer to be registered.\n";
    09509
    09510 static char no_debug_usage[] =
    09511 "Usage: sip no debug\n"
    09512 "       Disables dumping of SIP packets for debugging purposes\n";
    09513
    09514 static char no_history_usage[] =
    09515 "Usage: sip no history\n"
    09516 "       Disables recording of SIP dialog history for debugging purposes\n";
    09517
    09518 static char history_usage[] =
    09519 "Usage: sip history\n"
    09520 "       Enables recording of SIP dialog history for debugging purposes.\n"
    09521 "Use 'sip show history' to view the history of a call number.\n";
    09522
    09523 static char sip_reload_usage[] =
    09524 "Usage: sip reload\n"
    09525 "       Reloads SIP configuration from sip.conf\n";
    09526
    09527 static char show_subscriptions_usage[] =
    09528 "Usage: sip show subscriptions\n"
    09529 "       Shows active SIP subscriptions for extension states\n";
    09530
    09531 static char show_objects_usage[] =
    09532 "Usage: sip show objects\n"
    09533 "       Shows status of known SIP objects\n";
    09534
    09535 static char show_settings_usage[] =
    09536 "Usage: sip show settings\n"
    09537 "       Provides detailed list of the configuration of the SIP channel.\n";
    09538
    09539
    09540
    09541 /*! \brief  func_header_read: Read SIP header (dialplan function) */
    09542 static char *func_header_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
    09543 {
    09544    struct sip_pvt *p;
    09545    char *content;
    09546
    09547    if (!data) {
    09548       ast_log(LOG_WARNING, "This function requires a header name.\n");
    09549       return NULL;
    09550    }
    09551
    09552    ast_mutex_lock(&chan->lock);
    09553    if (chan->type != channeltype) {
    09554       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
    09555       ast_mutex_unlock(&chan->lock);
    09556       return NULL;
    09557    }
    09558
    09559    p = chan->tech_pvt;
    09560
    09561    /* If there is no private structure, this channel is no longer alive */
    09562    if (!p) {
    09563       ast_mutex_unlock(&chan->lock);
    09564       return NULL;
    09565    }
    09566
    09567    content = get_header(&p->initreq, data);
    09568
    09569    if (ast_strlen_zero(content)) {
    09570       ast_mutex_unlock(&chan->lock);
    09571       return NULL;
    09572    }
    09573
    09574    ast_copy_string(buf, content, len);
    09575    ast_mutex_unlock(&chan->lock);
    09576
    09577    return buf;
    09578 }
    09579
    09580
    09581 static struct ast_custom_function sip_header_function = {
    09582    .name = "SIP_HEADER",
    09583    .synopsis = "Gets the specified SIP header",
    09584    .syntax = "SIP_HEADER(<name>)",
    09585    .read = func_header_read,
    09586 };
    09587
    09588 /*! \brief  function_check_sipdomain: Dial plan function to check if domain is local */
    09589 static char *func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
    09590 {
    09591    if (ast_strlen_zero(data)) {
    09592       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
    09593       return buf;
    09594    }
    09595    if (check_sip_domain(data, NULL, 0))
    09596       ast_copy_string(buf, data, len);
    09597    else
    09598       buf[0] = '\0';
    09599    return buf;
    09600 }
    09601
    09602 static struct ast_custom_function checksipdomain_function = {
    09603    .name = "CHECKSIPDOMAIN",
    09604    .synopsis = "Checks if domain is a local domain",
    09605    .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
    09606    .read = func_check_sipdomain,
    09607    .desc = "This function checks if the domain in the argument is configured\n"
    09608       "as a local SIP domain that this Asterisk server is configured to handle.\n"
    09609       "Returns the domain name if it is locally handled, otherwise an empty string.\n"
    09610       "Check the domain= configuration in sip.conf\n",
    09611 };
    09612
    09613
    09614 /*! \brief  function_sippeer: ${SIPPEER()} Dialplan function - reads peer data */
    09615 static char *function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
    09616 {
    09617    char *ret = NULL;
    09618    struct sip_peer *peer;
    09619    char *peername, *colname;
    09620    char iabuf[INET_ADDRSTRLEN];
    09621
    09622    if (!(peername = ast_strdupa(data))) {
    09623       ast_log(LOG_ERROR, "Memory Error!\n");
    09624       return ret;
    09625    }
    09626
    09627    if ((colname = strchr(peername, ':'))) {
    09628       *colname = '\0';
    09629       colname++;
    09630    } else {
    09631       colname = "ip";
    09632    }
    09633    if (!(peer = find_peer(peername, NULL, 1)))
    09634       return ret;
    09635
    09636    if (!strcasecmp(colname, "ip")) {
    09637       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "", len);
    09638    } else  if (!strcasecmp(colname, "status")) {
    09639       peer_status(peer, buf, len);
    09640    } else  if (!strcasecmp(colname, "language")) {
    09641       ast_copy_string(buf, peer->language, len);
    09642    } else  if (!strcasecmp(colname, "regexten")) {
    09643       ast_copy_string(buf, peer->regexten, len);
    09644    } else  if (!strcasecmp(colname, "limit")) {
    09645       snprintf(buf, len, "%d", peer->call_limit);
    09646    } else  if (!strcasecmp(colname, "curcalls")) {
    09647       snprintf(buf, len, "%d", peer->inUse);
    09648    } else  if (!strcasecmp(colname, "accountcode")) {
    09649       ast_copy_string(buf, peer->accountcode, len);
    09650    } else  if (!strcasecmp(colname, "useragent")) {
    09651       ast_copy_string(buf, peer->useragent, len);
    09652    } else  if (!strcasecmp(colname, "mailbox")) {
    09653       ast_copy_string(buf, peer->mailbox, len);
    09654    } else  if (!strcasecmp(colname, "context")) {
    09655       ast_copy_string(buf, peer->context, len);
    09656    } else  if (!strcasecmp(colname, "expire")) {
    09657       snprintf(buf, len, "%d", peer->expire);
    09658    } else  if (!strcasecmp(colname, "dynamic")) {
    09659       ast_copy_string(buf, (ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
    09660    } else  if (!strcasecmp(colname, "callerid_name")) {
    09661       ast_copy_string(buf, peer->cid_name, len);
    09662    } else  if (!strcasecmp(colname, "callerid_num")) {
    09663       ast_copy_string(buf, peer->cid_num, len);
    09664    } else  if (!strcasecmp(colname, "codecs")) {
    09665       ast_getformatname_multiple(buf, len -1, peer->capability);
    09666    } else  if (!strncasecmp(colname, "codec[", 6)) {
    09667       char *codecnum, *ptr;
    09668       int index = 0, codec = 0;
    09669
    09670       codecnum = strchr(colname, '[');
    09671       *codecnum = '\0';
    09672       codecnum++;
    09673       if ((ptr = strchr(codecnum, ']'))) {
    09674          *ptr = '\0';
    09675       }
    09676       index = atoi(codecnum);
    09677       if((codec = ast_codec_pref_index(&peer->prefs, index))) {
    09678          ast_copy_string(buf, ast_getformatname(codec), len);
    09679       }
    09680    }
    09681    ret = buf;
    09682
    09683    ASTOBJ_UNREF(peer, sip_destroy_peer);
    09684
    09685    return ret;
    09686 }
    09687
    09688 /* Structure to declare a dialplan function: SIPPEER */
    09689 struct ast_custom_function sippeer_function = {
    09690    .name = "SIPPEER",
    09691    .synopsis = "Gets SIP peer information",
    09692    .syntax = "SIPPEER(<peername>[:item])",
    09693    .read = function_sippeer,
    09694    .desc = "Valid items are:\n"
    09695    "- ip (default)          The IP address.\n"
    09696    "- mailbox               The configured mailbox.\n"
    09697    "- context               The configured context.\n"
    09698    "- expire                The epoch time of the next expire.\n"
    09699    "- dynamic               Is it dynamic? (yes/no).\n"
    09700    "- callerid_name         The configured Caller ID name.\n"
    09701    "- callerid_num          The configured Caller ID number.\n"
    09702    "- codecs                The configured codecs.\n"
    09703    "- status                Status (if qualify=yes).\n"
    09704    "- regexten              Registration extension\n"
    09705    "- limit                 Call limit (call-limit)\n"
    09706    "- curcalls              Current amount of calls \n"
    09707    "                        Only available if call-limit is set\n"
    09708    "- language              Default language for peer\n"
    09709    "- accountcode           Account code for this peer\n"
    09710    "- useragent             Current user agent id for peer\n"
    09711    "- codec[x]              Preferred codec index number 'x' (beginning with zero).\n"
    09712    "\n"
    09713 };
    09714
    09715 /*! \brief  function_sipchaninfo_read: ${SIPCHANINFO()} Dialplan function - reads sip channel data */
    09716 static char *function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
    09717 {
    09718    struct sip_pvt *p;
    09719    char iabuf[INET_ADDRSTRLEN];
    09720
    09721    *buf = 0;
    09722
    09723    if (!data) {
    09724       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
    09725       return NULL;
    09726    }
    09727
    09728    ast_mutex_lock(&chan->lock);
    09729    if (chan->type != channeltype) {
    09730       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
    09731       ast_mutex_unlock(&chan->lock);
    09732       return NULL;
    09733    }
    09734
    09735 /*    ast_verbose("function_sipchaninfo_read: %s\n", data); */
    09736    p = chan->tech_pvt;
    09737
    09738    /* If there is no private structure, this channel is no longer alive */
    09739    if (!p) {
    09740       ast_mutex_unlock(&chan->lock);
    09741       return NULL;
    09742    }
    09743
    09744    if (!strcasecmp(data, "peerip")) {
    09745       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr) : "", len);
    09746    } else  if (!strcasecmp(data, "recvip")) {
    09747       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr) : "", len);
    09748    } else  if (!strcasecmp(data, "from")) {
    09749       ast_copy_string(buf, p->from, len);
    09750    } else  if (!strcasecmp(data, "uri")) {
    09751       ast_copy_string(buf, p->uri, len);
    09752    } else  if (!strcasecmp(data, "useragent")) {
    09753       ast_copy_string(buf, p->useragent, len);
    09754    } else  if (!strcasecmp(data, "peername")) {
    09755       ast_copy_string(buf, p->peername, len);
    09756    } else {
    09757       ast_mutex_unlock(&chan->lock);
    09758       return NULL;
    09759    }
    09760    ast_mutex_unlock(&chan->lock);
    09761
    09762    return buf;
    09763 }
    09764
    09765 /* Structure to declare a dialplan function: SIPCHANINFO */
    09766 static struct ast_custom_function sipchaninfo_function = {
    09767    .name = "SIPCHANINFO",
    09768    .synopsis = "Gets the specified SIP parameter from the current channel",
    09769    .syntax = "SIPCHANINFO(item)",
    09770    .read = function_sipchaninfo_read,
    09771    .desc = "Valid items are:\n"
    09772    "- peerip                The IP address of the peer.\n"
    09773    "- recvip                The source IP address of the peer.\n"
    09774    "- from                  The URI from the From: header.\n"
    09775    "- uri                   The URI from the Contact: header.\n"
    09776    "- useragent             The useragent.\n"
    09777    "- peername              The name of the peer.\n"
    09778 };
    09779
    09780
    09781
    09782 /*! \brief  parse_moved_contact: Parse 302 Moved temporalily response */
    09783 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
    09784 {
    09785    char tmp[256];
    09786    char *s, *e, *t;
    09787    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
    09788    if ((t = strchr(tmp, ',')))
    09789       *t = '\0';
    09790    s = get_in_brackets(tmp);
    09791    e = strchr(s, ';');
    09792    if (e)
    09793       *e = '\0';
    09794    if (ast_test_flag(p, SIP_PROMISCREDIR)) {
    09795       if (!strncasecmp(s, "sip:", 4))
    09796          s += 4;
    09797       e = strchr(s, '/');
    09798       if (e)
    09799          *e = '\0';
    09800       ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
    09801       if (p->owner)
    09802          snprintf(p->owner->call_forward, sizeof(p->owner->call_forward), "SIP/%s", s);
    09803    } else {
    09804       e = strchr(tmp, '@');
    09805       if (e)
    09806          *e = '\0';
    09807       e = strchr(tmp, '/');
    09808       if (e)
    09809          *e = '\0';
    09810       if (!strncasecmp(s, "sip:", 4))
    09811          s += 4;
    09812       ast_log(LOG_DEBUG, "Found 302 Redirect to extension '%s'\n", s);
    09813       if (p->owner)
    09814          ast_copy_string(p->owner->call_forward, s, sizeof(p->owner->call_forward));
    09815    }
    09816 }
    09817
    09818 /*! \brief  check_pendings: Check pending actions on SIP call ---*/
    09819 static void check_pendings(struct sip_pvt *p)
    09820 {
    09821    if (ast_test_flag(p, SIP_PENDINGBYE)) {
    09822       /* if we can't BYE, then this is really a pending CANCEL */
    09823       if (!ast_test_flag(p, SIP_CAN_BYE))
    09824          transmit_request(p, SIP_CANCEL, p->ocseq, 1, 0);
    09825          /* Actually don't destroy us yet, wait for the 487 on our original
    09826             INVITE, but do set an autodestruct just in case we never get it. */
    09827       else
    09828          transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
    09829       ast_clear_flag(p, SIP_PENDINGBYE);
    09830       sip_scheddestroy(p, 32000);
    09831    } else if (ast_test_flag(p, SIP_NEEDREINVITE)) {
    09832       ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
    09833       /* Didn't get to reinvite yet, so do it now */
    09834       transmit_reinvite_with_sdp(p);
    09835       ast_clear_flag(p, SIP_NEEDREINVITE);
    09836    }
    09837 }
    09838
    09839 /*! \brief  handle_response_invite: Handle SIP response in dialogue ---*/
    09840 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
    09841 {
    09842    int outgoing = ast_test_flag(p, SIP_OUTGOING);
    09843
    09844    if (option_debug > 3) {
    09845       int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
    09846       if (reinvite)
    09847          ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
    09848       else
    09849          ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
    09850    }
    09851
    09852    if (ast_test_flag(p, SIP_ALREADYGONE)) { /* This call is already gone */
    09853       ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
    09854       return;
    09855    }
    09856
    09857    /* RFC3261 says we must treat every 1xx response (but not 100)
    09858       that we don't recognize as if it was 183.
    09859    */
    09860    if ((resp > 100) &&
    09861        (resp < 200) &&
    09862        (resp != 180) &&
    09863        (resp != 183))
    09864       resp = 183;
    09865
    09866    switch (resp) {
    09867    case 100:   /* Trying */
    09868       if (!ignore)
    09869          sip_cancel_destroy(p);
    09870       check_pendings(p);
    09871       ast_set_flag(p, SIP_CAN_BYE);
    09872       break;
    09873    case 180:   /* 180 Ringing */
    09874       if (!ignore)
    09875          sip_cancel_destroy(p);
    09876       if (!ignore && p->owner) {
    09877          ast_queue_control(p->owner, AST_CONTROL_RINGING);
    09878          if (p->owner->_state != AST_STATE_UP)
    09879             ast_setstate(p->owner, AST_STATE_RINGING);
    09880       }
    09881       if (find_sdp(req)) {
    09882          process_sdp(p, req);
    09883          if (!ignore && p->owner) {
    09884             /* Queue a progress frame only if we have SDP in 180 */
    09885             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
    09886          }
    09887       }
    09888       ast_set_flag(p, SIP_CAN_BYE);
    09889       check_pendings(p);
    09890       break;
    09891    case 183:   /* Session progress */
    09892       if (!ignore)
    09893          sip_cancel_destroy(p);
    09894       /* Ignore 183 Session progress without SDP */
    09895       if (find_sdp(req)) {
    09896          process_sdp(p, req);
    09897          if (!ignore && p->owner) {
    09898             /* Queue a progress frame */
    09899             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
    09900          }
    09901       }
    09902       ast_set_flag(p, SIP_CAN_BYE);
    09903       check_pendings(p);
    09904       break;
    09905    case 200:   /* 200 OK on invite - someone's answering our call */
    09906       if (!ignore)
    09907          sip_cancel_destroy(p);
    09908       p->authtries = 0;
    09909       if (find_sdp(req)) {
    09910          process_sdp(p, req);
    09911       }
    09912
    09913       /* Parse contact header for continued conversation */
    09914       /* When we get 200 OK, we know which device (and IP) to contact for this call */
    09915       /* This is important when we have a SIP proxy between us and the phone */
    09916       if (outgoing) {
    09917          parse_ok_contact(p, req);
    09918
    09919          /* Save Record-Route for any later requests we make on this dialogue */
    09920          build_route(p, req, 1);
    09921       }
    09922
    09923       if (!ignore && p->owner) {
    09924          if (p->owner->_state != AST_STATE_UP) {
    09925 #ifdef OSP_SUPPORT
    09926             time(&p->ospstart);
    09927 #endif
    09928             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
    09929          } else { /* RE-invite */
    09930             struct ast_frame af = { AST_FRAME_NULL, };
    09931             ast_queue_frame(p->owner, &af);
    09932          }
    09933       } else {
    09934           /* It's possible we're getting an ACK after we've tried to disconnect
    09935               by sending CANCEL */
    09936          /* THIS NEEDS TO BE CHECKED: OEJ */
    09937          if (!ignore)
    09938             ast_set_flag(p, SIP_PENDINGBYE);
    09939       }
    09940       /* If I understand this right, the branch is different for a non-200 ACK only */
    09941       transmit_request(p, SIP_ACK, seqno, 0, 1);
    09942       ast_set_flag(p, SIP_CAN_BYE);
    09943       check_pendings(p);
    09944       break;
    09945    case 407: /* Proxy authentication */
    09946    case 401: /* Www auth */
    09947       /* First we ACK */
    09948       transmit_request(p, SIP_ACK, seqno, 0, 0);
    09949       if (p->options)
    09950          p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
    09951
    09952       /* Then we AUTH */
    09953       p->theirtag[0]='\0'; /* forget their old tag, so we don't match tags when getting response */
    09954       if (!ignore) {
    09955          char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
    09956          char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
    09957          if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
    09958             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
    09959             ast_set_flag(p, SIP_NEEDDESTROY);
    09960             ast_set_flag(p, SIP_ALREADYGONE);
    09961             if (p->owner)
    09962                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
    09963          }
    09964       }
    09965       break;
    09966    case 403: /* Forbidden */
    09967       /* First we ACK */
    09968       transmit_request(p, SIP_ACK, seqno, 0, 0);
    09969       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for INVITE to '%s'\n", get_header(&p->initreq, "From"));
    09970       if (!ignore && p->owner)
    09971          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
    09972       ast_set_flag(p, SIP_NEEDDESTROY);
    09973       ast_set_flag(p, SIP_ALREADYGONE);
    09974       break;
    09975    case 404: /* Not found */
    09976       transmit_request(p, SIP_ACK, seqno, 0, 0);
    09977       if (p->owner && !ignore)
    09978          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
    09979       ast_set_flag(p, SIP_ALREADYGONE);
    09980       break;
    09981    case 481: /* Call leg does not exist */
    09982       /* Could be REFER or INVITE */
    09983       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
    09984       transmit_request(p, SIP_ACK, seqno, 0, 0);
    09985       break;
    09986    case 487: /* Cancelled transaction */
    09987       /* We have sent CANCEL on an outbound INVITE
    09988          This transaction is already scheduled to be killed by sip_hangup().
    09989       */
    09990       transmit_request(p, SIP_ACK, seqno, 0, 0);
    09991       if (p->owner && !ignore) {
    09992          ast_queue_hangup(p->owner);
    09993          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
    09994       } else if (!ignore) {
    09995          update_call_counter(p, DEC_CALL_LIMIT);
    09996          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
    09997          ast_set_flag(p, SIP_NEEDDESTROY);
    09998          ast_set_flag(p, SIP_ALREADYGONE);
    09999       }
    10000       break;
    10001    case 491: /* Pending */
    10002       /* we have to wait a while, then retransmit */
    10003       /* Transmission is rescheduled, so everything should be taken care of.
    10004          We should support the retry-after at some point */
    10005       break;
    10006    case 501: /* Not implemented */
    10007       transmit_request(p, SIP_ACK, seqno, 0, 0);
    10008       if (p->owner)
    10009          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
    10010       break;
    10011    }
    10012 }
    10013
    10014 /*! \brief  handle_response_register: Handle responses on REGISTER to services ---*/
    10015 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
    10016 {
    10017    int expires, expires_ms;
    10018    struct sip_registry *r;
    10019    r=p->registry;
    10020
    10021    switch (resp) {
    10022    case 401:   /* Unauthorized */
    10023       if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
    10024          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
    10025          ast_set_flag(p, SIP_NEEDDESTROY);
    10026          }
    10027       break;
    10028    case 403:   /* Forbidden */
    10029       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
    10030       if (global_regattempts_max)
    10031          p->registry->regattempts = global_regattempts_max+1;
    10032       ast_sched_del(sched, r->timeout);
    10033       r->timeout = -1;
    10034       ast_set_flag(p, SIP_NEEDDESTROY);
    10035       break;
    10036    case 404:   /* Not found */
    10037       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
    10038       if (global_regattempts_max)
    10039          p->registry->regattempts = global_regattempts_max+1;
    10040       ast_set_flag(p, SIP_NEEDDESTROY);
    10041       r->call = NULL;
    10042       ast_sched_del(sched, r->timeout);
    10043       r->timeout = -1;
    10044       break;
    10045    case 407:   /* Proxy auth */
    10046       if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
    10047          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
    10048          ast_set_flag(p, SIP_NEEDDESTROY);
    10049       }
    10050       break;
    10051    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
    10052       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
    10053       if (global_regattempts_max)
    10054          p->registry->regattempts = global_regattempts_max+1;
    10055       ast_set_flag(p, SIP_NEEDDESTROY);
    10056       r->call = NULL;
    10057       ast_sched_del(sched, r->timeout);
    10058       r->timeout = -1;
    10059       break;
    10060    case 200:   /* 200 OK */
    10061       if (!r) {
    10062          ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
    10063          ast_set_flag(p, SIP_NEEDDESTROY);
    10064          return 0;
    10065       }
    10066
    10067       r->regstate=REG_STATE_REGISTERED;
    10068       manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
    10069       r->regattempts = 0;
    10070       ast_log(LOG_DEBUG, "Registration successful\n");
    10071       if (r->timeout > -1) {
    10072          ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
    10073          ast_sched_del(sched, r->timeout);
    10074       }
    10075       r->timeout=-1;
    10076       r->call = NULL;
    10077       p->registry = NULL;
    10078       /* Let this one hang around until we have all the responses */
    10079       sip_scheddestroy(p, 32000);
    10080       /* ast_set_flag(p, SIP_NEEDDESTROY);   */
    10081
    10082       /* set us up for re-registering */
    10083       /* figure out how long we got registered for */
    10084       if (r->expire > -1)
    10085          ast_sched_del(sched, r->expire);
    10086       /* according to section 6.13 of RFC, contact headers override
    10087          expires headers, so check those first */
    10088       expires = 0;
    10089       if (!ast_strlen_zero(get_header(req, "Contact"))) {
    10090          char *contact = NULL;
    10091          char *tmptmp = NULL;
    10092          int start = 0;
    10093          for(;;) {
    10094             contact = __get_header(req, "Contact", &start);
    10095             /* this loop ensures we get a contact header about our register request */
    10096             if(!ast_strlen_zero(contact)) {
    10097                if( (tmptmp=strstr(contact, p->our_contact))) {
    10098                   contact=tmptmp;
    10099                   break;
    10100                }
    10101             } else
    10102                break;
    10103          }
    10104          tmptmp = strcasestr(contact, "expires=");
    10105          if (tmptmp) {
    10106             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
    10107                expires = 0;
    10108          }
    10109
    10110       }
    10111       if (!expires)
    10112          expires=atoi(get_header(req, "expires"));
    10113       if (!expires)
    10114          expires=default_expiry;
    10115
    10116       expires_ms = expires * 1000;
    10117       if (expires <= EXPIRY_GUARD_LIMIT)
    10118          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
    10119       else
    10120          expires_ms -= EXPIRY_GUARD_SECS * 1000;
    10121       if (sipdebug)
    10122          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
    10123
    10124       r->refresh= (int) expires_ms / 1000;
    10125
    10126       /* Schedule re-registration before we expire */
    10127       r->expire=ast_sched_add(sched, expires_ms, sip_reregister, r);
    10128       ASTOBJ_UNREF(r, sip_registry_destroy);
    10129    }
    10130    return 1;
    10131 }
    10132
    10133 /*! \brief  handle_response_peerpoke: Handle qualification responses (OPTIONS) */
    10134 static int handle_response_peerpoke(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno, int sipmethod)
    10135 {
    10136    struct sip_peer *peer;
    10137    int pingtime;
    10138    struct timeval tv;
    10139
    10140    if (resp != 100) {
    10141       int statechanged = 0;
    10142       int newstate = 0;
    10143       peer = p->peerpoke;
    10144       gettimeofday(&tv, NULL);
    10145       pingtime = ast_tvdiff_ms(tv, peer->ps);
    10146       if (pingtime < 1)
    10147          pingtime = 1;
    10148       if ((peer->lastms < 0)  || (peer->lastms > peer->maxms)) {
    10149          if (pingtime <= peer->maxms) {
    10150             ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! (%dms / %dms)\n", peer->name, pingtime, peer->maxms);
    10151             statechanged = 1;
    10152             newstate = 1;
    10153          }
    10154       } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
    10155          if (pingtime > peer->maxms) {
    10156             ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED! (%dms / %dms)\n", peer->name, pingtime, peer->maxms);
    10157             statechanged = 1;
    10158             newstate = 2;
    10159          }
    10160       }
    10161       if (!peer->lastms)
    10162          statechanged = 1;
    10163       peer->lastms = pingtime;
    10164       peer->call = NULL;
    10165       if (statechanged) {
    10166          ast_device_state_changed("SIP/%s", peer->name);
    10167          if (newstate == 2) {
    10168             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, pingtime);
    10169          } else {
    10170             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, pingtime);
    10171          }
    10172       }
    10173
    10174       if (peer->pokeexpire > -1)
    10175          ast_sched_del(sched, peer->pokeexpire);
    10176       if (sipmethod == SIP_INVITE)  /* Does this really happen? */
    10177          transmit_request(p, SIP_ACK, seqno, 0, 0);
    10178       ast_set_flag(p, SIP_NEEDDESTROY);
    10179
    10180       /* Try again eventually */
    10181       if ((peer->lastms < 0)  || (peer->lastms > peer->maxms))
    10182          peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
    10183       else
    10184          peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
    10185    }
    10186    return 1;
    10187 }
    10188
    10189 /*! \brief  handle_response: Handle SIP response in dialogue ---*/
    10190 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
    10191 {
    10192    char *msg, *c;
    10193    struct ast_channel *owner;
    10194    char iabuf[INET_ADDRSTRLEN];
    10195    int sipmethod;
    10196    int res = 1;
    10197
    10198    c = get_header(req, "Cseq");
    10199    msg = strchr(c, ' ');
    10200    if (!msg)
    10201       msg = "";
    10202    else
    10203       msg++;
    10204    sipmethod = find_sip_method(msg);
    10205
    10206    owner = p->owner;
    10207    if (owner)
    10208       owner->hangupcause = hangup_sip2cause(resp);
    10209
    10210    /* Acknowledge whatever it is destined for */
    10211    if ((resp >= 100) && (resp <= 199))
    10212       __sip_semi_ack(p, seqno, 0, sipmethod);
    10213    else
    10214       __sip_ack(p, seqno, 0, sipmethod);
    10215
    10216    /* Get their tag if we haven't already */
    10217    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
    10218       gettag(req, "To", p->theirtag, sizeof(p->theirtag));
    10219    }
    10220    if (p->peerpoke) {
    10221       /* We don't really care what the response is, just that it replied back.
    10222          Well, as long as it's not a 100 response...  since we might
    10223          need to hang around for something more "definitive" */
    10224
    10225       res = handle_response_peerpoke(p, resp, rest, req, ignore, seqno, sipmethod);
    10226    } else if (ast_test_flag(p, SIP_OUTGOING)) {
    10227       /* Acknowledge sequence number */
    10228       if (p->initid > -1) {
    10229          /* Don't auto congest anymore since we've gotten something useful back */
    10230          ast_sched_del(sched, p->initid);
    10231          p->initid = -1;
    10232       }
    10233       switch(resp) {
    10234       case 100:   /* 100 Trying */
    10235          if (sipmethod == SIP_INVITE)
    10236             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10237          break;
    10238       case 183:   /* 183 Session Progress */
    10239          if (sipmethod == SIP_INVITE)
    10240             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10241          break;
    10242       case 180:   /* 180 Ringing */
    10243          if (sipmethod == SIP_INVITE)
    10244             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10245          break;
    10246       case 200:   /* 200 OK */
    10247          p->authtries = 0; /* Reset authentication counter */
    10248          if (sipmethod == SIP_MESSAGE) {
    10249             /* We successfully transmitted a message */
    10250             ast_set_flag(p, SIP_NEEDDESTROY);
    10251          } else if (sipmethod == SIP_NOTIFY) {
    10252             /* They got the notify, this is the end */
    10253             if (p->owner) {
    10254                ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
    10255                ast_queue_hangup(p->owner);
    10256             } else {
    10257                if (p->subscribed == NONE) {
    10258                   ast_set_flag(p, SIP_NEEDDESTROY);
    10259                }
    10260             }
    10261          } else if (sipmethod == SIP_INVITE) {
    10262             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10263          } else if (sipmethod == SIP_REGISTER) {
    10264             res = handle_response_register(p, resp, rest, req, ignore, seqno);
    10265          } else if (sipmethod == SIP_BYE) {
    10266             /* Ok, we're ready to go */
    10267             ast_set_flag(p, SIP_NEEDDESTROY);
    10268          }
    10269          break;
    10270       case 401: /* Not www-authorized on SIP method */
    10271          if (sipmethod == SIP_INVITE) {
    10272             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10273          } else if (p->registry && sipmethod == SIP_REGISTER) {
    10274             res = handle_response_register(p, resp, rest, req, ignore, seqno);
    10275          } else {
    10276             ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
    10277             ast_set_flag(p, SIP_NEEDDESTROY);
    10278          }
    10279          break;
    10280       case 403: /* Forbidden - we failed authentication */
    10281          if (sipmethod == SIP_INVITE) {
    10282             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10283          } else if (p->registry && sipmethod == SIP_REGISTER) {
    10284             res = handle_response_register(p, resp, rest, req, ignore, seqno);
    10285          } else {
    10286             ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for %s\n", msg);
    10287          }
    10288          break;
    10289       case 404: /* Not found */
    10290          if (p->registry && sipmethod == SIP_REGISTER) {
    10291             res = handle_response_register(p, resp, rest, req, ignore, seqno);
    10292          } else if (sipmethod == SIP_INVITE) {
    10293             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10294          } else if (owner)
    10295             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
    10296          break;
    10297       case 407: /* Proxy auth required */
    10298          if (sipmethod == SIP_INVITE) {
    10299             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10300          } else if (sipmethod == SIP_BYE || sipmethod == SIP_REFER) {
    10301             if (ast_strlen_zero(p->authname)) {
    10302                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
    10303                      msg, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
    10304                ast_set_flag(p, SIP_NEEDDESTROY);
    10305             }
    10306             if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
    10307                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
    10308                ast_set_flag(p, SIP_NEEDDESTROY);
    10309             }
    10310          } else if (p->registry && sipmethod == SIP_REGISTER) {
    10311             res = handle_response_register(p, resp, rest, req, ignore, seqno);
    10312          } else   /* We can't handle this, giving up in a bad way */
    10313             ast_set_flag(p, SIP_NEEDDESTROY);
    10314
    10315          break;
    10316       case 487:
    10317          if (sipmethod == SIP_INVITE)
    10318             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10319          break;
    10320       case 491: /* Pending */
    10321          if (sipmethod == SIP_INVITE) {
    10322             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10323          }
    10324       case 501: /* Not Implemented */
    10325          if (sipmethod == SIP_INVITE) {
    10326             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10327          } else
    10328             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), msg);
    10329          break;
    10330       default:
    10331          if ((resp >= 300) && (resp < 700)) {
    10332             if ((option_verbose > 2) && (resp != 487))
    10333                ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
    10334             if (sipmethod == SIP_INVITE) {
    10335                if (p->rtp) {
    10336                   /* Immediately stop RTP */
    10337                   ast_rtp_stop(p->rtp);
    10338                }
    10339                if (p->vrtp) {
    10340                   /* Immediately stop VRTP */
    10341                   ast_rtp_stop(p->vrtp);
    10342                }
    10343             }
    10344             /* XXX Locking issues?? XXX */
    10345             switch(resp) {
    10346             case 300: /* Multiple Choices */
    10347             case 301: /* Moved permenantly */
    10348             case 302: /* Moved temporarily */
    10349             case 305: /* Use Proxy */
    10350                parse_moved_contact(p, req);
    10351                /* Fall through */
    10352             case 486: /* Busy here */
    10353             case 600: /* Busy everywhere */
    10354             case 603: /* Decline */
    10355                if (p->owner)
    10356                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
    10357                break;
    10358             case 482: /* SIP is incapable of performing a hairpin call, which
    10359                          is yet another failure of not having a layer 2 (again, YAY
    10360                       IETF for thinking ahead).  So we treat this as a call
    10361                       forward and hope we end up at the right place... */
    10362                ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
    10363                if (p->owner)
    10364                   snprintf(p->owner->call_forward, sizeof(p->owner->call_forward), "Local/%s@%s", p->username, p->context);
    10365                /* Fall through */
    10366             case 488: /* Not acceptable here - codec error */
    10367             case 480: /* Temporarily Unavailable */
    10368             case 404: /* Not Found */
    10369             case 410: /* Gone */
    10370             case 400: /* Bad Request */
    10371             case 500: /* Server error */
    10372             case 503: /* Service Unavailable */
    10373             case 504: /* Server Timeout */
    10374                if (owner)
    10375                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
    10376                break;
    10377             default:
    10378                /* Send hangup */
    10379                if (owner)
    10380                   ast_queue_hangup(p->owner);
    10381                break;
    10382             }
    10383             /* ACK on invite */
    10384             if (sipmethod == SIP_INVITE)
    10385                transmit_request(p, SIP_ACK, seqno, 0, 0);
    10386             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
    10387                ast_set_flag(p, SIP_ALREADYGONE);
    10388             if (!p->owner)
    10389                ast_set_flag(p, SIP_NEEDDESTROY);
    10390          } else if ((resp >= 100) && (resp < 200)) {
    10391             if (sipmethod == SIP_INVITE) {
    10392                if (!ignore)
    10393                   sip_cancel_destroy(p);
    10394                if (find_sdp(req))
    10395                   process_sdp(p, req);
    10396                if (p->owner) {
    10397                   /* Queue a progress frame */
    10398                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
    10399                }
    10400             }
    10401          } else
    10402             ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
    10403       }
    10404    } else {
    10405       /* Responses to OUTGOING SIP requests on INCOMING calls
    10406          get handled here. As well as out-of-call message responses */
    10407       if (req->debug)
    10408          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
    10409       if (resp == 200) {
    10410          /* Tags in early session is replaced by the tag in 200 OK, which is
    10411          the final reply to our INVITE */
    10412          gettag(req, "To", p->theirtag, sizeof(p->theirtag));
    10413       }
    10414
    10415       switch(resp) {
    10416       case 200:
    10417          if (sipmethod == SIP_INVITE) {
    10418             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10419          } else if (sipmethod == SIP_CANCEL) {
    10420             ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");
    10421          } else if (sipmethod == SIP_MESSAGE)
    10422             /* We successfully transmitted a message */
    10423             ast_set_flag(p, SIP_NEEDDESTROY);
    10424          else if (sipmethod == SIP_BYE)
    10425             /* Ok, we're ready to go */
    10426             ast_set_flag(p, SIP_NEEDDESTROY);
    10427          break;
    10428       case 401:   /* www-auth */
    10429       case 407:
    10430          if (sipmethod == SIP_BYE || sipmethod == SIP_REFER) {
    10431             char *auth, *auth2;
    10432
    10433             if (resp == 407) {
    10434                auth = "Proxy-Authenticate";
    10435                auth2 = "Proxy-Authorization";
    10436             } else {
    10437                auth = "WWW-Authenticate";
    10438                auth2 = "Authorization";
    10439             }
    10440             if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
    10441                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
    10442                ast_set_flag(p, SIP_NEEDDESTROY);
    10443             }
    10444          } else if (sipmethod == SIP_INVITE) {
    10445             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10446          }
    10447          break;
    10448       case 481:   /* Call leg does not exist */
    10449          if (sipmethod == SIP_INVITE) {
    10450             /* Re-invite failed */
    10451             handle_response_invite(p, resp, rest, req, ignore, seqno);
    10452          }
    10453          break;
    10454       default: /* Errors without handlers */
    10455          if ((resp >= 100) && (resp < 200)) {
    10456             if (sipmethod == SIP_INVITE && !ignore)   /* re-invite */
    10457                sip_cancel_destroy(p);
    10458
    10459          }
    10460          if ((resp >= 300) && (resp < 700)) {
    10461             if ((option_verbose > 2) && (resp != 487))
    10462                ast_verbose(VERBOSE_PREFIX_3 "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
    10463             switch(resp) {
    10464             case 488: /* Not acceptable here - codec error */
    10465             case 603: /* Decline */
    10466             case 500: /* Server error */
    10467             case 503: /* Service Unavailable */
    10468             case 504: /* Server timeout */
    10469
    10470                if (sipmethod == SIP_INVITE && !ignore) { /* re-invite failed */
    10471                   sip_cancel_destroy(p);
    10472                }
    10473                break;
    10474             }
    10475          }
    10476          break;
    10477       }
    10478    }
    10479 }
    10480
    10481 struct sip_dual {
    10482    struct ast_channel *chan1;
    10483    struct ast_channel *chan2;
    10484    struct sip_request req;
    10485 };
    10486
    10487 /*! \brief  sip_park_thread: Park SIP call support function */
    10488 static void *sip_park_thread(void *stuff)
    10489 {
    10490    struct ast_channel *chan1, *chan2;
    10491    struct sip_dual *d;
    10492    struct sip_request req;
    10493    int ext;
    10494    int res;
    10495    d = stuff;
    10496    chan1 = d->chan1;
    10497    chan2 = d->chan2;
    10498    copy_request(&req, &d->req);
    10499    free(d);
    10500    ast_mutex_lock(&chan1->lock);
    10501    ast_do_masquerade(chan1);
    10502    ast_mutex_unlock(&chan1->lock);
    10503    res = ast_park_call(chan1, chan2, 0, &ext);
    10504    /* Then hangup */
    10505    ast_hangup(chan2);
    10506    ast_log(LOG_DEBUG, "Parked on extension '%d'\n", ext);
    10507    return NULL;
    10508 }
    10509
    10510 /*! \brief  sip_park: Park a call ---*/
    10511 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req)
    10512 {
    10513    struct sip_dual *d;
    10514    struct ast_channel *chan1m, *chan2m;
    10515    pthread_t th;
    10516    chan1m = ast_channel_alloc(0);
    10517    chan2m = ast_channel_alloc(0);
    10518    if ((!chan2m) || (!chan1m)) {
    10519       if (chan1m)
    10520          ast_hangup(chan1m);
    10521       if (chan2m)
    10522          ast_hangup(chan2m);
    10523       return -1;
    10524    }
    10525    snprintf(chan1m->name, sizeof(chan1m->name), "Parking/%s", chan1->name);
    10526    /* Make formats okay */
    10527    chan1m->readformat = chan1->readformat;
    10528    chan1m->writeformat = chan1->writeformat;
    10529    ast_channel_masquerade(chan1m, chan1);
    10530    /* Setup the extensions and such */
    10531    ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
    10532    ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
    10533    chan1m->priority = chan1->priority;
    10534
    10535    /* We make a clone of the peer channel too, so we can play
    10536       back the announcement */
    10537    snprintf(chan2m->name, sizeof (chan2m->name), "SIPPeer/%s",chan2->name);
    10538    /* Make formats okay */
    10539    chan2m->readformat = chan2->readformat;
    10540    chan2m->writeformat = chan2->writeformat;
    10541    ast_channel_masquerade(chan2m, chan2);
    10542    /* Setup the extensions and such */
    10543    ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
    10544    ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
    10545    chan2m->priority = chan2->priority;
    10546    ast_mutex_lock(&chan2m->lock);
    10547    if (ast_do_masquerade(chan2m)) {
    10548       ast_log(LOG_WARNING, "Masquerade failed :(\n");
    10549       ast_mutex_unlock(&chan2m->lock);
    10550       ast_hangup(chan2m);
    10551       return -1;
    10552    }
    10553    ast_mutex_unlock(&chan2m->lock);
    10554    d = malloc(sizeof(struct sip_dual));
    10555    if (d) {
    10556       pthread_attr_t attr;
    10557
    10558       pthread_attr_init(&attr);
    10559       pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    10560
    10561       memset(d, 0, sizeof(*d));
    10562       /* Save original request for followup */
    10563       copy_request(&d->req, req);
    10564       d->chan1 = chan1m;
    10565       d->chan2 = chan2m;
    10566       if (!ast_pthread_create(&th, &attr, sip_park_thread, d)) {
    10567          pthread_attr_destroy(&attr);
    10568          return 0;
    10569       }
    10570       pthread_attr_destroy(&attr);
    10571       free(d);
    10572    }
    10573    return -1;
    10574 }
    10575
    10576 /*! \brief  ast_quiet_chan: Turn off generator data */
    10577 static void ast_quiet_chan(struct ast_channel *chan)
    10578 {
    10579    if (chan && chan->_state == AST_STATE_UP) {
    10580       if (chan->generatordata)
    10581          ast_deactivate_generator(chan);
    10582    }
    10583 }
    10584
    10585 /*! \brief  attempt_transfer: Attempt transfer of SIP call ---*/
    10586 static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
    10587 {
    10588    int res = 0;
    10589    struct ast_channel
    10590       *chana = NULL,
    10591       *chanb = NULL,
    10592       *bridgea = NULL,
    10593       *bridgeb = NULL,
    10594       *peera = NULL,
    10595       *peerb = NULL,
    10596       *peerc = NULL,
    10597       *peerd = NULL;
    10598
    10599    if (!p1->owner || !p2->owner) {
    10600       ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
    10601       return -1;
    10602    }
    10603    chana = p1->owner;
    10604    chanb = p2->owner;
    10605    bridgea = ast_bridged_channel(chana);
    10606    bridgeb = ast_bridged_channel(chanb);
    10607
    10608    if (bridgea) {
    10609       peera = chana;
    10610       peerb = chanb;
    10611       peerc = bridgea;
    10612       peerd = bridgeb;
    10613    } else if (bridgeb) {
    10614       peera = chanb;
    10615       peerb = chana;
    10616       peerc = bridgeb;
    10617       peerd = bridgea;
    10618    }
    10619
    10620    if (peera && peerb && peerc && (peerb != peerc)) {
    10621       ast_quiet_chan(peera);
    10622       ast_quiet_chan(peerb);
    10623       ast_quiet_chan(peerc);
    10624       ast_quiet_chan(peerd);
    10625
    10626       if (peera->cdr && peerb->cdr) {
    10627          peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
    10628       } else if (peera->cdr) {
    10629          peerb->cdr = peera->cdr;
    10630       }
    10631       peera->cdr = NULL;
    10632
    10633       if (peerb->cdr && peerc->cdr) {
    10634          peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
    10635       } else if (peerc->cdr) {
    10636          peerb->cdr = peerc->cdr;
    10637       }
    10638       peerc->cdr = NULL;
    10639
    10640       if (ast_channel_masquerade(peerb, peerc)) {
    10641          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
    10642          res = -1;
    10643       }
    10644       return res;
    10645    } else {
    10646       ast_log(LOG_NOTICE, "Transfer attempted with no appropriate bridged calls to transfer\n");
    10647       if (chana)
    10648          ast_softhangup_nolock(chana, AST_SOFTHANGUP_DEV);
    10649       if (chanb)
    10650          ast_softhangup_nolock(chanb, AST_SOFTHANGUP_DEV);
    10651       return -1;
    10652    }
    10653    return 0;
    10654 }
    10655
    10656 /*! \brief  gettag: Get tag from packet */
    10657 static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize)
    10658 {
    10659
    10660    char *thetag, *sep;
    10661
    10662
    10663    if (!tagbuf)
    10664       return NULL;
    10665    tagbuf[0] = '\0';    /* reset the buffer */
    10666    thetag = get_header(req, header);
    10667    thetag = strcasestr(thetag, ";tag=");
    10668    if (thetag) {
    10669       thetag += 5;
    10670       ast_copy_string(tagbuf, thetag, tagbufsize);
    10671       sep = strchr(tagbuf, ';');
    10672       if (sep)
    10673          *sep = '\0';
    10674    }
    10675    return thetag;
    10676 }
    10677
    10678 /*! \brief  handle_request_options: Handle incoming OPTIONS request */
    10679 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, int debug)
    10680 {
    10681    int res;
    10682
    10683    res = get_destination(p, req);
    10684    build_contact(p);
    10685    /* XXX Should we authenticate OPTIONS? XXX */
    10686    if (ast_strlen_zero(p->context))
    10687       strcpy(p->context, default_context);
    10688    if (res < 0)
    10689       transmit_response_with_allow(p, "404 Not Found", req, 0);
    10690    else if (res > 0)
    10691       transmit_response_with_allow(p, "484 Address Incomplete", req, 0);
    10692    else
    10693       transmit_response_with_allow(p, "200 OK", req, 0);
    10694    /* Destroy if this OPTIONS was the opening request, but not if
    10695       it's in the middle of a normal call flow. */
    10696    if (!p->lastinvite)
    10697       ast_set_flag(p, SIP_NEEDDESTROY);
    10698
    10699    return res;
    10700 }
    10701
    10702 /*! \brief  handle_request_invite: Handle incoming INVITE request */
    10703 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin, int *recount, char *e)
    10704 {
    10705    int res = 1;
    10706    struct ast_channel *c=NULL;
    10707    int gotdest;
    10708    struct ast_frame af = { AST_FRAME_NULL, };
    10709    char *supported;
    10710    char *required;
    10711    unsigned int required_profile = 0;
    10712    int reinvite = 0;
    10713
    10714    /* Find out what they support */
    10715    if (!p->sipoptions) {
    10716       supported = get_header(req, "Supported");
    10717       if (supported)
    10718          parse_sip_options(p, supported);
    10719    }
    10720    required = get_header(req, "Require");
    10721    if (!ast_strlen_zero(required)) {
    10722       required_profile = parse_sip_options(NULL, required);
    10723       if (required_profile) {    /* They require something */
    10724          /* At this point we support no extensions, so fail */
    10725          transmit_response_with_unsupported(p, "420 Bad extension", req, required);
    10726          if (!p->lastinvite)
    10727             ast_set_flag(p, SIP_NEEDDESTROY);
    10728          return -1;
    10729
    10730       }
    10731    }
    10732
    10733    /* Check if this is a loop */
    10734    /* This happens since we do not properly support SIP domain
    10735       handling yet... -oej */
    10736    if (ast_test_flag(p, SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
    10737       /* This is a call to ourself.  Send ourselves an error code and stop
    10738          processing immediately, as SIP really has no good mechanism for
    10739          being able to call yourself */
    10740       transmit_response_reliable(p, "482 Loop Detected", req, 1);
    10741       if (!p->lastinvite)
    10742          ast_set_flag(p, SIP_NEEDDESTROY);
    10743       return 0;
    10744    }
    10745    if (!ignore) {
    10746       /* Use this as the basis */
    10747       if (debug)
    10748          ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
    10749       sip_cancel_destroy(p);
    10750       /* This call is no longer outgoing if it ever was */
    10751       ast_clear_flag(p, SIP_OUTGOING);
    10752       /* This also counts as a pending invite */
    10753       p->pendinginvite = seqno;
    10754       copy_request(&p->initreq, req);
    10755       check_via(p, req);
    10756       if (p->owner) {
    10757          /* Handle SDP here if we already have an owner */
    10758          if (find_sdp(req)) {
    10759             if (process_sdp(p, req)) {
    10760                transmit_response(p, "488 Not acceptable here", req);
    10761                if (!p->lastinvite)
    10762                   ast_set_flag(p, SIP_NEEDDESTROY);
    10763                return -1;
    10764             }
    10765          } else {
    10766             p->jointcapability = p->capability;
    10767             ast_log(LOG_DEBUG, "Hm....  No sdp for the moment\n");
    10768          }
    10769       }
    10770    } else if (debug)
    10771       ast_verbose("Ignoring this INVITE request\n");
    10772    if (!p->lastinvite && !ignore && !p->owner) {
    10773       /* Handle authentication if this is our first invite */
    10774       res = check_user(p, req, SIP_INVITE, e, 1, sin, ignore);
    10775       /* if an authentication challenge was sent, we are done here */
    10776       if (res > 0)
    10777          return 0;
    10778       if (res < 0) {
    10779          if (res == -4) {
    10780             ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
    10781             transmit_fake_auth_response(p, SIP_INVITE, req, p->randdata, sizeof(p->randdata), 1, ignore);
    10782          } else {
    10783             ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
    10784             transmit_response_reliable(p, "403 Forbidden", req, 1);
    10785          }
    10786          ast_set_flag(p, SIP_NEEDDESTROY);
    10787          p->theirtag[0] = '\0'; /* Forget their to-tag, we'll get a new one */
    10788          return 0;
    10789       }
    10790       /* Process the SDP portion */
    10791       if (find_sdp(req)) {
    10792          if (process_sdp(p, req)) {
    10793             transmit_response(p, "488 Not acceptable here", req);
    10794             ast_set_flag(p, SIP_NEEDDESTROY);
    10795             return -1;
    10796          }
    10797       } else {
    10798          p->jointcapability = p->capability;
    10799          ast_log(LOG_DEBUG, "Hm....  No sdp for the moment\n");
    10800       }
    10801       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
    10802       if (p->owner)
    10803          ast_queue_frame(p->owner, &af);
    10804       /* Initialize the context if it hasn't been already */
    10805       if (ast_strlen_zero(p->context))
    10806          strcpy(p->context, default_context);
    10807       /* Check number of concurrent calls -vs- incoming limit HERE */
    10808       ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
    10809       res = update_call_counter(p, INC_CALL_LIMIT);
    10810       if (res) {
    10811          if (res < 0) {
    10812             ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
    10813             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req, 1);
    10814             ast_set_flag(p, SIP_NEEDDESTROY);
    10815          }
    10816          return 0;
    10817       }
    10818       /* Get destination right away */
    10819       gotdest = get_destination(p, NULL);
    10820
    10821       get_rdnis(p, NULL);
    10822       extract_uri(p, req);
    10823       build_contact(p);
    10824
    10825       if (gotdest) {
    10826          if (gotdest < 0)
    10827             transmit_response_reliable(p, "404 Not Found", req, 1);
    10828          else
    10829             transmit_response_reliable(p, "484 Address Incomplete", req, 1);
    10830          update_call_counter(p, DEC_CALL_LIMIT);
    10831          ast_set_flag(p, SIP_NEEDDESTROY);
    10832          return 0;
    10833       } else {
    10834          /* If no extension was specified, use the s one */
    10835          if (ast_strlen_zero(p->exten))
    10836             ast_copy_string(p->exten, "s", sizeof(p->exten));
    10837          /* Initialize tag */
    10838          make_our_tag(p->tag, sizeof(p->tag));
    10839          /* First invitation */
    10840          c = sip_new(p, AST_STATE_DOWN, ast_strlen_zero(p->username) ? NULL : p->username );
    10841          *recount = 1;
    10842          /* Save Record-Route for any later requests we make on this dialogue */
    10843          build_route(p, req, 0);
    10844          if (c) {
    10845             /* Pre-lock the call */
    10846             ast_mutex_lock(&c->lock);
    10847          }
    10848       }
    10849
    10850    } else {
    10851       if (option_debug > 1 && sipdebug)
    10852          ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
    10853       reinvite = 1;
    10854       c = p->owner;
    10855    }
    10856    if (!ignore && p)
    10857       p->lastinvite = seqno;
    10858    if (c) {
    10859 #ifdef OSP_SUPPORT
    10860       ast_channel_setwhentohangup (c, p->osptimelimit);
    10861 #endif
    10862       switch(c->_state) {
    10863       case AST_STATE_DOWN:
    10864          transmit_response(p, "100 Trying", req);
    10865          ast_setstate(c, AST_STATE_RING);
    10866          if (strcmp(p->exten, ast_pickup_ext())) {
    10867             enum ast_pbx_result res;
    10868
    10869             res = ast_pbx_start(c);
    10870
    10871             switch (res) {
    10872             case AST_PBX_FAILED:
    10873                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
    10874                if (ignore)
    10875                   transmit_response(p, "503 Unavailable", req);
    10876                else
    10877                   transmit_response_reliable(p, "503 Unavailable", req, 1);
    10878                break;
    10879             case AST_PBX_CALL_LIMIT:
    10880                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
    10881                if (ignore)
    10882                   transmit_response(p, "480 Temporarily Unavailable", req);
    10883                else
    10884                   transmit_response_reliable(p, "480 Temporarily Unavailable", req, 1);
    10885                break;
    10886             case AST_PBX_SUCCESS:
    10887                /* nothing to do */
    10888                break;
    10889             }
    10890
    10891             if (res) {
    10892                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
    10893                /* Unlock locks so ast_hangup can do its magic */
    10894                ast_mutex_unlock(&c->lock);
    10895                ast_mutex_unlock(&p->lock);
    10896                ast_hangup(c);
    10897                ast_mutex_lock(&p->lock);
    10898                c = NULL;
    10899             }
    10900          } else {
    10901             ast_mutex_unlock(&c->lock);
    10902             if (ast_pickup_call(c)) {
    10903                ast_log(LOG_NOTICE, "Nothing to pick up\n");
    10904                if (ignore)
    10905                   transmit_response(p, "503 Unavailable", req);
    10906                else
    10907                   transmit_response_reliable(p, "503 Unavailable", req, 1);
    10908                ast_set_flag(p, SIP_ALREADYGONE);
    10909                /* Unlock locks so ast_hangup can do its magic */
    10910                ast_mutex_unlock(&p->lock);
    10911                ast_hangup(c);
    10912                ast_mutex_lock(&p->lock);
    10913                c = NULL;
    10914             } else {
    10915                ast_mutex_unlock(&p->lock);
    10916                ast_setstate(c, AST_STATE_DOWN);
    10917                ast_hangup(c);
    10918                ast_mutex_lock(&p->lock);
    10919                c = NULL;
    10920             }
    10921          }
    10922          break;
    10923       case AST_STATE_RING:
    10924          transmit_response(p, "100 Trying", req);
    10925          break;
    10926       case AST_STATE_RINGING:
    10927          transmit_response(p, "180 Ringing", req);
    10928          break;
    10929       case AST_STATE_UP:
    10930          /* If this is not a re-invite or something to ignore - it's critical */
    10931          transmit_response_with_sdp(p, "200 OK", req, (ignore || reinvite) ? 1 : 2);
    10932          break;
    10933       default:
    10934          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
    10935          transmit_response(p, "100 Trying", req);
    10936       }
    10937    } else {
    10938       if (p && !ast_test_flag(p, SIP_NEEDDESTROY) && !ignore) {
    10939          if (!p->jointcapability) {
    10940             transmit_response_reliable(p, "488 Not Acceptable Here (codec error)", req, 1);
    10941          } else {
    10942             ast_log(LOG_NOTICE, "Unable to create/find channel\n");
    10943             transmit_response_reliable(p, "503 Unavailable", req, 1);
    10944          }
    10945          ast_set_flag(p, SIP_NEEDDESTROY);
    10946       }
    10947    }
    10948    return res;
    10949 }
    10950
    10951 /*! \brief  handle_request_refer: Handle incoming REFER request ---*/
    10952 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
    10953 {
    10954    struct ast_channel *c=NULL;
    10955    int res;
    10956    struct ast_channel *transfer_to;
    10957    char *transfercontext = NULL;
    10958
    10959    if (option_debug > 2)
    10960       ast_log(LOG_DEBUG, "SIP call transfer received for call %s (REFER)!\n", p->callid);
    10961    res = get_refer_info(p, req, &transfercontext);
    10962    if (ast_strlen_zero(p->context))
    10963       strcpy(p->context, default_context);
    10964    if (ast_strlen_zero(transfercontext))
    10965       transfercontext = p->context;
    10966    if (res < 0)
    10967       transmit_response(p, "603 Declined", req);
    10968    else if (res > 0)
    10969       transmit_response(p, "484 Address Incomplete", req);
    10970    else {
    10971       int nobye = 0;
    10972       if (!ignore) {
    10973          if (p->refer_call) {
    10974             ast_log(LOG_DEBUG,"202 Accepted (supervised)\n");
    10975             attempt_transfer(p, p->refer_call);
    10976             if (p->refer_call->owner)
    10977                ast_mutex_unlock(&p->refer_call->owner->lock);
    10978             ast_mutex_unlock(&p->refer_call->lock);
    10979             p->refer_call = NULL;
    10980             ast_set_flag(p, SIP_GOTREFER);
    10981          } else {
    10982             ast_log(LOG_DEBUG,"202 Accepted (blind)\n");
    10983             c = p->owner;
    10984             if (c) {
    10985                transfer_to = ast_bridged_channel(c);
    10986                if (transfer_to) {
    10987                   ast_log(LOG_DEBUG, "Got SIP blind transfer, applying to '%s'\n", transfer_to->name);
    10988                   ast_moh_stop(transfer_to);
    10989                   if (!strcmp(p->refer_to, ast_parking_ext())) {
    10990                      /* Must release c's lock now, because it will not longer
    10991                          be accessible after the transfer! */
    10992                      *nounlock = 1;
    10993                      ast_mutex_unlock(&c->lock);
    10994                      sip_park(transfer_to, c, req);
    10995                      nobye = 1;
    10996                   } else {
    10997                      /* Must release c's lock now, because it will not longer
    10998                          be accessible after the transfer! */
    10999                      *nounlock = 1;
    11000                      ast_mutex_unlock(&c->lock);
    11001                      ast_async_goto(transfer_to, transfercontext, p->refer_to,1);
    11002                   }
    11003                } else {
    11004                   ast_log(LOG_DEBUG, "Got SIP blind transfer but nothing to transfer to.\n");
    11005                   ast_queue_hangup(p->owner);
    11006                }
    11007             }
    11008             ast_set_flag(p, SIP_GOTREFER);
    11009          }
    11010          transmit_response(p, "202 Accepted", req);
    11011          transmit_notify_with_sipfrag(p, seqno);
    11012          /* Always increment on a BYE */
    11013          if (!nobye) {
    11014             transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
    11015             ast_set_flag(p, SIP_ALREADYGONE);
    11016          }
    11017       }
    11018    }
    11019    return res;
    11020 }
    11021
    11022 /*! \brief  handle_request_cancel: Handle incoming CANCEL request ---*/
    11023 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req, int debug, int ignore)
    11024 {
    11025
    11026    check_via(p, req);
    11027    ast_set_flag(p, SIP_ALREADYGONE);
    11028
    11029    if (ast_test_flag(p, SIP_INC_COUNT))
    11030       update_call_counter(p, DEC_CALL_LIMIT);
    11031
    11032    if (p->rtp) {
    11033       /* Immediately stop RTP */
    11034       ast_rtp_stop(p->rtp);
    11035    }
    11036    if (p->vrtp) {
    11037       /* Immediately stop VRTP */
    11038       ast_rtp_stop(p->vrtp);
    11039    }
    11040    if (p->owner)
    11041       ast_queue_hangup(p->owner);
    11042    else
    11043       ast_set_flag(p, SIP_NEEDDESTROY);
    11044    if (p->initreq.len > 0) {
    11045       if (!ignore)
    11046          transmit_response_reliable(p, "487 Request Terminated", &p->initreq, 1);
    11047       transmit_response(p, "200 OK", req);
    11048       return 1;
    11049    } else {
    11050       transmit_response(p, "481 Call Leg Does Not Exist", req);
    11051       return 0;
    11052    }
    11053 }
    11054
    11055 /*! \brief  handle_request_bye: Handle incoming BYE request ---*/
    11056 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req, int debug, int ignore)
    11057 {
    11058    struct ast_channel *c=NULL;
    11059    int res;
    11060    struct ast_channel *bridged_to;
    11061    char iabuf[INET_ADDRSTRLEN];
    11062
    11063    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
    11064    if (p->pendinginvite && !ast_test_flag(p, SIP_OUTGOING) && !ignore && !p->owner)
    11065       transmit_response_reliable(p, "487 Request Terminated", &p->initreq, 1);
    11066
    11067    copy_request(&p->initreq, req);
    11068    check_via(p, req);
    11069    ast_set_flag(p, SIP_ALREADYGONE);
    11070    if (p->rtp) {
    11071       /* Immediately stop RTP */
    11072       ast_rtp_stop(p->rtp);
    11073    }
    11074    if (p->vrtp) {
    11075       /* Immediately stop VRTP */
    11076       ast_rtp_stop(p->vrtp);
    11077    }
    11078    if (!ast_strlen_zero(get_header(req, "Also"))) {
    11079       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
    11080          ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
    11081       if (ast_strlen_zero(p->context))
    11082          strcpy(p->context, default_context);
    11083       res = get_also_info(p, req);
    11084       if (!res) {
    11085          c = p->owner;
    11086          if (c) {
    11087             bridged_to = ast_bridged_channel(c);
    11088             if (bridged_to) {
    11089                /* Don't actually hangup here... */
    11090                ast_moh_stop(bridged_to);
    11091                ast_async_goto(bridged_to, p->context, p->refer_to,1);
    11092             } else
    11093                ast_queue_hangup(p->owner);
    11094          }
    11095       } else {
    11096          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
    11097          if (p->owner)
    11098             ast_queue_hangup(p->owner);
    11099       }
    11100    } else if (p->owner) {
    11101       ast_queue_hangup(p->owner);
    11102       if (option_debug > 2)
    11103          ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
    11104    } else {
    11105       ast_set_flag(p, SIP_NEEDDESTROY);
    11106       if (option_debug > 2)
    11107          ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
    11108    }
    11109    transmit_response(p, "200 OK", req);
    11110
    11111    return 1;
    11112 }
    11113
    11114 /*! \brief  handle_request_message: Handle incoming MESSAGE request ---*/
    11115 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, int debug, int ignore)
    11116 {
    11117    if (!ignore) {
    11118       if (debug)
    11119          ast_verbose("Receiving message!\n");
    11120       receive_message(p, req);
    11121    } else {
    11122       transmit_response(p, "202 Accepted", req);
    11123    }
    11124    return 1;
    11125 }
    11126 /*! \brief  handle_request_subscribe: Handle incoming SUBSCRIBE request ---*/
    11127 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, struct sockaddr_in *sin, int seqno, char *e)
    11128 {
    11129    int gotdest;
    11130    int res = 0;
    11131    int firststate = AST_EXTENSION_REMOVED;
    11132
    11133    if (p->initreq.headers) {
    11134       /* We already have a dialog */
    11135       if (p->initreq.method != SIP_SUBSCRIBE) {
    11136          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
    11137          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
    11138          transmit_response(p, "403 Forbidden (within dialog)", req);
    11139          /* Do not destroy session, since we will break the call if we do */
    11140          ast_log(LOG_DEBUG, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
    11141          return 0;
    11142       } else {
    11143          if (debug)
    11144             ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
    11145       }
    11146    }
    11147    if (!ignore && !p->initreq.headers) {
    11148       /* Use this as the basis */
    11149       if (debug)
    11150          ast_verbose("Using latest SUBSCRIBE request as basis request\n");
    11151       /* This call is no longer outgoing if it ever was */
    11152       ast_clear_flag(p, SIP_OUTGOING);
    11153       copy_request(&p->initreq, req);
    11154       check_via(p, req);
    11155    } else if (debug && ignore)
    11156       ast_verbose("Ignoring this SUBSCRIBE request\n");
    11157
    11158    if (!p->lastinvite) {
    11159       char mailboxbuf[256]="";
    11160       int found = 0;
    11161       char *mailbox = NULL;
    11162       int mailboxsize = 0;
    11163       char *eventparam;
    11164
    11165       char *event = get_header(req, "Event");   /* Get Event package name */
    11166       char *accept = get_header(req, "Accept");
    11167
    11168       /* Find parameters to Event: header value and remove them for now */
    11169       eventparam = strchr(event, ';');
    11170       if (eventparam) {
    11171          *eventparam = '\0';
    11172          eventparam++;
    11173       }
    11174
    11175       if (!strcmp(event, "message-summary") && !strcmp(accept, "application/simple-message-summary")) {
    11176          mailbox = mailboxbuf;
    11177          mailboxsize = sizeof(mailboxbuf);
    11178       }
    11179       /* Handle authentication if this is our first subscribe */
    11180       res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, ignore, mailbox, mailboxsize);
    11181       /* if an authentication challenge was sent, we are done here */
    11182       if (res > 0)
    11183          return 0;
    11184       if (res < 0) {
    11185          if (res == -4) {
    11186             ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
    11187             transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, p->randdata, sizeof(p->randdata), 1, ignore);
    11188          } else {
    11189             ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
    11190             if (ignore)
    11191                transmit_response(p, "403 Forbidden", req);
    11192             else
    11193                transmit_response_reliable(p, "403 Forbidden", req, 1);
    11194          }
    11195          ast_set_flag(p, SIP_NEEDDESTROY);
    11196          return 0;
    11197       }
    11198       gotdest = get_destination(p, NULL);
    11199       /* Initialize the context if it hasn't been already;
    11200          note this is done _after_ handling any domain lookups,
    11201          because the context specified there is for calls, not
    11202          subscriptions
    11203       */
    11204       if (!ast_strlen_zero(p->subscribecontext))
    11205          ast_copy_string(p->context, p->subscribecontext, sizeof(p->context));
    11206       else if (ast_strlen_zero(p->context))
    11207          strcpy(p->context, default_context);
    11208
    11209       /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
    11210       parse_ok_contact(p, req);
    11211
    11212       /* Get destination right away */
    11213       build_contact(p);
    11214       if (gotdest) {
    11215          if (gotdest < 0)
    11216             transmit_response(p, "404 Not Found", req);
    11217          else
    11218             transmit_response(p, "484 Address Incomplete", req);  /* Overlap dialing on SUBSCRIBE?? */
    11219          ast_set_flag(p, SIP_NEEDDESTROY);
    11220       } else {
    11221
    11222          /* Initialize tag for new subscriptions */
    11223          if (ast_strlen_zero(p->tag))
    11224             make_our_tag(p->tag, sizeof(p->tag));
    11225
    11226          if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
    11227
    11228             /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
    11229             /* Polycom phones only handle xpidf+xml, even if they say they can
    11230                handle pidf+xml as well
    11231             */
    11232             if (strstr(p->useragent, "Polycom")) {
    11233                p->subscribed = XPIDF_XML;
    11234             } else if (strstr(accept, "application/pidf+xml")) {
    11235                p->subscribed = PIDF_XML;         /* RFC 3863 format */
    11236             } else if (strstr(accept, "application/dialog-info+xml")) {
    11237                p->subscribed = DIALOG_INFO_XML;
    11238                /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
    11239             } else if (strstr(accept, "application/cpim-pidf+xml")) {
    11240                p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
    11241             } else if (strstr(accept, "application/xpidf+xml")) {
    11242                p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
    11243             } else if (ast_strlen_zero(accept)) {
    11244                if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
    11245                   transmit_response(p, "489 Bad Event", req);
    11246
    11247                   ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s'\n",
    11248                      p->stateid, p->laststate, p->dialogver, p->subscribecontext);
    11249                   ast_set_flag(p, SIP_NEEDDESTROY);
    11250                   return 0;
    11251                }
    11252                /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
    11253                   so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
    11254             } else {
    11255                /* Can't find a format for events that we know about */
    11256                char mybuf[200];
    11257                snprintf(mybuf,sizeof(mybuf),"489 Bad Event (format %s)", accept);
    11258                transmit_response(p, mybuf, req);
    11259                ast_set_flag(p, SIP_NEEDDESTROY);
    11260                return 0;
    11261             }
    11262             if (option_debug > 2)
    11263                ast_log(LOG_DEBUG, "Subscription type: Event: %s Format: %s\n",  subscription_types[p->subscribed].event, subscription_types[p->subscribed].mediatype);
    11264          } else if (!strcmp(event, "message-summary") && !strcmp(accept, "application/simple-message-summary")) {
    11265             /* Looks like they actually want a mailbox status */
    11266
    11267             /* At this point, we should check if they subscribe to a mailbox that
    11268               has the same extension as the peer or the mailbox id. If we configure
    11269               the context to be the same as a SIP domain, we could check mailbox
    11270               context as well. To be able to securely accept subscribes on mailbox
    11271               IDs, not extensions, we need to check the digest auth user to make
    11272               sure that the user has access to the mailbox.
    11273
    11274               Since we do not act on this subscribe anyway, we might as well
    11275               accept any authenticated peer with a mailbox definition in their
    11276               config section.
    11277
    11278             */
    11279             if (!ast_strlen_zero(mailbox)) {
    11280                found++;
    11281             }
    11282
    11283             if (found){
    11284                transmit_response(p, "200 OK", req);
    11285                ast_set_flag(p, SIP_NEEDDESTROY);
    11286             } else {
    11287                transmit_response(p, "404 Not found", req);
    11288                ast_set_flag(p, SIP_NEEDDESTROY);
    11289             }
    11290             return 0;
    11291          } else { /* At this point, Asterisk does not understand the specified event */
    11292             transmit_response(p, "489 Bad Event", req);
    11293             if (option_debug > 1)
    11294                ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
    11295             ast_set_flag(p, SIP_NEEDDESTROY);
    11296             return 0;
    11297          }
    11298          if (p->subscribed != NONE) {
    11299             if (p->stateid > -1)
    11300                ast_extension_state_del(p->stateid, cb_extensionstate);
    11301             p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
    11302          }
    11303       }
    11304    }
    11305
    11306    if (!ignore && p)
    11307       p->lastinvite = seqno;
    11308    if (p && !ast_test_flag(p, SIP_NEEDDESTROY)) {
    11309       p->expiry = atoi(get_header(req, "Expires"));
    11310
    11311       /* The next 4 lines can be removed if the SNOM Expires bug is fixed */
    11312       if (p->subscribed == DIALOG_INFO_XML) {
    11313          if (p->expiry > max_expiry)
    11314             p->expiry = max_expiry;
    11315       }
    11316       if (sipdebug || option_debug > 1)
    11317          ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
    11318       if (p->autokillid > -1)
    11319          sip_cancel_destroy(p);  /* Remove subscription expiry for renewals */
    11320       sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
    11321
    11322       if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
    11323          char iabuf[INET_ADDRSTRLEN];
    11324
    11325          ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension\n", p->exten, p->context, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
    11326          transmit_response(p, "404 Not found", req);
    11327          ast_set_flag(p, SIP_NEEDDESTROY);
    11328          return 0;
    11329       } else {
    11330          struct sip_pvt *p_old;
    11331
    11332          transmit_response(p, "200 OK", req);
    11333          transmit_state_notify(p, firststate, 1, 1, 0);  /* Send first notification */
    11334          append_history(p, "Subscribestatus", ast_extension_state2str(firststate));
    11335
    11336          /* remove any old subscription from this peer for the same exten/context,
    11337             as the peer has obviously forgotten about it and it's wasteful to wait
    11338             for it to expire and send NOTIFY messages to the peer only to have them
    11339             ignored (or generate errors)
    11340          */
    11341          ast_mutex_lock(&iflock);
    11342          for (p_old = iflist; p_old; p_old = p_old->next) {
    11343             if (p_old == p)
    11344                continue;
    11345             if (p_old->initreq.method != SIP_SUBSCRIBE)
    11346                continue;
    11347             if (p_old->subscribed == NONE)
    11348                continue;
    11349             ast_mutex_lock(&p_old->lock);
    11350             if (!strcmp(p_old->username, p->username)) {
    11351                if (!strcmp(p_old->exten, p->exten) &&
    11352                    !strcmp(p_old->context, p->context)) {
    11353                   ast_set_flag(p_old, SIP_NEEDDESTROY);
    11354                   ast_mutex_unlock(&p_old->lock);
    11355                   break;
    11356                }
    11357             }
    11358             ast_mutex_unlock(&p_old->lock);
    11359          }
    11360          ast_mutex_unlock(&iflock);
    11361       }
    11362       if (!p->expiry)
    11363          ast_set_flag(p, SIP_NEEDDESTROY);
    11364    }
    11365    return 1;
    11366 }
    11367
    11368 /*! \brief  handle_request_register: Handle incoming REGISTER request ---*/
    11369 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, struct sockaddr_in *sin, char *e)
    11370 {
    11371    int res = 0;
    11372    char iabuf[INET_ADDRSTRLEN];
    11373
    11374    /* Use this as the basis */
    11375    if (debug)
    11376       ast_verbose("Using latest REGISTER request as basis request\n");
    11377    copy_request(&p->initreq, req);
    11378    check_via(p, req);
    11379    if ((res = register_verify(p, sin, req, e, ignore)) < 0)  {
    11380       const char *error;
    11381       switch (res) {
    11382       case -1: error = "Wrong password";
    11383          break;
    11384       case -2: error = "Username/auth name mismatch";
    11385          break;
    11386       case -3: error = "Not a local SIP domain";
    11387          break;
    11388       case -4: error = "ACL error (permit/deny)";
    11389          break;
    11390       case -5: error = "Peer is not supposed to register";
    11391          break;
    11392       default: error = "Unknown error";
    11393          break;
    11394       }
    11395       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n", get_header(req, "To"), ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), error);
    11396    }
    11397    if (res < 1) {
    11398       /* Destroy the session, but keep us around for just a bit in case they don't
    11399          get our 200 OK */
    11400       sip_scheddestroy(p, 15*1000);
    11401    }
    11402    return res;
    11403 }
    11404
    11405 /*! \brief  handle_request: Handle SIP requests (methods) ---*/
    11406 /*      this is where all incoming requests go first   */
    11407 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
    11408 {
    11409    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
    11410       relatively static */
    11411    char *cmd;
    11412    char *cseq;
    11413    char *useragent;
    11414    int seqno;
    11415    int len;
    11416    int ignore=0;
    11417    int respid;
    11418    int res = 0;
    11419    char iabuf[INET_ADDRSTRLEN];
    11420    int debug = sip_debug_test_pvt(p);
    11421    char *e;
    11422    int error = 0;
    11423
    11424    /* Get Method and Cseq */
    11425    cseq = get_header(req, "Cseq");
    11426    cmd = req->header[0];
    11427
    11428    /* Must have Cseq */
    11429    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
    11430       ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
    11431       error = 1;
    11432    }
    11433    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
    11434       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
    11435       error = 1;
    11436    }
    11437    if (error) {
    11438       if (!p->initreq.headers)   /* New call */
    11439          ast_set_flag(p, SIP_NEEDDESTROY);   /* Make sure we destroy this dialog */
    11440       return -1;
    11441    }
    11442    /* Get the command XXX */
    11443
    11444    cmd = req->rlPart1;
    11445    e = req->rlPart2;
    11446
    11447    /* Save useragent of the client */
    11448    useragent = get_header(req, "User-Agent");
    11449    if (!ast_strlen_zero(useragent))
    11450       ast_copy_string(p->useragent, useragent, sizeof(p->useragent));
    11451
    11452    /* Find out SIP method for incoming request */
    11453    if (req->method == SIP_RESPONSE) {  /* Response to our request */
    11454       /* Response to our request -- Do some sanity checks */
    11455       if (!p->initreq.headers) {
    11456          ast_log(LOG_DEBUG, "That's odd...  Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
    11457          ast_set_flag(p, SIP_NEEDDESTROY);
    11458          return 0;
    11459       } else if (p->ocseq && (p->ocseq < seqno)) {
    11460          ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
    11461          return -1;
    11462       } else if (p->ocseq && (p->ocseq != seqno)) {
    11463          /* ignore means "don't do anything with it" but still have to
    11464             respond appropriately  */
    11465          ignore=1;
    11466       } else if (e) {
    11467          e = ast_skip_blanks(e);
    11468          if (sscanf(e, "%30d %n", &respid, &len) != 1) {
    11469             ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
    11470          } else {
    11471             /* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
    11472             if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
    11473                extract_uri(p, req);
    11474             handle_response(p, respid, e + len, req, ignore, seqno);
    11475          }
    11476       }
    11477       return 0;
    11478    }
    11479
    11480    /* New SIP request coming in
    11481       (could be new request in existing SIP dialog as well...)
    11482     */
    11483
    11484    p->method = req->method;   /* Find out which SIP method they are using */
    11485    if (option_debug > 2)
    11486       ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
    11487
    11488    if (p->icseq && (p->icseq > seqno)) {
    11489       if (option_debug)
    11490          ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
    11491       if (req->method != SIP_ACK)
    11492          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
    11493       return -1;
    11494    } else if (p->icseq && (p->icseq == seqno) && req->method != SIP_ACK &&(p->method != SIP_CANCEL|| ast_test_flag(p, SIP_ALREADYGONE))) {
    11495       /* ignore means "don't do anything with it" but still have to
    11496          respond appropriately.  We do this if we receive a repeat of
    11497          the last sequence number  */
    11498       ignore=2;
    11499       if (option_debug > 2)
    11500          ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
    11501    }
    11502
    11503    if (seqno >= p->icseq)
    11504       /* Next should follow monotonically (but not necessarily
    11505          incrementally -- thanks again to the genius authors of SIP --
    11506          increasing */
    11507       p->icseq = seqno;
    11508
    11509    /* Find their tag if we haven't got it */
    11510    if (ast_strlen_zero(p->theirtag)) {
    11511       gettag(req, "From", p->theirtag, sizeof(p->theirtag));
    11512    }
    11513    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
    11514
    11515    if (pedanticsipchecking) {
    11516       /* If this is a request packet without a from tag, it's not
    11517          correct according to RFC 3261  */
    11518       /* Check if this a new request in a new dialog with a totag already attached to it,
    11519          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
    11520       if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
    11521          /* If this is a first request and it got a to-tag, it is not for us */
    11522          if (!ignore && req->method == SIP_INVITE) {
    11523             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req, 1);
    11524             /* Will cease to exist after ACK */
    11525          } else if (req->method != SIP_ACK) {
    11526             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
    11527             ast_set_flag(p, SIP_NEEDDESTROY);
    11528          }
    11529          return res;
    11530       }
    11531    }
    11532
    11533    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
    11534       transmit_response(p, "400 Bad request", req);
    11535       ast_set_flag(p, SIP_NEEDDESTROY);
    11536       return -1;
    11537    }
    11538
    11539    /* Handle various incoming SIP methods in requests */
    11540    switch (p->method) {
    11541    case SIP_OPTIONS:
    11542       res = handle_request_options(p, req, debug);
    11543       break;
    11544    case SIP_INVITE:
    11545       res = handle_request_invite(p, req, debug, ignore, seqno, sin, recount, e);
    11546       break;
    11547    case SIP_REFER:
    11548       res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
    11549       break;
    11550    case SIP_CANCEL:
    11551       res = handle_request_cancel(p, req, debug, ignore);
    11552       break;
    11553    case SIP_BYE:
    11554       res = handle_request_bye(p, req, debug, ignore);
    11555       break;
    11556    case SIP_MESSAGE:
    11557       res = handle_request_message(p, req, debug, ignore);
    11558       break;
    11559    case SIP_SUBSCRIBE:
    11560       res = handle_request_subscribe(p, req, debug, ignore, sin, seqno, e);
    11561       break;
    11562    case SIP_REGISTER:
    11563       res = handle_request_register(p, req, debug, ignore, sin, e);
    11564       break;
    11565    case SIP_INFO:
    11566       if (!ignore) {
    11567          if (debug)
    11568             ast_verbose("Receiving INFO!\n");
    11569          handle_request_info(p, req);
    11570       } else { /* if ignoring, transmit response */
    11571          transmit_response(p, "200 OK", req);
    11572       }
    11573       break;
    11574    case SIP_NOTIFY:
    11575       /* XXX we get NOTIFY's from some servers. WHY?? Maybe we should
    11576          look into this someday XXX */
    11577       transmit_response(p, "200 OK", req);
    11578       if (!p->lastinvite)
    11579          ast_set_flag(p, SIP_NEEDDESTROY);
    11580       break;
    11581    case SIP_ACK:
    11582       /* Make sure we don't ignore this */
    11583       if (seqno == p->pendinginvite) {
    11584          p->pendinginvite = 0;
    11585          __sip_ack(p, seqno, FLAG_RESPONSE, 0);
    11586          if (find_sdp(req)) {
    11587             if (process_sdp(p, req))
    11588                return -1;
    11589          }
    11590          check_pendings(p);
    11591       }
    11592       if (!p->lastinvite && ast_strlen_zero(p->randdata))
    11593          ast_set_flag(p, SIP_NEEDDESTROY);
    11594       break;
    11595    default:
    11596       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
    11597       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
    11598          cmd, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
    11599       /* If this is some new method, and we don't have a call, destroy it now */
    11600       if (!p->initreq.headers)
    11601          ast_set_flag(p, SIP_NEEDDESTROY);
    11602       break;
    11603    }
    11604    return res;
    11605 }
    11606
    11607 /*! \brief  sipsock_read: Read data from SIP socket ---*/
    11608 /*    Successful messages is connected to SIP call and forwarded to handle_request() */
    11609 static int sipsock_read(int *id, int fd, short events, void *ignore)
    11610 {
    11611    struct sip_request req;
    11612    struct sockaddr_in sin = { 0, };
    11613    struct sip_pvt *p;
    11614    int res;
    11615    socklen_t len;
    11616    int nounlock;
    11617    int recount = 0;
    11618    char iabuf[INET_ADDRSTRLEN];
    11619    unsigned int lockretry = 100;
    11620
    11621    len = sizeof(sin);
    11622    memset(&req, 0, sizeof(req));
    11623    res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
    11624    if (res < 0) {
    11625 #if !defined(__FreeBSD__)
    11626       if (errno == EAGAIN)
    11627          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
    11628       else
    11629 #endif
    11630       if (errno != ECONNREFUSED)
    11631          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
    11632       return 1;
    11633    }
    11634    if (res == sizeof(req.data)) {
    11635       ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
    11636       req.data[sizeof(req.data) - 1] = '\0';
    11637    } else
    11638       req.data[res] = '\0';
    11639    req.len = res;
    11640    if(sip_debug_test_addr(&sin))
    11641       ast_set_flag(&req, SIP_PKT_DEBUG);
    11642    if (pedanticsipchecking)
    11643       req.len = lws2sws(req.data, req.len);  /* Fix multiline headers */
    11644    if (ast_test_flag(&req, SIP_PKT_DEBUG)) {
    11645       ast_verbose("\n<-- SIP read from %s:%d: \n%s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), req.data);
    11646    }
    11647    parse_request(&req);
    11648    req.method = find_sip_method(req.rlPart1);
    11649    if (ast_test_flag(&req, SIP_PKT_DEBUG)) {
    11650       ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");
    11651    }
    11652
    11653    if (req.headers < 2) {
    11654       /* Must have at least two headers */
    11655       return 1;
    11656    }
    11657
    11658
    11659    /* Process request, with netlock held */
    11660 retrylock:
    11661    ast_mutex_lock(&netlock);
    11662    p = find_call(&req, &sin, req.method);
    11663    if (p) {
    11664       /* Go ahead and lock the owner if it has one -- we may need it */
    11665       if (p->owner && ast_mutex_trylock(&p->owner->lock)) {
    11666          ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
    11667          if (--lockretry) {
    11668             ast_mutex_unlock(&p->lock);
    11669             ast_mutex_unlock(&netlock);
    11670             usleep(1);
    11671             goto retrylock;
    11672          }
    11673       }
    11674       if (!lockretry) {
    11675          if (p->owner)
    11676             ast_log(LOG_ERROR, "We could NOT get the channel lock for %s - Call ID %s! \n", p->owner->name, p->callid);
    11677          ast_log(LOG_ERROR, "SIP MESSAGE JUST IGNORED: %s \n", req.data);
    11678          ast_log(LOG_ERROR, "BAD! BAD! BAD!\n");
    11679          ast_mutex_unlock(&p->lock);
    11680          ast_mutex_unlock(&netlock);
    11681          return 1;
    11682       }
    11683       memcpy(&p->recv, &sin, sizeof(p->recv));
    11684       if (recordhistory) {
    11685          char tmp[80];
    11686          /* This is a response, note what it was for */
    11687          snprintf(tmp, sizeof(tmp), "%s / %s /%s", req.data, get_header(&req, "CSeq"), req.rlPart2);
    11688          append_history(p, "Rx", tmp);
    11689       }
    11690       nounlock = 0;
    11691       if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
    11692          /* Request failed */
    11693          ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
    11694       }
    11695
    11696       if (p->owner && !nounlock)
    11697          ast_mutex_unlock(&p->owner->lock);
    11698       ast_mutex_unlock(&p->lock);
    11699    }
    11700    ast_mutex_unlock(&netlock);
    11701    if (recount)
    11702       ast_update_use_count();
    11703
    11704    return 1;
    11705 }
    11706
    11707 /*! \brief  sip_send_mwi_to_peer: Send message waiting indication ---*/
    11708 static int sip_send_mwi_to_peer(struct sip_peer *peer)
    11709 {
    11710    /* Called with peerl lock, but releases it */
    11711    struct sip_pvt *p;
    11712    int newmsgs, oldmsgs;
    11713
    11714    /* Do we have an IP address? If not, skip this peer */
    11715    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
    11716       return 0;
    11717
    11718    /* Check for messages */
    11719    ast_app_messagecount(peer->mailbox, &newmsgs, &oldmsgs);
    11720
    11721    time(&peer->lastmsgcheck);
    11722
    11723    /* Return now if it's the same thing we told them last time */
    11724    if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
    11725       return 0;
    11726    }
    11727
    11728    p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY);
    11729    if (!p) {
    11730       ast_log(LOG_WARNING, "Unable to build sip pvt data for MWI\n");
    11731       return -1;
    11732    }
    11733    peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));
    11734    if (create_addr_from_peer(p, peer)) {
    11735       /* Maybe they're not registered, etc. */
    11736       sip_destroy(p);
    11737       return 0;
    11738    }
    11739    /* Recalculate our side, and recalculate Call ID */
    11740    if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
    11741       memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
    11742    build_via(p, p->via, sizeof(p->via));
    11743    build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
    11744    /* Send MWI */
    11745    ast_set_flag(p, SIP_OUTGOING);
    11746    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
    11747    sip_scheddestroy(p, 15000);
    11748    return 0;
    11749 }
    11750
    11751 /*! \brief  do_monitor: The SIP monitoring thread ---*/
    11752 static void *do_monitor(void *data)
    11753 {
    11754    int res;
    11755    struct sip_pvt *sip;
    11756    struct sip_peer *peer = NULL;
    11757    time_t t;
    11758    int fastrestart =0;
    11759    int lastpeernum = -1;
    11760    int curpeernum;
    11761    int reloading;
    11762
    11763    /* Add an I/O event to our UDP socket */
    11764    if (sipsock > -1)
    11765       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
    11766
    11767    /* This thread monitors all the frame relay interfaces which are not yet in use
    11768       (and thus do not have a separate thread) indefinitely */
    11769    /* From here on out, we die whenever asked */
    11770    for(;;) {
    11771       /* Check for a reload request */
    11772       ast_mutex_lock(&sip_reload_lock);
    11773       reloading = sip_reloading;
    11774       sip_reloading = 0;
    11775       ast_mutex_unlock(&sip_reload_lock);
    11776       if (reloading) {
    11777          if (option_verbose > 0)
    11778             ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
    11779          sip_do_reload();
    11780
    11781          /* Change the I/O fd of our UDP socket */
    11782          if (sipsock > -1) {
    11783             if (sipsock_read_id)
    11784                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
    11785             else
    11786                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
    11787          }
    11788       }
    11789       /* Check for interfaces needing to be killed */
    11790       ast_mutex_lock(&iflock);
    11791 restartsearch:
    11792       time(&t);
    11793       sip = iflist;
    11794       /* don't scan the interface list if it hasn't been a reasonable period
    11795          of time since the last time we did it (when MWI is being sent, we can
    11796          get back to this point every millisecond or less)
    11797       */
    11798       while(!fastrestart && sip) {
    11799          ast_mutex_lock(&sip->lock);
    11800          if (sip->rtp && sip->owner && (sip->owner->_state == AST_STATE_UP) && !sip->redirip.sin_addr.s_addr) {
    11801             if (sip->lastrtptx && sip->rtpkeepalive && t > sip->lastrtptx + sip->rtpkeepalive) {
    11802                /* Need to send an empty RTP packet */
    11803                time(&sip->lastrtptx);
    11804                ast_rtp_sendcng(sip->rtp, 0);
    11805             }
    11806             if (sip->lastrtprx && (sip->rtptimeout || sip->rtpholdtimeout) && t > sip->lastrtprx + sip->rtptimeout) {
    11807                /* Might be a timeout now -- see if we're on hold */
    11808                struct sockaddr_in sin;
    11809                ast_rtp_get_peer(sip->rtp, &sin);
    11810                if (sin.sin_addr.s_addr ||
    11811                      (sip->rtpholdtimeout &&
    11812                        (t > sip->lastrtprx + sip->rtpholdtimeout))) {
    11813                   /* Needs a hangup */
    11814                   if (sip->rtptimeout) {
    11815                      while(sip->owner && ast_mutex_trylock(&sip->owner->lock)) {
    11816                         ast_mutex_unlock(&sip->lock);
    11817                         usleep(1);
    11818                         ast_mutex_lock(&sip->lock);
    11819                      }
    11820                      if (sip->owner) {
    11821                         ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n", sip->owner->name, (long)(t - sip->lastrtprx));
    11822                         /* Issue a softhangup */
    11823                         ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
    11824                         ast_mutex_unlock(&sip->owner->lock);
    11825                         /* forget the timeouts for this call, since a hangup
    11826                            has already been requested and we don't want to
    11827                            repeatedly request hangups
    11828                         */
    11829                         sip->rtptimeout = 0;
    11830                         sip->rtpholdtimeout = 0;
    11831                      }
    11832                   }
    11833                }
    11834             }
    11835          }
    11836          if (ast_test_flag(sip, SIP_NEEDDESTROY) && !sip->packets && !sip->owner) {
    11837             ast_mutex_unlock(&sip->lock);
    11838             __sip_destroy(sip, 1);
    11839             goto restartsearch;
    11840          }
    11841          ast_mutex_unlock(&sip->lock);
    11842          sip = sip->next;
    11843       }
    11844       ast_mutex_unlock(&iflock);
    11845       /* Don't let anybody kill us right away.  Nobody should lock the interface list
    11846          and wait for the monitor list, but the other way around is okay. */
    11847       ast_mutex_lock(&monlock);
    11848       /* Lock the network interface */
    11849       ast_mutex_lock(&netlock);
    11850       /* Okay, now that we know what to do, release the network lock */
    11851       ast_mutex_unlock(&netlock);
    11852       /* And from now on, we're okay to be killed, so release the monitor lock as well */
    11853       ast_mutex_unlock(&monlock);
    11854       pthread_testcancel();
    11855       /* Wait for sched or io */
    11856       res = ast_sched_wait(sched);
    11857       if ((res < 0) || (res > 1000))
    11858          res = 1000;
    11859       /* If we might need to send more mailboxes, don't wait long at all.*/
    11860       if (fastrestart)
    11861          res = 1;
    11862       res = ast_io_wait(io, res);
    11863       if (res > 20)
    11864          ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
    11865       ast_mutex_lock(&monlock);
    11866       if (res >= 0)  {
    11867          res = ast_sched_runq(sched);
    11868          if (res >= 20)
    11869             ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
    11870       }
    11871
    11872       /* needs work to send mwi to realtime peers */
    11873       time(&t);
    11874       fastrestart = 0;
    11875       curpeernum = 0;
    11876       peer = NULL;
    11877       ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
    11878          if ((curpeernum > lastpeernum) && !ast_strlen_zero(iterator->mailbox) && ((t - iterator->lastmsgcheck) > global_mwitime)) {
    11879             fastrestart = 1;
    11880             lastpeernum = curpeernum;
    11881             peer = ASTOBJ_REF(iterator);
    11882          };
    11883          curpeernum++;
    11884       } while (0)
    11885       );
    11886       if (peer) {
    11887          ASTOBJ_WRLOCK(peer);
    11888          sip_send_mwi_to_peer(peer);
    11889          ASTOBJ_UNLOCK(peer);
    11890          ASTOBJ_UNREF(peer,sip_destroy_peer);
    11891       } else {
    11892          /* Reset where we come from */
    11893          lastpeernum = -1;
    11894       }
    11895       ast_mutex_unlock(&monlock);
    11896    }
    11897    /* Never reached */
    11898    return NULL;
    11899
    11900 }
    11901
    11902 /*! \brief  restart_monitor: Start the channel monitor thread ---*/
    11903 static int restart_monitor(void)
    11904 {
    11905    /* If we're supposed to be stopped -- stay stopped */
    11906    if (monitor_thread == AST_PTHREADT_STOP)
    11907       return 0;
    11908    if (ast_mutex_lock(&monlock)) {
    11909       ast_log(LOG_WARNING, "Unable to lock monitor\n");
    11910       return -1;
    11911    }
    11912    if (monitor_thread == pthread_self()) {
    11913       ast_mutex_unlock(&monlock);
    11914       ast_log(LOG_WARNING, "Cannot kill myself\n");
    11915       return -1;
    11916    }
    11917    if (monitor_thread != AST_PTHREADT_NULL) {
    11918       /* Wake up the thread */
    11919       pthread_kill(monitor_thread, SIGURG);
    11920    } else {
    11921       /* Start a new monitor */
    11922       if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
    11923          ast_mutex_unlock(&monlock);
    11924          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
    11925          return -1;
    11926       }
    11927    }
    11928    ast_mutex_unlock(&monlock);
    11929    return 0;
    11930 }
    11931
    11932 /*! \brief  sip_poke_noanswer: No answer to Qualify poke ---*/
    11933 static int sip_poke_noanswer(void *data)
    11934 {
    11935    struct sip_peer *peer = data;
    11936
    11937    peer->pokeexpire = -1;
    11938    if (peer->lastms > -1) {
    11939       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
    11940       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
    11941    }
    11942    if (peer->call)
    11943       sip_destroy(peer->call);
    11944    peer->call = NULL;
    11945    peer->lastms = -1;
    11946    ast_device_state_changed("SIP/%s", peer->name);
    11947    /* Try again quickly */
    11948    peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
    11949    return 0;
    11950 }
    11951
    11952 /*! \brief  sip_poke_peer: Check availability of peer, also keep NAT open ---*/
    11953 /* This is done with the interval in qualify= option in sip.conf */
    11954 /* Default is 2 seconds */
    11955 static int sip_poke_peer(struct sip_peer *peer)
    11956 {
    11957    struct sip_pvt *p;
    11958    if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
    11959       /* IF we have no IP, or this isn't to be monitored, return
    11960         imeediately after clearing things out */
    11961       if (peer->pokeexpire > -1)
    11962          ast_sched_del(sched, peer->pokeexpire);
    11963       peer->lastms = 0;
    11964       peer->pokeexpire = -1;
    11965       peer->call = NULL;
    11966       return 0;
    11967    }
    11968    if (peer->call) {
    11969       if (sipdebug)
    11970          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
    11971       sip_destroy(peer->call);
    11972    }
    11973    p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS);
    11974    if (!peer->call) {
    11975       ast_log(LOG_WARNING, "Unable to allocate dialog for poking peer '%s'\n", peer->name);
    11976       return -1;
    11977    }
    11978    memcpy(&p->sa, &peer->addr, sizeof(p->sa));
    11979    memcpy(&p->recv, &peer->addr, sizeof(p->sa));
    11980    ast_copy_flags(p, peer, SIP_FLAGS_TO_COPY);
    11981
    11982    /* Send OPTIONs to peer's fullcontact */
    11983    if (!ast_strlen_zero(peer->fullcontact)) {
    11984       ast_copy_string (p->fullcontact, peer->fullcontact, sizeof(p->fullcontact));
    11985    }
    11986
    11987    if (!ast_strlen_zero(peer->tohost))
    11988       ast_copy_string(p->tohost, peer->tohost, sizeof(p->tohost));
    11989    else
    11990       ast_inet_ntoa(p->tohost, sizeof(p->tohost), peer->addr.sin_addr);
    11991
    11992    /* Recalculate our side, and recalculate Call ID */
    11993    if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
    11994       memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
    11995    build_via(p, p->via, sizeof(p->via));
    11996    build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
    11997
    11998    if (peer->pokeexpire > -1)
    11999       ast_sched_del(sched, peer->pokeexpire);
    12000    p->peerpoke = peer;
    12001    ast_set_flag(p, SIP_OUTGOING);
    12002 #ifdef VOCAL_DATA_HACK
    12003    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
    12004    transmit_invite(p, SIP_INVITE, 0, 2);
    12005 #else
    12006    transmit_invite(p, SIP_OPTIONS, 0, 2);
    12007 #endif
    12008    gettimeofday(&peer->ps, NULL);
    12009    peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
    12010
    12011    return 0;
    12012 }
    12013
    12014 /*! \brief  sip_devicestate: Part of PBX channel interface ---*/
    12015
    12016 /* Return values:---
    12017    If we have qualify on and the device is not reachable, regardless of registration
    12018    state we return AST_DEVICE_UNAVAILABLE
    12019
    12020    For peers with call limit:
    12021       not registered       AST_DEVICE_UNAVAILABLE
    12022       registered, no call     AST_DEVICE_NOT_INUSE
    12023       registered, calls possible AST_DEVICE_INUSE
    12024       registered, call limit reached   AST_DEVICE_BUSY
    12025    For peers without call limit:
    12026       not registered       AST_DEVICE_UNAVAILABLE
    12027       registered        AST_DEVICE_UNKNOWN
    12028 */
    12029 static int sip_devicestate(void *data)
    12030 {
    12031    char *host;
    12032    char *tmp;
    12033
    12034    struct hostent *hp;
    12035    struct ast_hostent ahp;
    12036    struct sip_peer *p;
    12037
    12038    int res = AST_DEVICE_INVALID;
    12039
    12040    host = ast_strdupa(data);
    12041    if ((tmp = strchr(host, '@')))
    12042       host = tmp + 1;
    12043
    12044    if (option_debug > 2)
    12045       ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);
    12046
    12047    if ((p = find_peer(host, NULL, 1))) {
    12048       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
    12049          /* we have an address for the peer */
    12050          /* if qualify is turned on, check the status */
    12051          if (p->maxms && (p->lastms > p->maxms)) {
    12052             res = AST_DEVICE_UNAVAILABLE;
    12053          } else {
    12054             /* qualify is not on, or the peer is responding properly */
    12055             /* check call limit */
    12056             if (p->call_limit && (p->inUse == p->call_limit))
    12057                res = AST_DEVICE_BUSY;
    12058             else if (p->call_limit && p->inUse)
    12059                res = AST_DEVICE_INUSE;
    12060             else if (p->call_limit)
    12061                res = AST_DEVICE_NOT_INUSE;
    12062             else
    12063                res = AST_DEVICE_UNKNOWN;
    12064          }
    12065       } else {
    12066          /* there is no address, it's unavailable */
    12067          res = AST_DEVICE_UNAVAILABLE;
    12068       }
    12069       ASTOBJ_UNREF(p,sip_destroy_peer);
    12070    } else {
    12071       hp = ast_gethostbyname(host, &ahp);
    12072       if (hp)
    12073          res = AST_DEVICE_UNKNOWN;
    12074    }
    12075
    12076    return res;
    12077 }
    12078
    12079 /*! \brief  sip_request: PBX interface function -build SIP pvt structure ---*/
    12080 /* SIP calls initiated by the PBX arrive here */
    12081 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
    12082 {
    12083    int oldformat;
    12084    struct sip_pvt *p;
    12085    struct ast_channel *tmpc = NULL;
    12086    char *ext, *host;
    12087    char tmp[256];
    12088    char *dest = data;
    12089
    12090    oldformat = format;
    12091    format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
    12092    if (!format) {
    12093       ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
    12094       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
    12095       return NULL;
    12096    }
    12097    p = sip_alloc(NULL, NULL, 0, SIP_INVITE);
    12098    if (!p) {
    12099       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory)\n", (char *)data);
    12100       *cause = AST_CAUSE_SWITCH_CONGESTION;
    12101       return NULL;
    12102    }
    12103
    12104    p->options = calloc(1, sizeof(*p->options));
    12105    if (!p->options) {
    12106       sip_destroy(p);
    12107       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
    12108       *cause = AST_CAUSE_SWITCH_CONGESTION;
    12109       return NULL;
    12110    }
    12111
    12112    ast_copy_string(tmp, dest, sizeof(tmp));
    12113    host = strchr(tmp, '@');
    12114    if (host) {
    12115       *host = '\0';
    12116       host++;
    12117       ext = tmp;
    12118    } else {
    12119       ext = strchr(tmp, '/');
    12120       if (ext) {
    12121          *ext++ = '\0';
    12122          host = tmp;
    12123       }
    12124       else {
    12125          host = tmp;
    12126          ext = NULL;
    12127       }
    12128    }
    12129
    12130    if (create_addr(p, host)) {
    12131       *cause = AST_CAUSE_UNREGISTERED;
    12132       sip_destroy(p);
    12133       return NULL;
    12134    }
    12135    if (ast_strlen_zero(p->peername) && ext)
    12136       ast_copy_string(p->peername, ext, sizeof(p->peername));
    12137    /* Recalculate our side, and recalculate Call ID */
    12138    if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
    12139       memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
    12140    build_via(p, p->via, sizeof(p->via));
    12141    build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
    12142
    12143    /* We have an extension to call, don't use the full contact here */
    12144    /* This to enable dialling registered peers with extension dialling,
    12145       like SIP/peername/extension
    12146       SIP/peername will still use the full contact */
    12147    if (ext) {
    12148       ast_copy_string(p->username, ext, sizeof(p->username));
    12149       p->fullcontact[0] = 0;
    12150    }
    12151 #if 0
    12152    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
    12153 #endif
    12154    p->prefcodec = format;
    12155    ast_mutex_lock(&p->lock);
    12156    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
    12157    ast_mutex_unlock(&p->lock);
    12158    if (!tmpc)
    12159       sip_destroy(p);
    12160    ast_update_use_count();
    12161    restart_monitor();
    12162    return tmpc;
    12163 }
    12164
    12165 /*! \brief  handle_common_options: Handle flag-type options common to users and peers ---*/
    12166 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
    12167 {
    12168    int res = 1;
    12169
    12170    if (!strcasecmp(v->name, "trustrpid")) {
    12171       ast_set_flag(mask, SIP_TRUSTRPID);
    12172       ast_set2_flag(flags, ast_true(v->value), SIP_TRUSTRPID);
    12173    } else if (!strcasecmp(v->name, "sendrpid")) {
    12174       ast_set_flag(mask, SIP_SENDRPID);
    12175       ast_set2_flag(flags, ast_true(v->value), SIP_SENDRPID);
    12176    } else if (!strcasecmp(v->name, "useclientcode")) {
    12177       ast_set_flag(mask, SIP_USECLIENTCODE);
    12178       ast_set2_flag(flags, ast_true(v->value), SIP_USECLIENTCODE);
    12179    } else if (!strcasecmp(v->name, "dtmfmode")) {
    12180       ast_set_flag(mask, SIP_DTMF);
    12181       ast_clear_flag(flags, SIP_DTMF);
    12182       if (!strcasecmp(v->value, "inband"))
    12183          ast_set_flag(flags, SIP_DTMF_INBAND);
    12184       else if (!strcasecmp(v->value, "rfc2833"))
    12185          ast_set_flag(flags, SIP_DTMF_RFC2833);
    12186       else if (!strcasecmp(v->value, "info"))
    12187          ast_set_flag(flags, SIP_DTMF_INFO);
    12188       else if (!strcasecmp(v->value, "auto"))
    12189          ast_set_flag(flags, SIP_DTMF_AUTO);
    12190       else {
    12191          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
    12192          ast_set_flag(flags, SIP_DTMF_RFC2833);
    12193       }
    12194    } else if (!strcasecmp(v->name, "nat")) {
    12195       ast_set_flag(mask, SIP_NAT);
    12196       ast_clear_flag(flags, SIP_NAT);
    12197       if (!strcasecmp(v->value, "never"))
    12198          ast_set_flag(flags, SIP_NAT_NEVER);
    12199       else if (!strcasecmp(v->value, "route"))
    12200          ast_set_flag(flags, SIP_NAT_ROUTE);
    12201       else if (ast_true(v->value))
    12202          ast_set_flag(flags, SIP_NAT_ALWAYS);
    12203       else
    12204          ast_set_flag(flags, SIP_NAT_RFC3581);
    12205    } else if (!strcasecmp(v->name, "canreinvite")) {
    12206       ast_set_flag(mask, SIP_REINVITE);
    12207       ast_clear_flag(flags, SIP_REINVITE);
    12208       if (!strcasecmp(v->value, "update"))
    12209          ast_set_flag(flags, SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
    12210       else
    12211          ast_set2_flag(flags, ast_true(v->value), SIP_CAN_REINVITE);
    12212    } else if (!strcasecmp(v->name, "insecure")) {
    12213       ast_set_flag(mask, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
    12214       ast_clear_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
    12215       if (!strcasecmp(v->value, "very"))
    12216          ast_set_flag(flags, SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
    12217       else if (ast_true(v->value))
    12218          ast_set_flag(flags, SIP_INSECURE_PORT);
    12219       else if (!ast_false(v->value)) {
    12220          char buf[64];
    12221          char *word, *next;
    12222
    12223          ast_copy_string(buf, v->value, sizeof(buf));
    12224          next = buf;
    12225          while ((word = strsep(&next, ","))) {
    12226             if (!strcasecmp(word, "port"))
    12227                ast_set_flag(flags, SIP_INSECURE_PORT);
    12228             else if (!strcasecmp(word, "invite"))
    12229                ast_set_flag(flags, SIP_INSECURE_INVITE);
    12230             else
    12231                ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", v->value, v->lineno);
    12232          }
    12233       }
    12234    } else if (!strcasecmp(v->name, "progressinband")) {
    12235       ast_set_flag(mask, SIP_PROG_INBAND);
    12236       ast_clear_flag(flags, SIP_PROG_INBAND);
    12237       if (ast_true(v->value))
    12238          ast_set_flag(flags, SIP_PROG_INBAND_YES);
    12239       else if (strcasecmp(v->value, "never"))
    12240          ast_set_flag(flags, SIP_PROG_INBAND_NO);
    12241    } else if (!strcasecmp(v->name, "allowguest")) {
    12242 #ifdef OSP_SUPPORT
    12243       if (!strcasecmp(v->value, "osp"))
    12244          global_allowguest = 2;
    12245       else
    12246 #endif
    12247          if (ast_true(v->value))
    12248             global_allowguest = 1;
    12249          else
    12250             global_allowguest = 0;
    12251 #ifdef OSP_SUPPORT
    12252    } else if (!strcasecmp(v->name, "ospauth")) {
    12253       ast_set_flag(mask, SIP_OSPAUTH);
    12254       ast_clear_flag(flags, SIP_OSPAUTH);
    12255       if (!strcasecmp(v->value, "proxy"))
    12256          ast_set_flag(flags, SIP_OSPAUTH_PROXY);
    12257       else if (!strcasecmp(v->value, "gateway"))
    12258          ast_set_flag(flags, SIP_OSPAUTH_GATEWAY);
    12259       else if(!strcasecmp (v->value, "exclusive"))
    12260          ast_set_flag(flags, SIP_OSPAUTH_EXCLUSIVE);
    12261 #endif
    12262    } else if (!strcasecmp(v->name, "promiscredir")) {
    12263       ast_set_flag(mask, SIP_PROMISCREDIR);
    12264       ast_set2_flag(flags, ast_true(v->value), SIP_PROMISCREDIR);
    12265    } else
    12266       res = 0;
    12267
    12268    return res;
    12269 }
    12270
    12271 /*! \brief  add_sip_domain: Add SIP domain to list of domains we are responsible for */
    12272 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
    12273 {
    12274    struct domain *d;
    12275
    12276    if (ast_strlen_zero(domain)) {
    12277       ast_log(LOG_WARNING, "Zero length domain.\n");
    12278       return 1;
    12279    }
    12280
    12281    d = calloc(1, sizeof(*d));
    12282    if (!d) {
    12283       ast_log(LOG_ERROR, "Allocation of domain structure failed, Out of memory\n");
    12284       return 0;
    12285    }
    12286
    12287    ast_copy_string(d->domain, domain, sizeof(d->domain));
    12288
    12289    if (!ast_strlen_zero(context))
    12290       ast_copy_string(d->context, context, sizeof(d->context));
    12291
    12292    d->mode = mode;
    12293
    12294    AST_LIST_LOCK(&domain_list);
    12295    AST_LIST_INSERT_TAIL(&domain_list, d, list);
    12296    AST_LIST_UNLOCK(&domain_list);
    12297
    12298    if (sipdebug)
    12299       ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);
    12300
    12301    return 1;
    12302 }
    12303
    12304 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
    12305 static int check_sip_domain(const char *domain, char *context, size_t len)
    12306 {
    12307    struct domain *d;
    12308    int result = 0;
    12309
    12310    AST_LIST_LOCK(&domain_list);
    12311    AST_LIST_TRAVERSE(&domain_list, d, list) {
    12312       if (strcasecmp(d->domain, domain))
    12313          continue;
    12314
    12315       if (len && !ast_strlen_zero(d->context))
    12316          ast_copy_string(context, d->context, len);
    12317
    12318       result = 1;
    12319       break;
    12320    }
    12321    AST_LIST_UNLOCK(&domain_list);
    12322
    12323    return result;
    12324 }
    12325
    12326 /*! \brief  clear_sip_domains: Clear our domain list (at reload) */
    12327 static void clear_sip_domains(void)
    12328 {
    12329    struct domain *d;
    12330
    12331    AST_LIST_LOCK(&domain_list);
    12332    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
    12333       free(d);
    12334    AST_LIST_UNLOCK(&domain_list);
    12335 }
    12336
    12337
    12338 /*! \brief  add_realm_authentication: Add realm authentication in list ---*/
    12339 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
    12340 {
    12341    char authcopy[256];
    12342    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
    12343    char *stringp;
    12344    struct sip_auth *auth;
    12345    struct sip_auth *b = NULL, *a = authlist;
    12346
    12347    if (ast_strlen_zero(configuration))
    12348       return authlist;
    12349
    12350    ast_log(LOG_DEBUG, "Auth config ::  %s\n", configuration);
    12351
    12352    ast_copy_string(authcopy, configuration, sizeof(authcopy));
    12353    stringp = authcopy;
    12354
    12355    username = stringp;
    12356    realm = strrchr(stringp, '@');
    12357    if (realm) {
    12358       *realm = '\0';
    12359       realm++;
    12360    }
    12361    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
    12362       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
    12363       return authlist;
    12364    }
    12365    stringp = username;
    12366    username = strsep(&stringp, ":");
    12367    if (username) {
    12368       secret = strsep(&stringp, ":");
    12369       if (!secret) {
    12370          stringp = username;
    12371          md5secret = strsep(&stringp,"#");
    12372       }
    12373    }
    12374    auth = malloc(sizeof(struct sip_auth));
    12375    if (auth) {
    12376       memset(auth, 0, sizeof(struct sip_auth));
    12377       ast_copy_string(auth->realm, realm, sizeof(auth->realm));
    12378       ast_copy_string(auth->username, username, sizeof(auth->username));
    12379       if (secret)
    12380          ast_copy_string(auth->secret, secret, sizeof(auth->secret));
    12381       if (md5secret)
    12382          ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
    12383    } else {
    12384       ast_log(LOG_ERROR, "Allocation of auth structure failed, Out of memory\n");
    12385       return authlist;
    12386    }
    12387
    12388    /* Add authentication to authl */
    12389    if (!authlist) {  /* No existing list */
    12390       return auth;
    12391    }
    12392    while(a) {
    12393       b = a;
    12394       a = a->next;
    12395    }
    12396    b->next = auth;   /* Add structure add end of list */
    12397
    12398    if (option_verbose > 2)
    12399       ast_verbose("Added authentication for realm %s\n", realm);
    12400
    12401    return authlist;
    12402
    12403 }
    12404
    12405 /*! \brief  clear_realm_authentication: Clear realm authentication list (at reload) ---*/
    12406 static int clear_realm_authentication(struct sip_auth *authlist)
    12407 {
    12408    struct sip_auth *a = authlist;
    12409    struct sip_auth *b;
    12410
    12411    while (a) {
    12412       b = a;
    12413       a = a->next;
    12414       free(b);
    12415    }
    12416
    12417    return 1;
    12418 }
    12419
    12420 /*! \brief  find_realm_authentication: Find authentication for a specific realm ---*/
    12421 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm)
    12422 {
    12423    struct sip_auth *a = authlist;   /* First entry in auth list */
    12424
    12425    while (a) {
    12426       if (!strcasecmp(a->realm, realm)){
    12427          break;
    12428       }
    12429       a = a->next;
    12430    }
    12431
    12432    return a;
    12433 }
    12434
    12435 /*! \brief  build_user: Initiate a SIP user structure from sip.conf ---*/
    12436 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime)
    12437 {
    12438    struct sip_user *user;
    12439    int format;
    12440    struct ast_ha *oldha = NULL;
    12441    char *varname = NULL, *varval = NULL;
    12442    struct ast_variable *tmpvar = NULL;
    12443    struct ast_flags userflags = {(0)};
    12444    struct ast_flags mask = {(0)};
    12445
    12446
    12447    user = (struct sip_user *)malloc(sizeof(struct sip_user));
    12448    if (!user) {
    12449       return NULL;
    12450    }
    12451    memset(user, 0, sizeof(struct sip_user));
    12452    suserobjs++;
    12453    ASTOBJ_INIT(user);
    12454    ast_copy_string(user->name, name, sizeof(user->name));
    12455    oldha = user->ha;
    12456    user->ha = NULL;
    12457    ast_copy_flags(user, &global_flags, SIP_FLAGS_TO_COPY);
    12458    user->capability = global_capability;
    12459    user->prefs = prefs;
    12460    /* set default context */
    12461    strcpy(user->context, default_context);
    12462    strcpy(user->language, default_language);
    12463    strcpy(user->musicclass, global_musicclass);
    12464    while(v) {
    12465       if (handle_common_options(&userflags, &mask, v)) {
    12466          v = v->next;
    12467          continue;
    12468       }
    12469
    12470       if (!strcasecmp(v->name, "context")) {
    12471          ast_copy_string(user->context, v->value, sizeof(user->context));
    12472       } else if (!strcasecmp(v->name, "subscribecontext")) {
    12473          ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
    12474       } else if (!strcasecmp(v->name, "setvar")) {
    12475          varname = ast_strdupa(v->value);
    12476          if (varname && (varval = strchr(varname,'='))) {
    12477             *varval = '\0';
    12478             varval++;
    12479             if ((tmpvar = ast_variable_new(varname, varval))) {
    12480                tmpvar->next = user->chanvars;
    12481                user->chanvars = tmpvar;
    12482             }
    12483          }
    12484       } else if (!strcasecmp(v->name, "permit") ||
    12485                !strcasecmp(v->name, "deny")) {
    12486          user->ha = ast_append_ha(v->name, v->value, user->ha);
    12487       } else if (!strcasecmp(v->name, "secret")) {
    12488          ast_copy_string(user->secret, v->value, sizeof(user->secret));
    12489       } else if (!strcasecmp(v->name, "md5secret")) {
    12490          ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
    12491       } else if (!strcasecmp(v->name, "callerid")) {
    12492          ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
    12493       } else if (!strcasecmp(v->name, "callgroup")) {
    12494          user->callgroup = ast_get_group(v->value);
    12495       } else if (!strcasecmp(v->name, "pickupgroup")) {
    12496          user->pickupgroup = ast_get_group(v->value);
    12497       } else if (!strcasecmp(v->name, "language")) {
    12498          ast_copy_string(user->language, v->value, sizeof(user->language));
    12499       } else if (!strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
    12500          ast_copy_string(user->musicclass, v->value, sizeof(user->musicclass));
    12501       } else if (!strcasecmp(v->name, "accountcode")) {
    12502          ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
    12503       } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
    12504          user->call_limit = atoi(v->value);
    12505          if (user->call_limit < 0)
    12506             user->call_limit = 0;
    12507       } else if (!strcasecmp(v->name, "amaflags")) {
    12508          format = ast_cdr_amaflags2int(v->value);
    12509          if (format < 0) {
    12510             ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
    12511          } else {
    12512             user->amaflags = format;
    12513          }
    12514       } else if (!strcasecmp(v->name, "allow")) {
    12515          ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
    12516       } else if (!strcasecmp(v->name, "disallow")) {
    12517          ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
    12518       } else if (!strcasecmp(v->name, "callingpres")) {
    12519          user->callingpres = ast_parse_caller_presentation(v->value);
    12520          if (user->callingpres == -1)
    12521             user->callingpres = atoi(v->value);
    12522       }
    12523       /* We can't just report unknown options here because this may be a
    12524        * type=friend entry.  All user options are valid for a peer, but not
    12525        * the other way around.  */
    12526       v = v->next;
    12527    }
    12528    ast_copy_flags(user, &userflags, mask.flags);
    12529    ast_free_ha(oldha);
    12530    return user;
    12531 }
    12532
    12533 /*! \brief  temp_peer: Create temporary peer (used in autocreatepeer mode) ---*/
    12534 static struct sip_peer *temp_peer(const char *name)
    12535 {
    12536    struct sip_peer *peer;
    12537
    12538    peer = malloc(sizeof(*peer));
    12539    if (!peer)
    12540       return NULL;
    12541
    12542    memset(peer, 0, sizeof(*peer));
    12543    apeerobjs++;
    12544    ASTOBJ_INIT(peer);
    12545
    12546    peer->expire = -1;
    12547    peer->pokeexpire = -1;
    12548    ast_copy_string(peer->name, name, sizeof(peer->name));
    12549    ast_copy_flags(peer, &global_flags, SIP_FLAGS_TO_COPY);
    12550    strcpy(peer->context, default_context);
    12551    strcpy(peer->subscribecontext, default_subscribecontext);
    12552    strcpy(peer->language, default_language);
    12553    strcpy(peer->musicclass, global_musicclass);
    12554    peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
    12555    peer->addr.sin_family = AF_INET;
    12556    peer->capability = global_capability;
    12557    peer->rtptimeout = global_rtptimeout;
    12558    peer->rtpholdtimeout = global_rtpholdtimeout;
    12559    peer->rtpkeepalive = global_rtpkeepalive;
    12560    ast_set_flag(peer, SIP_SELFDESTRUCT);
    12561    ast_set_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC);
    12562    peer->prefs = prefs;
    12563    reg_source_db(peer);
    12564
    12565    return peer;
    12566 }
    12567
    12568 /*! \brief  build_peer: Build peer from config file ---*/
    12569 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime)
    12570 {
    12571    struct sip_peer *peer = NULL;
    12572    struct ast_ha *oldha = NULL;
    12573    int obproxyfound=0;
    12574    int found=0;
    12575    int format=0;     /* Ama flags */
    12576    time_t regseconds;
    12577    char *varname = NULL, *varval = NULL;
    12578    struct ast_variable *tmpvar = NULL;
    12579    struct ast_flags peerflags = {(0)};
    12580    struct ast_flags mask = {(0)};
    12581
    12582
    12583    if (!realtime)
    12584       /* Note we do NOT use find_peer here, to avoid realtime recursion */
    12585       /* We also use a case-sensitive comparison (unlike find_peer) so
    12586          that case changes made to the peer name will be properly handled
    12587          during reload
    12588       */
    12589       peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
    12590
    12591    if (peer) {
    12592       /* Already in the list, remove it and it will be added back (or FREE'd)  */
    12593       found = 1;
    12594    } else {
    12595       peer = malloc(sizeof(*peer));
    12596       if (peer) {
    12597          memset(peer, 0, sizeof(*peer));
    12598          if (realtime)
    12599             rpeerobjs++;
    12600          else
    12601             speerobjs++;
    12602          ASTOBJ_INIT(peer);
    12603          peer->expire = -1;
    12604          peer->pokeexpire = -1;
    12605       } else {
    12606          ast_log(LOG_WARNING, "Can't allocate SIP peer memory\n");
    12607       }
    12608    }
    12609    /* Note that our peer HAS had its reference count incrased */
    12610    if (!peer)
    12611       return NULL;
    12612
    12613    peer->lastmsgssent = -1;
    12614    if (!found) {
    12615       if (name)
    12616          ast_copy_string(peer->name, name, sizeof(peer->name));
    12617       peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
    12618       peer->addr.sin_family = AF_INET;
    12619       peer->defaddr.sin_family = AF_INET;
    12620    }
    12621    /* If we have channel variables, remove them (reload) */
    12622    if (peer->chanvars) {
    12623       ast_variables_destroy(peer->chanvars);
    12624       peer->chanvars = NULL;
    12625    }
    12626    /* If we have realm authentication information, remove them (reload) */
    12627    clear_realm_authentication(peer->auth);
    12628    peer->auth = (struct sip_auth *) NULL;
    12629    strcpy(peer->context, default_context);
    12630    strcpy(peer->subscribecontext, default_subscribecontext);
    12631    strcpy(peer->vmexten, global_vmexten);
    12632    strcpy(peer->language, default_language);
    12633    strcpy(peer->musicclass, global_musicclass);
    12634    ast_copy_flags(peer, &global_flags, SIP_USEREQPHONE);
    12635    peer->secret[0] = '\0';
    12636    peer->md5secret[0] = '\0';
    12637    peer->cid_num[0] = '\0';
    12638    peer->cid_name[0] = '\0';
    12639    peer->fromdomain[0] = '\0';
    12640    peer->fromuser[0] = '\0';
    12641    peer->regexten[0] = '\0';
    12642    peer->mailbox[0] = '\0';
    12643    peer->callgroup = 0;
    12644    peer->pickupgroup = 0;
    12645    peer->rtpkeepalive = global_rtpkeepalive;
    12646    peer->maxms = default_qualify;
    12647    peer->prefs = prefs;
    12648    oldha = peer->ha;
    12649    peer->ha = NULL;
    12650    peer->addr.sin_family = AF_INET;
    12651    ast_copy_flags(peer, &global_flags, SIP_FLAGS_TO_COPY);
    12652    peer->capability = global_capability;
    12653    peer->rtptimeout = global_rtptimeout;
    12654    peer->rtpholdtimeout = global_rtpholdtimeout;
    12655    while(v) {
    12656       if (handle_common_options(&peerflags, &mask, v)) {
    12657          v = v->next;
    12658          continue;
    12659       }
    12660
    12661       if (realtime && !strcasecmp(v->name, "regseconds")) {
    12662          if (sscanf(v->value, "%30ld", (time_t *)&regseconds) != 1)
    12663             regseconds = 0;
    12664       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
    12665          inet_aton(v->value, &(peer->addr.sin_addr));
    12666       } else if (realtime && !strcasecmp(v->name, "name"))
    12667          ast_copy_string(peer->name, v->value, sizeof(peer->name));
    12668       else if (realtime && !strcasecmp(v->name, "fullcontact")) {
    12669          ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
    12670          ast_set_flag((&peer->flags_page2), SIP_PAGE2_RT_FROMCONTACT);
    12671       } else if (!strcasecmp(v->name, "secret"))
    12672          ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
    12673       else if (!strcasecmp(v->name, "md5secret"))
    12674          ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
    12675       else if (!strcasecmp(v->name, "auth"))
    12676          peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
    12677       else if (!strcasecmp(v->name, "callerid")) {
    12678          ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
    12679       } else if (!strcasecmp(v->name, "context")) {
    12680          ast_copy_string(peer->context, v->value, sizeof(peer->context));
    12681       } else if (!strcasecmp(v->name, "subscribecontext")) {
    12682          ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
    12683       } else if (!strcasecmp(v->name, "fromdomain"))
    12684          ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
    12685       else if (!strcasecmp(v->name, "usereqphone"))
    12686          ast_set2_flag(peer, ast_true(v->value), SIP_USEREQPHONE);
    12687       else if (!strcasecmp(v->name, "fromuser"))
    12688          ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
    12689       else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
    12690          if (!strcasecmp(v->value, "dynamic")) {
    12691             if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
    12692                ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
    12693             } else {
    12694                /* They'll register with us */
    12695                if (!found || !ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC)) {
    12696                   /* Initialize stuff if this is a new peer, or if it used to be
    12697                    * non-dynamic before the reload. */
    12698                   memset(&peer->addr.sin_addr, 0, 4);
    12699                   if (peer->addr.sin_port) {
    12700                      /* If we've already got a port, make it the default rather than absolute */
    12701                      peer->defaddr.sin_port = peer->addr.sin_port;
    12702                      peer->addr.sin_port = 0;
    12703                   }
    12704                }
    12705                ast_set_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC);
    12706             }
    12707          } else {
    12708             /* Non-dynamic.  Make sure we become that way if we're not */
    12709             if (peer->expire > -1)
    12710                ast_sched_del(sched, peer->expire);
    12711             peer->expire = -1;
    12712             ast_clear_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC);
    12713             if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
    12714                if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
    12715                   ASTOBJ_UNREF(peer, sip_destroy_peer);
    12716                   return NULL;
    12717                }
    12718             }
    12719             if (!strcasecmp(v->name, "outboundproxy"))
    12720                obproxyfound=1;
    12721             else {
    12722                ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
    12723                if (!peer->addr.sin_port)
    12724                   peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
    12725             }
    12726          }
    12727       } else if (!strcasecmp(v->name, "defaultip")) {
    12728          if (ast_get_ip(&peer->defaddr, v->value)) {
    12729             ASTOBJ_UNREF(peer, sip_destroy_peer);
    12730             return NULL;
    12731          }
    12732       } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
    12733          peer->ha = ast_append_ha(v->name, v->value, peer->ha);
    12734       } else if (!strcasecmp(v->name, "port")) {
    12735          if (!realtime && ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC))
    12736             peer->defaddr.sin_port = htons(atoi(v->value));
    12737          else
    12738             peer->addr.sin_port = htons(atoi(v->value));
    12739       } else if (!strcasecmp(v->name, "callingpres")) {
    12740          peer->callingpres = ast_parse_caller_presentation(v->value);
    12741          if (peer->callingpres == -1)
    12742             peer->callingpres = atoi(v->value);
    12743       } else if (!strcasecmp(v->name, "username")) {
    12744          ast_copy_string(peer->username, v->value, sizeof(peer->username));
    12745       } else if (!strcasecmp(v->name, "language")) {
    12746          ast_copy_string(peer->language, v->value, sizeof(peer->language));
    12747       } else if (!strcasecmp(v->name, "regexten")) {
    12748          ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
    12749       } else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
    12750          peer->call_limit = atoi(v->value);
    12751          if (peer->call_limit < 0)
    12752             peer->call_limit = 0;
    12753       } else if (!strcasecmp(v->name, "amaflags")) {
    12754          format = ast_cdr_amaflags2int(v->value);
    12755          if (format < 0) {
    12756             ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
    12757          } else {
    12758             peer->amaflags = format;
    12759          }
    12760       } else if (!strcasecmp(v->name, "accountcode")) {
    12761          ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
    12762       } else if (!strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
    12763          ast_copy_string(peer->musicclass, v->value, sizeof(peer->musicclass));
    12764       } else if (!strcasecmp(v->name, "mailbox")) {
    12765          ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
    12766       } else if (!strcasecmp(v->name, "vmexten")) {
    12767          ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
    12768       } else if (!strcasecmp(v->name, "callgroup")) {
    12769          peer->callgroup = ast_get_group(v->value);
    12770       } else if (!strcasecmp(v->name, "pickupgroup")) {
    12771          peer->pickupgroup = ast_get_group(v->value);
    12772       } else if (!strcasecmp(v->name, "allow")) {
    12773          ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
    12774       } else if (!strcasecmp(v->name, "disallow")) {
    12775          ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
    12776       } else if (!strcasecmp(v->name, "rtptimeout")) {
    12777          if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
    12778             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
    12779             peer->rtptimeout = global_rtptimeout;
    12780          }
    12781       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
    12782          if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
    12783             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
    12784             peer->rtpholdtimeout = global_rtpholdtimeout;
    12785          }
    12786       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
    12787          if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
    12788             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
    12789             peer->rtpkeepalive = global_rtpkeepalive;
    12790          }
    12791       } else if (!strcasecmp(v->name, "setvar")) {
    12792          /* Set peer channel variable */
    12793          varname = ast_strdupa(v->value);
    12794          if (varname && (varval = strchr(varname,'='))) {
    12795             *varval = '\0';
    12796             varval++;
    12797             if ((tmpvar = ast_variable_new(varname, varval))) {
    12798                tmpvar->next = peer->chanvars;
    12799                peer->chanvars = tmpvar;
    12800             }
    12801          }
    12802       } else if (!strcasecmp(v->name, "qualify")) {
    12803          if (!strcasecmp(v->value, "no")) {
    12804             peer->maxms = 0;
    12805          } else if (!strcasecmp(v->value, "yes")) {
    12806             peer->maxms = DEFAULT_MAXMS;
    12807          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
    12808             ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
    12809             peer->maxms = 0;
    12810          }
    12811       }
    12812       v = v->next;
    12813    }
    12814    if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC) && realtime) {
    12815       time_t nowtime;
    12816
    12817       time(&nowtime);
    12818       if ((nowtime - regseconds) > 0) {
    12819          destroy_association(peer);
    12820          memset(&peer->addr, 0, sizeof(peer->addr));
    12821          if (option_debug)
    12822             ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
    12823       }
    12824    }
    12825    ast_copy_flags(peer, &peerflags, mask.flags);
    12826    if (!found && ast_test_flag(&peer->flags_page2, SIP_PAGE2_DYNAMIC) && !ast_test_flag(peer, SIP_REALTIME))
    12827       reg_source_db(peer);
    12828    ASTOBJ_UNMARK(peer);
    12829    ast_free_ha(oldha);
    12830    return peer;
    12831 }
    12832
    12833 /*! \brief  reload_config: Re-read SIP.conf config file ---*/
    12834 /* This function reloads all config data, except for
    12835    active peers (with registrations). They will only
    12836    change configuration data at restart, not at reload.
    12837    SIP debug and recordhistory state will not change
    12838  */
    12839 static int reload_config(void)
    12840 {
    12841    struct ast_config *cfg;
    12842    struct ast_variable *v;
    12843    struct sip_peer *peer;
    12844    struct sip_user *user;
    12845    struct ast_hostent ahp;
    12846    char *cat;
    12847    char *utype;
    12848    struct hostent *hp;
    12849    int format;
    12850    char iabuf[INET_ADDRSTRLEN];
    12851    struct ast_flags dummy;
    12852    int auto_sip_domains = 0;
    12853    struct sockaddr_in old_bindaddr = bindaddr;
    12854
    12855    cfg = ast_config_load(config);
    12856
    12857    /* We *must* have a config file otherwise stop immediately */
    12858    if (!cfg) {
    12859       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
    12860       return -1;
    12861    }
    12862
    12863    /* Reset IP addresses  */
    12864    memset(&bindaddr, 0, sizeof(bindaddr));
    12865    ast_free_ha(localaddr);
    12866    memset(&localaddr, 0, sizeof(localaddr));
    12867    memset(&externip, 0, sizeof(externip));
    12868    memset(&prefs, 0 , sizeof(prefs));
    12869    sipdebug &= ~SIP_DEBUG_CONFIG;
    12870
    12871    /* Initialize some reasonable defaults at SIP reload */
    12872    ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
    12873    default_subscribecontext[0] = '\0';
    12874    default_language[0] = '\0';
    12875    default_fromdomain[0] = '\0';
    12876    default_qualify = 0;
    12877    allow_external_domains = 1;   /* Allow external invites */
    12878    externhost[0] = '\0';
    12879    externexpire = 0;
    12880    externrefresh = 10;
    12881    ast_copy_string(default_useragent, DEFAULT_USERAGENT, sizeof(default_useragent));
    12882    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
    12883    global_notifyringing = 1;
    12884    global_alwaysauthreject = 0;
    12885    ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
    12886    ast_copy_string(global_musicclass, "default", sizeof(global_musicclass));
    12887    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
    12888    memset(&outboundproxyip, 0, sizeof(outboundproxyip));
    12889    outboundproxyip.sin_port = htons(DEFAULT_SIP_PORT);
    12890    outboundproxyip.sin_family = AF_INET;  /* Type of address: IPv4 */
    12891    videosupport = 0;
    12892    compactheaders = 0;
    12893    dumphistory = 0;
    12894    recordhistory = 0;
    12895    relaxdtmf = 0;
    12896    callevents = 0;
    12897    ourport = DEFAULT_SIP_PORT;
    12898    global_rtptimeout = 0;
    12899    global_rtpholdtimeout = 0;
    12900    global_rtpkeepalive = 0;
    12901    global_rtautoclear = 120;
    12902    pedanticsipchecking = 0;
    12903    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
    12904    global_regattempts_max = 0;
    12905    ast_clear_flag(&global_flags, AST_FLAGS_ALL);
    12906    ast_clear_flag(&global_flags_page2, AST_FLAGS_ALL);
    12907    ast_set_flag(&global_flags, SIP_DTMF_RFC2833);
    12908    ast_set_flag(&global_flags, SIP_NAT_RFC3581);
    12909    ast_set_flag(&global_flags, SIP_CAN_REINVITE);
    12910    ast_set_flag(&global_flags_page2, SIP_PAGE2_RTUPDATE);
    12911    global_mwitime = DEFAULT_MWITIME;
    12912    strcpy(global_vmexten, DEFAULT_VMEXTEN);
    12913    srvlookup = 0;
    12914    autocreatepeer = 0;
    12915    regcontext[0] = '\0';
    12916    tos = 0;
    12917    expiry = DEFAULT_EXPIRY;
    12918    global_allowguest = 1;
    12919
    12920    /* Read the [general] config section of sip.conf (or from realtime config) */
    12921    v = ast_variable_browse(cfg, "general");
    12922    while(v) {
    12923       if (handle_common_options(&global_flags, &dummy, v)) {
    12924          v = v->next;
    12925          continue;
    12926       }
    12927
    12928       /* Create the interface list */
    12929       if (!strcasecmp(v->name, "context")) {
    12930          ast_copy_string(default_context, v->value, sizeof(default_context));
    12931       } else if (!strcasecmp(v->name, "realm")) {
    12932          ast_copy_string(global_realm, v->value, sizeof(global_realm));
    12933       } else if (!strcasecmp(v->name, "useragent")) {
    12934          ast_copy_string(default_useragent, v->value, sizeof(default_useragent));
    12935          ast_log(LOG_DEBUG, "Setting User Agent Name to %s\n",
    12936             default_useragent);
    12937       } else if (!strcasecmp(v->name, "rtcachefriends")) {
    12938          ast_set2_flag((&global_flags_page2), ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
    12939       } else if (!strcasecmp(v->name, "rtupdate")) {
    12940          ast_set2_flag((&global_flags_page2), ast_true(v->value), SIP_PAGE2_RTUPDATE);
    12941       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
    12942          ast_set2_flag((&global_flags_page2), ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);
    12943       } else if (!strcasecmp(v->name, "rtautoclear")) {
    12944          int i = atoi(v->value);
    12945          if (i > 0)
    12946             global_rtautoclear = i;
    12947          else
    12948             i = 0;
    12949          ast_set2_flag((&global_flags_page2), i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
    12950       } else if (!strcasecmp(v->name, "usereqphone")) {
    12951          ast_set2_flag((&global_flags), ast_true(v->value), SIP_USEREQPHONE);
    12952       } else if (!strcasecmp(v->name, "relaxdtmf")) {
    12953          relaxdtmf = ast_true(v->value);
    12954       } else if (!strcasecmp(v->name, "checkmwi")) {
    12955          if ((sscanf(v->value, "%30d", &global_mwitime) != 1) || (global_mwitime < 0)) {
    12956             ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d.  Using default (10).\n", v->value, v->lineno);
    12957             global_mwitime = DEFAULT_MWITIME;
    12958          }
    12959       } else if (!strcasecmp(v->name, "vmexten")) {
    12960          ast_copy_string(global_vmexten, v->value, sizeof(global_vmexten));
    12961       } else if (!strcasecmp(v->name, "rtptimeout")) {
    12962          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
    12963             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
    12964             global_rtptimeout = 0;
    12965          }
    12966       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
    12967          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
    12968             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
    12969             global_rtpholdtimeout = 0;
    12970          }
    12971       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
    12972          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
    12973             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
    12974             global_rtpkeepalive = 0;
    12975          }
    12976       } else if (!strcasecmp(v->name, "videosupport")) {
    12977          videosupport = ast_true(v->value);
    12978       } else if (!strcasecmp(v->name, "compactheaders")) {
    12979          compactheaders = ast_true(v->value);
    12980       } else if (!strcasecmp(v->name, "notifymimetype")) {
    12981          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
    12982       } else if (!strcasecmp(v->name, "notifyringing")) {
    12983          global_notifyringing = ast_true(v->value);
    12984       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
    12985          global_alwaysauthreject = ast_true(v->value);
    12986       } else if (!strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
    12987          ast_copy_string(global_musicclass, v->value, sizeof(global_musicclass));
    12988       } else if (!strcasecmp(v->name, "language")) {
    12989          ast_copy_string(default_language, v->value, sizeof(default_language));
    12990       } else if (!strcasecmp(v->name, "regcontext")) {
    12991          ast_copy_string(regcontext, v->value, sizeof(regcontext));
    12992          /* Create context if it doesn't exist already */
    12993          if (!ast_context_find(regcontext))
    12994             ast_context_create(NULL, regcontext, channeltype);
    12995       } else if (!strcasecmp(v->name, "callerid")) {
    12996          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
    12997       } else if (!strcasecmp(v->name, "fromdomain")) {
    12998          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
    12999       } else if (!strcasecmp(v->name, "outboundproxy")) {
    13000          if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
    13001             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
    13002       } else if (!strcasecmp(v->name, "outboundproxyport")) {
    13003          /* Port needs to be after IP */
    13004          sscanf(v->value, "%30d", &format);
    13005          outboundproxyip.sin_port = htons(format);
    13006       } else if (!strcasecmp(v->name, "autocreatepeer")) {
    13007          autocreatepeer = ast_true(v->value);
    13008       } else if (!strcasecmp(v->name, "srvlookup")) {
    13009          srvlookup = ast_true(v->value);
    13010       } else if (!strcasecmp(v->name, "pedantic")) {
    13011          pedanticsipchecking = ast_true(v->value);
    13012       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
    13013          max_expiry = atoi(v->value);
    13014          if (max_expiry < 1)
    13015             max_expiry = DEFAULT_MAX_EXPIRY;
    13016       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
    13017          default_expiry = atoi(v->value);
    13018          if (default_expiry < 1)
    13019             default_expiry = DEFAULT_DEFAULT_EXPIRY;
    13020       } else if (!strcasecmp(v->name, "sipdebug")) {
    13021          if (ast_true(v->value))
    13022             sipdebug |= SIP_DEBUG_CONFIG;
    13023       } else if (!strcasecmp(v->name, "dumphistory")) {
    13024          dumphistory = ast_true(v->value);
    13025       } else if (!strcasecmp(v->name, "recordhistory")) {
    13026          recordhistory = ast_true(v->value);
    13027       } else if (!strcasecmp(v->name, "registertimeout")) {
    13028          global_reg_timeout = atoi(v->value);
    13029          if (global_reg_timeout < 1)
    13030             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
    13031       } else if (!strcasecmp(v->name, "registerattempts")) {
    13032          global_regattempts_max = atoi(v->value);
    13033       } else if (!strcasecmp(v->name, "bindaddr")) {
    13034          if (!(hp = ast_gethostbyname(v->value, &ahp))) {
    13035             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
    13036          } else {
    13037             memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
    13038          }
    13039       } else if (!strcasecmp(v->name, "localnet")) {
    13040          struct ast_ha *na;
    13041          if (!(na = ast_append_ha("d", v->value, localaddr)))
    13042             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
    13043          else
    13044             localaddr = na;
    13045       } else if (!strcasecmp(v->name, "localmask")) {
    13046          ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
    13047       } else if (!strcasecmp(v->name, "externip")) {
    13048          if (!(hp = ast_gethostbyname(v->value, &ahp)))
    13049             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
    13050          else
    13051             memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
    13052          externexpire = 0;
    13053       } else if (!strcasecmp(v->name, "externhost")) {
    13054          ast_copy_string(externhost, v->value, sizeof(externhost));
    13055          if (!(hp = ast_gethostbyname(externhost, &ahp)))
    13056             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
    13057          else
    13058             memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
    13059          time(&externexpire);
    13060       } else if (!strcasecmp(v->name, "externrefresh")) {
    13061          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
    13062             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
    13063             externrefresh = 10;
    13064          }
    13065       } else if (!strcasecmp(v->name, "allow")) {
    13066          ast_parse_allow_disallow(&prefs, &global_capability, v->value, 1);
    13067       } else if (!strcasecmp(v->name, "disallow")) {
    13068          ast_parse_allow_disallow(&prefs, &global_capability, v->value, 0);
    13069       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
    13070          allow_external_domains = ast_true(v->value);
    13071       } else if (!strcasecmp(v->name, "autodomain")) {
    13072          auto_sip_domains = ast_true(v->value);
    13073       } else if (!strcasecmp(v->name, "domain")) {
    13074          char *domain = ast_strdupa(v->value);
    13075          char *context = strchr(domain, ',');
    13076
    13077          if (context)
    13078             *context++ = '\0';
    13079
    13080          if (option_debug && ast_strlen_zero(context))
    13081             ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
    13082          if (ast_strlen_zero(domain))
    13083             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
    13084          else
    13085             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
    13086       } else if (!strcasecmp(v->name, "register")) {
    13087          sip_register(v->value, v->lineno);
    13088       } else if (!strcasecmp(v->name, "tos")) {
    13089          if (ast_str2tos(v->value, &tos))
    13090             ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
    13091       } else if (!strcasecmp(v->name, "bindport")) {
    13092          if (sscanf(v->value, "%30d", &ourport) == 1) {
    13093             bindaddr.sin_port = htons(ourport);
    13094          } else {
    13095             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
    13096          }
    13097       } else if (!strcasecmp(v->name, "qualify")) {
    13098          if (!strcasecmp(v->value, "no")) {
    13099             default_qualify = 0;
    13100          } else if (!strcasecmp(v->value, "yes")) {
    13101             default_qualify = DEFAULT_MAXMS;
    13102          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
    13103             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
    13104             default_qualify = 0;
    13105          }
    13106       } else if (!strcasecmp(v->name, "callevents")) {
    13107          callevents = ast_true(v->value);
    13108       }
    13109       v = v->next;
    13110    }
    13111
    13112    if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
    13113       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
    13114       allow_external_domains = 1;
    13115    }
    13116
    13117    /* Build list of authentication to various SIP realms, i.e. service providers */
    13118    v = ast_variable_browse(cfg, "authentication");
    13119    while(v) {
    13120       /* Format for authentication is auth = username:password@realm */
    13121       if (!strcasecmp(v->name, "auth")) {
    13122          authl = add_realm_authentication(authl, v->value, v->lineno);
    13123       }
    13124       v = v->next;
    13125    }
    13126
    13127    /* Load peers, users and friends */
    13128    cat = ast_category_browse(cfg, NULL);
    13129    while(cat) {
    13130       if (strcasecmp(cat, "general") && strcasecmp(cat, "authentication")) {
    13131          utype = ast_variable_retrieve(cfg, cat, "type");
    13132          if (utype) {
    13133             if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
    13134                user = build_user(cat, ast_variable_browse(cfg, cat), 0);
    13135                if (user) {
    13136                   ASTOBJ_CONTAINER_LINK(&userl,user);
    13137                   ASTOBJ_UNREF(user, sip_destroy_user);
    13138                }
    13139             }
    13140             if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
    13141                peer = build_peer(cat, ast_variable_browse(cfg, cat), 0);
    13142                if (peer) {
    13143                   ast_device_state_changed("SIP/%s", peer->name);
    13144                   ASTOBJ_CONTAINER_LINK(&peerl,peer);
    13145                   ASTOBJ_UNREF(peer, sip_destroy_peer);
    13146                }
    13147             } else if (strcasecmp(utype, "user")) {
    13148                ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
    13149             }
    13150          } else
    13151             ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
    13152       }
    13153       cat = ast_category_browse(cfg, cat);
    13154    }
    13155    if (ast_find_ourip(&__ourip, bindaddr)) {
    13156       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
    13157       return 0;
    13158    }
    13159    if (!ntohs(bindaddr.sin_port))
    13160       bindaddr.sin_port = ntohs(DEFAULT_SIP_PORT);
    13161    bindaddr.sin_family = AF_INET;
    13162    ast_mutex_lock(&netlock);
    13163    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
    13164       close(sipsock);
    13165       sipsock = -1;
    13166    }
    13167    if (sipsock < 0) {
    13168       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
    13169       if (sipsock < 0) {
    13170          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
    13171       } else {
    13172          /* Allow SIP clients on the same host to access us: */
    13173          const int reuseFlag = 1;
    13174
    13175          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
    13176                (const char*)&reuseFlag,
    13177                sizeof reuseFlag);
    13178
    13179          ast_enable_packet_fragmentation(sipsock);
    13180
    13181          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
    13182             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
    13183             ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port),
    13184             strerror(errno));
    13185             close(sipsock);
    13186             sipsock = -1;
    13187          } else {
    13188             if (option_verbose > 1) {
    13189                ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
    13190                ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port));
    13191                ast_verbose(VERBOSE_PREFIX_2 "Using TOS bits %d\n", tos);
    13192             }
    13193             if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)))
    13194                ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
    13195          }
    13196       }
    13197    }
    13198    ast_mutex_unlock(&netlock);
    13199
    13200    /* Add default domains - host name, IP address and IP:port */
    13201    /* Only do this if user added any sip domain with "localdomains" */
    13202    /* In order to *not* break backwards compatibility */
    13203    /*    Some phones address us at IP only, some with additional port number */
    13204    if (auto_sip_domains) {
    13205       char temp[MAXHOSTNAMELEN];
    13206
    13207       /* First our default IP address */
    13208       if (bindaddr.sin_addr.s_addr) {
    13209          ast_inet_ntoa(temp, sizeof(temp), bindaddr.sin_addr);
    13210          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
    13211       } else {
    13212          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
    13213       }
    13214
    13215       /* Our extern IP address, if configured */
    13216       if (externip.sin_addr.s_addr) {
    13217          ast_inet_ntoa(temp, sizeof(temp), externip.sin_addr);
    13218          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
    13219       }
    13220
    13221       /* Extern host name (NAT traversal support) */
    13222       if (!ast_strlen_zero(externhost))
    13223          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
    13224
    13225       /* Our host name */
    13226       if (!gethostname(temp, sizeof(temp)))
    13227          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
    13228    }
    13229
    13230    /* Release configuration from memory */
    13231    ast_config_destroy(cfg);
    13232
    13233    /* Load the list of manual NOTIFY types to support */
    13234    if (notify_types)
    13235       ast_config_destroy(notify_types);
    13236    notify_types = ast_config_load(notify_config);
    13237
    13238    return 0;
    13239 }
    13240
    13241 /*! \brief  sip_get_rtp_peer: Returns null if we can't reinvite (part of RTP interface) */
    13242 static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan)
    13243 {
    13244    struct sip_pvt *p;
    13245    struct ast_rtp *rtp = NULL;
    13246    p = chan->tech_pvt;
    13247    if (!p)
    13248       return NULL;
    13249    ast_mutex_lock(&p->lock);
    13250    if (p->rtp && ast_test_flag(p, SIP_CAN_REINVITE))
    13251       rtp =  p->rtp;
    13252    ast_mutex_unlock(&p->lock);
    13253    return rtp;
    13254 }
    13255
    13256 /*! \brief  sip_get_vrtp_peer: Returns null if we can't reinvite video (part of RTP interface) */
    13257 static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan)
    13258 {
    13259    struct sip_pvt *p;
    13260    struct ast_rtp *rtp = NULL;
    13261    p = chan->tech_pvt;
    13262    if (!p)
    13263       return NULL;
    13264
    13265    ast_mutex_lock(&p->lock);
    13266    if (p->vrtp && ast_test_flag(p, SIP_CAN_REINVITE))
    13267       rtp = p->vrtp;
    13268    ast_mutex_unlock(&p->lock);
    13269    return rtp;
    13270 }
    13271
    13272 /*! \brief  sip_set_rtp_peer: Set the RTP peer for this call ---*/
    13273 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
    13274 {
    13275    struct sip_pvt *p;
    13276    int changed = 0;
    13277
    13278    p = chan->tech_pvt;
    13279    if (!p)
    13280       return -1;
    13281    ast_mutex_lock(&p->lock);
    13282    if (rtp) {
    13283       changed |= ast_rtp_get_peer(rtp, &p->redirip);
    13284    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
    13285       memset(&p->redirip, 0, sizeof(p->redirip));
    13286       changed = 1;
    13287    }
    13288    if (vrtp) {
    13289       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
    13290    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
    13291       memset(&p->vredirip, 0, sizeof(p->vredirip));
    13292       changed = 1;
    13293    }
    13294    if (codecs && (p->redircodecs != codecs)) {
    13295       p->redircodecs = codecs;
    13296       changed = 1;
    13297    }
    13298    if (changed && !ast_test_flag(p, SIP_GOTREFER)) {
    13299       if (!p->pendinginvite) {
    13300          if (option_debug > 2) {
    13301             char iabuf[INET_ADDRSTRLEN];
    13302             ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp ? p->redirip.sin_addr : p->ourip));
    13303          }
    13304          transmit_reinvite_with_sdp(p);
    13305       } else if (!ast_test_flag(p, SIP_PENDINGBYE)) {
    13306          if (option_debug > 2) {
    13307             char iabuf[INET_ADDRSTRLEN];
    13308             ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp ? p->redirip.sin_addr : p->ourip));
    13309          }
    13310          ast_set_flag(p, SIP_NEEDREINVITE);
    13311       }
    13312    }
    13313    /* Reset lastrtprx timer */
    13314    time(&p->lastrtprx);
    13315    time(&p->lastrtptx);
    13316    ast_mutex_unlock(&p->lock);
    13317    return 0;
    13318 }
    13319
    13320 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
    13321 static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
    13322 static char *app_dtmfmode = "SIPDtmfMode";
    13323
    13324 static char *app_sipaddheader = "SIPAddHeader";
    13325 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
    13326
    13327
    13328 static char *descrip_sipaddheader = ""
    13329 "  SIPAddHeader(Header: Content)\n"
    13330 "Adds a header to a SIP call placed with DIAL.\n"
    13331 "Remember to user the X-header if you are adding non-standard SIP\n"
    13332 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
    13333 "Adding the wrong headers may jeopardize the SIP dialog.\n"
    13334 "Always returns 0\n";
    13335
    13336 static char *app_sipgetheader = "SIPGetHeader";
    13337 static char *synopsis_sipgetheader = "Get a SIP header from an incoming call";
    13338
    13339 static char *descrip_sipgetheader = ""
    13340 "  SIPGetHeader(var=headername[|options]): \n"
    13341 "Sets a channel variable to the content of a SIP header\n"
    13342 "  Options:\n"
    13343 "    j - Jump to priority n+101 if the requested header isn't found.\n"
    13344 "  This application sets the following channel variable upon completion:\n"
    13345 "      SIPGETSTATUS - This variable will contain the status of the attempt\n"
    13346 "                     FOUND | NOTFOUND\n"
    13347 "  This application has been deprecated in favor of the SIP_HEADER function.\n";
    13348
    13349 /*! \brief  sip_dtmfmode: change the DTMFmode for a SIP call (application) ---*/
    13350 static int sip_dtmfmode(struct ast_channel *chan, void *data)
    13351 {
    13352    struct sip_pvt *p;
    13353    char *mode;
    13354    if (data)
    13355       mode = (char *)data;
    13356    else {
    13357       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
    13358       return 0;
    13359    }
    13360    ast_mutex_lock(&chan->lock);
    13361    if (chan->type != channeltype) {
    13362       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
    13363       ast_mutex_unlock(&chan->lock);
    13364       return 0;
    13365    }
    13366    p = chan->tech_pvt;
    13367    if (!p) {
    13368       ast_mutex_unlock(&chan->lock);
    13369       return 0;
    13370    }
    13371    ast_mutex_lock(&p->lock);
    13372    if (!strcasecmp(mode,"info")) {
    13373       ast_clear_flag(p, SIP_DTMF);
    13374       ast_set_flag(p, SIP_DTMF_INFO);
    13375    } else if (!strcasecmp(mode,"rfc2833")) {
    13376       ast_clear_flag(p, SIP_DTMF);
    13377       ast_set_flag(p, SIP_DTMF_RFC2833);
    13378    } else if (!strcasecmp(mode,"inband")) {
    13379       ast_clear_flag(p, SIP_DTMF);
    13380       ast_set_flag(p, SIP_DTMF_INBAND);
    13381    } else
    13382       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
    13383    if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) {
    13384       if (!p->vad) {
    13385          p->vad = ast_dsp_new();
    13386          ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
    13387       }
    13388    } else {
    13389       if (p->vad) {
    13390          ast_dsp_free(p->vad);
    13391          p->vad = NULL;
    13392       }
    13393    }
    13394    ast_mutex_unlock(&p->lock);
    13395    ast_mutex_unlock(&chan->lock);
    13396    return 0;
    13397 }
    13398
    13399 /*! \brief  sip_addheader: Add a SIP header ---*/
    13400 static int sip_addheader(struct ast_channel *chan, void *data)
    13401 {
    13402    int no = 0;
    13403    int ok = 0;
    13404    char varbuf[128];
    13405
    13406    if (ast_strlen_zero((char *)data)) {
    13407       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
    13408       return 0;
    13409    }
    13410    ast_mutex_lock(&chan->lock);
    13411
    13412    /* Check for headers */
    13413    while (!ok && no <= 50) {
    13414       no++;
    13415       snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%02d", no);
    13416       if (ast_strlen_zero(pbx_builtin_getvar_helper(chan, varbuf + 1)))
    13417          ok = 1;
    13418    }
    13419    if (ok) {
    13420       pbx_builtin_setvar_helper (chan, varbuf, (char *)data);
    13421       if (sipdebug)
    13422          ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", (char *) data, varbuf);
    13423    } else {
    13424       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
    13425    }
    13426    ast_mutex_unlock(&chan->lock);
    13427    return 0;
    13428 }
    13429
    13430 /*! \brief  sip_getheader: Get a SIP header (dialplan app) ---*/
    13431 static int sip_getheader(struct ast_channel *chan, void *data)
    13432 {
    13433    char *argv, *varname = NULL, *header = NULL, *content, *options = NULL;
    13434    static int dep_warning = 0;
    13435    struct sip_pvt *p;
    13436    int priority_jump = 0;
    13437
    13438    if (!dep_warning) {
    13439       ast_log(LOG_WARNING, "SIPGetHeader is deprecated, use the SIP_HEADER function instead.\n");
    13440       dep_warning = 1;
    13441    }
    13442
    13443    argv = ast_strdupa(data);
    13444    if (!argv) {
    13445       ast_log(LOG_DEBUG, "Memory allocation failed\n");
    13446       return 0;
    13447    }
    13448
    13449    if (strchr (argv, '=') ) { /* Pick out argument */
    13450       varname = strsep (&argv, "=");
    13451       if (strchr(argv, '|')) {
    13452          header = strsep (&argv, "|");
    13453          options = strsep (&argv, "\0");
    13454       } else {
    13455          header = strsep (&argv, "\0");
    13456       }
    13457
    13458    }
    13459
    13460    if (!varname || !header) {
    13461       ast_log(LOG_DEBUG, "SIPGetHeader: Ignoring command, Syntax error in argument\n");
    13462       return 0;
    13463    }
    13464
    13465    if (options) {
    13466       if (strchr(options, 'j'))
    13467          priority_jump = 1;
    13468    }
    13469
    13470    ast_mutex_lock(&chan->lock);
    13471    if (chan->type != channeltype) {
    13472       ast_log(LOG_WARNING, "Call this application only on incoming SIP calls\n");
    13473       ast_mutex_unlock(&chan->lock);
    13474       return 0;
    13475    }
    13476
    13477    p = chan->tech_pvt;
    13478    content = get_header(&p->initreq, header);   /* Get the header */
    13479    if (!ast_strlen_zero(content)) {
    13480       pbx_builtin_setvar_helper(chan, varname, content);
    13481       if (option_verbose > 2)
    13482          ast_verbose(VERBOSE_PREFIX_3 "SIPGetHeader: set variable %s to %s\n", varname, content);
    13483       pbx_builtin_setvar_helper(chan, "SIPGETSTATUS", "FOUND");
    13484    } else {
    13485       ast_log(LOG_WARNING,"SIP Header %s not found for channel variable %s\n", header, varname);
    13486       if (priority_jump || option_priority_jumping) {
    13487          /* Goto priority n+101 if it exists, where n is the current priority number */
    13488          ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
    13489       }
    13490       pbx_builtin_setvar_helper(chan, "SIPGETSTATUS", "NOTFOUND");
    13491    }
    13492
    13493    ast_mutex_unlock(&chan->lock);
    13494    return 0;
    13495 }
    13496
    13497 /*! \brief  sip_sipredirect: Transfer call before connect with a 302 redirect ---*/
    13498 /* Called by the transfer() dialplan application through the sip_transfer() */
    13499 /* pbx interface function if the call is in ringing state */
    13500 /* coded by Martin Pycko (m78pl@yahoo.com) */
    13501 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
    13502 {
    13503    char *cdest;
    13504    char *extension, *host, *port;
    13505    char tmp[80];
    13506
    13507    cdest = ast_strdupa(dest);
    13508    if (!cdest) {
    13509       ast_log(LOG_ERROR, "Problem allocating the memory\n");
    13510       return 0;
    13511    }
    13512    extension = strsep(&cdest, "@");
    13513    host = strsep(&cdest, ":");
    13514    port = strsep(&cdest, ":");
    13515    if (!extension) {
    13516       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
    13517       return 0;
    13518    }
    13519
    13520    /* we'll issue the redirect message here */
    13521    if (!host) {
    13522       char *localtmp;
    13523       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
    13524       if (!strlen(tmp)) {
    13525          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
    13526          return 0;
    13527       }
    13528       if ((localtmp = strcasestr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
    13529          char lhost[80], lport[80];
    13530          memset(lhost, 0, sizeof(lhost));
    13531          memset(lport, 0, sizeof(lport));
    13532          localtmp++;
    13533          /* This is okey because lhost and lport are as big as tmp */
    13534          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
    13535          if (!strlen(lhost)) {
    13536             ast_log(LOG_ERROR, "Can't find the host address\n");
    13537             return 0;
    13538          }
    13539          host = ast_strdupa(lhost);
    13540          if (!host) {
    13541             ast_log(LOG_ERROR, "Problem allocating the memory\n");
    13542             return 0;
    13543          }
    13544          if (!ast_strlen_zero(lport)) {
    13545             port = ast_strdupa(lport);
    13546             if (!port) {
    13547                ast_log(LOG_ERROR, "Problem allocating the memory\n");
    13548                return 0;
    13549             }
    13550          }
    13551       }
    13552    }
    13553
    13554    snprintf(p->our_contact, sizeof(p->our_contact), "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
    13555    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq, 1);
    13556
    13557    sip_scheddestroy(p, 32000);   /* Make sure we stop send this reply. */
    13558
    13559    /* hangup here */
    13560    return -1;
    13561 }
    13562
    13563 /*! \brief  sip_get_codec: Return SIP UA's codec (part of the RTP interface) ---*/
    13564 static int sip_get_codec(struct ast_channel *chan)
    13565 {
    13566    struct sip_pvt *p = chan->tech_pvt;
    13567    return p->peercapability;
    13568 }
    13569
    13570 /*! \brief  sip_rtp: Interface structure with callbacks used to connect to rtp module --*/
    13571 static struct ast_rtp_protocol sip_rtp = {
    13572    type: channeltype,
    13573    get_rtp_info: sip_get_rtp_peer,
    13574    get_vrtp_info: sip_get_vrtp_peer,
    13575    set_rtp_peer: sip_set_rtp_peer,
    13576    get_codec: sip_get_codec,
    13577 };
    13578
    13579 /*! \brief  sip_poke_all_peers: Send a poke to all known peers */
    13580 static void sip_poke_all_peers(void)
    13581 {
    13582    ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
    13583       ASTOBJ_WRLOCK(iterator);
    13584       sip_poke_peer(iterator);
    13585       ASTOBJ_UNLOCK(iterator);
    13586    } while (0)
    13587    );
    13588 }
    13589
    13590 /*! \brief  sip_send_all_registers: Send all known registrations */
    13591 static void sip_send_all_registers(void)
    13592 {
    13593    int ms;
    13594    int regspacing;
    13595    if (!regobjs)
    13596       return;
    13597    regspacing = default_expiry * 1000/regobjs;
    13598    if (regspacing > 100)
    13599       regspacing = 100;
    13600    ms = regspacing;
    13601    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
    13602       ASTOBJ_WRLOCK(iterator);
    13603       if (iterator->expire > -1)
    13604          ast_sched_del(sched, iterator->expire);
    13605       ms += regspacing;
    13606       iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
    13607       ASTOBJ_UNLOCK(iterator);
    13608    } while (0)
    13609    );
    13610 }
    13611
    13612 /*! \brief  sip_do_reload: Reload module */
    13613 static int sip_do_reload(void)
    13614 {
    13615    clear_realm_authentication(authl);
    13616    clear_sip_domains();
    13617    authl = NULL;
    13618
    13619    /* First, destroy all outstanding registry calls */
    13620    /* This is needed, since otherwise active registry entries will not be destroyed */
    13621    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
    13622       ASTOBJ_RDLOCK(iterator);
    13623       if (iterator->call) {
    13624          if (option_debug > 2)
    13625             ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
    13626          /* This will also remove references to the registry */
    13627          sip_destroy(iterator->call);
    13628       }
    13629       ASTOBJ_UNLOCK(iterator);
    13630
    13631    } while(0));
    13632
    13633
    13634    ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
    13635    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
    13636    ASTOBJ_CONTAINER_MARKALL(&peerl);
    13637    reload_config();
    13638    /* Prune peers who still are supposed to be deleted */
    13639    ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
    13640
    13641    sip_poke_all_peers();
    13642    sip_send_all_registers();
    13643
    13644    return 0;
    13645 }
    13646
    13647 /*! \brief  sip_reload: Force reload of module from cli ---*/
    13648 static int sip_reload(int fd, int argc, char *argv[])
    13649 {
    13650
    13651    ast_mutex_lock(&sip_reload_lock);
    13652    if (sip_reloading) {
    13653       ast_verbose("Previous SIP reload not yet done\n");
    13654    } else
    13655       sip_reloading = 1;
    13656    ast_mutex_unlock(&sip_reload_lock);
    13657    restart_monitor();
    13658
    13659    return 0;
    13660 }
    13661
    13662 /*! \brief  reload: Part of Asterisk module interface ---*/
    13663 int reload(void)
    13664 {
    13665    return sip_reload(0, 0, NULL);
    13666 }
    13667
    13668 static struct ast_cli_entry  my_clis[] = {
    13669    { { "sip", "notify", NULL }, sip_notify, "Send a notify packet to a SIP peer", notify_usage, complete_sipnotify },
    13670    { { "sip", "show", "objects", NULL }, sip_show_objects, "Show all SIP object allocations", show_objects_usage },
    13671    { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage },
    13672    { { "sip", "show", "user", NULL }, sip_show_user, "Show details on specific SIP user", show_user_usage, complete_sip_show_user },
    13673    { { "sip", "show", "subscriptions", NULL }, sip_show_subscriptions, "Show active SIP subscriptions", show_subscriptions_usage},
    13674    { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage},
    13675    { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch  },
    13676    { { "sip", "show", "history", NULL }, sip_show_history, "Show SIP dialog history", show_history_usage, complete_sipch  },
    13677    { { "sip", "show", "domains", NULL }, sip_show_domains, "List our local SIP domains.", show_domains_usage },
    13678    { { "sip", "show", "settings", NULL }, sip_show_settings, "Show SIP global settings", show_settings_usage  },
    13679    { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage },
    13680    { { "sip", "debug", "ip", NULL }, sip_do_debug, "Enable SIP debugging on IP", debug_usage },
    13681    { { "sip", "debug", "peer", NULL }, sip_do_debug, "Enable SIP debugging on Peername", debug_usage, complete_sip_debug_peer },
    13682    { { "sip", "show", "peer", NULL }, sip_show_peer, "Show details on specific SIP peer", show_peer_usage, complete_sip_show_peer },
    13683    { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage },
    13684    { { "sip", "prune", "realtime", NULL }, sip_prune_realtime,
    13685      "Prune cached Realtime object(s)", prune_realtime_usage },
    13686    { { "sip", "prune", "realtime", "peer", NULL }, sip_prune_realtime,
    13687      "Prune cached Realtime peer(s)", prune_realtime_usage, complete_sip_prune_realtime_peer },
    13688    { { "sip", "prune", "realtime", "user", NULL }, sip_prune_realtime,
    13689      "Prune cached Realtime user(s)", prune_realtime_usage, complete_sip_prune_realtime_user },
    13690    { { "sip", "show", "inuse", NULL }, sip_show_inuse, "List all inuse/limits", show_inuse_usage },
    13691    { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage },
    13692    { { "sip", "history", NULL }, sip_do_history, "Enable SIP history", history_usage },
    13693    { { "sip", "no", "history", NULL }, sip_no_history, "Disable SIP history", no_history_usage },
    13694    { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage },
    13695    { { "sip", "reload", NULL }, sip_reload, "Reload SIP configuration", sip_reload_usage },
    13696 };
    13697
    13698 /*! \brief  load_module: PBX load module - initialization ---*/
    13699 int load_module()
    13700 {
    13701    ASTOBJ_CONTAINER_INIT(&userl);   /* User object list */
    13702    ASTOBJ_CONTAINER_INIT(&peerl);   /* Peer object list */
    13703    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list */
    13704
    13705    sched = sched_context_create();
    13706    if (!sched) {
    13707       ast_log(LOG_WARNING, "Unable to create schedule context\n");
    13708    }
    13709
    13710    io = io_context_create();
    13711    if (!io) {
    13712       ast_log(LOG_WARNING, "Unable to create I/O context\n");
    13713    }
    13714
    13715    reload_config();  /* Load the configuration from sip.conf */
    13716
    13717    /* Make sure we can register our sip channel type */
    13718    if (ast_channel_register(&sip_tech)) {
    13719       ast_log(LOG_ERROR, "Unable to register channel type %s\n", channeltype);
    13720       return -1;
    13721    }
    13722
    13723    /* Register all CLI functions for SIP */
    13724    ast_cli_register_multiple(my_clis, sizeof(my_clis)/ sizeof(my_clis[0]));
    13725
    13726    /* Tell the RTP subdriver that we're here */
    13727    ast_rtp_proto_register(&sip_rtp);
    13728
    13729    /* Register dialplan applications */
    13730    ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
    13731
    13732    /* These will be removed soon */
    13733    ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
    13734    ast_register_application(app_sipgetheader, sip_getheader, synopsis_sipgetheader, descrip_sipgetheader);
    13735
    13736    /* Register dialplan functions */
    13737    ast_custom_function_register(&sip_header_function);
    13738    ast_custom_function_register(&sippeer_function);
    13739    ast_custom_function_register(&sipchaninfo_function);
    13740    ast_custom_function_register(&checksipdomain_function);
    13741
    13742    /* Register manager commands */
    13743    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
    13744          "List SIP peers (text format)", mandescr_show_peers);
    13745    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
    13746          "Show SIP peer (text format)", mandescr_show_peer);
    13747
    13748    sip_poke_all_peers();
    13749    sip_send_all_registers();
    13750
    13751    /* And start the monitor for the first time */
    13752    restart_monitor();
    13753
    13754    return 0;
    13755 }
    13756
    13757 int unload_module()
    13758 {
    13759    struct sip_pvt *p, *pl;
    13760
    13761    /* First, take us out of the channel type list */
    13762    ast_channel_unregister(&sip_tech);
    13763
    13764    ast_custom_function_unregister(&sipchaninfo_function);
    13765    ast_custom_function_unregister(&sippeer_function);
    13766    ast_custom_function_unregister(&sip_header_function);
    13767    ast_custom_function_unregister(&checksipdomain_function);
    13768
    13769    ast_unregister_application(app_dtmfmode);
    13770    ast_unregister_application(app_sipaddheader);
    13771    ast_unregister_application(app_sipgetheader);
    13772
    13773    ast_cli_unregister_multiple(my_clis, sizeof(my_clis) / sizeof(my_clis[0]));
    13774
    13775    ast_rtp_proto_unregister(&sip_rtp);
    13776
    13777    ast_manager_unregister("SIPpeers");
    13778    ast_manager_unregister("SIPshowpeer");
    13779
    13780    if (!ast_mutex_lock(&iflock)) {
    13781       /* Hangup all interfaces if they have an owner */
    13782       p = iflist;
    13783       while (p) {
    13784          if (p->owner)
    13785             ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
    13786          p = p->next;
    13787       }
    13788       ast_mutex_unlock(&iflock);
    13789    } else {
    13790       ast_log(LOG_WARNING, "Unable to lock the interface list\n");
    13791       return -1;
    13792    }
    13793
    13794    if (!ast_mutex_lock(&monlock)) {
    13795       if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
    13796          pthread_cancel(monitor_thread);
    13797          pthread_kill(monitor_thread, SIGURG);
    13798          pthread_join(monitor_thread, NULL);
    13799       }
    13800       monitor_thread = AST_PTHREADT_STOP;
    13801       ast_mutex_unlock(&monlock);
    13802    } else {
    13803       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
    13804       return -1;
    13805    }
    13806
    13807    if (!ast_mutex_lock(&iflock)) {
    13808       /* Destroy all the interfaces and free their memory */
    13809       p = iflist;
    13810       while (p) {
    13811          pl = p;
    13812          p = p->next;
    13813          __sip_destroy(pl, 1);
    13814       }
    13815       iflist = NULL;
    13816       ast_mutex_unlock(&iflock);
    13817    } else {
    13818       ast_log(LOG_WARNING, "Unable to lock the interface list\n");
    13819       return -1;
    13820    }
    13821
    13822    /* Free memory for local network address mask */
    13823    ast_free_ha(localaddr);
    13824
    13825    ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
    13826    ASTOBJ_CONTAINER_DESTROY(&userl);
    13827    ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
    13828    ASTOBJ_CONTAINER_DESTROY(&peerl);
    13829    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
    13830    ASTOBJ_CONTAINER_DESTROY(&regl);
    13831
    13832    clear_realm_authentication(authl);
    13833    clear_sip_domains();
    13834    close(sipsock);
    13835    sched_context_destroy(sched);
    13836
    13837    return 0;
    13838 }
    13839
    13840 int usecount()
    13841 {
    13842    return usecnt;
    13843 }
    13844
    13845 char *key()
    13846 {
    13847    return ASTERISK_GPL_KEY;
    13848 }
    13849
    13850 char *description()
    13851 {
    13852    return (char *) desc;
    13853 }
    13854
    13855