![]() |
Home page |
Mailing list |
Docs
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 */ 00727 #define SIP_NAT_RFC3581 (1 << 18) /*!< NAT RFC3581 */ 00728 #define SIP_NAT_ROUTE (2 << 18) /*!< NAT Only ROUTE */ 00729 #define SIP_NAT_ALWAYS (3 << 18) /*!< NAT Both ROUTE and RFC3581 */ 00730 /* re-INVITE related settings */ 00731 #define SIP_REINVITE (7 << 20) /*!< three bits used */ 00732 #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */ 00733 #define SIP_CAN_REINVITE_NAT (2 << 20) /*!< allow media reinvite when new peer is behind NAT */ 00734 #define SIP_REINVITE_UPDATE (4 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */ 00735 /* "insecure" settings */ 00736 #define SIP_INSECURE_PORT (1 << 23) /*!< don't require matching port for incoming requests */ 00737 #define SIP_INSECURE_INVITE (1 << 24) /*!< don't require authentication for incoming INVITEs */ 00738 /* Sending PROGRESS in-band settings */ 00739 #define SIP_PROG_INBAND (3 << 25) /*!< three settings, uses two bits */ 00740 #define SIP_PROG_INBAND_NEVER (0 << 25) 00741 #define SIP_PROG_INBAND_NO (1 << 25) 00742 #define SIP_PROG_INBAND_YES (2 << 25) 00743 #define SIP_NO_HISTORY (1 << 27) /*!< Suppress recording request/response history */ 00744 #define SIP_CALL_LIMIT (1 << 28) /*!< Call limit enforced for this call */ 00745 #define SIP_SENDRPID (1 << 29) /*!< Remote Party-ID Support */ 00746 #define SIP_INC_COUNT (1 << 30) /*!< Did this connection increment the counter of in-use calls? */ 00747 #define SIP_G726_NONSTANDARD (1 << 31) /*!< Use non-standard packing for G726-32 data */ 00748 00749 #define SIP_FLAGS_TO_COPY \ 00750 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \ 00751 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \ 00752 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE) 00753 00754 /*--- a new page of flags (for flags[1] */ 00755 /* realtime flags */ 00756 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) 00757 #define SIP_PAGE2_RTUPDATE (1 << 1) 00758 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) 00759 #define SIP_PAGE2_RT_FROMCONTACT (1 << 4) 00760 #define SIP_PAGE2_RTSAVE_SYSNAME (1 << 5) 00761 /* Space for addition of other realtime flags in the future */ 00762 #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 10) 00763 #define SIP_PAGE2_DEBUG (3 << 11) 00764 #define SIP_PAGE2_DEBUG_CONFIG (1 << 11) 00765 #define SIP_PAGE2_DEBUG_CONSOLE (1 << 12) 00766 #define SIP_PAGE2_DYNAMIC (1 << 13) /*!< Dynamic Peers register with Asterisk */ 00767 #define SIP_PAGE2_SELFDESTRUCT (1 << 14) /*!< Automatic peers need to destruct themselves */ 00768 #define SIP_PAGE2_VIDEOSUPPORT (1 << 15) 00769 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16) /*!< Allow subscriptions from this peer? */ 00770 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17) /*!< Allow overlap dialing ? */ 00771 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18) /*!< Only issue MWI notification if subscribed to */ 00772 #define SIP_PAGE2_INC_RINGING (1 << 19) /*!< Did this connection increment the counter of in-use calls? */ 00773 #define SIP_PAGE2_T38SUPPORT (7 << 20) /*!< T38 Fax Passthrough Support */ 00774 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20) /*!< 20: T38 Fax Passthrough Support */ 00775 #define SIP_PAGE2_T38SUPPORT_RTP (2 << 20) /*!< 21: T38 Fax Passthrough Support (not implemented) */ 00776 #define SIP_PAGE2_T38SUPPORT_TCP (4 << 20) /*!< 22: T38 Fax Passthrough Support (not implemented) */ 00777 #define SIP_PAGE2_CALL_ONHOLD (3 << 23) /*!< Call states */ 00778 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (1 << 23) /*!< 23: One directional hold */ 00779 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (1 << 24) /*!< 24: Inactive */ 00780 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25) /*!< 25: ???? */ 00781 #define SIP_PAGE2_BUGGY_MWI (1 << 26) /*!< 26: Buggy CISCO MWI fix */ 00782 00783 #define SIP_PAGE2_FLAGS_TO_COPY \ 00784 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \ 00785 SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI) 00786 00787 /* SIP packet flags */ 00788 #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */ 00789 #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */ 00790 #define SIP_PKT_IGNORE (1 << 2) /*!< This is a re-transmit, ignore it */ 00791 00792 /* T.38 set of flags */ 00793 #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/ 00794 #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/ 00795 #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/ 00796 /* Rate management */ 00797 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3) 00798 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */ 00799 /* UDP Error correction */ 00800 #define T38FAX_UDP_EC_NONE (0 << 4) /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/ 00801 #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */ 00802 #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */ 00803 /* T38 Spec version */ 00804 #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */ 00805 #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */ 00806 #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */ 00807 /* Maximum Fax Rate */ 00808 #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */ 00809 #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */ 00810 #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */ 00811 #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */ 00812 #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */ 00813 #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */ 00814 00815 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */ 00816 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600; 00817 00818 #define sipdebug ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG) 00819 #define sipdebug_config ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG) 00820 #define sipdebug_console ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE) 00821 00822 /*! \brief T38 States for a call */ 00823 enum t38state { 00824 T38_DISABLED = 0, /*!< Not enabled */ 00825 T38_LOCAL_DIRECT, /*!< Offered from local */ 00826 T38_LOCAL_REINVITE, /*!< Offered from local - REINVITE */ 00827 T38_PEER_DIRECT, /*!< Offered from peer */ 00828 T38_PEER_REINVITE, /*!< Offered from peer - REINVITE */ 00829 T38_ENABLED /*!< Negotiated (enabled) */ 00830 }; 00831 00832 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */ 00833 struct t38properties { 00834 struct ast_flags t38support; /*!< Flag for udptl, rtp or tcp support for this session */ 00835 int capability; /*!< Our T38 capability */ 00836 int peercapability; /*!< Peers T38 capability */ 00837 int jointcapability; /*!< Supported T38 capability at both ends */ 00838 enum t38state state; /*!< T.38 state */ 00839 }; 00840 00841 /*! \brief Parameters to know status of transfer */ 00842 enum referstatus { 00843 REFER_IDLE, /*!< No REFER is in progress */ 00844 REFER_SENT, /*!< Sent REFER to transferee */ 00845 REFER_RECEIVED, /*!< Received REFER from transferrer */ 00846 REFER_CONFIRMED, /*!< Refer confirmed with a 100 TRYING */ 00847 REFER_ACCEPTED, /*!< Accepted by transferee */ 00848 REFER_RINGING, /*!< Target Ringing */ 00849 REFER_200OK, /*!< Answered by transfer target */ 00850 REFER_FAILED, /*!< REFER declined - go on */ 00851 REFER_NOAUTH /*!< We had no auth for REFER */ 00852 }; 00853 00854 static const struct c_referstatusstring { 00855 enum referstatus status; 00856 char *text; 00857 } referstatusstrings[] = { 00858 { REFER_IDLE, "<none>" }, 00859 { REFER_SENT, "Request sent" }, 00860 { REFER_RECEIVED, "Request received" }, 00861 { REFER_ACCEPTED, "Accepted" }, 00862 { REFER_RINGING, "Target ringing" }, 00863 { REFER_200OK, "Done" }, 00864 { REFER_FAILED, "Failed" }, 00865 { REFER_NOAUTH, "Failed - auth failure" } 00866 } ; 00867 00868 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed */ 00869 /* OEJ: Should be moved to string fields */ 00870 struct sip_refer { 00871 char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */ 00872 char refer_to_domain[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO domain */ 00873 char refer_to_urioption[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO uri options */ 00874 char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */ 00875 char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */ 00876 char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */ 00877 char refer_contact[AST_MAX_EXTENSION]; /*!< Place to store Contact info from a REFER extension */ 00878 char replaces_callid[BUFSIZ]; /*!< Replace info: callid */ 00879 char replaces_callid_totag[BUFSIZ/2]; /*!< Replace info: to-tag */ 00880 char replaces_callid_fromtag[BUFSIZ/2]; /*!< Replace info: from-tag */ 00881 struct sip_pvt *refer_call; /*!< Call we are referring */ 00882 int attendedtransfer; /*!< Attended or blind transfer? */ 00883 int localtransfer; /*!< Transfer to local domain? */ 00884 enum referstatus status; /*!< REFER status */ 00885 }; 00886 00887 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe */ 00888 struct sip_pvt { 00889 ast_mutex_t pvt_lock; /*!< Dialog private lock */ 00890 enum invitestates invitestate; /*!< Track state of SIP_INVITEs */ 00891 int method; /*!< SIP method that opened this dialog */ 00892 AST_DECLARE_STRING_FIELDS( 00893 AST_STRING_FIELD(callid); /*!< Global CallID */ 00894 AST_STRING_FIELD(randdata); /*!< Random data */ 00895 AST_STRING_FIELD(accountcode); /*!< Account code */ 00896 AST_STRING_FIELD(realm); /*!< Authorization realm */ 00897 AST_STRING_FIELD(nonce); /*!< Authorization nonce */ 00898 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */ 00899 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */ 00900 AST_STRING_FIELD(domain); /*!< Authorization domain */ 00901 AST_STRING_FIELD(from); /*!< The From: header */ 00902 AST_STRING_FIELD(useragent); /*!< User agent in SIP request */ 00903 AST_STRING_FIELD(exten); /*!< Extension where to start */ 00904 AST_STRING_FIELD(context); /*!< Context for this call */ 00905 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */ 00906 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */ 00907 AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */ 00908 AST_STRING_FIELD(fromuser); /*!< User to show in the user field */ 00909 AST_STRING_FIELD(fromname); /*!< Name to show in the user field */ 00910 AST_STRING_FIELD(tohost); /*!< Host we should put in the "to" field */ 00911 AST_STRING_FIELD(language); /*!< Default language for this call */ 00912 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */ 00913 AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */ 00914 AST_STRING_FIELD(rdnis); /*!< Referring DNIS */ 00915 AST_STRING_FIELD(redircause); /*!< Referring cause */ 00916 AST_STRING_FIELD(theirtag); /*!< Their tag */ 00917 AST_STRING_FIELD(username); /*!< [user] name */ 00918 AST_STRING_FIELD(peername); /*!< [peer] name, not set if [user] */ 00919 AST_STRING_FIELD(authname); /*!< Who we use for authentication */ 00920 AST_STRING_FIELD(uri); /*!< Original requested URI */ 00921 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */ 00922 AST_STRING_FIELD(peersecret); /*!< Password */ 00923 AST_STRING_FIELD(peermd5secret); 00924 AST_STRING_FIELD(cid_num); /*!< Caller*ID number */ 00925 AST_STRING_FIELD(cid_name); /*!< Caller*ID name */ 00926 AST_STRING_FIELD(via); /*!< Via: header */ 00927 AST_STRING_FIELD(fullcontact); /*!< The Contact: that the UA registers with us */ 00928 /* we only store the part in <brackets> in this field. */ 00929 AST_STRING_FIELD(our_contact); /*!< Our contact header */ 00930 AST_STRING_FIELD(rpid); /*!< Our RPID header */ 00931 AST_STRING_FIELD(rpid_from); /*!< Our RPID From header */ 00932 ); 00933 unsigned int ocseq; /*!< Current outgoing seqno */ 00934 unsigned int icseq; /*!< Current incoming seqno */ 00935 ast_group_t callgroup; /*!< Call group */ 00936 ast_group_t pickupgroup; /*!< Pickup group */ 00937 int lastinvite; /*!< Last Cseq of invite */ 00938 struct ast_flags flags[2]; /*!< SIP_ flags */ 00939 int timer_t1; /*!< SIP timer T1, ms rtt */ 00940 unsigned int sipoptions; /*!< Supported SIP options on the other end */ 00941 struct ast_codec_pref prefs; /*!< codec prefs */ 00942 int capability; /*!< Special capability (codec) */ 00943 int jointcapability; /*!< Supported capability at both ends (codecs) */ 00944 int peercapability; /*!< Supported peer capability */ 00945 int prefcodec; /*!< Preferred codec (outbound only) */ 00946 int noncodeccapability; /*!< DTMF RFC2833 telephony-event */ 00947 int jointnoncodeccapability; /*!< Joint Non codec capability */ 00948 int redircodecs; /*!< Redirect codecs */ 00949 int maxcallbitrate; /*!< Maximum Call Bitrate for Video Calls */ 00950 struct t38properties t38; /*!< T38 settings */ 00951 struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */ 00952 struct ast_udptl *udptl; /*!< T.38 UDPTL session */ 00953 int callingpres; /*!< Calling presentation */ 00954 int authtries; /*!< Times we've tried to authenticate */ 00955 int expiry; /*!< How long we take to expire */ 00956 long branch; /*!< The branch identifier of this session */ 00957 char tag[11]; /*!< Our tag for this session */ 00958 int sessionid; /*!< SDP Session ID */ 00959 int sessionversion; /*!< SDP Session Version */ 00960 struct sockaddr_in sa; /*!< Our peer */ 00961 struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */ 00962 struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */ 00963 time_t lastrtprx; /*!< Last RTP received */ 00964 time_t lastrtptx; /*!< Last RTP sent */ 00965 int rtptimeout; /*!< RTP timeout time */ 00966 struct sockaddr_in recv; /*!< Received as */ 00967 struct in_addr ourip; /*!< Our IP */ 00968 struct ast_channel *owner; /*!< Who owns us (if we have an owner) */ 00969 struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */ 00970 int route_persistant; /*!< Is this the "real" route? */ 00971 struct sip_auth *peerauth; /*!< Realm authentication */ 00972 int noncecount; /*!< Nonce-count */ 00973 char lastmsg[256]; /*!< Last Message sent/received */ 00974 int amaflags; /*!< AMA Flags */ 00975 int pendinginvite; /*!< Any pending invite ? (seqno of this) */ 00976 struct sip_request initreq; /*!< Latest request that opened a new transaction 00977 within this dialog. 00978 NOT the request that opened the dialog 00979 */ 00980 00981 int initid; /*!< Auto-congest ID if appropriate (scheduler) */ 00982 int autokillid; /*!< Auto-kill ID (scheduler) */ 00983 enum transfermodes allowtransfer; /*!< REFER: restriction scheme */ 00984 struct sip_refer *refer; /*!< REFER: SIP transfer data structure */ 00985 enum subscriptiontype subscribed; /*!< SUBSCRIBE: Is this dialog a subscription? */ 00986 int stateid; /*!< SUBSCRIBE: ID for devicestate subscriptions */ 00987 int laststate; /*!< SUBSCRIBE: Last known extension state */ 00988 int dialogver; /*!< SUBSCRIBE: Version for subscription dialog-info */ 00989 00990 struct ast_dsp *vad; /*!< Inband DTMF Detection dsp */ 00991 00992 struct sip_peer *relatedpeer; /*!< If this dialog is related to a peer, which one 00993 Used in peerpoke, mwi subscriptions */ 00994 struct sip_registry *registry; /*!< If this is a REGISTER dialog, to which registry */ 00995 struct ast_rtp *rtp; /*!< RTP Session */ 00996 struct ast_rtp *vrtp; /*!< Video RTP session */ 00997 struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */ 00998 struct sip_history_head *history; /*!< History of this SIP dialog */ 00999 struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */ 01000 struct sip_pvt *next; /*!< Next dialog in chain */ 01001 struct sip_invite_param *options; /*!< Options for INVITE */ 01002 int autoframing; /*!< The number of Asters we group in a Pyroflax 01003 before strolling to the Grokyzpå 01004 (A bit unsure of this, please correct if 01005 you know more) */ 01006 }; 01007 01008 static struct sip_pvt *dialoglist = NULL; 01009 01010 /*! \brief Protect the SIP dialog list (of sip_pvt's) */ 01011 AST_MUTEX_DEFINE_STATIC(dialoglock); 01012 01013 /*! \brief hide the way the list is locked/unlocked */ 01014 static void dialoglist_lock(void) 01015 { 01016 ast_mutex_lock(&dialoglock); 01017 } 01018 01019 static void dialoglist_unlock(void) 01020 { 01021 ast_mutex_unlock(&dialoglock); 01022 } 01023 01024 #define FLAG_RESPONSE (1 << 0) 01025 #define FLAG_FATAL (1 << 1) 01026 01027 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */ 01028 struct sip_pkt { 01029 struct sip_pkt *next; /*!< Next packet in linked list */ 01030 int retrans; /*!< Retransmission number */ 01031 int method; /*!< SIP method for this packet */ 01032 int seqno; /*!< Sequence number */ 01033 unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */ 01034 struct sip_pvt *owner; /*!< Owner AST call */ 01035 int retransid; /*!< Retransmission ID */ 01036 int timer_a; /*!< SIP timer A, retransmission timer */ 01037 int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */ 01038 int packetlen; /*!< Length of packet */ 01039 char data[0]; 01040 }; 01041 01042 /*! \brief Structure for SIP user data. User's place calls to us */ 01043 struct sip_user { 01044 /* Users who can access various contexts */ 01045 ASTOBJ_COMPONENTS(struct sip_user); 01046 char secret[80]; /*!< Password */ 01047 char md5secret[80]; /*!< Password in md5 */ 01048 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */ 01049 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */ 01050 char cid_num[80]; /*!< Caller ID num */ 01051 char cid_name[80]; /*!< Caller ID name */ 01052 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */ 01053 char language[MAX_LANGUAGE]; /*!< Default language for this user */ 01054 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */ 01055 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */ 01056 char useragent[256]; /*!< User agent in SIP request */ 01057 struct ast_codec_pref prefs; /*!< codec prefs */ 01058 ast_group_t callgroup; /*!< Call group */ 01059 ast_group_t pickupgroup; /*!< Pickup Group */ 01060 unsigned int sipoptions; /*!< Supported SIP options */ 01061 struct ast_flags flags[2]; /*!< SIP_ flags */ 01062 int amaflags; /*!< AMA flags for billing */ 01063 int callingpres; /*!< Calling id presentation */ 01064 int capability; /*!< Codec capability */ 01065 int inUse; /*!< Number of calls in use */ 01066 int call_limit; /*!< Limit of concurrent calls */ 01067 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */ 01068 struct ast_ha *ha; /*!< ACL setting */ 01069 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */ 01070 int maxcallbitrate; /*!< Maximum Bitrate for a video call */ 01071 int autoframing; 01072 }; 01073 01074 /*! \brief Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */ 01075 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */ 01076 struct sip_peer { 01077 ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */ 01078 /*!< peer->name is the unique name of this object */ 01079 char secret[80]; /*!< Password */ 01080 char md5secret[80]; /*!< Password in MD5 */ 01081 struct sip_auth *auth; /*!< Realm authentication list */ 01082 char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */ 01083 char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */ 01084 char username[80]; /*!< Temporary username until registration */ 01085 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */ 01086 int amaflags; /*!< AMA Flags (for billing) */ 01087 char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */ 01088 char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */ 01089 char fromuser[80]; /*!< From: user when calling this peer */ 01090 char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */ 01091 char fullcontact[256]; /*!< Contact registered with us (not in sip.conf) */ 01092 char cid_num[80]; /*!< Caller ID num */ 01093 char cid_name[80]; /*!< Caller ID name */ 01094 int callingpres; /*!< Calling id presentation */ 01095 int inUse; /*!< Number of calls in use */ 01096 int inRinging; /*!< Number of calls ringing */ 01097 int onHold; /*!< Peer has someone on hold */ 01098 int call_limit; /*!< Limit of concurrent calls */ 01099 int busy_limit; /*!< Limit where we signal busy */ 01100 enum transfermodes allowtransfer; /*! SIP Refer restriction scheme */ 01101 char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/ 01102 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */ 01103 char language[MAX_LANGUAGE]; /*!< Default language for prompts */ 01104 char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */ 01105 char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */ 01106 char useragent[256]; /*!< User agent in SIP request (saved from registration) */ 01107 struct ast_codec_pref prefs; /*!< codec prefs */ 01108 int lastmsgssent; 01109 time_t lastmsgcheck; /*!< Last time we checked for MWI */ 01110 unsigned int sipoptions; /*!< Supported SIP options */ 01111 struct ast_flags flags[2]; /*!< SIP_ flags */ 01112 int expire; /*!< When to expire this peer registration */ 01113 int capability; /*!< Codec capability */ 01114 int rtptimeout; /*!< RTP timeout */ 01115 int rtpholdtimeout; /*!< RTP Hold Timeout */ 01116 int rtpkeepalive; /*!< Send RTP packets for keepalive */ 01117 ast_group_t callgroup; /*!< Call group */ 01118 ast_group_t pickupgroup; /*!< Pickup group */ 01119 struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */ 01120 struct sockaddr_in addr; /*!< IP address of peer */ 01121 int maxcallbitrate; /*!< Maximum Bitrate for a video call */ 01122 01123 /* Qualification */ 01124 struct sip_pvt *call; /*!< Call pointer */ 01125 int pokeexpire; /*!< When to expire poke (qualify= checking) */ 01126 int lastms; /*!< How long last response took (in ms), or -1 for no response */ 01127 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */ 01128 struct timeval ps; /*!< Time for sending SIP OPTION in sip_pke_peer() */ 01129 struct sockaddr_in defaddr; /*!< Default IP address, used until registration */ 01130 struct ast_ha *ha; /*!< Access control list */ 01131 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */ 01132 struct sip_pvt *mwipvt; /*!< Subscription for MWI */ 01133 int autoframing; 01134 }; 01135 01136 01137 01138 /*! \brief Registrations with other SIP proxies */ 01139 struct sip_registry { 01140 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1); 01141 AST_DECLARE_STRING_FIELDS( 01142 AST_STRING_FIELD(callid); /*!< Global Call-ID */ 01143 AST_STRING_FIELD(realm); /*!< Authorization realm */ 01144 AST_STRING_FIELD(nonce); /*!< Authorization nonce */ 01145 AST_STRING_FIELD(opaque); /*!< Opaque nonsense */ 01146 AST_STRING_FIELD(qop); /*!< Quality of Protection, since SIP wasn't complicated enough yet. */ 01147 AST_STRING_FIELD(domain); /*!< Authorization domain */ 01148 AST_STRING_FIELD(username); /*!< Who we are registering as */ 01149 AST_STRING_FIELD(authuser); /*!< Who we *authenticate* as */ 01150 AST_STRING_FIELD(hostname); /*!< Domain or host we register to */ 01151 AST_STRING_FIELD(secret); /*!< Password in clear text */ 01152 AST_STRING_FIELD(md5secret); /*!< Password in md5 */ 01153 AST_STRING_FIELD(callback); /*!< Contact extension */ 01154 AST_STRING_FIELD(random); 01155 ); 01156 int portno; /*!< Optional port override */ 01157 int expire; /*!< Sched ID of expiration */ 01158 int expiry; /*!< Value to use for the Expires header */ 01159 int regattempts; /*!< Number of attempts (since the last success) */ 01160 int timeout; /*!< sched id of sip_reg_timeout */ 01161 int refresh; /*!< How often to refresh */ 01162 struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */ 01163 enum sipregistrystate regstate; /*!< Registration state (see above) */ 01164 time_t regtime; /*!< Last successful registration time */ 01165 int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */ 01166 unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */ 01167 struct sockaddr_in us; /*!< Who the server thinks we are */ 01168 int noncecount; /*!< Nonce-count */ 01169 char lastmsg[256]; /*!< Last Message sent/received */ 01170 }; 01171 01172 /* --- Linked lists of various objects --------*/ 01173 01174 /*! \brief The user list: Users and friends */ 01175 static struct ast_user_list { 01176 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user); 01177 } userl; 01178 01179 /*! \brief The peer list: Peers and Friends */ 01180 static struct ast_peer_list { 01181 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer); 01182 } peerl; 01183 01184 /*! \brief The register list: Other SIP proxies we register with and place calls to */ 01185 static struct ast_register_list { 01186 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry); 01187 int recheck; 01188 } regl; 01189 01190 static int temp_pvt_init(void *); 01191 static void temp_pvt_cleanup(void *); 01192 01193 /*! \brief A per-thread temporary pvt structure */ 01194 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup); 01195 01196 /*! \todo Move the sip_auth list to AST_LIST */ 01197 static struct sip_auth *authl = NULL; /*!< Authentication list for realm authentication */ 01198 01199 01200 /* --- Sockets and networking --------------*/ 01201 static int sipsock = -1; /*!< Main socket for SIP network communication */ 01202 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */ 01203 static struct sockaddr_in externip; /*!< External IP address if we are behind NAT */ 01204 static char externhost[MAXHOSTNAMELEN]; /*!< External host name (possibly with dynamic DNS and DHCP */ 01205 static time_t externexpire = 0; /*!< Expiration counter for re-resolving external host name in dynamic DNS */ 01206 static int externrefresh = 10; 01207 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */ 01208 static struct in_addr __ourip; 01209 static struct sockaddr_in outboundproxyip; 01210 static int ourport; 01211 static struct sockaddr_in debugaddr; 01212 01213 static struct ast_config *notify_types; /*!< The list of manual NOTIFY types we know how to send */ 01214 01215 /*---------------------------- Forward declarations of functions in chan_sip.c */ 01216 /*! \note This is added to help splitting up chan_sip.c into several files 01217 in coming releases */ 01218 01219 /*--- PBX interface functions */ 01220 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause); 01221 static int sip_devicestate(void *data); 01222 static int sip_sendtext(struct ast_channel *ast, const char *text); 01223 static int sip_call(struct ast_channel *ast, char *dest, int timeout); 01224 static int sip_hangup(struct ast_channel *ast); 01225 static int sip_answer(struct ast_channel *ast); 01226 static struct ast_frame *sip_read(struct ast_channel *ast); 01227 static int sip_write(struct ast_channel *ast, struct ast_frame *frame); 01228 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen); 01229 static int sip_transfer(struct ast_channel *ast, const char *dest); 01230 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan); 01231 static int sip_senddigit_begin(struct ast_channel *ast, char digit); 01232 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration); 01233 01234 /*--- Transmitting responses and requests */ 01235 static int sipsock_read(int *id, int fd, short events, void *ignore); 01236 static int __sip_xmit(struct sip_pvt *p, char *data, int len); 01237 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod); 01238 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable); 01239 static int retrans_pkt(void *data); 01240 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req); 01241 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg); 01242 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req); 01243 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req); 01244 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req); 01245 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable); 01246 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported); 01247 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale); 01248 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable); 01249 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable); 01250 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch); 01251 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch); 01252 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init); 01253 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version); 01254 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration); 01255 static int transmit_info_with_vidupdate(struct sip_pvt *p); 01256 static int transmit_message_with_text(struct sip_pvt *p, const char *text); 01257 static int transmit_refer(struct sip_pvt *p, const char *dest); 01258 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten); 01259 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate); 01260 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader); 01261 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno); 01262 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno); 01263 static void copy_request(struct sip_request *dst, const struct sip_request *src); 01264 static void receive_message(struct sip_pvt *p, struct sip_request *req); 01265 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req); 01266 static int sip_send_mwi_to_peer(struct sip_peer *peer); 01267 static int does_peer_need_mwi(struct sip_peer *peer); 01268 01269 /*--- Dialog management */ 01270 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin, 01271 int useglobal_nat, const int intended_method); 01272 static int __sip_autodestruct(void *data); 01273 static void sip_scheddestroy(struct sip_pvt *p, int ms); 01274 static void sip_cancel_destroy(struct sip_pvt *p); 01275 static void sip_destroy(struct sip_pvt *p); 01276 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist); 01277 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod); 01278 static void __sip_pretend_ack(struct sip_pvt *p); 01279 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod); 01280 static int auto_congest(void *nothing); 01281 static int update_call_counter(struct sip_pvt *fup, int event); 01282 static int hangup_sip2cause(int cause); 01283 static const char *hangup_cause2sip(int cause); 01284 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method); 01285 static void free_old_route(struct sip_route *route); 01286 static void list_route(struct sip_route *route); 01287 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards); 01288 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin, 01289 struct sip_request *req, char *uri); 01290 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag); 01291 static void check_pendings(struct sip_pvt *p); 01292 static void *sip_park_thread(void *stuff); 01293 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno); 01294 static int sip_sipredirect(struct sip_pvt *p, const char *dest); 01295 01296 /*--- Codec handling / SDP */ 01297 static void try_suggested_sip_codec(struct sip_pvt *p); 01298 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name); 01299 static const char *get_sdp(struct sip_request *req, const char *name); 01300 static int find_sdp(struct sip_request *req); 01301 static int process_sdp(struct sip_pvt *p, struct sip_request *req); 01302 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate, 01303 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size, 01304 int debug, int *min_packet_size); 01305 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate, 01306 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size, 01307 int debug); 01308 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p); 01309 static void do_setnat(struct sip_pvt *p, int natflags); 01310 01311 /*--- Authentication stuff */ 01312 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len); 01313 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len); 01314 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username, 01315 const char *secret, const char *md5secret, int sipmethod, 01316 char *uri, enum xmittype reliable, int ignore); 01317 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req, 01318 int sipmethod, char *uri, enum xmittype reliable, 01319 struct sockaddr_in *sin, struct sip_peer **authpeer); 01320 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin); 01321 01322 /*--- Domain handling */ 01323 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */ 01324 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context); 01325 static void clear_sip_domains(void); 01326 01327 /*--- SIP realm authentication */ 01328 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); 01329 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */ 01330 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm); 01331 01332 /*--- Misc functions */ 01333 static int sip_do_reload(enum channelreloadreason reason); 01334 static int reload_config(enum channelreloadreason reason); 01335 static int expire_register(void *data); 01336 static void *do_monitor(void *data); 01337 static int restart_monitor(void); 01338 static int sip_send_mwi_to_peer(struct sip_peer *peer); 01339 static void sip_destroy(struct sip_pvt *p); 01340 static int sip_addrcmp(char *name, struct sockaddr_in *sin); /* Support for peer matching */ 01341 static int sip_refer_allocate(struct sip_pvt *p); 01342 static void ast_quiet_chan(struct ast_channel *chan); 01343 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target); 01344 01345 /*--- Device monitoring and Device/extension state handling */ 01346 static int cb_extensionstate(char *context, char* exten, int state, void *data); 01347 static int sip_devicestate(void *data); 01348 static int sip_poke_noanswer(void *data); 01349 static int sip_poke_peer(struct sip_peer *peer); 01350 static void sip_poke_all_peers(void); 01351 static void sip_peer_hold(struct sip_pvt *p, int hold); 01352 01353 /*--- Applications, functions, CLI and manager command helpers */ 01354 static const char *sip_nat_mode(const struct sip_pvt *p); 01355 static int sip_show_inuse(int fd, int argc, char *argv[]); 01356 static char *transfermode2str(enum transfermodes mode) attribute_const; 01357 static char *nat2str(int nat) attribute_const; 01358 static int peer_status(struct sip_peer *peer, char *status, int statuslen); 01359 static int sip_show_users(int fd, int argc, char *argv[]); 01360 static int _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]); 01361 static int sip_show_peers(int fd, int argc, char *argv[]); 01362 static int sip_show_objects(int fd, int argc, char *argv[]); 01363 static void print_group(int fd, ast_group_t group, int crlf); 01364 static const char *dtmfmode2str(int mode) attribute_const; 01365 static const char *insecure2str(int port, int invite) attribute_const; 01366 static void cleanup_stale_contexts(char *new, char *old); 01367 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref); 01368 static const char *domain_mode_to_text(const enum domain_mode mode); 01369 static int sip_show_domains(int fd, int argc, char *argv[]); 01370 static int _sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]); 01371 static int sip_show_peer(int fd, int argc, char *argv[]); 01372 static int sip_show_user(int fd, int argc, char *argv[]); 01373 static int sip_show_registry(int fd, int argc, char *argv[]); 01374 static int sip_show_settings(int fd, int argc, char *argv[]); 01375 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure; 01376 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype); 01377 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions); 01378 static int sip_show_channels(int fd, int argc, char *argv[]); 01379 static int sip_show_subscriptions(int fd, int argc, char *argv[]); 01380 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions); 01381 static char *complete_sipch(const char *line, const char *word, int pos, int state); 01382 static char *complete_sip_peer(const char *word, int state, int flags2); 01383 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state); 01384 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state); 01385 static char *complete_sip_user(const char *word, int state, int flags2); 01386 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state); 01387 static char *complete_sipnotify(const char *line, const char *word, int pos, int state); 01388 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state); 01389 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state); 01390 static int sip_show_channel(int fd, int argc, char *argv[]); 01391 static int sip_show_history(int fd, int argc, char *argv[]); 01392 static int sip_do_debug_ip(int fd, int argc, char *argv[]); 01393 static int sip_do_debug_peer(int fd, int argc, char *argv[]); 01394 static int sip_do_debug(int fd, int argc, char *argv[]); 01395 static int sip_no_debug(int fd, int argc, char *argv[]); 01396 static int sip_notify(int fd, int argc, char *argv[]); 01397 static int sip_do_history(int fd, int argc, char *argv[]); 01398 static int sip_no_history(int fd, int argc, char *argv[]); 01399 static int sip_dtmfmode(struct ast_channel *chan, void *data); 01400 static int sip_addheader(struct ast_channel *chan, void *data); 01401 static int sip_do_reload(enum channelreloadreason reason); 01402 static int sip_reload(int fd, int argc, char *argv[]); 01403 01404 /*--- Debugging 01405 Functions for enabling debug per IP or fully, or enabling history logging for 01406 a SIP dialog 01407 */ 01408 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */ 01409 static inline int sip_debug_test_addr(const struct sockaddr_in *addr); 01410 static inline int sip_debug_test_pvt(struct sip_pvt *p); 01411 static void append_history_full(struct sip_pvt *p, const char *fmt, ...); 01412 static void sip_dump_history(struct sip_pvt *dialog); 01413 01414 /*--- Device object handling */ 01415 static struct sip_peer *temp_peer(const char *name); 01416 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime); 01417 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime); 01418 static int update_call_counter(struct sip_pvt *fup, int event); 01419 static void sip_destroy_peer(struct sip_peer *peer); 01420 static void sip_destroy_user(struct sip_user *user); 01421 static int sip_poke_peer(struct sip_peer *peer); 01422 static void set_peer_defaults(struct sip_peer *peer); 01423 static struct sip_peer *temp_peer(const char *name); 01424 static void register_peer_exten(struct sip_peer *peer, int onoff); 01425 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime); 01426 static struct sip_user *find_user(const char *name, int realtime); 01427 static int sip_poke_peer_s(void *data); 01428 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req); 01429 static void reg_source_db(struct sip_peer *peer); 01430 static void destroy_association(struct sip_peer *peer); 01431 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v); 01432 01433 /* Realtime device support */ 01434 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey); 01435 static struct sip_user *realtime_user(const char *username); 01436 static void update_peer(struct sip_peer *p, int expiry); 01437 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin); 01438 static int sip_prune_realtime(int fd, int argc, char *argv[]); 01439 01440 /*--- Internal UA client handling (outbound registrations) */ 01441 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us); 01442 static void sip_registry_destroy(struct sip_registry *reg); 01443 static int sip_register(char *value, int lineno); 01444 static char *regstate2str(enum sipregistrystate regstate) attribute_const; 01445 static int sip_reregister(void *data); 01446 static int __sip_do_register(struct sip_registry *r); 01447 static int sip_reg_timeout(void *data); 01448 static void sip_send_all_registers(void); 01449 01450 /*--- Parsing SIP requests and responses */ 01451 static void append_date(struct sip_request *req); /* Append date to SIP packet */ 01452 static int determine_firstline_parts(struct sip_request *req); 01453 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype); 01454 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize); 01455 static int find_sip_method(const char *msg); 01456 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported); 01457 static void parse_request(struct sip_request *req); 01458 static const char *get_header(const struct sip_request *req, const char *name); 01459 static const char *referstatus2str(enum referstatus rstatus) attribute_pure; 01460 static int method_match(enum sipmethod id, const char *name); 01461 static void parse_copy(struct sip_request *dst, const struct sip_request *src); 01462 static char *get_in_brackets(char *tmp); 01463 static const char *find_alias(const char *name, const char *_default); 01464 static const char *__get_header(const struct sip_request *req, const char *name, int *start); 01465 static int lws2sws(char *msgbuf, int len); 01466 static void extract_uri(struct sip_pvt *p, struct sip_request *req); 01467 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req); 01468 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq); 01469 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req); 01470 static int set_address_from_contact(struct sip_pvt *pvt); 01471 static void check_via(struct sip_pvt *p, struct sip_request *req); 01472 static char *get_calleridname(const char *input, char *output, size_t outputsize); 01473 static int get_rpid_num(const char *input, char *output, int maxlen); 01474 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq); 01475 static int get_destination(struct sip_pvt *p, struct sip_request *oreq); 01476 static int get_msg_text(char *buf, int len, struct sip_request *req); 01477 static void free_old_route(struct sip_route *route); 01478 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout); 01479 01480 /*--- Constructing requests and responses */ 01481 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req); 01482 static int init_req(struct sip_request *req, int sipmethod, const char *recip); 01483 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch); 01484 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod); 01485 static int init_resp(struct sip_request *resp, const char *msg); 01486 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req); 01487 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p); 01488 static void build_via(struct sip_pvt *p); 01489 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer); 01490 static int create_addr(struct sip_pvt *dialog, const char *opeer); 01491 static char *generate_random_string(char *buf, size_t size); 01492 static void build_callid_pvt(struct sip_pvt *pvt); 01493 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain); 01494 static void make_our_tag(char *tagbuf, size_t len); 01495 static int add_header(struct sip_request *req, const char *var, const char *value); 01496 static int add_header_contentLength(struct sip_request *req, int len); 01497 static int add_line(struct sip_request *req, const char *line); 01498 static int add_text(struct sip_request *req, const char *text); 01499 static int add_digit(struct sip_request *req, char digit, unsigned int duration); 01500 static int add_vidupdate(struct sip_request *req); 01501 static void add_route(struct sip_request *req, struct sip_route *route); 01502 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field); 01503 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field); 01504 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field); 01505 static void set_destination(struct sip_pvt *p, char *uri); 01506 static void append_date(struct sip_request *req); 01507 static void build_contact(struct sip_pvt *p); 01508 static void build_rpid(struct sip_pvt *p); 01509 01510 /*------Request handling functions */ 01511 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock); 01512 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e); 01513 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock); 01514 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req); 01515 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e); 01516 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req); 01517 static int handle_request_message(struct sip_pvt *p, struct sip_request *req); 01518 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e); 01519 static void handle_request_info(struct sip_pvt *p, struct sip_request *req); 01520 static int handle_request_options(struct sip_pvt *p, struct sip_request *req); 01521 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin); 01522 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e); 01523 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno); 01524 01525 /*------Response handling functions */ 01526 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno); 01527 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno); 01528 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno); 01529 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno); 01530 01531 /*----- RTP interface functions */ 01532 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active); 01533 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp); 01534 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp); 01535 static int sip_get_codec(struct ast_channel *chan); 01536 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect); 01537 01538 /*------ T38 Support --------- */ 01539 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */ 01540 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans); 01541 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan); 01542 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl); 01543 01544 /*! \brief Definition of this channel for PBX channel registration */ 01545 static const struct ast_channel_tech sip_tech = { 01546 .type = "SIP", 01547 .description = "Session Initiation Protocol (SIP)", 01548 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1), 01549 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, 01550 .requester = sip_request_call, 01551 .devicestate = sip_devicestate, 01552 .call = sip_call, 01553 .hangup = sip_hangup, 01554 .answer = sip_answer, 01555 .read = sip_read, 01556 .write = sip_write, 01557 .write_video = sip_write, 01558 .indicate = sip_indicate, 01559 .transfer = sip_transfer, 01560 .fixup = sip_fixup, 01561 .send_digit_begin = sip_senddigit_begin, 01562 .send_digit_end = sip_senddigit_end, 01563 .bridge = ast_rtp_bridge, 01564 .early_bridge = ast_rtp_early_bridge, 01565 .send_text = sip_sendtext, 01566 }; 01567 01568 /*! \brief This version of the sip channel tech has no send_digit_begin 01569 * callback. This is for use with channels using SIP INFO DTMF so that 01570 * the core knows that the channel doesn't want DTMF BEGIN frames. */ 01571 static const struct ast_channel_tech sip_tech_info = { 01572 .type = "SIP", 01573 .description = "Session Initiation Protocol (SIP)", 01574 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1), 01575 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, 01576 .requester = sip_request_call, 01577 .devicestate = sip_devicestate, 01578 .call = sip_call, 01579 .hangup = sip_hangup, 01580 .answer = sip_answer, 01581 .read = sip_read, 01582 .write = sip_write, 01583 .write_video = sip_write, 01584 .indicate = sip_indicate, 01585 .transfer = sip_transfer, 01586 .fixup = sip_fixup, 01587 .send_digit_end = sip_senddigit_end, 01588 .bridge = ast_rtp_bridge, 01589 .send_text = sip_sendtext, 01590 }; 01591 01592 /**--- some list management macros. **/ 01593 01594 #define UNLINK(element, head, prev) do { \ 01595 if (prev) \ 01596 (prev)->next = (element)->next; \ 01597 else \ 01598 (head) = (element)->next; \ 01599 } while (0) 01600 01601 /*! \brief Interface structure with callbacks used to connect to RTP module */ 01602 static struct ast_rtp_protocol sip_rtp = { 01603 type: "SIP", 01604 get_rtp_info: sip_get_rtp_peer, 01605 get_vrtp_info: sip_get_vrtp_peer, 01606 set_rtp_peer: sip_set_rtp_peer, 01607 get_codec: sip_get_codec, 01608 }; 01609 01610 /*! \brief Helper function to lock, hiding the underlying locking mechanism. */ 01611 static void sip_pvt_lock(struct sip_pvt *pvt) 01612 { 01613 ast_mutex_lock(&pvt->pvt_lock); 01614 } 01615 01616 /*! \brief Helper function to unlock pvt, hiding the underlying locking mechanism. */ 01617 static void sip_pvt_unlock(struct sip_pvt *pvt) 01618 { 01619 ast_mutex_unlock(&pvt->pvt_lock); 01620 } 01621 01622 /*! 01623 * helper functions to unreference various types of objects. 01624 * By handling them this way, we don't have to declare the 01625 * destructor on each call, which removes the chance of errors. 01626 */ 01627 static void unref_peer(struct sip_peer *peer) 01628 { 01629 ASTOBJ_UNREF(peer, sip_destroy_peer); 01630 } 01631 01632 static void unref_user(struct sip_user *user) 01633 { 01634 ASTOBJ_UNREF(user, sip_destroy_user); 01635 } 01636 01637 static void registry_unref(struct sip_registry *reg) 01638 { 01639 if (option_debug > 2) 01640 ast_log(LOG_DEBUG, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1); 01641 ASTOBJ_UNREF(reg, sip_registry_destroy); 01642 } 01643 01644 /*! \brief Add object reference to SIP registry */ 01645 static struct sip_registry *registry_addref(struct sip_registry *reg) 01646 { 01647 if (option_debug > 2) 01648 ast_log(LOG_DEBUG, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1); 01649 return ASTOBJ_REF(reg); /* Add pointer to registry in packet */ 01650 } 01651 01652 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/ 01653 static struct ast_udptl_protocol sip_udptl = { 01654 type: "SIP", 01655 get_udptl_info: sip_get_udptl_peer, 01656 set_udptl_peer: sip_set_udptl_peer, 01657 }; 01658 01659 /*! \brief Convert transfer status to string */ 01660 static const char *referstatus2str(enum referstatus rstatus) 01661 { 01662 int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0])); 01663 int x; 01664 01665 for (x = 0; x < i; x++) { 01666 if (referstatusstrings[x].status == rstatus) 01667 return referstatusstrings[x].text; 01668 } 01669 return ""; 01670 } 01671 01672 /*! \brief Initialize the initital request packet in the pvt structure. 01673 This packet is used for creating replies and future requests in 01674 a dialog */ 01675 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req) 01676 { 01677 if (option_debug) { 01678 if (p->initreq.headers) 01679 ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid); 01680 else 01681 ast_log(LOG_DEBUG, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid); 01682 } 01683 /* Use this as the basis */ 01684 copy_request(&p->initreq, req); 01685 parse_request(&p->initreq); 01686 if (ast_test_flag(req, SIP_PKT_DEBUG)) 01687 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines); 01688 } 01689 01690 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */ 01691 static void sip_alreadygone(struct sip_pvt *dialog) 01692 { 01693 if (option_debug > 2) 01694 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid); 01695 ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE); 01696 } 01697 01698 01699 /*! \brief returns true if 'name' (with optional trailing whitespace) 01700 * matches the sip method 'id'. 01701 * Strictly speaking, SIP methods are case SENSITIVE, but we do 01702 * a case-insensitive comparison to be more tolerant. 01703 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send 01704 */ 01705 static int method_match(enum sipmethod id, const char *name) 01706 { 01707 int len = strlen(sip_methods[id].text); 01708 int l_name = name ? strlen(name) : 0; 01709 /* true if the string is long enough, and ends with whitespace, and matches */ 01710 return (l_name >= len && name[len] < 33 && 01711 !strncasecmp(sip_methods[id].text, name, len)); 01712 } 01713 01714 /*! \brief find_sip_method: Find SIP method from header */ 01715 static int find_sip_method(const char *msg) 01716 { 01717 int i, res = 0; 01718 01719 if (ast_strlen_zero(msg)) 01720 return 0; 01721 for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) { 01722 if (method_match(i, msg)) 01723 res = sip_methods[i].id; 01724 } 01725 return res; 01726 } 01727 01728 /*! \brief Parse supported header in incoming packet */ 01729 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported) 01730 { 01731 char *next, *sep; 01732 char *temp; 01733 unsigned int profile = 0; 01734 int i, found; 01735 01736 if (ast_strlen_zero(supported) ) 01737 return 0; 01738 temp = ast_strdupa(supported); 01739 01740 if (option_debug > 2 && sipdebug) 01741 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported); 01742 01743 for (next = temp; next; next = sep) { 01744 found = FALSE; 01745 if ( (sep = strchr(next, ',')) != NULL) 01746 *sep++ = '\0'; 01747 next = ast_skip_blanks(next); 01748 if (option_debug > 2 && sipdebug) 01749 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next); 01750 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) { 01751 if (!strcasecmp(next, sip_options[i].text)) { 01752 profile |= sip_options[i].id; 01753 found = TRUE; 01754 if (option_debug > 2 && sipdebug) 01755 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next); 01756 break; 01757 } 01758 } 01759 if (!found && option_debug > 2 && sipdebug) { 01760 if (!strncasecmp(next, "x-", 2)) 01761 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next); 01762 else 01763 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next); 01764 } 01765 } 01766 01767 if (pvt) 01768 pvt->sipoptions = profile; 01769 return profile; 01770 } 01771 01772 /*! \brief See if we pass debug IP filter */ 01773 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 01774 { 01775 if (!sipdebug) 01776 return 0; 01777 if (debugaddr.sin_addr.s_addr) { 01778 if (((ntohs(debugaddr.sin_port) != 0) 01779 && (debugaddr.sin_port != addr->sin_port)) 01780 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr)) 01781 return 0; 01782 } 01783 return 1; 01784 } 01785 01786 /*! \brief The real destination address for a write */ 01787 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p) 01788 { 01789 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa; 01790 } 01791 01792 /*! \brief Display SIP nat mode */ 01793 static const char *sip_nat_mode(const struct sip_pvt *p) 01794 { 01795 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT"; 01796 } 01797 01798 /*! \brief Test PVT for debugging output */ 01799 static inline int sip_debug_test_pvt(struct sip_pvt *p) 01800 { 01801 if (!sipdebug) 01802 return 0; 01803 return sip_debug_test_addr(sip_real_dst(p)); 01804 } 01805 01806 /*! \brief Transmit SIP message */ 01807 static int __sip_xmit(struct sip_pvt *p, char *data, int len) 01808 { 01809 int res; 01810 const struct sockaddr_in *dst = sip_real_dst(p); 01811 res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in)); 01812 01813 if (res != len) 01814 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno)); 01815 return res; 01816 } 01817 01818 01819 /*! \brief Build a Via header for a request */ 01820 static void build_via(struct sip_pvt *p) 01821 { 01822 /* Work around buggy UNIDEN UIP200 firmware */ 01823 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : ""; 01824 01825 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */ 01826 ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s", 01827 ast_inet_ntoa(p->ourip), ourport, p->branch, rport); 01828 } 01829 01830 /*! \brief NAT fix - decide which IP address to use for ASterisk server? 01831 * 01832 * Using the localaddr structure built up with localnet statements in sip.conf 01833 * apply it to their address to see if we need to substitute our 01834 * externip or can get away with our internal bindaddr 01835 */ 01836 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us) 01837 { 01838 struct sockaddr_in theirs, ours; 01839 01840 /* Get our local information */ 01841 ast_ouraddrfor(them, us); 01842 theirs.sin_addr = *them; 01843 ours.sin_addr = *us; 01844 01845 if (localaddr && externip.sin_addr.s_addr && 01846 ast_apply_ha(localaddr, &theirs) && 01847 !ast_apply_ha(localaddr, &ours)) { 01848 if (externexpire && time(NULL) >= externexpire) { 01849 struct ast_hostent ahp; 01850 struct hostent *hp; 01851 01852 externexpire = time(NULL) + externrefresh; 01853 if ((hp = ast_gethostbyname(externhost, &ahp))) { 01854 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr)); 01855 } else 01856 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost); 01857 } 01858 *us = externip.sin_addr; 01859 if (option_debug) { 01860 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", 01861 ast_inet_ntoa(*(struct in_addr *)&them->s_addr)); 01862 } 01863 } else if (bindaddr.sin_addr.s_addr) 01864 *us = bindaddr.sin_addr; 01865 return AST_SUCCESS; 01866 } 01867 01868 /*! \brief Append to SIP dialog history 01869 \return Always returns 0 */ 01870 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args) 01871 01872 static void append_history_full(struct sip_pvt *p, const char *fmt, ...) 01873 __attribute__ ((format (printf, 2, 3))); 01874 01875 /*! \brief Append to SIP dialog history with arg list */ 01876 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap) 01877 { 01878 char buf[80], *c = buf; /* max history length */ 01879 struct sip_history *hist; 01880 int l; 01881 01882 vsnprintf(buf, sizeof(buf), fmt, ap); 01883 strsep(&c, "\r\n"); /* Trim up everything after \r or \n */ 01884 l = strlen(buf) + 1; 01885 if (!(hist = ast_calloc(1, sizeof(*hist) + l))) 01886 return; 01887 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) { 01888 free(hist); 01889 return; 01890 } 01891 memcpy(hist->event, buf, l); 01892 AST_LIST_INSERT_TAIL(p->history, hist, list); 01893 } 01894 01895 /*! \brief Append to SIP dialog history with arg list */ 01896 static void append_history_full(struct sip_pvt *p, const char *fmt, ...) 01897 { 01898 va_list ap; 01899 01900 if (!p) 01901 return; 01902 va_start(ap, fmt); 01903 append_history_va(p, fmt, ap); 01904 va_end(ap); 01905 01906 return; 01907 } 01908 01909 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */ 01910 static int retrans_pkt(void *data) 01911 { 01912 struct sip_pkt *pkt = data, *prev, *cur = NULL; 01913 int reschedule = DEFAULT_RETRANS; 01914 01915 /* Lock channel PVT */ 01916 sip_pvt_lock(pkt->owner); 01917 01918 if (pkt->retrans < MAX_RETRANS) { 01919 pkt->retrans++; 01920 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */ 01921 if (sipdebug && option_debug > 3) 01922 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); 01923 } else { 01924 int siptimer_a; 01925 01926 if (sipdebug && option_debug > 3) 01927 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method); 01928 if (!pkt->timer_a) 01929 pkt->timer_a = 2 ; 01930 else 01931 pkt->timer_a = 2 * pkt->timer_a; 01932 01933 /* For non-invites, a maximum of 4 secs */ 01934 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */ 01935 if (pkt->method != SIP_INVITE && siptimer_a > 4000) 01936 siptimer_a = 4000; 01937 01938 /* Reschedule re-transmit */ 01939 reschedule = siptimer_a; 01940 if (option_debug > 3) 01941 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); 01942 } 01943 01944 if (sip_debug_test_pvt(pkt->owner)) { 01945 const struct sockaddr_in *dst = sip_real_dst(pkt->owner); 01946 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n", 01947 pkt->retrans, sip_nat_mode(pkt->owner), 01948 ast_inet_ntoa(dst->sin_addr), 01949 ntohs(dst->sin_port), pkt->data); 01950 } 01951 01952 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data); 01953 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); 01954 sip_pvt_unlock(pkt->owner); 01955 return reschedule; 01956 } 01957 /* Too many retries */ 01958 if (pkt->owner && pkt->method != SIP_OPTIONS) { 01959 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */ 01960 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"); 01961 } else { 01962 if ((pkt->method == SIP_OPTIONS) && sipdebug) 01963 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid); 01964 } 01965 append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)"); 01966 01967 pkt->retransid = -1; 01968 01969 if (ast_test_flag(pkt, FLAG_FATAL)) { 01970 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) { 01971 sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */ 01972 usleep(1); 01973 sip_pvt_lock(pkt->owner); 01974 } 01975 if (pkt->owner->owner) { 01976 sip_alreadygone(pkt->owner); 01977 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid); 01978 ast_queue_hangup(pkt->owner->owner); 01979 ast_channel_unlock(pkt->owner->owner); 01980 } else { 01981 /* If no channel owner, destroy now */ 01982 01983 /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */ 01984 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) 01985 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY); 01986 } 01987 } 01988 /* Remove the packet */ 01989 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) { 01990 if (cur == pkt) { 01991 UNLINK(cur, pkt->owner->packets, prev); 01992 sip_pvt_unlock(pkt->owner); 01993 free(pkt); 01994 return 0; 01995 } 01996 } 01997 /* error case */ 01998 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n"); 01999 sip_pvt_unlock(pkt->owner); 02000 return 0; 02001 } 02002 02003 /*! \brief Transmit packet with retransmits 02004 \return 0 on success, -1 on failure to allocate packet 02005 */ 02006 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod) 02007 { 02008 struct sip_pkt *pkt; 02009 int siptimer_a = DEFAULT_RETRANS; 02010 02011 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) 02012 return AST_FAILURE; 02013 memcpy(pkt->data, data, len); 02014 pkt->method = sipmethod; 02015 pkt->packetlen = len; 02016 pkt->next = p->packets; 02017 pkt->owner = p; 02018 pkt->seqno = seqno; 02019 if (resp) 02020 ast_set_flag(pkt, FLAG_RESPONSE); 02021 pkt->data[len] = '\0'; 02022 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */ 02023 if (fatal) 02024 ast_set_flag(pkt, FLAG_FATAL); 02025 if (pkt->timer_t1) 02026 siptimer_a = pkt->timer_t1 * 2; 02027 02028 /* Schedule retransmission */ 02029 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1); 02030 if (option_debug > 3 && sipdebug) 02031 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid); 02032 pkt->next = p->packets; 02033 p->packets = pkt; 02034 02035 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */ 02036 if (sipmethod == SIP_INVITE) { 02037 /* Note this is a pending invite */ 02038 p->pendinginvite = seqno; 02039 } 02040 return AST_SUCCESS; 02041 } 02042 02043 /*! \brief Kill a SIP dialog (called by scheduler) */ 02044 static int __sip_autodestruct(void *data) 02045 { 02046 struct sip_pvt *p = data; 02047 02048 /* If this is a subscription, tell the phone that we got a timeout */ 02049 if (p->subscribed) { 02050 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE); /* Send last notification */ 02051 p->subscribed = NONE; 02052 append_history(p, "Subscribestatus", "timeout"); 02053 if (option_debug > 2) 02054 ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>"); 02055 return 10000; /* Reschedule this destruction so that we know that it's gone */ 02056 } 02057 02058 if (p->subscribed == MWI_NOTIFICATION) 02059 if (p->relatedpeer) 02060 unref_peer(p->relatedpeer); /* Remove link to peer. If it's realtime, make sure it's gone from memory) */ 02061 02062 /* Reset schedule ID */ 02063 p->autokillid = -1; 02064 02065 if (p->owner) { 02066 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text); 02067 ast_queue_hangup(p->owner); 02068 } else if (p->refer) { 02069 if (option_debug > 2) 02070 ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid); 02071 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1); 02072 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid); 02073 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); 02074 } else { 02075 append_history(p, "AutoDestroy", "%s", p->callid); 02076 if (option_debug) 02077 ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid); 02078 sip_destroy(p); /* Go ahead and destroy dialog. All attempts to recover is done */ 02079 } 02080 return 0; 02081 } 02082 02083 /*! \brief Schedule destruction of SIP dialog */ 02084 static void sip_scheddestroy(struct sip_pvt *p, int ms) 02085 { 02086 if (ms < 0) { 02087 if (p->timer_t1 == 0) 02088 p->timer_t1 = SIP_TIMER_T1; /* Set timer T1 if not set (RFC 3261) */ 02089 ms = p->timer_t1 * 64; 02090 } 02091 if (sip_debug_test_pvt(p)) 02092 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text); 02093 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) 02094 append_history(p, "SchedDestroy", "%d ms", ms); 02095 02096 if (p->autokillid > -1) 02097 ast_sched_del(sched, p->autokillid); 02098 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p); 02099 } 02100 02101 /*! \brief Cancel destruction of SIP dialog */ 02102 static void sip_cancel_destroy(struct sip_pvt *p) 02103 { 02104 if (p->autokillid > -1) { 02105 ast_sched_del(sched, p->autokillid); 02106 append_history(p, "CancelDestroy", ""); 02107 p->autokillid = -1; 02108 } 02109 } 02110 02111 /*! \brief Acknowledges receipt of a packet and stops retransmission */ 02112 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod) 02113 { 02114 struct sip_pkt *cur, *prev = NULL; 02115 const char *msg = "Not Found"; /* used only for debugging */ 02116 02117 sip_pvt_lock(p); 02118 for (cur = p->packets; cur; prev = cur, cur = cur->next) { 02119 if (cur->seqno != seqno || ast_test_flag(cur, FLAG_RESPONSE) != resp) 02120 continue; 02121 if (ast_test_flag(cur, FLAG_RESPONSE) || cur->method == sipmethod) { 02122 msg = "Found"; 02123 if (!resp && (seqno == p->pendinginvite)) { 02124 if (option_debug) 02125 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite); 02126 p->pendinginvite = 0; 02127 } 02128 if (cur->retransid > -1) { 02129 if (sipdebug && option_debug > 3) 02130 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid); 02131 ast_sched_del(sched, cur->retransid); 02132 cur->retransid = -1; 02133 } 02134 UNLINK(cur, p->packets, prev); 02135 free(cur); 02136 break; 02137 } 02138 } 02139 sip_pvt_unlock(p); 02140 if (option_debug) 02141 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", 02142 p->callid, resp ? "Response" : "Request", seqno, msg); 02143 } 02144 02145 /*! \brief Pretend to ack all packets 02146 * maybe the lock on p is not strictly necessary but there might be a race */ 02147 static void __sip_pretend_ack(struct sip_pvt *p) 02148 { 02149 struct sip_pkt *cur = NULL; 02150 02151 while (p->packets) { 02152 int method; 02153 if (cur == p->packets) { 02154 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text); 02155 return; 02156 } 02157 cur = p->packets; 02158 method = (cur->method) ? cur->method : find_sip_method(cur->data); 02159 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method); 02160 } 02161 } 02162 02163 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */ 02164 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod) 02165 { 02166 struct sip_pkt *cur; 02167 int res = -1; 02168 02169 for (cur = p->packets; cur; cur = cur->next) { 02170 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp && 02171 (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) { 02172 /* this is our baby */ 02173 if (cur->retransid > -1) { 02174 if (option_debug > 3 && sipdebug) 02175 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text); 02176 ast_sched_del(sched, cur->retransid); 02177 cur->retransid = -1; 02178 } 02179 res = 0; 02180 break; 02181 } 02182 } 02183 if (option_debug) 02184 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"); 02185 return res; 02186 } 02187 02188 02189 /*! \brief Copy SIP request, parse it */ 02190 static void parse_copy(struct sip_request *dst, const struct sip_request *src) 02191 { 02192 memset(dst, 0, sizeof(*dst)); 02193 memcpy(dst->data, src->data, sizeof(dst->data)); 02194 dst->len = src->len; 02195 parse_request(dst); 02196 } 02197 02198 /*! \brief add a blank line if no body */ 02199 static void add_blank(struct sip_request *req) 02200 { 02201 if (!req->lines) { 02202 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */ 02203 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n"); 02204 req->len += strlen(req->data + req->len); 02205 } 02206 } 02207 02208 /*! \brief Transmit response on SIP request*/ 02209 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno) 02210 { 02211 int res; 02212 02213 add_blank(req); 02214 if (sip_debug_test_pvt(p)) { 02215 const struct sockaddr_in *dst = sip_real_dst(p); 02216 02217 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n", 02218 reliable ? "Reliably " : "", sip_nat_mode(p), 02219 ast_inet_ntoa(dst->sin_addr), 02220 ntohs(dst->sin_port), req->data); 02221 } 02222 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) { 02223 struct sip_request tmp; 02224 parse_copy(&tmp, req); 02225 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), 02226 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text); 02227 } 02228 res = (reliable) ? 02229 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) : 02230 __sip_xmit(p, req->data, req->len); 02231 if (res > 0) 02232 return 0; 02233 return res; 02234 } 02235 02236 /*! \brief Send SIP Request to the other part of the dialogue */ 02237 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno) 02238 { 02239 int res; 02240 02241 add_blank(req); 02242 if (sip_debug_test_pvt(p)) { 02243 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE)) 02244 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data); 02245 else 02246 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data); 02247 } 02248 if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) { 02249 struct sip_request tmp; 02250 parse_copy(&tmp, req); 02251 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text); 02252 } 02253 res = (reliable) ? 02254 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) : 02255 __sip_xmit(p, req->data, req->len); 02256 return res; 02257 } 02258 02259 /*! \brief Locate closing quote in a string, skipping escaped quotes. 02260 * optionally with a limit on the search. 02261 * start must be past the first quote. 02262 */ 02263 static const char *find_closing_quote(const char *start, const char *lim) 02264 { 02265 char last_char = '\0'; 02266 const char *s; 02267 for (s = start; *s && s != lim; last_char = *s++) { 02268 if (*s == '"' && last_char != '\\') 02269 break; 02270 } 02271 return s; 02272 } 02273 02274 /*! \brief Pick out text in brackets from character string 02275 \return pointer to terminated stripped string 02276 \param tmp input string that will be modified 02277 Examples: 02278 02279 "foo" <bar> valid input, returns bar 02280 foo returns the whole string 02281 < "foo ... > returns the string between brackets 02282 < "foo... bogus (missing closing bracket), returns the whole string 02283 XXX maybe should still skip the opening bracket 02284 */ 02285 static char *get_in_brackets(char *tmp) 02286 { 02287 const char *parse = tmp; 02288 char *first_bracket; 02289 02290 /* 02291 * Skip any quoted text until we find the part in brackets. 02292 * On any error give up and return the full string. 02293 */ 02294 while ( (first_bracket = strchr(parse, '<')) ) { 02295 char *first_quote = strchr(parse, '"'); 02296 02297 if (!first_quote || first_quote > first_bracket) 02298 break; /* no need to look at quoted part */ 02299 /* the bracket is within quotes, so ignore it */ 02300 parse = find_closing_quote(first_quote + 1, NULL); 02301 if (!*parse) { /* not found, return full string ? */ 02302 /* XXX or be robust and return in-bracket part ? */ 02303 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp); 02304 break; 02305 } 02306 parse++; 02307 } 02308 if (first_bracket) { 02309 char *second_bracket = strchr(first_bracket + 1, '>'); 02310 if (second_bracket) { 02311 *second_bracket = '\0'; 02312 tmp = first_bracket + 1; 02313 } else { 02314 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp); 02315 } 02316 } 02317 return tmp; 02318 } 02319 02320 /*! 02321 * parses a URI in its components. 02322 * If scheme is specified, drop it from the top. 02323 * If a component is not requested, do not split around it. 02324 * This means that if we don't have domain, we cannot split 02325 * name:pass and domain:port. 02326 * It is safe to call with ret_name, pass, domain, port 02327 * pointing all to the same place. 02328 * Init pointers to empty string so we never get NULL dereferencing. 02329 * Overwrites the string. 02330 * return 0 on success, other values on error. 02331 */ 02332 static int parse_uri(char *uri, char *scheme, 02333 char **ret_name, char **pass, char **domain, char **port, char **options) 02334 { 02335 char *name = NULL; 02336 int error = 0; 02337 02338 /* init field as required */ 02339 if (pass) 02340 *pass = ""; 02341 if (port) 02342 *port = ""; 02343 name = strsep(&uri, ";"); /* remove options */ 02344 if (scheme) { 02345 int l = strlen(scheme); 02346 if (!strncmp(name, scheme, l)) 02347 name += l; 02348 else { 02349 ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, name); 02350 error = -1; 02351 } 02352 } 02353 if (!domain) { 02354 /* if we don't want to split around domain, keep everything as a name, 02355 * so we need to do nothing here, except remember why. 02356 */ 02357 } else { 02358 /* store the result in a temp. variable to avoid it being 02359 * overwritten if arguments point to the same place. 02360 */ 02361 char *c, *dom = ""; 02362 02363 if ((c = strchr(name, '@')) == NULL) { 02364 /* domain-only URI, according to the SIP RFC. */ 02365 dom = name; 02366 name = ""; 02367 } else { 02368 *c++ = '\0'; 02369 dom = c; 02370 } 02371 if (port && (c = strchr(dom, ':'))) { /* Remove :port */ 02372 *c++ = '\0'; 02373 *port = c; 02374 } 02375 if (pass && (c = strchr(name, ':'))) { /* user:password */ 02376 *c++ = '\0'; 02377 *pass = c; 02378 } 02379 *domain = dom; 02380 } 02381 if (ret_name) /* same as for domain, store the result only at the end */ 02382 *ret_name = name; 02383 if (options) 02384 *options = uri ? uri : ""; 02385 02386 return error; 02387 } 02388 02389 /*! \brief Send SIP MESSAGE text within a call 02390 Called from PBX core sendtext() application */ 02391 static int sip_sendtext(struct ast_channel *ast, const char *text) 02392 { 02393 struct sip_pvt *p = ast->tech_pvt; 02394 int debug = sip_debug_test_pvt(p); 02395 02396 if (debug) 02397 ast_verbose("Sending text %s on %s\n", text, ast->name); 02398 if (!p) 02399 return -1; 02400 if (ast_strlen_zero(text)) 02401 return 0; 02402 if (debug) 02403 ast_verbose("Really sending text %s on %s\n", text, ast->name); 02404 transmit_message_with_text(p, text); 02405 return 0; 02406 } 02407 02408 /*! \brief Update peer object in realtime storage 02409 If the Asterisk system name is set in asterisk.conf, we will use 02410 that name and store that in the "regserver" field in the sippeers 02411 table to facilitate multi-server setups. 02412 */ 02413 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey) 02414 { 02415 char port[10]; 02416 char ipaddr[INET_ADDRSTRLEN]; 02417 char regseconds[20]; 02418 02419 char *sysname = ast_config_AST_SYSTEM_NAME; 02420 char *syslabel = NULL; 02421 02422 time_t nowtime = time(NULL) + expirey; 02423 const char *fc = fullcontact ? "fullcontact" : NULL; 02424 02425 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */ 02426 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr)); 02427 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port)); 02428 02429 if (ast_strlen_zero(sysname)) /* No system name, disable this */ 02430 sysname = NULL; 02431 else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME)) 02432 syslabel = "regserver"; 02433 02434 if (fc) 02435 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, 02436 "port", port, "regseconds", regseconds, 02437 "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */ 02438 else 02439 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, 02440 "port", port, "regseconds", regseconds, 02441 "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */ 02442 } 02443 02444 /*! \brief Automatically add peer extension to dial plan */ 02445 static void register_peer_exten(struct sip_peer *peer, int onoff) 02446 { 02447 char multi[256]; 02448 char *stringp, *ext, *context; 02449 02450 /* XXX note that global_regcontext is both a global 'enable' flag and 02451 * the name of the global regexten context, if not specified 02452 * individually. 02453 */ 02454 if (ast_strlen_zero(global_regcontext)) 02455 return; 02456 02457 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi)); 02458 stringp = multi; 02459 while ((ext = strsep(&stringp, "&"))) { 02460 if ((context = strchr(ext, '@'))) { 02461 *context++ = '\0'; /* split ext@context */ 02462 if (!ast_context_find(context)) { 02463 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context); 02464 continue; 02465 } 02466 } else { 02467 context = global_regcontext; 02468 } 02469 if (onoff) 02470 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop", 02471 ast_strdup(peer->name), ast_free, "SIP"); 02472 else 02473 ast_context_remove_extension(context, ext, 1, NULL); 02474 } 02475 } 02476 02477 /*! \brief Destroy peer object from memory */ 02478 static void sip_destroy_peer(struct sip_peer *peer) 02479 { 02480 if (option_debug > 2) 02481 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name); 02482 02483 /* Delete it, it needs to disappear */ 02484 if (peer->call) 02485 sip_destroy(peer->call); 02486 02487 if (peer->mwipvt) /* We have an active subscription, delete it */ 02488 sip_destroy(peer->mwipvt); 02489 02490 if (peer->chanvars) { 02491 ast_variables_destroy(peer->chanvars); 02492 peer->chanvars = NULL; 02493 } 02494 if (peer->expire > -1) 02495 ast_sched_del(sched, peer->expire); 02496 02497 if (peer->pokeexpire > -1) 02498 ast_sched_del(sched, peer->pokeexpire); 02499 register_peer_exten(peer, FALSE); 02500 ast_free_ha(peer->ha); 02501 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT)) 02502 apeerobjs--; 02503 else if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) { 02504 rpeerobjs--; 02505 if (option_debug > 2) 02506 ast_log(LOG_DEBUG,"-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs); 02507 } else 02508 speerobjs--; 02509 clear_realm_authentication(peer->auth); 02510 peer->auth = NULL; 02511 if (peer->dnsmgr) 02512 ast_dnsmgr_release(peer->dnsmgr); 02513 free(peer); 02514 } 02515 02516 /*! \brief Update peer data in database (if used) */ 02517 static void update_peer(struct sip_peer *p, int expiry) 02518 { 02519 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS); 02520 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) && 02521 (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) { 02522 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry); 02523 } 02524 } 02525 02526 02527 /*! \brief realtime_peer: Get peer from realtime storage 02528 * Checks the "sippeers" realtime family from extconfig.conf 02529 * \todo Consider adding check of port address when matching here to follow the same 02530 * algorithm as for static peers. Will we break anything by adding that? 02531 */ 02532 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin) 02533 { 02534 struct sip_peer *peer; 02535 struct ast_variable *var = NULL; 02536 struct ast_variable *tmp; 02537 char ipaddr[INET_ADDRSTRLEN]; 02538 02539 /* First check on peer name */ 02540 if (newpeername) 02541 var = ast_load_realtime("sippeers", "name", newpeername, NULL); 02542 else if (sin) { /* Then check on IP address for dynamic peers */ 02543 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr)); 02544 var = ast_load_realtime("sippeers", "host", ipaddr, NULL); /* First check for fixed IP hosts */ 02545 if (!var) 02546 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL); /* Then check for registred hosts */ 02547 } 02548 02549 if (!var) 02550 return NULL; 02551 02552 for (tmp = var; tmp; tmp = tmp->next) { 02553 /* If this is type=user, then skip this object. */ 02554 if (!strcasecmp(tmp->name, "type") && 02555 !strcasecmp(tmp->value, "user")) { 02556 ast_variables_destroy(var); 02557 return NULL; 02558 } else if (!newpeername && !strcasecmp(tmp->name, "name")) { 02559 newpeername = tmp->value; 02560 } 02561 } 02562 02563 if (!newpeername) { /* Did not find peer in realtime */ 02564 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr); 02565 ast_variables_destroy(var); 02566 return NULL; 02567 } 02568 02569 02570 /* Peer found in realtime, now build it in memory */ 02571 peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)); 02572 if (!peer) { 02573 ast_variables_destroy(var); 02574 return NULL; 02575 } 02576 02577 if (option_debug > 2) 02578 ast_log(LOG_DEBUG,"-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs); 02579 02580 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) { 02581 /* Cache peer */ 02582 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS); 02583 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) { 02584 if (peer->expire > -1) { 02585 ast_sched_del(sched, peer->expire); 02586 } 02587 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer); 02588 } 02589 ASTOBJ_CONTAINER_LINK(&peerl,peer); 02590 } else { 02591 ast_set_flag(&peer->flags[0], SIP_REALTIME); 02592 } 02593 ast_variables_destroy(var); 02594 02595 return peer; 02596 } 02597 02598 /*! \brief Support routine for find_peer */ 02599 static int sip_addrcmp(char *name, struct sockaddr_in *sin) 02600 { 02601 /* We know name is the first field, so we can cast */ 02602 struct sip_peer *p = (struct sip_peer *) name; 02603 return !(!inaddrcmp(&p->addr, sin) || 02604 (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) && 02605 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))); 02606 } 02607 02608 /*! \brief Locate peer by name or ip address 02609 * This is used on incoming SIP message to find matching peer on ip 02610 or outgoing message to find matching peer on name */ 02611 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime) 02612 { 02613 struct sip_peer *p = NULL; 02614 02615 if (peer) 02616 p = ASTOBJ_CONTAINER_FIND(&peerl, peer); 02617 else 02618 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); 02619 02620 if (!p && realtime) 02621 p = realtime_peer(peer, sin); 02622 02623 return p; 02624 } 02625 02626 /*! \brief Remove user object from in-memory storage */