Sat Nov 1 06:28:28 2008

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  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * See Also:
00026  * \arg \ref AstCREDITS
00027  *
00028  * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
00029  * Configuration file \link Config_sip sip.conf \endlink
00030  *
00031  *
00032  * \todo SIP over TCP
00033  * \todo SIP over TLS
00034  * \todo Better support of forking
00035  * \todo VIA branch tag transaction checking
00036  * \todo Transaction support
00037  *
00038  * \ingroup channel_drivers
00039  *
00040  * \par Overview of the handling of SIP sessions
00041  * The SIP channel handles several types of SIP sessions, or dialogs,
00042  * not all of them being "telephone calls".
00043  * - Incoming calls that will be sent to the PBX core
00044  * - Outgoing calls, generated by the PBX
00045  * - SIP subscriptions and notifications of states and voicemail messages
00046  * - SIP registrations, both inbound and outbound
00047  * - SIP peer management (peerpoke, OPTIONS)
00048  * - SIP text messages
00049  *
00050  * In the SIP channel, there's a list of active SIP dialogs, which includes
00051  * all of these when they are active. "sip show channels" in the CLI will
00052  * show most of these, excluding subscriptions which are shown by
00053  * "sip show subscriptions"
00054  *
00055  * \par incoming packets
00056  * Incoming packets are received in the monitoring thread, then handled by
00057  * sipsock_read(). This function parses the packet and matches an existing
00058  * dialog or starts a new SIP dialog.
00059  * 
00060  * sipsock_read sends the packet to handle_request(), that parses a bit more.
00061  * if it's a response to an outbound request, it's sent to handle_response().
00062  * If it is a request, handle_request sends it to one of a list of functions
00063  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
00064  * sipsock_read locks the ast_channel if it exists (an active call) and
00065  * unlocks it after we have processed the SIP message.
00066  *
00067  * A new INVITE is sent to handle_request_invite(), that will end up
00068  * starting a new channel in the PBX, the new channel after that executing
00069  * in a separate channel thread. This is an incoming "call".
00070  * When the call is answered, either by a bridged channel or the PBX itself
00071  * the sip_answer() function is called.
00072  *
00073  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
00074  * in rtp.c 
00075  * 
00076  * \par Outbound calls
00077  * Outbound calls are set up by the PBX through the sip_request_call()
00078  * function. After that, they are activated by sip_call().
00079  * 
00080  * \par Hanging up
00081  * The PBX issues a hangup on both incoming and outgoing calls through
00082  * the sip_hangup() function
00083  *
00084  * \par Deprecated stuff
00085  * This is deprecated and will be removed after the 1.4 release
00086  * - the SIPUSERAGENT dialplan variable
00087  * - the ALERT_INFO dialplan variable
00088  */
00089 
00090 /*** MODULEINFO
00091         <depend>res_features</depend>
00092  ***/
00093 
00094 
00095 #include "asterisk.h"
00096 
00097 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 153114 $")
00098 
00099 #include <stdio.h>
00100 #include <ctype.h>
00101 #include <string.h>
00102 #include <unistd.h>
00103 #include <sys/socket.h>
00104 #include <sys/ioctl.h>
00105 #include <net/if.h>
00106 #include <errno.h>
00107 #include <stdlib.h>
00108 #include <fcntl.h>
00109 #include <netdb.h>
00110 #include <signal.h>
00111 #include <sys/signal.h>
00112 #include <netinet/in.h>
00113 #include <netinet/in_systm.h>
00114 #include <arpa/inet.h>
00115 #include <netinet/ip.h>
00116 #include <regex.h>
00117 
00118 #include "asterisk/lock.h"
00119 #include "asterisk/channel.h"
00120 #include "asterisk/config.h"
00121 #include "asterisk/logger.h"
00122 #include "asterisk/module.h"
00123 #include "asterisk/pbx.h"
00124 #include "asterisk/options.h"
00125 #include "asterisk/sched.h"
00126 #include "asterisk/io.h"
00127 #include "asterisk/rtp.h"
00128 #include "asterisk/udptl.h"
00129 #include "asterisk/acl.h"
00130 #include "asterisk/manager.h"
00131 #include "asterisk/callerid.h"
00132 #include "asterisk/cli.h"
00133 #include "asterisk/app.h"
00134 #include "asterisk/musiconhold.h"
00135 #include "asterisk/dsp.h"
00136 #include "asterisk/features.h"
00137 #include "asterisk/srv.h"
00138 #include "asterisk/astdb.h"
00139 #include "asterisk/causes.h"
00140 #include "asterisk/utils.h"
00141 #include "asterisk/file.h"
00142 #include "asterisk/astobj.h"
00143 #include "asterisk/devicestate.h"
00144 #include "asterisk/linkedlists.h"
00145 #include "asterisk/stringfields.h"
00146 #include "asterisk/monitor.h"
00147 #include "asterisk/localtime.h"
00148 #include "asterisk/abstract_jb.h"
00149 #include "asterisk/compiler.h"
00150 #include "asterisk/threadstorage.h"
00151 #include "asterisk/translate.h"
00152 
00153 #ifndef FALSE
00154 #define FALSE    0
00155 #endif
00156 
00157 #ifndef TRUE
00158 #define TRUE     1
00159 #endif
00160 
00161 #define  SIPBUFSIZE     512
00162 
00163 #define XMIT_ERROR      -2
00164 
00165 #define VIDEO_CODEC_MASK        0x1fc0000       /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
00166 #ifndef IPTOS_MINCOST
00167 #define IPTOS_MINCOST           0x02
00168 #endif
00169 
00170 #define SIP_RESERVED ";/?:@&=+$,# "
00171 
00172 /* #define VOCAL_DATA_HACK */
00173 
00174 #define DEFAULT_DEFAULT_EXPIRY  120
00175 #define DEFAULT_MIN_EXPIRY      60
00176 #define DEFAULT_MAX_EXPIRY      3600
00177 #define DEFAULT_REGISTRATION_TIMEOUT 20
00178 #define DEFAULT_MAX_FORWARDS    "70"
00179 
00180 /* guard limit must be larger than guard secs */
00181 /* guard min must be < 1000, and should be >= 250 */
00182 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
00183 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
00184                                                    EXPIRY_GUARD_SECS */
00185 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
00186                                                    GUARD_PCT turns out to be lower than this, it 
00187                                                    will use this time instead.
00188                                                    This is in milliseconds. */
00189 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
00190                                                     below EXPIRY_GUARD_LIMIT */
00191 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
00192 
00193 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00194 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00195 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00196 static int expiry = DEFAULT_EXPIRY;
00197 
00198 #ifndef MAX
00199 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00200 #endif
00201 
00202 #define CALLERID_UNKNOWN        "Unknown"
00203 
00204 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
00205 #define DEFAULT_FREQ_OK              60 * 1000        /*!< Qualification: How often to check for the host to be up */
00206 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
00207 
00208 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
00209 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
00210 #define SIP_TRANS_TIMEOUT            32000            /*!< SIP request timeout (rfc 3261) 64*T1 
00211                                                       \todo Use known T1 for timeout (peerpoke)
00212                                                       */
00213 #define DEFAULT_TRANS_TIMEOUT        -1               /* Use default SIP transaction timeout */
00214 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
00215 
00216 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
00217 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
00218 #define SIP_MAX_PACKET               4096             /*!< Also from RFC 3261 (2543), should sub headers tho */
00219 
00220 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
00221 
00222 #define INITIAL_CSEQ                 101              /*!< our initial sip sequence number */
00223 
00224 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00225 static struct ast_jb_conf default_jbconf =
00226 {
00227         .flags = 0,
00228    .max_size = -1,
00229    .resync_threshold = -1,
00230    .impl = ""
00231 };
00232 static struct ast_jb_conf global_jbconf;
00233 
00234 static const char config[] = "sip.conf";
00235 static const char notify_config[] = "sip_notify.conf";
00236 
00237 #define RTP    1
00238 #define NO_RTP 0
00239 
00240 /*! \brief Authorization scheme for call transfers 
00241 \note Not a bitfield flag, since there are plans for other modes,
00242    like "only allow transfers for authenticated devices" */
00243 enum transfermodes {
00244    TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
00245    TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
00246 };
00247 
00248 
00249 enum sip_result {
00250    AST_SUCCESS = 0,
00251    AST_FAILURE = -1,
00252 };
00253 
00254 /*! \brief States for the INVITE transaction, not the dialog 
00255    \note this is for the INVITE that sets up the dialog
00256 */
00257 enum invitestates {
00258    INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
00259    INV_CALLING = 1,  /*!< Invite sent, no answer */
00260    INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
00261    INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
00262    INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
00263    INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
00264    INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
00265                     The only way out of this is a BYE from one side */
00266    INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
00267 };
00268 
00269 /* Do _NOT_ make any changes to this enum, or the array following it;
00270    if you think you are doing the right thing, you are probably
00271    not doing the right thing. If you think there are changes
00272    needed, get someone else to review them first _before_
00273    submitting a patch. If these two lists do not match properly
00274    bad things will happen.
00275 */
00276 
00277 enum xmittype {
00278    XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
00279                                               If it fails, it's critical and will cause a teardown of the session */
00280    XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
00281    XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
00282 };
00283 
00284 enum parse_register_result {
00285    PARSE_REGISTER_FAILED,
00286    PARSE_REGISTER_UPDATE,
00287    PARSE_REGISTER_QUERY,
00288 };
00289 
00290 enum subscriptiontype { 
00291    NONE = 0,
00292    XPIDF_XML,
00293    DIALOG_INFO_XML,
00294    CPIM_PIDF_XML,
00295    PIDF_XML,
00296    MWI_NOTIFICATION
00297 };
00298 
00299 static const struct cfsubscription_types {
00300    enum subscriptiontype type;
00301    const char * const event;
00302    const char * const mediatype;
00303    const char * const text;
00304 } subscription_types[] = {
00305    { NONE,        "-",        "unknown",               "unknown" },
00306    /* RFC 4235: SIP Dialog event package */
00307    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00308    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00309    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00310    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00311    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00312 };
00313 
00314 /*! \brief SIP Request methods known by Asterisk */
00315 enum sipmethod {
00316    SIP_UNKNOWN,      /* Unknown response */
00317    SIP_RESPONSE,     /* Not request, response to outbound request */
00318    SIP_REGISTER,
00319    SIP_OPTIONS,
00320    SIP_NOTIFY,
00321    SIP_INVITE,
00322    SIP_ACK,
00323    SIP_PRACK,     /* Not supported at all */
00324    SIP_BYE,
00325    SIP_REFER,
00326    SIP_SUBSCRIBE,
00327    SIP_MESSAGE,
00328    SIP_UPDATE,    /* We can send UPDATE; but not accept it */
00329    SIP_INFO,
00330    SIP_CANCEL,
00331    SIP_PUBLISH,      /* Not supported at all */
00332    SIP_PING,      /* Not supported at all, no standard but still implemented out there */
00333 };
00334 
00335 /*! \brief Authentication types - proxy or www authentication 
00336    \note Endpoints, like Asterisk, should always use WWW authentication to
00337    allow multiple authentications in the same call - to the proxy and
00338    to the end point.
00339 */
00340 enum sip_auth_type {
00341    PROXY_AUTH,
00342    WWW_AUTH,
00343 };
00344 
00345 /*! \brief Authentication result from check_auth* functions */
00346 enum check_auth_result {
00347    AUTH_SUCCESSFUL = 0,
00348    AUTH_CHALLENGE_SENT = 1,
00349    AUTH_SECRET_FAILED = -1,
00350    AUTH_USERNAME_MISMATCH = -2,
00351    AUTH_NOT_FOUND = -3,
00352    AUTH_FAKE_AUTH = -4,
00353    AUTH_UNKNOWN_DOMAIN = -5,
00354    AUTH_PEER_NOT_DYNAMIC = -6,
00355    AUTH_ACL_FAILED = -7,
00356 };
00357 
00358 /*! \brief States for outbound registrations (with register= lines in sip.conf */
00359 enum sipregistrystate {
00360    REG_STATE_UNREGISTERED = 0,   /*!< We are not registred */
00361    REG_STATE_REGSENT,   /*!< Registration request sent */
00362    REG_STATE_AUTHSENT,  /*!< We have tried to authenticate */
00363    REG_STATE_REGISTERED,   /*!< Registred and done */
00364    REG_STATE_REJECTED,  /*!< Registration rejected */
00365    REG_STATE_TIMEOUT,   /*!< Registration timed out */
00366    REG_STATE_NOAUTH, /*!< We have no accepted credentials */
00367    REG_STATE_FAILED, /*!< Registration failed after several tries */
00368 };
00369 
00370 #define CAN_NOT_CREATE_DIALOG 0
00371 #define CAN_CREATE_DIALOG  1
00372 #define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD 2
00373 
00374 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
00375 static const struct  cfsip_methods { 
00376    enum sipmethod id;
00377    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00378    char * const text;
00379    int can_create;
00380 } sip_methods[] = {
00381    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
00382    { SIP_RESPONSE,    NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00383    { SIP_REGISTER,    NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
00384    { SIP_OPTIONS,  NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00385    { SIP_NOTIFY,   NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00386    { SIP_INVITE,   RTP,    "INVITE",   CAN_CREATE_DIALOG },
00387    { SIP_ACK,   NO_RTP, "ACK",   CAN_NOT_CREATE_DIALOG },
00388    { SIP_PRACK,    NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00389    { SIP_BYE,   NO_RTP, "BYE",   CAN_NOT_CREATE_DIALOG },
00390    { SIP_REFER,    NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00391    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",  CAN_CREATE_DIALOG },
00392    { SIP_MESSAGE,  NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00393    { SIP_UPDATE,   NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00394    { SIP_INFO,  NO_RTP, "INFO",  CAN_NOT_CREATE_DIALOG },
00395    { SIP_CANCEL,   NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00396    { SIP_PUBLISH,  NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00397    { SIP_PING,  NO_RTP, "PING",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00398 };
00399 
00400 /*!  Define SIP option tags, used in Require: and Supported: headers 
00401    We need to be aware of these properties in the phones to use 
00402    the replace: header. We should not do that without knowing
00403    that the other end supports it... 
00404    This is nothing we can configure, we learn by the dialog
00405    Supported: header on the REGISTER (peer) or the INVITE
00406    (other devices)
00407    We are not using many of these today, but will in the future.
00408    This is documented in RFC 3261
00409 */
00410 #define SUPPORTED    1
00411 #define NOT_SUPPORTED      0
00412 
00413 #define SIP_OPT_REPLACES   (1 << 0)
00414 #define SIP_OPT_100REL     (1 << 1)
00415 #define SIP_OPT_TIMER      (1 << 2)
00416 #define SIP_OPT_EARLY_SESSION (1 << 3)
00417 #define SIP_OPT_JOIN    (1 << 4)
00418 #define SIP_OPT_PATH    (1 << 5)
00419 #define SIP_OPT_PREF    (1 << 6)
00420 #define SIP_OPT_PRECONDITION  (1 << 7)
00421 #define SIP_OPT_PRIVACY    (1 << 8)
00422 #define SIP_OPT_SDP_ANAT   (1 << 9)
00423 #define SIP_OPT_SEC_AGREE  (1 << 10)
00424 #define SIP_OPT_EVENTLIST  (1 << 11)
00425 #define SIP_OPT_GRUU    (1 << 12)
00426 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00427 #define SIP_OPT_NOREFERSUB (1 << 14)
00428 #define SIP_OPT_HISTINFO   (1 << 15)
00429 #define SIP_OPT_RESPRIORITY   (1 << 16)
00430 
00431 /*! \brief List of well-known SIP options. If we get this in a require,
00432    we should check the list and answer accordingly. */
00433 static const struct cfsip_options {
00434    int id;        /*!< Bitmap ID */
00435    int supported;    /*!< Supported by Asterisk ? */
00436    char * const text;   /*!< Text id, as in standard */
00437 } sip_options[] = {  /* XXX used in 3 places */
00438    /* RFC3891: Replaces: header for transfer */
00439    { SIP_OPT_REPLACES,  SUPPORTED,  "replaces" },  
00440    /* One version of Polycom firmware has the wrong label */
00441    { SIP_OPT_REPLACES,  SUPPORTED,  "replace" },   
00442    /* RFC3262: PRACK 100% reliability */
00443    { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" }, 
00444    /* RFC4028: SIP Session Timers */
00445    { SIP_OPT_TIMER,  NOT_SUPPORTED, "timer" },
00446    /* RFC3959: SIP Early session support */
00447    { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,   "early-session" },
00448    /* RFC3911: SIP Join header support */
00449    { SIP_OPT_JOIN,      NOT_SUPPORTED, "join" },
00450    /* RFC3327: Path support */
00451    { SIP_OPT_PATH,      NOT_SUPPORTED, "path" },
00452    /* RFC3840: Callee preferences */
00453    { SIP_OPT_PREF,      NOT_SUPPORTED, "pref" },
00454    /* RFC3312: Precondition support */
00455    { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00456    /* RFC3323: Privacy with proxies*/
00457    { SIP_OPT_PRIVACY,   NOT_SUPPORTED, "privacy" },
00458    /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
00459    { SIP_OPT_SDP_ANAT,  NOT_SUPPORTED, "sdp-anat" },
00460    /* RFC3329: Security agreement mechanism */
00461    { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00462    /* SIMPLE events:  RFC4662 */
00463    { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00464    /* GRUU: Globally Routable User Agent URI's */
00465    { SIP_OPT_GRUU,      NOT_SUPPORTED, "gruu" },
00466    /* RFC4538: Target-dialog */
00467    { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00468    /* Disable the REFER subscription, RFC 4488 */
00469    { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED, "norefersub" },
00470    /* ietf-sip-history-info-06.txt */
00471    { SIP_OPT_HISTINFO,  NOT_SUPPORTED, "histinfo" },
00472    /* ietf-sip-resource-priority-10.txt */
00473    { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED, "resource-priority" },
00474 };
00475 
00476 
00477 /*! \brief SIP Methods we support */
00478 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
00479 
00480 /*! \brief SIP Extensions we support */
00481 #define SUPPORTED_EXTENSIONS "replaces" 
00482 
00483 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
00484 #define STANDARD_SIP_PORT  5060
00485 /* Note: in many SIP headers, absence of a port number implies port 5060,
00486  * and this is why we cannot change the above constant.
00487  * There is a limited number of places in asterisk where we could,
00488  * in principle, use a different "default" port number, but
00489  * we do not support this feature at the moment.
00490  */
00491 
00492 /* Default values, set and reset in reload_config before reading configuration */
00493 /* These are default values in the source. There are other recommended values in the
00494    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
00495    yet encouraging new behaviour on new installations 
00496  */
00497 #define DEFAULT_CONTEXT    "default"
00498 #define DEFAULT_MOHINTERPRET    "default"
00499 #define DEFAULT_MOHSUGGEST      ""
00500 #define DEFAULT_VMEXTEN    "asterisk"
00501 #define DEFAULT_CALLERID   "asterisk"
00502 #define DEFAULT_NOTIFYMIME    "application/simple-message-summary"
00503 #define DEFAULT_MWITIME    10
00504 #define DEFAULT_ALLOWGUEST TRUE
00505 #define DEFAULT_SRVLOOKUP  TRUE     /*!< Recommended setting is ON */
00506 #define DEFAULT_COMPACTHEADERS   FALSE
00507 #define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
00508 #define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
00509 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
00510 #define DEFAULT_ALLOW_EXT_DOM TRUE
00511 #define DEFAULT_REALM      "asterisk"
00512 #define DEFAULT_NOTIFYRINGING TRUE
00513 #define DEFAULT_PEDANTIC   FALSE
00514 #define DEFAULT_AUTOCREATEPEER   FALSE
00515 #define DEFAULT_QUALIFY    FALSE
00516 #define DEFAULT_T1MIN      100      /*!< 100 MS for minimal roundtrip time */
00517 #define DEFAULT_MAX_CALL_BITRATE (384)    /*!< Max bitrate for video */
00518 #ifndef DEFAULT_USERAGENT
00519 #define DEFAULT_USERAGENT "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
00520 #endif
00521 
00522 
00523 /* Default setttings are used as a channel setting and as a default when
00524    configuring devices */
00525 static char default_context[AST_MAX_CONTEXT];
00526 static char default_subscribecontext[AST_MAX_CONTEXT];
00527 static char default_language[MAX_LANGUAGE];
00528 static char default_callerid[AST_MAX_EXTENSION];
00529 static char default_fromdomain[AST_MAX_EXTENSION];
00530 static char default_notifymime[AST_MAX_EXTENSION];
00531 static int default_qualify;      /*!< Default Qualify= setting */
00532 static char default_vmexten[AST_MAX_EXTENSION];
00533 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00534 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
00535                                                     *   a bridged channel on hold */
00536 static int default_maxcallbitrate;  /*!< Maximum bitrate for call */
00537 static struct ast_codec_pref default_prefs;     /*!< Default codec prefs */
00538 
00539 /* Global settings only apply to the channel */
00540 static int global_directrtpsetup;   /*!< Enable support for Direct RTP setup (no re-invites) */
00541 static int global_limitonpeers;     /*!< Match call limit on peers only */
00542 static int global_rtautoclear;
00543 static int global_notifyringing; /*!< Send notifications on ringing */
00544 static int global_notifyhold;    /*!< Send notifications on hold */
00545 static int global_alwaysauthreject; /*!< Send 401 Unauthorized for all failing requests */
00546 static int srvlookup;         /*!< SRV Lookup on or off. Default is on */
00547 static int pedanticsipchecking;     /*!< Extra checking ?  Default off */
00548 static int autocreatepeer;    /*!< Auto creation of peers at registration? Default off. */
00549 static int global_relaxdtmf;        /*!< Relax DTMF */
00550 static int global_rtptimeout;    /*!< Time out call if no RTP */
00551 static int global_rtpholdtimeout;
00552 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00553 static int global_reg_timeout;   
00554 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00555 static int global_allowguest;    /*!< allow unauthenticated users/peers to connect? */
00556 static int global_allowsubscribe;   /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
00557                    the global setting is in globals_flags[1] */
00558 static int global_mwitime;    /*!< Time between MWI checks for peers */
00559 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
00560 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
00561 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
00562 static int compactheaders;    /*!< send compact sip headers */
00563 static int recordhistory;     /*!< Record SIP history. Off by default */
00564 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
00565 static char global_realm[MAXHOSTNAMELEN];       /*!< Default realm */
00566 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
00567 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
00568 static int allow_external_domains;  /*!< Accept calls to external SIP domains? */
00569 static int global_callevents;    /*!< Whether we send manager events or not */
00570 static int global_t1min;      /*!< T1 roundtrip time minimum */
00571 static int global_autoframing;          /*!< Turn autoframing on or off. */
00572 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
00573 
00574 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
00575 
00576 /*! \brief Codecs that we support by default: */
00577 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00578 
00579 /*! \brief Global list of addresses dynamic peers are not allowed to use */
00580 static struct ast_ha *global_contact_ha = NULL;
00581 static int global_dynamic_exclude_static = 0;
00582 
00583 /* Object counters */
00584 static int suserobjs = 0;                /*!< Static users */
00585 static int ruserobjs = 0;                /*!< Realtime users */
00586 static int speerobjs = 0;                /*!< Statis peers */
00587 static int rpeerobjs = 0;                /*!< Realtime peers */
00588 static int apeerobjs = 0;                /*!< Autocreated peer objects */
00589 static int regobjs = 0;                  /*!< Registry objects */
00590 
00591 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
00592 
00593 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
00594 AST_MUTEX_DEFINE_STATIC(iflock);
00595 
00596 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00597    when it's doing something critical. */
00598 AST_MUTEX_DEFINE_STATIC(netlock);
00599 
00600 AST_MUTEX_DEFINE_STATIC(monlock);
00601 
00602 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00603 
00604 /*! \brief This is the thread for the monitor which checks for input on the channels
00605    which are not currently in use.  */
00606 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00607 
00608 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00609 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00610 
00611 static struct sched_context *sched;     /*!< The scheduling context */
00612 static struct io_context *io;           /*!< The IO context */
00613 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00614 
00615 #define DEC_CALL_LIMIT  0
00616 #define INC_CALL_LIMIT  1
00617 #define DEC_CALL_RINGING 2
00618 #define INC_CALL_RINGING 3
00619 
00620 /*! \brief sip_request: The data grabbed from the UDP socket */
00621 struct sip_request {
00622    char *rlPart1;            /*!< SIP Method Name or "SIP/2.0" protocol version */
00623    char *rlPart2;            /*!< The Request URI or Response Status */
00624    int len;                /*!< Length */
00625    int headers;            /*!< # of SIP Headers */
00626    int method;             /*!< Method of this request */
00627    int lines;              /*!< Body Content */
00628    unsigned int flags;     /*!< SIP_PKT Flags for this packet */
00629    char *header[SIP_MAX_HEADERS];
00630    char *line[SIP_MAX_LINES];
00631    char data[SIP_MAX_PACKET];
00632    unsigned int sdp_start; /*!< the line number where the SDP begins */
00633    unsigned int sdp_end;   /*!< the line number where the SDP ends */
00634 };
00635 
00636 /*
00637  * A sip packet is stored into the data[] buffer, with the header followed
00638  * by an empty line and the body of the message.
00639  * On outgoing packets, data is accumulated in data[] with len reflecting
00640  * the next available byte, headers and lines count the number of lines
00641  * in both parts. There are no '\0' in data[0..len-1].
00642  *
00643  * On received packet, the input read from the socket is copied into data[],
00644  * len is set and the string is NUL-terminated. Then a parser fills up
00645  * the other fields -header[] and line[] to point to the lines of the
00646  * message, rlPart1 and rlPart2 parse the first lnie as below:
00647  *
00648  * Requests have in the first line  METHOD URI SIP/2.0
00649  * rlPart1 = method; rlPart2 = uri;
00650  * Responses have in the first line SIP/2.0 code description
00651  * rlPart1 = SIP/2.0; rlPart2 = code + description;
00652  *
00653  */
00654 
00655 /*! \brief structure used in transfers */
00656 struct sip_dual {
00657    struct ast_channel *chan1; /*!< First channel involved */
00658    struct ast_channel *chan2; /*!< Second channel involved */
00659    struct sip_request req;    /*!< Request that caused the transfer (REFER) */
00660    int seqno;        /*!< Sequence number */
00661 };
00662 
00663 struct sip_pkt;
00664 
00665 /*! \brief Parameters to the transmit_invite function */
00666 struct sip_invite_param {
00667    const char *distinctive_ring; /*!< Distinctive ring header */
00668    int addsipheaders;      /*!< Add extra SIP headers */
00669    const char *uri_options;   /*!< URI options to add to the URI */
00670    const char *vxml_url;      /*!< VXML url for Cisco phones */
00671    char *auth;       /*!< Authentication */
00672    char *authheader;    /*!< Auth header */
00673    enum sip_auth_type auth_type; /*!< Authentication type */
00674    const char *replaces;      /*!< Replaces header for call transfers */
00675    int transfer;        /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
00676 };
00677 
00678 /*! \brief Structure to save routing information for a SIP session */
00679 struct sip_route {
00680    struct sip_route *next;
00681    char hop[0];
00682 };
00683 
00684 /*! \brief Modes for SIP domain handling in the PBX */
00685 enum domain_mode {
00686    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
00687    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
00688 };
00689 
00690 /*! \brief Domain data structure. 
00691    \note In the future, we will connect this to a configuration tree specific
00692    for this domain
00693 */
00694 struct domain {
00695    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
00696    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
00697    enum domain_mode mode;        /*!< How did we find this domain? */
00698    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
00699 };
00700 
00701 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
00702 
00703 
00704 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
00705 struct sip_history {
00706    AST_LIST_ENTRY(sip_history) list;
00707    char event[0]; /* actually more, depending on needs */
00708 };
00709 
00710 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00711 
00712 /*! \brief sip_auth: Credentials for authentication to other SIP services */
00713 struct sip_auth {
00714    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
00715    char username[256];             /*!< Username */
00716    char secret[256];               /*!< Secret */
00717    char md5secret[256];            /*!< MD5Secret */
00718    struct sip_auth *next;          /*!< Next auth structure in list */
00719 };
00720 
00721 /*--- Various flags for the flags field in the pvt structure */
00722 #define SIP_ALREADYGONE    (1 << 0) /*!< Whether or not we've already been destroyed by our peer */
00723 #define SIP_NEEDDESTROY    (1 << 1) /*!< if we need to be destroyed by the monitor thread */
00724 #define SIP_NOVIDEO     (1 << 2) /*!< Didn't get video in invite, don't offer */
00725 #define SIP_RINGING     (1 << 3) /*!< Have sent 180 ringing */
00726 #define SIP_PROGRESS_SENT  (1 << 4) /*!< Have sent 183 message progress */
00727 #define SIP_NEEDREINVITE   (1 << 5) /*!< Do we need to send another reinvite? */
00728 #define SIP_PENDINGBYE     (1 << 6) /*!< Need to send bye after we ack? */
00729 #define SIP_GOTREFER    (1 << 7) /*!< Got a refer? */
00730 #define SIP_PROMISCREDIR   (1 << 8) /*!< Promiscuous redirection */
00731 #define SIP_TRUSTRPID      (1 << 9) /*!< Trust RPID headers? */
00732 #define SIP_USEREQPHONE    (1 << 10)   /*!< Add user=phone to numeric URI. Default off */
00733 #define SIP_REALTIME    (1 << 11)   /*!< Flag for realtime users */
00734 #define SIP_USECLIENTCODE  (1 << 12)   /*!< Trust X-ClientCode info message */
00735 #define SIP_OUTGOING    (1 << 13)   /*!< Direction of the last transaction in this dialog */
00736 #define SIP_FREE_BIT    (1 << 14)   /*!< ---- */
00737 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 15)   /*!< Do not hangup at first ast_hangup */
00738 #define SIP_DTMF     (3 <<