Codename Pineapple

Home page | Mailing list | Docs

Last updated: Sat Feb 3 05:00:37 2007

Asterisk developer's documentation :: Codename Pineapple


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