/* * Asterisk -- An open source telephony toolkit. * * Copyright (C) 1999 - 2006, Digium, Inc. * * Mark Spencer * * See http://www.asterisk.org for more information about * the Asterisk project. Please do not directly contact * any of the maintainers of this project for assistance; * the project provides a web site, mailing lists and IRC * channels for your use. * * This program is free software, distributed under the terms of * the GNU General Public License Version 2. See the LICENSE file * at the top of the source tree. */ /*! * \file * \brief Implementation of Session Initiation Protocol * * Implementation of RFC 3261 - without S/MIME, TCP and TLS support * Configuration file \link Config_sip sip.conf \endlink * * \todo SIP over TCP * \todo SIP over TLS * \todo Better support of forking */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "asterisk.h" ASTERISK_FILE_VERSION(__FILE__, "$Revision: 42535 $") #include "asterisk/lock.h" #include "asterisk/channel.h" #include "asterisk/config.h" #include "asterisk/logger.h" #include "asterisk/module.h" #include "asterisk/pbx.h" #include "asterisk/options.h" #include "asterisk/lock.h" #include "asterisk/sched.h" #include "asterisk/io.h" #include "asterisk/rtp.h" #include "asterisk/acl.h" #include "asterisk/manager.h" #include "asterisk/callerid.h" #include "asterisk/cli.h" #include "asterisk/app.h" #include "asterisk/musiconhold.h" #include "asterisk/dsp.h" #include "asterisk/features.h" #include "asterisk/acl.h" #include "asterisk/srv.h" #include "asterisk/astdb.h" #include "asterisk/causes.h" #include "asterisk/utils.h" #include "asterisk/file.h" #include "asterisk/astobj.h" #include "asterisk/dnsmgr.h" #include "asterisk/devicestate.h" #include "asterisk/linkedlists.h" #ifdef OSP_SUPPORT #include "asterisk/astosp.h" #endif #ifndef DEFAULT_USERAGENT #define DEFAULT_USERAGENT "Asterisk PBX" #endif #define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */ #ifndef IPTOS_MINCOST #define IPTOS_MINCOST 0x02 #endif /* #define VOCAL_DATA_HACK */ #define SIPDUMPER #define DEFAULT_DEFAULT_EXPIRY 120 #define DEFAULT_MAX_EXPIRY 3600 #define DEFAULT_REGISTRATION_TIMEOUT 20 #define DEFAULT_MAX_FORWARDS "70" /* guard limit must be larger than guard secs */ /* guard min must be < 1000, and should be >= 250 */ #define EXPIRY_GUARD_SECS 15 /* How long before expiry do we reregister */ #define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of EXPIRY_GUARD_SECS */ #define EXPIRY_GUARD_MIN 500 /* This is the minimum guard time applied. If GUARD_PCT turns out to be lower than this, it will use this time instead. This is in milliseconds. */ #define EXPIRY_GUARD_PCT 0.20 /* Percentage of expires timeout to use when below EXPIRY_GUARD_LIMIT */ #define SIP_LEN_CONTACT 256 static int max_expiry = DEFAULT_MAX_EXPIRY; static int default_expiry = DEFAULT_DEFAULT_EXPIRY; #ifndef MAX #define MAX(a,b) ((a) > (b) ? (a) : (b)) #endif #define CALLERID_UNKNOWN "Unknown" #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */ #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */ #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */ #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */ /* 2 * 500 ms in RFC 3261 */ #define MAX_RETRANS 6 /* Try only 6 times for retransmissions, a total of 7 transmissions */ #define MAX_AUTHTRIES 3 /* Try authentication three times, then fail */ #define DEBUG_READ 0 /* Recieved data */ #define DEBUG_SEND 1 /* Transmit data */ static const char desc[] = "Session Initiation Protocol (SIP)"; static const char channeltype[] = "SIP"; static const char config[] = "sip.conf"; static const char notify_config[] = "sip_notify.conf"; #define RTP 1 #define NO_RTP 0 #define SIP_RETVAL_IGNORE 1 /* Do _NOT_ make any changes to this enum, or the array following it; if you think you are doing the right thing, you are probably not doing the right thing. If you think there are changes needed, get someone else to review them first _before_ submitting a patch. If these two lists do not match properly bad things will happen. */ enum subscriptiontype { NONE = 0, TIMEOUT, XPIDF_XML, DIALOG_INFO_XML, CPIM_PIDF_XML, PIDF_XML }; static const struct cfsubscription_types { enum subscriptiontype type; const char * const event; const char * const mediatype; const char * const text; } subscription_types[] = { { NONE, "-", "unknown", "unknown" }, /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */ { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" }, { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */ { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */ { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" } /* Pre-RFC 3863 with MS additions */ }; enum sipmethod { SIP_UNKNOWN, SIP_RESPONSE, SIP_REGISTER, SIP_OPTIONS, SIP_NOTIFY, SIP_INVITE, SIP_ACK, SIP_PRACK, SIP_BYE, SIP_REFER, SIP_SUBSCRIBE, SIP_MESSAGE, SIP_UPDATE, SIP_INFO, SIP_CANCEL, SIP_PUBLISH, } sip_method_list; enum sip_auth_type { PROXY_AUTH, WWW_AUTH, }; /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */ static const struct cfsip_methods { enum sipmethod id; int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */ char * const text; } sip_methods[] = { { SIP_UNKNOWN, RTP, "-UNKNOWN-" }, { SIP_RESPONSE, NO_RTP, "SIP/2.0" }, { SIP_REGISTER, NO_RTP, "REGISTER" }, { SIP_OPTIONS, NO_RTP, "OPTIONS" }, { SIP_NOTIFY, NO_RTP, "NOTIFY" }, { SIP_INVITE, RTP, "INVITE" }, { SIP_ACK, NO_RTP, "ACK" }, { SIP_PRACK, NO_RTP, "PRACK" }, { SIP_BYE, NO_RTP, "BYE" }, { SIP_REFER, NO_RTP, "REFER" }, { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" }, { SIP_MESSAGE, NO_RTP, "MESSAGE" }, { SIP_UPDATE, NO_RTP, "UPDATE" }, { SIP_INFO, NO_RTP, "INFO" }, { SIP_CANCEL, NO_RTP, "CANCEL" }, { SIP_PUBLISH, NO_RTP, "PUBLISH" } }; /*! \brief Structure for conversion between compressed SIP and "normal" SIP */ static const struct cfalias { char * const fullname; char * const shortname; } aliases[] = { { "Content-Type", "c" }, { "Content-Encoding", "e" }, { "From", "f" }, { "Call-ID", "i" }, { "Contact", "m" }, { "Content-Length", "l" }, { "Subject", "s" }, { "To", "t" }, { "Supported", "k" }, { "Refer-To", "r" }, { "Referred-By", "b" }, { "Allow-Events", "u" }, { "Event", "o" }, { "Via", "v" }, { "Accept-Contact", "a" }, { "Reject-Contact", "j" }, { "Request-Disposition", "d" }, { "Session-Expires", "x" }, }; /*! Define SIP option tags, used in Require: and Supported: headers We need to be aware of these properties in the phones to use the replace: header. We should not do that without knowing that the other end supports it... This is nothing we can configure, we learn by the dialog Supported: header on the REGISTER (peer) or the INVITE (other devices) We are not using many of these today, but will in the future. This is documented in RFC 3261 */ #define SUPPORTED 1 #define NOT_SUPPORTED 0 #define SIP_OPT_REPLACES (1 << 0) #define SIP_OPT_100REL (1 << 1) #define SIP_OPT_TIMER (1 << 2) #define SIP_OPT_EARLY_SESSION (1 << 3) #define SIP_OPT_JOIN (1 << 4) #define SIP_OPT_PATH (1 << 5) #define SIP_OPT_PREF (1 << 6) #define SIP_OPT_PRECONDITION (1 << 7) #define SIP_OPT_PRIVACY (1 << 8) #define SIP_OPT_SDP_ANAT (1 << 9) #define SIP_OPT_SEC_AGREE (1 << 10) #define SIP_OPT_EVENTLIST (1 << 11) #define SIP_OPT_GRUU (1 << 12) #define SIP_OPT_TARGET_DIALOG (1 << 13) /*! \brief List of well-known SIP options. If we get this in a require, we should check the list and answer accordingly. */ static const struct cfsip_options { int id; /*!< Bitmap ID */ int supported; /*!< Supported by Asterisk ? */ char * const text; /*!< Text id, as in standard */ } sip_options[] = { /* Replaces: header for transfer */ { SIP_OPT_REPLACES, SUPPORTED, "replaces" }, /* RFC3262: PRACK 100% reliability */ { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" }, /* SIP Session Timers */ { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" }, /* RFC3959: SIP Early session support */ { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" }, /* SIP Join header support */ { SIP_OPT_JOIN, NOT_SUPPORTED, "join" }, /* RFC3327: Path support */ { SIP_OPT_PATH, NOT_SUPPORTED, "path" }, /* RFC3840: Callee preferences */ { SIP_OPT_PREF, NOT_SUPPORTED, "pref" }, /* RFC3312: Precondition support */ { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" }, /* RFC3323: Privacy with proxies*/ { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" }, /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */ { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" }, /* RFC3329: Security agreement mechanism */ { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" }, /* SIMPLE events: draft-ietf-simple-event-list-07.txt */ { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" }, /* GRUU: Globally Routable User Agent URI's */ { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" }, /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */ { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" }, }; /*! \brief SIP Methods we support */ #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY" /*! \brief SIP Extensions we support */ #define SUPPORTED_EXTENSIONS "replaces" #define DEFAULT_SIP_PORT 5060 /*!< From RFC 3261 (former 2543) */ #define SIP_MAX_PACKET 4096 /*!< Also from RFC 3261 (2543), should sub headers tho */ static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT; #define DEFAULT_CONTEXT "default" static char default_context[AST_MAX_CONTEXT] = DEFAULT_CONTEXT; static char default_subscribecontext[AST_MAX_CONTEXT]; #define DEFAULT_VMEXTEN "asterisk" static char global_vmexten[AST_MAX_EXTENSION] = DEFAULT_VMEXTEN; static char default_language[MAX_LANGUAGE] = ""; #define DEFAULT_CALLERID "asterisk" static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID; static char default_fromdomain[AST_MAX_EXTENSION] = ""; #define DEFAULT_NOTIFYMIME "application/simple-message-summary" static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME; static int global_notifyringing = 1; /*!< Send notifications on ringing */ static int global_alwaysauthreject = 0; /*!< Send 401 Unauthorized for all failing requests */ static int default_qualify = 0; /*!< Default Qualify= setting */ static struct ast_flags global_flags = {0}; /*!< global SIP_ flags */ static struct ast_flags global_flags_page2 = {0}; /*!< more global SIP_ flags */ static int srvlookup = 0; /*!< SRV Lookup on or off. Default is off, RFC behavior is on */ static int pedanticsipchecking = 0; /*!< Extra checking ? Default off */ static int autocreatepeer = 0; /*!< Auto creation of peers at registration? Default off. */ static int relaxdtmf = 0; static int global_rtptimeout = 0; static int global_rtpholdtimeout = 0; static int global_rtpkeepalive = 0; static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT; static int global_regattempts_max = 0; /* Object counters */ static int suserobjs = 0; static int ruserobjs = 0; static int speerobjs = 0; static int rpeerobjs = 0; static int apeerobjs = 0; static int regobjs = 0; static int global_allowguest = 1; /*!< allow unauthenticated users/peers to connect? */ #define DEFAULT_MWITIME 10 static int global_mwitime = DEFAULT_MWITIME; /*!< Time between MWI checks for peers */ static int usecnt =0; AST_MUTEX_DEFINE_STATIC(usecnt_lock); AST_MUTEX_DEFINE_STATIC(rand_lock); /*! \brief Protect the interface list (of sip_pvt's) */ AST_MUTEX_DEFINE_STATIC(iflock); /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not when it's doing something critical. */ AST_MUTEX_DEFINE_STATIC(netlock); AST_MUTEX_DEFINE_STATIC(monlock); /*! \brief This is the thread for the monitor which checks for input on the channels which are not currently in use. */ static pthread_t monitor_thread = AST_PTHREADT_NULL; static int restart_monitor(void); /*! \brief Codecs that we support by default: */ static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263; static int noncodeccapability = AST_RTP_DTMF; static struct in_addr __ourip; static struct sockaddr_in outboundproxyip; static int ourport; #define SIP_DEBUG_CONFIG 1 << 0 #define SIP_DEBUG_CONSOLE 1 << 1 static int sipdebug = 0; static struct sockaddr_in debugaddr; static int tos = 0; static int videosupport = 0; static int compactheaders = 0; /*!< send compact sip headers */ static int recordhistory = 0; /*!< Record SIP history. Off by default */ static int dumphistory = 0; /*!< Dump history to verbose before destroying SIP dialog */ static char global_musicclass[MAX_MUSICCLASS] = ""; /*!< Global music on hold class */ #define DEFAULT_REALM "asterisk" static char global_realm[MAXHOSTNAMELEN] = DEFAULT_REALM; /*!< Default realm */ static char regcontext[AST_MAX_CONTEXT] = ""; /*!< Context for auto-extensions */ #define DEFAULT_EXPIRY 900 /*!< Expire slowly */ static int expiry = DEFAULT_EXPIRY; static struct sched_context *sched; static struct io_context *io; #define SIP_MAX_HEADERS 64 /*!< Max amount of SIP headers to read */ #define SIP_MAX_LINES 64 /*!< Max amount of lines in SIP attachment (like SDP) */ #define DEC_CALL_LIMIT 0 #define INC_CALL_LIMIT 1 static struct ast_codec_pref prefs; /*! \brief sip_request: The data grabbed from the UDP socket */ struct sip_request { char *rlPart1; /*!< SIP Method Name or "SIP/2.0" protocol version */ char *rlPart2; /*!< The Request URI or Response Status */ int len; /*!< Length */ int headers; /*!< # of SIP Headers */ int method; /*!< Method of this request */ char *header[SIP_MAX_HEADERS]; int lines; /*!< Body Content */ char *line[SIP_MAX_LINES]; char data[SIP_MAX_PACKET]; int debug; /*!< Debug flag for this packet */ unsigned int flags; /*!< SIP_PKT Flags for this packet */ unsigned int sdp_start; /*!< the line number where the SDP begins */ unsigned int sdp_end; /*!< the line number where the SDP ends */ }; struct sip_pkt; /*! \brief Parameters to the transmit_invite function */ struct sip_invite_param { char *distinctive_ring; /*!< Distinctive ring header */ char *osptoken; /*!< OSP token for this call */ int addsipheaders; /*!< Add extra SIP headers */ char *uri_options; /*!< URI options to add to the URI */ char *vxml_url; /*!< VXML url for Cisco phones */ char *auth; /*!< Authentication */ char *authheader; /*!< Auth header */ enum sip_auth_type auth_type; /*!< Authentication type */ }; struct sip_route { struct sip_route *next; char hop[0]; }; enum domain_mode { SIP_DOMAIN_AUTO, /*!< This domain is auto-configured */ SIP_DOMAIN_CONFIG, /*!< This domain is from configuration */ }; struct domain { char domain[MAXHOSTNAMELEN]; /*!< SIP domain we are responsible for */ char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */ enum domain_mode mode; /*!< How did we find this domain? */ AST_LIST_ENTRY(domain) list; /*!< List mechanics */ }; static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */ int allow_external_domains; /*!< Accept calls to external SIP domains? */ /*! \brief sip_history: Structure for saving transactions within a SIP dialog */ struct sip_history { char event[80]; struct sip_history *next; }; /*! \brief sip_auth: Creadentials for authentication to other SIP services */ struct sip_auth { char realm[AST_MAX_EXTENSION]; /*!< Realm in which these credentials are valid */ char username[256]; /*!< Username */ char secret[256]; /*!< Secret */ char md5secret[256]; /*!< MD5Secret */ struct sip_auth *next; /*!< Next auth structure in list */ }; #define SIP_ALREADYGONE (1 << 0) /*!< Whether or not we've already been destroyed by our peer */ #define SIP_NEEDDESTROY (1 << 1) /*!< if we need to be destroyed */ #define SIP_NOVIDEO (1 << 2) /*!< Didn't get video in invite, don't offer */ #define SIP_RINGING (1 << 3) /*!< Have sent 180 ringing */ #define SIP_PROGRESS_SENT (1 << 4) /*!< Have sent 183 message progress */ #define SIP_NEEDREINVITE (1 << 5) /*!< Do we need to send another reinvite? */ #define SIP_PENDINGBYE (1 << 6) /*!< Need to send bye after we ack? */ #define SIP_GOTREFER (1 << 7) /*!< Got a refer? */ #define SIP_PROMISCREDIR (1 << 8) /*!< Promiscuous redirection */ #define SIP_TRUSTRPID (1 << 9) /*!< Trust RPID headers? */ #define SIP_USEREQPHONE (1 << 10) /*!< Add user=phone to numeric URI. Default off */ #define SIP_REALTIME (1 << 11) /*!< Flag for realtime users */ #define SIP_USECLIENTCODE (1 << 12) /*!< Trust X-ClientCode info message */ #define SIP_OUTGOING (1 << 13) /*!< Is this an outgoing call? */ #define SIP_SELFDESTRUCT (1 << 14) /*!< This is an autocreated peer */ #define SIP_CAN_BYE (1 << 15) /*!< Can we send BYE for this dialog? */ /* --- Choices for DTMF support in SIP channel */ #define SIP_DTMF (3 << 16) /*!< three settings, uses two bits */ #define SIP_DTMF_RFC2833 (0 << 16) /*!< RTP DTMF */ #define SIP_DTMF_INBAND (1 << 16) /*!< Inband audio, only for ULAW/ALAW */ #define SIP_DTMF_INFO (2 << 16) /*!< SIP Info messages */ #define SIP_DTMF_AUTO (3 << 16) /*!< AUTO switch between rfc2833 and in-band DTMF */ /* NAT settings */ #define SIP_NAT (3 << 18) /*!< four settings, uses two bits */ #define SIP_NAT_NEVER (0 << 18) /*!< No nat support */ #define SIP_NAT_RFC3581 (1 << 18) #define SIP_NAT_ROUTE (2 << 18) #define SIP_NAT_ALWAYS (3 << 18) /* re-INVITE related settings */ #define SIP_REINVITE (3 << 20) /*!< two bits used */ #define SIP_CAN_REINVITE (1 << 20) /*!< allow peers to be reinvited to send media directly p2p */ #define SIP_REINVITE_UPDATE (2 << 20) /*!< use UPDATE (RFC3311) when reinviting this peer */ /* "insecure" settings */ #define SIP_INSECURE_PORT (1 << 22) /*!< don't require matching port for incoming requests */ #define SIP_INSECURE_INVITE (1 << 23) /*!< don't require authentication for incoming INVITEs */ /* Sending PROGRESS in-band settings */ #define SIP_PROG_INBAND (3 << 24) /*!< three settings, uses two bits */ #define SIP_PROG_INBAND_NEVER (0 << 24) #define SIP_PROG_INBAND_NO (1 << 24) #define SIP_PROG_INBAND_YES (2 << 24) /* Open Settlement Protocol authentication */ #define SIP_OSPAUTH (3 << 26) /*!< four settings, uses two bits */ #define SIP_OSPAUTH_NO (0 << 26) #define SIP_OSPAUTH_GATEWAY (1 << 26) #define SIP_OSPAUTH_PROXY (2 << 26) #define SIP_OSPAUTH_EXCLUSIVE (3 << 26) /* Call states */ #define SIP_CALL_ONHOLD (1 << 28) #define SIP_CALL_LIMIT (1 << 29) /* Remote Party-ID Support */ #define SIP_SENDRPID (1 << 30) /* Did this connection increment the counter of in-use calls? */ #define SIP_INC_COUNT (1 << 31) #define SIP_FLAGS_TO_COPY \ (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \ SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \ SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE) /* a new page of flags for peer */ #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) #define SIP_PAGE2_RTUPDATE (1 << 1) #define SIP_PAGE2_RTAUTOCLEAR (1 << 2) #define SIP_PAGE2_IGNOREREGEXPIRE (1 << 3) #define SIP_PAGE2_RT_FROMCONTACT (1 << 4) #define SIP_PAGE2_DYNAMIC (1 << 5) /*!< Is this a dynamic peer? */ /* SIP packet flags */ #define SIP_PKT_DEBUG (1 << 0) /*!< Debug this packet */ #define SIP_PKT_WITH_TOTAG (1 << 1) /*!< This packet has a to-tag */ static int global_rtautoclear; /*! \brief sip_pvt: PVT structures are used for each SIP conversation, ie. a call */ static struct sip_pvt { ast_mutex_t lock; /*!< Channel private lock */ int method; /*!< SIP method of this packet */ char callid[128]; /*!< Global CallID */ char randdata[80]; /*!< Random data */ struct ast_codec_pref prefs; /*!< codec prefs */ unsigned int ocseq; /*!< Current outgoing seqno */ unsigned int icseq; /*!< Current incoming seqno */ ast_group_t callgroup; /*!< Call group */ ast_group_t pickupgroup; /*!< Pickup group */ int lastinvite; /*!< Last Cseq of invite */ unsigned int flags; /*!< SIP_ flags */ int timer_t1; /*!< SIP timer T1, ms rtt */ unsigned int sipoptions; /*!< Supported SIP sipoptions on the other end */ int capability; /*!< Special capability (codec) */ int jointcapability; /*!< Supported capability at both ends (codecs ) */ int peercapability; /*!< Supported peer capability */ int prefcodec; /*!< Preferred codec (outbound only) */ int noncodeccapability; int callingpres; /*!< Calling presentation */ int authtries; /*!< Times we've tried to authenticate */ int expiry; /*!< How long we take to expire */ int branch; /*!< One random number */ char tag[11]; /*!< Another random number */ int sessionid; /*!< SDP Session ID */ int sessionversion; /*!< SDP Session Version */ struct sockaddr_in sa; /*!< Our peer */ struct sockaddr_in redirip; /*!< Where our RTP should be going if not to us */ struct sockaddr_in vredirip; /*!< Where our Video RTP should be going if not to us */ int redircodecs; /*!< Redirect codecs */ struct sockaddr_in recv; /*!< Received as */ struct in_addr ourip; /*!< Our IP */ struct ast_channel *owner; /*!< Who owns us */ char exten[AST_MAX_EXTENSION]; /*!< Extension where to start */ char refer_to[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */ char referred_by[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */ char refer_contact[SIP_LEN_CONTACT]; /*!< Place to store Contact info from a REFER extension */ struct sip_pvt *refer_call; /*!< Call we are referring */ struct sip_route *route; /*!< Head of linked list of routing steps (fm Record-Route) */ int route_persistant; /*!< Is this the "real" route? */ char from[256]; /*!< The From: header */ char useragent[256]; /*!< User agent in SIP request */ char context[AST_MAX_CONTEXT]; /*!< Context for this call */ char subscribecontext[AST_MAX_CONTEXT]; /*!< Subscribecontext */ char fromdomain[MAXHOSTNAMELEN]; /*!< Domain to show in the from field */ char fromuser[AST_MAX_EXTENSION]; /*!< User to show in the user field */ char fromname[AST_MAX_EXTENSION]; /*!< Name to show in the user field */ char tohost[MAXHOSTNAMELEN]; /*!< Host we should put in the "to" field */ char language[MAX_LANGUAGE]; /*!< Default language for this call */ char musicclass[MAX_MUSICCLASS]; /*!< Music on Hold class */ char rdnis[256]; /*!< Referring DNIS */ char theirtag[256]; /*!< Their tag */ char username[256]; /*!< [user] name */ char peername[256]; /*!< [peer] name, not set if [user] */ char authname[256]; /*!< Who we use for authentication */ char uri[256]; /*!< Original requested URI */ char okcontacturi[SIP_LEN_CONTACT]; /*!< URI from the 200 OK on INVITE */ char peersecret[256]; /*!< Password */ char peermd5secret[256]; struct sip_auth *peerauth; /*!< Realm authentication */ char cid_num[256]; /*!< Caller*ID */ char cid_name[256]; /*!< Caller*ID */ char via[256]; /*!< Via: header */ char fullcontact[SIP_LEN_CONTACT]; /*!< The Contact: that the UA registers with us */ char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */ char our_contact[SIP_LEN_CONTACT]; /*!< Our contact header */ char *rpid; /*!< Our RPID header */ char *rpid_from; /*!< Our RPID From header */ char realm[MAXHOSTNAMELEN]; /*!< Authorization realm */ char nonce[256]; /*!< Authorization nonce */ int noncecount; /*!< Nonce-count */ char opaque[256]; /*!< Opaque nonsense */ char qop[80]; /*!< Quality of Protection, since SIP wasn't complicated enough yet. */ char domain[MAXHOSTNAMELEN]; /*!< Authorization domain */ char lastmsg[256]; /*!< Last Message sent/received */ int amaflags; /*!< AMA Flags */ int pendinginvite; /*!< Any pending invite */ #ifdef OSP_SUPPORT int osphandle; /*!< OSP Handle for call */ time_t ospstart; /*!< OSP Start time */ unsigned int osptimelimit; /*!< OSP call duration limit */ #endif struct sip_request initreq; /*!< Initial request */ int maxtime; /*!< Max time for first response */ int initid; /*!< Auto-congest ID if appropriate */ int autokillid; /*!< Auto-kill ID */ time_t lastrtprx; /*!< Last RTP received */ time_t lastrtptx; /*!< Last RTP sent */ int rtptimeout; /*!< RTP timeout time */ int rtpholdtimeout; /*!< RTP timeout when on hold */ int rtpkeepalive; /*!< Send RTP packets for keepalive */ enum subscriptiontype subscribed; /*!< Is this call a subscription? */ int stateid; int laststate; /*!< Last known extension state */ int dialogver; struct ast_dsp *vad; /*!< Voice Activation Detection dsp */ struct sip_peer *peerpoke; /*!< If this calls is to poke a peer, which one */ struct sip_registry *registry; /*!< If this is a REGISTER call, to which registry */ struct ast_rtp *rtp; /*!< RTP Session */ struct ast_rtp *vrtp; /*!< Video RTP session */ struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */ struct sip_history *history; /*!< History of this SIP dialog */ struct ast_variable *chanvars; /*!< Channel variables to set for call */ struct sip_pvt *next; /*!< Next call in chain */ struct sip_invite_param *options; /*!< Options for INVITE */ } *iflist = NULL; #define FLAG_RESPONSE (1 << 0) #define FLAG_FATAL (1 << 1) /*! \brief sip packet - read in sipsock_read, transmitted in send_request */ struct sip_pkt { struct sip_pkt *next; /*!< Next packet */ int retrans; /*!< Retransmission number */ int method; /*!< SIP method for this packet */ int seqno; /*!< Sequence number */ unsigned int flags; /*!< non-zero if this is a response packet (e.g. 200 OK) */ struct sip_pvt *owner; /*!< Owner call */ int retransid; /*!< Retransmission ID */ int timer_a; /*!< SIP timer A, retransmission timer */ int timer_t1; /*!< SIP Timer T1, estimated RTT or 500 ms */ int packetlen; /*!< Length of packet */ char data[0]; }; /*! \brief Structure for SIP user data. User's place calls to us */ struct sip_user { /* Users who can access various contexts */ ASTOBJ_COMPONENTS(struct sip_user); char secret[80]; /*!< Password */ char md5secret[80]; /*!< Password in md5 */ char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */ char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */ char cid_num[80]; /*!< Caller ID num */ char cid_name[80]; /*!< Caller ID name */ char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */ char language[MAX_LANGUAGE]; /*!< Default language for this user */ char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */ char useragent[256]; /*!< User agent in SIP request */ struct ast_codec_pref prefs; /*!< codec prefs */ ast_group_t callgroup; /*!< Call group */ ast_group_t pickupgroup; /*!< Pickup Group */ unsigned int flags; /*!< SIP flags */ unsigned int sipoptions; /*!< Supported SIP options */ struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */ int amaflags; /*!< AMA flags for billing */ int callingpres; /*!< Calling id presentation */ int capability; /*!< Codec capability */ int inUse; /*!< Number of calls in use */ int call_limit; /*!< Limit of concurrent calls */ struct ast_ha *ha; /*!< ACL setting */ struct ast_variable *chanvars; /*!< Variables to set for channel created by user */ }; /* Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */ struct sip_peer { ASTOBJ_COMPONENTS(struct sip_peer); /*!< name, refcount, objflags, object pointers */ /*!< peer->name is the unique name of this object */ char secret[80]; /*!< Password */ char md5secret[80]; /*!< Password in MD5 */ struct sip_auth *auth; /*!< Realm authentication list */ char context[AST_MAX_CONTEXT]; /*!< Default context for incoming calls */ char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */ char username[80]; /*!< Temporary username until registration */ char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */ int amaflags; /*!< AMA Flags (for billing) */ char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address */ char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */ char fromuser[80]; /*!< From: user when calling this peer */ char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */ char fullcontact[SIP_LEN_CONTACT]; /*!< Contact registered with us (not in sip.conf) */ char cid_num[80]; /*!< Caller ID num */ char cid_name[80]; /*!< Caller ID name */ int callingpres; /*!< Calling id presentation */ int inUse; /*!< Number of calls in use */ int call_limit; /*!< Limit of concurrent calls */ char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/ char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */ char language[MAX_LANGUAGE]; /*!< Default language for prompts */ char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */ char useragent[256]; /*!< User agent in SIP request (saved from registration) */ struct ast_codec_pref prefs; /*!< codec prefs */ int lastmsgssent; time_t lastmsgcheck; /*!< Last time we checked for MWI */ unsigned int flags; /*!< SIP flags */ unsigned int sipoptions; /*!< Supported SIP options */ struct ast_flags flags_page2; /*!< SIP_PAGE2 flags */ int expire; /*!< When to expire this peer registration */ int capability; /*!< Codec capability */ int rtptimeout; /*!< RTP timeout */ int rtpholdtimeout; /*!< RTP Hold Timeout */ int rtpkeepalive; /*!< Send RTP packets for keepalive */ ast_group_t callgroup; /*!< Call group */ ast_group_t pickupgroup; /*!< Pickup group */ struct ast_dnsmgr_entry *dnsmgr;/*!< DNS refresh manager for peer */ struct sockaddr_in addr; /*!< IP address of peer */ /* Qualification */ struct sip_pvt *call; /*!< Call pointer */ int pokeexpire; /*!< When to expire poke (qualify= checking) */ int lastms; /*!< How long last response took (in ms), or -1 for no response */ int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */ struct timeval ps; /*!< Ping send time */ struct sockaddr_in defaddr; /*!< Default IP address, used until registration */ struct ast_ha *ha; /*!< Access control list */ struct ast_variable *chanvars; /*!< Variables to set for channel created by user */ int lastmsg; }; AST_MUTEX_DEFINE_STATIC(sip_reload_lock); static int sip_reloading = 0; /* States for outbound registrations (with register= lines in sip.conf */ #define REG_STATE_UNREGISTERED 0 #define REG_STATE_REGSENT 1 #define REG_STATE_AUTHSENT 2 #define REG_STATE_REGISTERED 3 #define REG_STATE_REJECTED 4 #define REG_STATE_TIMEOUT 5 #define REG_STATE_NOAUTH 6 #define REG_STATE_FAILED 7 /*! \brief sip_registry: Registrations with other SIP proxies */ struct sip_registry { ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1); int portno; /*!< Optional port override */ char username[80]; /*!< Who we are registering as */ char authuser[80]; /*!< Who we *authenticate* as */ char hostname[MAXHOSTNAMELEN]; /*!< Domain or host we register to */ char secret[80]; /*!< Password in clear text */ char md5secret[80]; /*!< Password in md5 */ char contact[SIP_LEN_CONTACT]; /*!< Contact extension */ char random[80]; int expire; /*!< Sched ID of expiration */ int regattempts; /*!< Number of attempts (since the last success) */ int timeout; /*!< sched id of sip_reg_timeout */ int refresh; /*!< How often to refresh */ struct sip_pvt *call; /*!< create a sip_pvt structure for each outbound "registration call" in progress */ int regstate; /*!< Registration state (see above) */ int callid_valid; /*!< 0 means we haven't chosen callid for this registry yet. */ char callid[128]; /*!< Global CallID for this registry */ unsigned int ocseq; /*!< Sequence number we got to for REGISTERs for this registry */ struct sockaddr_in us; /*!< Who the server thinks we are */ /* Saved headers */ char realm[MAXHOSTNAMELEN]; /*!< Authorization realm */ char nonce[256]; /*!< Authorization nonce */ char domain[MAXHOSTNAMELEN]; /*!< Authorization domain */ char opaque[256]; /*!< Opaque nonsense */ char qop[80]; /*!< Quality of Protection. */ int noncecount; /*!< Nonce-count */ char lastmsg[256]; /*!< Last Message sent/received */ }; /*! \brief The user list: Users and friends ---*/ static struct ast_user_list { ASTOBJ_CONTAINER_COMPONENTS(struct sip_user); } userl; /*! \brief The peer list: Peers and Friends ---*/ static struct ast_peer_list { ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer); } peerl; /*! \brief The register list: Other SIP proxys we register with and call ---*/ static struct ast_register_list { ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry); int recheck; } regl; static int __sip_do_register(struct sip_registry *r); static int sipsock = -1; static struct sockaddr_in bindaddr = { 0, }; static struct sockaddr_in externip; static char externhost[MAXHOSTNAMELEN] = ""; static time_t externexpire = 0; static int externrefresh = 10; static struct ast_ha *localaddr; /* The list of manual NOTIFY types we know how to send */ struct ast_config *notify_types; static struct sip_auth *authl; /*!< Authentication list */ static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req); static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans); static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported); static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header, int stale); static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch); static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch); static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init); static int transmit_reinvite_with_sdp(struct sip_pvt *p); static int transmit_info_with_digit(struct sip_pvt *p, char digit); static int transmit_info_with_vidupdate(struct sip_pvt *p); static int transmit_message_with_text(struct sip_pvt *p, const char *text); static int transmit_refer(struct sip_pvt *p, const char *dest); static int sip_sipredirect(struct sip_pvt *p, const char *dest); static struct sip_peer *temp_peer(const char *name); static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init); static void free_old_route(struct sip_route *route); static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len); static int update_call_counter(struct sip_pvt *fup, int event); static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime); static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime); static int sip_do_reload(void); static int expire_register(void *data); static int callevents = 0; static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause); static int sip_devicestate(void *data); static int sip_sendtext(struct ast_channel *ast, const char *text); static int sip_call(struct ast_channel *ast, char *dest, int timeout); static int sip_hangup(struct ast_channel *ast); static int sip_answer(struct ast_channel *ast); static struct ast_frame *sip_read(struct ast_channel *ast); static int sip_write(struct ast_channel *ast, struct ast_frame *frame); static int sip_indicate(struct ast_channel *ast, int condition); static int sip_transfer(struct ast_channel *ast, const char *dest); static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan); static int sip_senddigit(struct ast_channel *ast, char digit); static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */ static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */ static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm); /* Find authentication for a specific realm */ static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */ static void append_date(struct sip_request *req); /* Append date to SIP packet */ static int determine_firstline_parts(struct sip_request *req); static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */ static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype); static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate); static int sip_addheader(struct ast_channel *chan, void *data); static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize); /*! \brief Definition of this channel for PBX channel registration */ static const struct ast_channel_tech sip_tech = { .type = channeltype, .description = "Session Initiation Protocol (SIP)", .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1), .properties = AST_CHAN_TP_WANTSJITTER, .requester = sip_request_call, .devicestate = sip_devicestate, .call = sip_call, .hangup = sip_hangup, .answer = sip_answer, .read = sip_read, .write = sip_write, .write_video = sip_write, .indicate = sip_indicate, .transfer = sip_transfer, .fixup = sip_fixup, .send_digit = sip_senddigit, .bridge = ast_rtp_bridge, .send_text = sip_sendtext, }; #ifdef __AST_DEBUG_MALLOC static void FREE(void *ptr) { free(ptr); } #else #define FREE free #endif /*! \brief Thread-safe random number generator \return a random number This function uses a mutex lock to guarantee that no two threads will receive the same random number. */ static force_inline int thread_safe_rand(void) { int val; ast_mutex_lock(&rand_lock); val = rand(); ast_mutex_unlock(&rand_lock); return val; } /*! \brief find_sip_method: Find SIP method from header * Strictly speaking, SIP methods are case SENSITIVE, but we don't check * following Jon Postel's rule: Be gentle in what you accept, strict with what you send */ int find_sip_method(char *msg) { int i, res = 0; if (ast_strlen_zero(msg)) return 0; for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) { if (!strcasecmp(sip_methods[i].text, msg)) res = sip_methods[i].id; } return res; } /*! \brief parse_sip_options: Parse supported header in incoming packet */ unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported) { char *next = NULL; char *sep = NULL; char *temp = ast_strdupa(supported); int i; unsigned int profile = 0; if (ast_strlen_zero(supported) ) return 0; if (option_debug > 2 && sipdebug) ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported); next = temp; while (next) { char res=0; if ( (sep = strchr(next, ',')) != NULL) { *sep = '\0'; sep++; } while (*next == ' ') /* Skip spaces */ next++; if (option_debug > 2 && sipdebug) ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next); for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) { if (!strcasecmp(next, sip_options[i].text)) { profile |= sip_options[i].id; res = 1; if (option_debug > 2 && sipdebug) ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next); } } if (!res) if (option_debug > 2 && sipdebug) ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next); next = sep; } if (pvt) { pvt->sipoptions = profile; if (option_debug) ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid); } return profile; } /*! \brief sip_debug_test_addr: See if we pass debug IP filter */ static inline int sip_debug_test_addr(struct sockaddr_in *addr) { if (sipdebug == 0) return 0; if (debugaddr.sin_addr.s_addr) { if (((ntohs(debugaddr.sin_port) != 0) && (debugaddr.sin_port != addr->sin_port)) || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr)) return 0; } return 1; } /*! \brief sip_debug_test_pvt: Test PVT for debugging output */ static inline int sip_debug_test_pvt(struct sip_pvt *p) { if (sipdebug == 0) return 0; return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa)); } /*! \brief __sip_xmit: Transmit SIP message ---*/ static int __sip_xmit(struct sip_pvt *p, char *data, int len) { int res; char iabuf[INET_ADDRSTRLEN]; if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in)); else res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in)); if (res != len) { ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), res, strerror(errno)); } return res; } static void sip_destroy(struct sip_pvt *p); /*! \brief build_via: Build a Via header for a request ---*/ static void build_via(struct sip_pvt *p, char *buf, int len) { char iabuf[INET_ADDRSTRLEN]; /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */ if (ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581) snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch); else /* Work around buggy UNIDEN UIP200 firmware */ snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch); } /*! \brief ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/ /* Only used for outbound registrations */ static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us) { /* * Using the localaddr structure built up with localnet statements * apply it to their address to see if we need to substitute our * externip or can get away with our internal bindaddr */ struct sockaddr_in theirs; theirs.sin_addr = *them; if (localaddr && externip.sin_addr.s_addr && ast_apply_ha(localaddr, &theirs)) { char iabuf[INET_ADDRSTRLEN]; if (externexpire && (time(NULL) >= externexpire)) { struct ast_hostent ahp; struct hostent *hp; time(&externexpire); externexpire += externrefresh; if ((hp = ast_gethostbyname(externhost, &ahp))) { memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr)); } else ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost); } memcpy(us, &externip.sin_addr, sizeof(struct in_addr)); ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr); ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf); } else if (bindaddr.sin_addr.s_addr) memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr)); else return ast_ouraddrfor(them, us); return 0; } /*! \brief append_history: Append to SIP dialog history */ /* Always returns 0 */ static int append_history(struct sip_pvt *p, const char *event, const char *data) { struct sip_history *hist, *prev; char *c; if (!recordhistory || !p) return 0; if(!(hist = malloc(sizeof(struct sip_history)))) { ast_log(LOG_WARNING, "Can't allocate memory for history"); return 0; } memset(hist, 0, sizeof(struct sip_history)); snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data); /* Trim up nicely */ c = hist->event; while(*c) { if ((*c == '\r') || (*c == '\n')) { *c = '\0'; break; } c++; } /* Enqueue into history */ prev = p->history; if (prev) { while(prev->next) prev = prev->next; prev->next = hist; } else { p->history = hist; } return 0; } /*! \brief retrans_pkt: Retransmit SIP message if no answer ---*/ static int retrans_pkt(void *data) { struct sip_pkt *pkt=data, *prev, *cur = NULL; char iabuf[INET_ADDRSTRLEN]; int reschedule = DEFAULT_RETRANS; /* Lock channel */ ast_mutex_lock(&pkt->owner->lock); if (pkt->retrans < MAX_RETRANS) { char buf[80]; pkt->retrans++; if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */ if (sipdebug && option_debug > 3) 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); } else { int siptimer_a; if (sipdebug && option_debug > 3) ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method); if (!pkt->timer_a) pkt->timer_a = 2 ; else pkt->timer_a = 2 * pkt->timer_a; /* For non-invites, a maximum of 4 secs */ siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */ if (pkt->method != SIP_INVITE && siptimer_a > 4000) siptimer_a = 4000; /* Reschedule re-transmit */ reschedule = siptimer_a; if (option_debug > 3) 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); } if (pkt->owner && sip_debug_test_pvt(pkt->owner)) { if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE) ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data); else ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data); } snprintf(buf, sizeof(buf), "ReTx %d", reschedule); append_history(pkt->owner, buf, pkt->data); __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); ast_mutex_unlock(&pkt->owner->lock); return reschedule; } /* Too many retries */ if (pkt->owner && pkt->method != SIP_OPTIONS) { if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */ 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"); } else { if (pkt->method == SIP_OPTIONS && sipdebug) ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid); } append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)"); pkt->retransid = -1; if (ast_test_flag(pkt, FLAG_FATAL)) { while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) { ast_mutex_unlock(&pkt->owner->lock); usleep(1); ast_mutex_lock(&pkt->owner->lock); } if (pkt->owner->owner) { ast_set_flag(pkt->owner, SIP_ALREADYGONE); ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid); ast_queue_hangup(pkt->owner->owner); ast_mutex_unlock(&pkt->owner->owner->lock); } else { /* If no channel owner, destroy now */ ast_set_flag(pkt->owner, SIP_NEEDDESTROY); } } /* In any case, go ahead and remove the packet */ prev = NULL; cur = pkt->owner->packets; while(cur) { if (cur == pkt) break; prev = cur; cur = cur->next; } if (cur) { if (prev) prev->next = cur->next; else pkt->owner->packets = cur->next; ast_mutex_unlock(&pkt->owner->lock); free(cur); pkt = NULL; } else ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n"); if (pkt) ast_mutex_unlock(&pkt->owner->lock); return 0; } /*! \brief __sip_reliable_xmit: transmit packet with retransmits ---*/ static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod) { struct sip_pkt *pkt; int siptimer_a = DEFAULT_RETRANS; pkt = malloc(sizeof(struct sip_pkt) + len + 1); if (!pkt) return -1; memset(pkt, 0, sizeof(struct sip_pkt)); memcpy(pkt->data, data, len); pkt->method = sipmethod; pkt->packetlen = len; pkt->next = p->packets; pkt->owner = p; pkt->seqno = seqno; pkt->flags = resp; pkt->data[len] = '\0'; pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */ if (fatal) ast_set_flag(pkt, FLAG_FATAL); if (pkt->timer_t1) siptimer_a = pkt->timer_t1 * 2; /* Schedule retransmission */ pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1); if (option_debug > 3 && sipdebug) ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid); pkt->next = p->packets; p->packets = pkt; __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */ if (sipmethod == SIP_INVITE) { /* Note this is a pending invite */ p->pendinginvite = seqno; } return 0; } /*! \brief __sip_autodestruct: Kill a call (called by scheduler) ---*/ static int __sip_autodestruct(void *data) { struct sip_pvt *p = data; /* If this is a subscription, tell the phone that we got a timeout */ if (p->subscribed) { p->subscribed = TIMEOUT; transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, 1); /* Send first notification */ p->subscribed = NONE; append_history(p, "Subscribestatus", "timeout"); return 10000; /* Reschedule this destruction so that we know that it's gone */ } /* This scheduled event is now considered done. */ p->autokillid = -1; ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid); append_history(p, "AutoDestroy", ""); if (p->owner) { ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid); ast_queue_hangup(p->owner); } else { sip_destroy(p); } return 0; } /*! \brief sip_scheddestroy: Schedule destruction of SIP call ---*/ static int sip_scheddestroy(struct sip_pvt *p, int ms) { char tmp[80]; if (sip_debug_test_pvt(p)) ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms); if (recordhistory) { snprintf(tmp, sizeof(tmp), "%d ms", ms); append_history(p, "SchedDestroy", tmp); } if (p->autokillid > -1) ast_sched_del(sched, p->autokillid); p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p); return 0; } /*! \brief sip_cancel_destroy: Cancel destruction of SIP call ---*/ static int sip_cancel_destroy(struct sip_pvt *p) { if (p->autokillid > -1) ast_sched_del(sched, p->autokillid); append_history(p, "CancelDestroy", ""); p->autokillid = -1; return 0; } /*! \brief __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/ static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod) { struct sip_pkt *cur, *prev = NULL; int res = -1; int resetinvite = 0; /* Just in case... */ char *msg; msg = sip_methods[sipmethod].text; ast_mutex_lock(&p->lock); cur = p->packets; while(cur) { if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) && ((ast_test_flag(cur, FLAG_RESPONSE)) || (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) { if (!resp && (seqno == p->pendinginvite)) { ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite); p->pendinginvite = 0; resetinvite = 1; } /* this is our baby */ if (prev) prev->next = cur->next; else p->packets = cur->next; if (cur->retransid > -1) { if (sipdebug && option_debug > 3) ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid); ast_sched_del(sched, cur->retransid); } free(cur); res = 0; break; } prev = cur; cur = cur->next; } ast_mutex_unlock(&p->lock); ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found"); return res; } /* Pretend to ack all packets */ static int __sip_pretend_ack(struct sip_pvt *p) { struct sip_pkt *cur=NULL; while(p->packets) { if (cur == p->packets) { ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text); return -1; } cur = p->packets; if (cur->method) __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method); else { /* Unknown packet type */ char *c; char method[128]; ast_copy_string(method, p->packets->data, sizeof(method)); c = ast_skip_blanks(method); /* XXX what ? */ *c = '\0'; __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method)); } } return 0; } /*! \brief __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/ static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod) { struct sip_pkt *cur; int res = -1; char *msg = sip_methods[sipmethod].text; cur = p->packets; while(cur) { if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) && ((ast_test_flag(cur, FLAG_RESPONSE)) || (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) { /* this is our baby */ if (cur->retransid > -1) { if (option_debug > 3 && sipdebug) ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg); ast_sched_del(sched, cur->retransid); } cur->retransid = -1; res = 0; break; } cur = cur->next; } 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"); return res; } static void parse_request(struct sip_request *req); static char *get_header(struct sip_request *req, char *name); static void copy_request(struct sip_request *dst,struct sip_request *src); /*! \brief parse_copy: Copy SIP request, parse it */ static void parse_copy(struct sip_request *dst, struct sip_request *src) { memset(dst, 0, sizeof(*dst)); memcpy(dst->data, src->data, sizeof(dst->data)); dst->len = src->len; parse_request(dst); } /*! \brief send_response: Transmit response on SIP request---*/ static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno) { int res; char iabuf[INET_ADDRSTRLEN]; struct sip_request tmp; char tmpmsg[80]; if (sip_debug_test_pvt(p)) { if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data); else ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data); } if (reliable) { if (recordhistory) { parse_copy(&tmp, req); snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq")); append_history(p, "TxRespRel", tmpmsg); } res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1), req->method); } else { if (recordhistory) { parse_copy(&tmp, req); snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq")); append_history(p, "TxResp", tmpmsg); } res = __sip_xmit(p, req->data, req->len); } if (res > 0) return 0; return res; } /*! \brief send_request: Send SIP Request to the other part of the dialogue ---*/ static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno) { int res; char iabuf[INET_ADDRSTRLEN]; struct sip_request tmp; char tmpmsg[80]; if (sip_debug_test_pvt(p)) { if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data); else ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data); } if (reliable) { if (recordhistory) { parse_copy(&tmp, req); snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq")); append_history(p, "TxReqRel", tmpmsg); } res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method); } else { if (recordhistory) { parse_copy(&tmp, req); snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq")); append_history(p, "TxReq", tmpmsg); } res = __sip_xmit(p, req->data, req->len); } return res; } /*! \brief get_in_brackets: Pick out text in brackets from character string ---*/ /* returns pointer to terminated stripped string. modifies input string. */ static char *get_in_brackets(char *tmp) { char *parse; char *first_quote; char *first_bracket; char *second_bracket; char last_char; parse = tmp; while (1) { first_quote = strchr(parse, '"'); first_bracket = strchr(parse, '<'); if (first_quote && first_bracket && (first_quote < first_bracket)) { last_char = '\0'; for (parse = first_quote + 1; *parse; parse++) { if ((*parse == '"') && (last_char != '\\')) break; last_char = *parse; } if (!*parse) { ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp); return tmp; } parse++; continue; } if (first_bracket) { second_bracket = strchr(first_bracket + 1, '>'); if (second_bracket) { *second_bracket = '\0'; return first_bracket + 1; } else { ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp); return tmp; } } return tmp; } } /*! \brief sip_sendtext: Send SIP MESSAGE text within a call ---*/ /* Called from PBX core text message functions */ static int sip_sendtext(struct ast_channel *ast, const char *text) { struct sip_pvt *p = ast->tech_pvt; int debug=sip_debug_test_pvt(p); if (debug) ast_verbose("Sending text %s on %s\n", text, ast->name); if (!p) return -1; if (ast_strlen_zero(text)) return 0; if (debug) ast_verbose("Really sending text %s on %s\n", text, ast->name); transmit_message_with_text(p, text); return 0; } /*! \brief realtime_update_peer: Update peer object in realtime storage ---*/ static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey) { char port[10]; char ipaddr[20]; char regseconds[20]; time_t nowtime; time(&nowtime); nowtime += expirey; snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */ ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr); snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port)); if (fullcontact) ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL); else ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL); } /*! \brief register_peer_exten: Automatically add peer extension to dial plan ---*/ static void register_peer_exten(struct sip_peer *peer, int onoff) { char multi[256]; char *stringp, *ext; if (!ast_strlen_zero(regcontext)) { ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi)); stringp = multi; while((ext = strsep(&stringp, "&"))) { if (onoff) ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), FREE, channeltype); else ast_context_remove_extension(regcontext, ext, 1, NULL); } } } /*! \brief sip_destroy_peer: Destroy peer object from memory */ static void sip_destroy_peer(struct sip_peer *peer) { /* Delete it, it needs to disappear */ if (peer->call) sip_destroy(peer->call); if (peer->chanvars) { ast_variables_destroy(peer->chanvars); peer->chanvars = NULL; } if (peer->expire > -1) ast_sched_del(sched, peer->expire); if (peer->pokeexpire > -1) ast_sched_del(sched, peer->pokeexpire); register_peer_exten(peer, 0); ast_free_ha(peer->ha); if (ast_test_flag(peer, SIP_SELFDESTRUCT)) apeerobjs--; else if (ast_test_flag(peer, SIP_REALTIME)) rpeerobjs--; else speerobjs--; clear_realm_authentication(peer->auth); peer->auth = (struct sip_auth *) NULL; if (peer->dnsmgr) ast_dnsmgr_release(peer->dnsmgr); free(peer); } /*! \brief update_peer: Update peer data in database (if used) ---*/ static void update_peer(struct sip_peer *p, int expiry) { int rtcachefriends = ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS); if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) && (ast_test_flag(p, SIP_REALTIME) || rtcachefriends)) { realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry); } } /*! \brief realtime_peer: Get peer from realtime storage * Checks the "sippeers" realtime family from extconfig.conf */ static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin) { struct sip_peer *peer=NULL; struct ast_variable *var; struct ast_variable *tmp; char *newpeername = (char *) peername; char iabuf[80]; /* First check on peer name */ if (newpeername) var = ast_load_realtime("sippeers", "name", peername, NULL); else if (sin) { /* Then check on IP address */ ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr); var = ast_load_realtime("sippeers", "host", iabuf, NULL); /* First check for fixed IP hosts */ if (!var) var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL); /* Then check for registred hosts */ } else return NULL; if (!var) return NULL; tmp = var; /* If this is type=user, then skip this object. */ while(tmp) { if (!strcasecmp(tmp->name, "type") && !strcasecmp(tmp->value, "user")) { ast_variables_destroy(var); return NULL; } else if (!newpeername && !strcasecmp(tmp->name, "name")) { newpeername = tmp->value; } tmp = tmp->next; } if (!newpeername) { /* Did not find peer in realtime */ ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf); ast_variables_destroy(var); return (struct sip_peer *) NULL; } /* Peer found in realtime, now build it in memory */ peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)); if (!peer) { ast_variables_destroy(var); return (struct sip_peer *) NULL; } if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) { /* Cache peer */ ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS); if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) { if (peer->expire > -1) { ast_sched_del(sched, peer->expire); } peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer); } ASTOBJ_CONTAINER_LINK(&peerl,peer); } else { ast_set_flag(peer, SIP_REALTIME); } ast_variables_destroy(var); return peer; } /*! \brief sip_addrcmp: Support routine for find_peer ---*/ static int sip_addrcmp(char *name, struct sockaddr_in *sin) { /* We know name is the first field, so we can cast */ struct sip_peer *p = (struct sip_peer *)name; return !(!inaddrcmp(&p->addr, sin) || (ast_test_flag(p, SIP_INSECURE_PORT) && (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))); } /*! \brief find_peer: Locate peer by name or ip address * This is used on incoming SIP message to find matching peer on ip or outgoing message to find matching peer on name */ static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime) { struct sip_peer *p = NULL; if (peer) p = ASTOBJ_CONTAINER_FIND(&peerl,peer); else p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp); if (!p && realtime) { p = realtime_peer(peer, sin); } return p; } /*! \brief sip_destroy_user: Remove user object from in-memory storage ---*/ static void sip_destroy_user(struct sip_user *user) { ast_free_ha(user->ha); if (user->chanvars) { ast_variables_destroy(user->chanvars); user->chanvars = NULL; } if (ast_test_flag(user, SIP_REALTIME)) ruserobjs--; else suserobjs--; free(user); } /*! \brief realtime_user: Load user from realtime storage * Loads user from "sipusers" category in realtime (extconfig.conf) * Users are matched on From: user name (the domain in skipped) */ static struct sip_user *realtime_user(const char *username) { struct ast_variable *var; struct ast_variable *tmp; struct sip_user *user = NULL; var = ast_load_realtime("sipusers", "name", username, NULL); if (!var) return NULL; tmp = var; while (tmp) { if (!strcasecmp(tmp->name, "type") && !strcasecmp(tmp->value, "peer")) { ast_variables_destroy(var); return NULL; } tmp = tmp->next; } user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)); if (!user) { /* No user found */ ast_variables_destroy(var); return NULL; } if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) { ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS); suserobjs++; ASTOBJ_CONTAINER_LINK(&userl,user); } else { /* Move counter from s to r... */ suserobjs--; ruserobjs++; ast_set_flag(user, SIP_REALTIME); } ast_variables_destroy(var); return user; } /*! \brief find_user: Locate user by name * Locates user by name (From: sip uri user name part) first * from in-memory list (static configuration) then from * realtime storage (defined in extconfig.conf) */ static struct sip_user *find_user(const char *name, int realtime) { struct sip_user *u = NULL; u = ASTOBJ_CONTAINER_FIND(&userl,name); if (!u && realtime) { u = realtime_user(name); } return u; } /*! \brief create_addr_from_peer: create address structure from peer reference ---*/ static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer) { char *callhost; if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) && (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) { if (peer->addr.sin_addr.s_addr) { r->sa.sin_family = peer->addr.sin_family; r->sa.sin_addr = peer->addr.sin_addr; r->sa.sin_port = peer->addr.sin_port; } else { r->sa.sin_family = peer->defaddr.sin_family; r->sa.sin_addr = peer->defaddr.sin_addr; r->sa.sin_port = peer->defaddr.sin_port; } memcpy(&r->recv, &r->sa, sizeof(r->recv)); } else { return -1; } ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY); r->capability = peer->capability; r->prefs = peer->prefs; if (r->rtp) { ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE)); ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE)); } if (r->vrtp) { ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE)); ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE)); } ast_copy_string(r->peername, peer->username, sizeof(r->peername)); ast_copy_string(r->authname, peer->username, sizeof(r->authname)); ast_copy_string(r->username, peer->username, sizeof(r->username)); ast_copy_string(r->peersecret, peer->secret, sizeof(r->peersecret)); ast_copy_string(r->peermd5secret, peer->md5secret, sizeof(r->peermd5secret)); ast_copy_string(r->tohost, peer->tohost, sizeof(r->tohost)); ast_copy_string(r->fullcontact, peer->fullcontact, sizeof(r->fullcontact)); if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) { if ((callhost = strchr(r->callid, '@'))) { strncpy(callhost + 1, peer->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2); } } if (ast_strlen_zero(r->tohost)) { if (peer->addr.sin_addr.s_addr) ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->addr.sin_addr); else ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->defaddr.sin_addr); } if (!ast_strlen_zero(peer->fromdomain)) ast_copy_string(r->fromdomain, peer->fromdomain, sizeof(r->fromdomain)); if (!ast_strlen_zero(peer->fromuser)) ast_copy_string(r->fromuser, peer->fromuser, sizeof(r->fromuser)); r->maxtime = peer->maxms; r->callgroup = peer->callgroup; r->pickupgroup = peer->pickupgroup; /* Set timer T1 to RTT for this peer (if known by qualify=) */ if (peer->maxms && peer->lastms) r->timer_t1 = peer->lastms; if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO)) r->noncodeccapability |= AST_RTP_DTMF; else r->noncodeccapability &= ~AST_RTP_DTMF; ast_copy_string(r->context, peer->context,sizeof(r->context)); r->rtptimeout = peer->rtptimeout; r->rtpholdtimeout = peer->rtpholdtimeout; r->rtpkeepalive = peer->rtpkeepalive; if (peer->call_limit) ast_set_flag(r, SIP_CALL_LIMIT); return 0; } /*! \brief create_addr: create address structure from peer name * Or, if peer not found, find it in the global DNS * returns TRUE (-1) on failure, FALSE on success */ static int create_addr(struct sip_pvt *dialog, char *opeer) { struct hostent *hp; struct ast_hostent ahp; struct sip_peer *p; int found=0; char *port, *ptr, *hostp, *hostn; int portno; char host[MAXHOSTNAMELEN]; char peer[256]; ast_copy_string(peer, opeer, sizeof(peer)); port = strchr(peer, ':'); if (port) { *port = '\0'; port++; } dialog->sa.sin_family = AF_INET; dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */ p = find_peer(peer, NULL, 1); if (p) { found++; if (create_addr_from_peer(dialog, p)) ASTOBJ_UNREF(p, sip_destroy_peer); } if (!p) { if (found) return -1; hostn = peer; if (port) portno = atoi(port); else portno = DEFAULT_SIP_PORT; if (srvlookup) { char service[MAXHOSTNAMELEN]; int tportno; int ret; snprintf(service, sizeof(service), "_sip._udp.%s", peer); ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service); if (ret > 0) { hostn = host; portno = tportno; } } if ((hostp = ast_strdupa(hostn))) { if ((ptr = strchr(hostp, '?'))) *ptr = '\0'; } else hostp = peer; hp = ast_gethostbyname(hostp, &ahp); if (hp) { ast_copy_string(dialog->tohost, peer, sizeof(dialog->tohost)); memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr)); dialog->sa.sin_port = htons(portno); memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv)); return 0; } else { ast_log(LOG_WARNING, "No such host: %s\n", peer); return -1; } } else { ASTOBJ_UNREF(p, sip_destroy_peer); return 0; } } /*! \brief auto_congest: Scheduled congestion on a call ---*/ static int auto_congest(void *nothing) { struct sip_pvt *p = nothing; ast_mutex_lock(&p->lock); p->initid = -1; if (p->owner) { if (!ast_mutex_trylock(&p->owner->lock)) { ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name); ast_queue_control(p->owner, AST_CONTROL_CONGESTION); ast_mutex_unlock(&p->owner->lock); } } ast_mutex_unlock(&p->lock); return 0; } /*! \brief sip_call: Initiate SIP call from PBX * used from the dial() application */ static int sip_call(struct ast_channel *ast, char *dest, int timeout) { int res; struct sip_pvt *p; #ifdef OSP_SUPPORT char *osphandle = NULL; #endif struct varshead *headp; struct ast_var_t *current; p = ast->tech_pvt; if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) { ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name); return -1; } /* Check whether there is vxml_url, distinctive ring variables */ headp=&ast->varshead; AST_LIST_TRAVERSE(headp,current,entries) { /* Check whether there is a VXML_URL variable */ if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) { p->options->vxml_url = ast_var_value(current); } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) { p->options->uri_options = ast_var_value(current); } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) { /* Check whether there is a ALERT_INFO variable */ p->options->distinctive_ring = ast_var_value(current); } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) { /* Check whether there is a variable with a name starting with SIPADDHEADER */ p->options->addsipheaders = 1; } #ifdef OSP_SUPPORT else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) { p->options->osptoken = ast_var_value(current); } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) { osphandle = ast_var_value(current); } #endif } res = 0; ast_set_flag(p, SIP_OUTGOING); #ifdef OSP_SUPPORT if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) { /* Force Disable OSP support */ ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle); p->options->osptoken = NULL; osphandle = NULL; p->osphandle = -1; } #endif ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username); res = update_call_counter(p, INC_CALL_LIMIT); if ( res != -1 ) { p->callingpres = ast->cid.cid_pres; p->jointcapability = p->capability; transmit_invite(p, SIP_INVITE, 1, 2); if (p->maxtime) { /* Initialize auto-congest time */ p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p); } } return res; } /*! \brief sip_registry_destroy: Destroy registry object ---*/ /* Objects created with the register= statement in static configuration */ static void sip_registry_destroy(struct sip_registry *reg) { /* Really delete */ if (reg->call) { /* Clear registry before destroying to ensure we don't get reentered trying to grab the registry lock */ reg->call->registry = NULL; sip_destroy(reg->call); } if (reg->expire > -1) ast_sched_del(sched, reg->expire); if (reg->timeout > -1) ast_sched_del(sched, reg->timeout); regobjs--; free(reg); } /*! \brief __sip_destroy: Execute destrucion of call structure, release memory---*/ static void __sip_destroy(struct sip_pvt *p, int lockowner) { struct sip_pvt *cur, *prev = NULL; struct sip_pkt *cp; struct sip_history *hist; if (sip_debug_test_pvt(p)) ast_verbose("Destroying call '%s'\n", p->callid); if (dumphistory) sip_dump_history(p); if (p->options) free(p->options); if (p->stateid > -1) ast_extension_state_del(p->stateid, NULL); if (p->initid > -1) ast_sched_del(sched, p->initid); if (p->autokillid > -1) ast_sched_del(sched, p->autokillid); if (p->rtp) { ast_rtp_destroy(p->rtp); } if (p->vrtp) { ast_rtp_destroy(p->vrtp); } if (p->route) { free_old_route(p->route); p->route = NULL; } if (p->registry) { if (p->registry->call == p) p->registry->call = NULL; ASTOBJ_UNREF(p->registry,sip_registry_destroy); } if (p->rpid) free(p->rpid); if (p->rpid_from) free(p->rpid_from); /* Unlink us from the owner if we have one */ if (p->owner) { if (lockowner) ast_mutex_lock(&p->owner->lock); ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name); p->owner->tech_pvt = NULL; if (lockowner) ast_mutex_unlock(&p->owner->lock); } /* Clear history */ while(p->history) { hist = p->history; p->history = p->history->next; free(hist); } cur = iflist; while(cur) { if (cur == p) { if (prev) prev->next = cur->next; else iflist = cur->next; break; } prev = cur; cur = cur->next; } if (!cur) { ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid); return; } while((cp = p->packets)) { p->packets = p->packets->next; if (cp->retransid > -1) { ast_sched_del(sched, cp->retransid); } free(cp); } if (p->chanvars) { ast_variables_destroy(p->chanvars); p->chanvars = NULL; } ast_mutex_destroy(&p->lock); free(p); } /*! \brief update_call_counter: Handle call_limit for SIP users * Note: This is going to be replaced by app_groupcount * Thought: For realtime, we should propably update storage with inuse counter... */ static int update_call_counter(struct sip_pvt *fup, int event) { char name[256]; int *inuse, *call_limit; int outgoing = ast_test_flag(fup, SIP_OUTGOING); struct sip_user *u = NULL; struct sip_peer *p = NULL; if (option_debug > 2) ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming"); /* Test if we need to check call limits, in order to avoid realtime lookups if we do not need it */ if (!ast_test_flag(fup, SIP_CALL_LIMIT)) return 0; ast_copy_string(name, fup->username, sizeof(name)); /* Check the list of users */ u = find_user(name, 1); if (u) { inuse = &u->inUse; call_limit = &u->call_limit; p = NULL; } else { /* Try to find peer */ if (!p) p = find_peer(fup->peername, NULL, 1); if (p) { inuse = &p->inUse; call_limit = &p->call_limit; ast_copy_string(name, fup->peername, sizeof(name)); } else { if (option_debug > 1) ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name); return 0; } } switch(event) { /* incoming and outgoing affects the inUse counter */ case DEC_CALL_LIMIT: if ( *inuse > 0 ) { if (ast_test_flag(fup,SIP_INC_COUNT)) (*inuse)--; } else { *inuse = 0; } if (option_debug > 1 || sipdebug) { ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit); } break; case INC_CALL_LIMIT: if (*call_limit > 0 ) { if (*inuse >= *call_limit) { ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit); if (u) ASTOBJ_UNREF(u,sip_destroy_user); else ASTOBJ_UNREF(p,sip_destroy_peer); return -1; } } (*inuse)++; ast_set_flag(fup,SIP_INC_COUNT); if (option_debug > 1 || sipdebug) { ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit); } break; default: ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event); } if (u) ASTOBJ_UNREF(u,sip_destroy_user); else ASTOBJ_UNREF(p,sip_destroy_peer); return 0; } /*! \brief sip_destroy: Destroy SIP call structure ---*/ static void sip_destroy(struct sip_pvt *p) { ast_mutex_lock(&iflock); __sip_destroy(p, 1); ast_mutex_unlock(&iflock); } static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal); /*! \brief hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes ---*/ static int hangup_sip2cause(int cause) { /* Possible values taken from causes.h */ switch(cause) { case 603: /* Declined */ case 403: /* Not found */ case 487: /* Call cancelled */ return AST_CAUSE_CALL_REJECTED; case 404: /* Not found */ return AST_CAUSE_UNALLOCATED; case 408: /* No reaction */ return AST_CAUSE_NO_USER_RESPONSE; case 480: /* No answer */ return AST_CAUSE_FAILURE; case 483: /* Too many hops */ return AST_CAUSE_NO_ANSWER; case 486: /* Busy everywhere */ return AST_CAUSE_BUSY; case 488: /* No codecs approved */ return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL; case 500: /* Server internal failure */ return AST_CAUSE_FAILURE; case 501: /* Call rejected */ return AST_CAUSE_FACILITY_REJECTED; case 502: return AST_CAUSE_DESTINATION_OUT_OF_ORDER; case 503: /* Service unavailable */ return AST_CAUSE_CONGESTION; default: return AST_CAUSE_NORMAL; } /* Never reached */ return 0; } /*! \brief hangup_cause2sip: Convert Asterisk hangup causes to SIP codes \verbatim Possible values from causes.h AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED In addition to these, a lot of PRI codes is defined in causes.h ...should we take care of them too ? Quote RFC 3398 ISUP Cause value SIP response ---------------- ------------ 1 unallocated number 404 Not Found 2 no route to network 404 Not found 3 no route to destination 404 Not found 16 normal call clearing --- (*) 17 user busy 486 Busy here 18 no user responding 408 Request Timeout 19 no answer from the user 480 Temporarily unavailable 20 subscriber absent 480 Temporarily unavailable 21 call rejected 403 Forbidden (+) 22 number changed (w/o diagnostic) 410 Gone 22 number changed (w/ diagnostic) 301 Moved Permanently 23 redirection to new destination 410 Gone 26 non-selected user clearing 404 Not Found (=) 27 destination out of order 502 Bad Gateway 28 address incomplete 484 Address incomplete 29 facility rejected 501 Not implemented 31 normal unspecified 480 Temporarily unavailable \endverbatim */ static char *hangup_cause2sip(int cause) { switch(cause) { case AST_CAUSE_UNALLOCATED: /* 1 */ case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */ case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */ return "404 Not Found"; case AST_CAUSE_CONGESTION: /* 34 */ case AST_CAUSE_SWITCH_CONGESTION: /* 42 */ return "503 Service Unavailable"; case AST_CAUSE_NO_USER_RESPONSE: /* 18 */ return "408 Request Timeout"; case AST_CAUSE_NO_ANSWER: /* 19 */ return "480 Temporarily unavailable"; case AST_CAUSE_CALL_REJECTED: /* 21 */ return "403 Forbidden"; case AST_CAUSE_NUMBER_CHANGED: /* 22 */ return "410 Gone"; case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */ return "480 Temporarily unavailable"; case AST_CAUSE_INVALID_NUMBER_FORMAT: return "484 Address incomplete"; case AST_CAUSE_USER_BUSY: return "486 Busy here"; case AST_CAUSE_FAILURE: return "500 Server internal failure"; case AST_CAUSE_FACILITY_REJECTED: /* 29 */ return "501 Not Implemented"; case AST_CAUSE_CHAN_NOT_IMPLEMENTED: return "503 Service Unavailable"; /* Used in chan_iax2 */ case AST_CAUSE_DESTINATION_OUT_OF_ORDER: return "502 Bad Gateway"; case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */ return "488 Not Acceptable Here"; case AST_CAUSE_NOTDEFINED: default: ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause); return NULL; } /* Never reached */ return 0; } /*! \brief sip_hangup: Hangup SIP call * Part of PBX interface, called from ast_hangup */ static int sip_hangup(struct ast_channel *ast) { struct sip_pvt *p = ast->tech_pvt; int needcancel = 0; int needdestroy = 0; if (!p) { ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n"); return 0; } if (option_debug) ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid); ast_mutex_lock(&p->lock); #ifdef OSP_SUPPORT if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) { ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart); } #endif ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter\n", p->username); update_call_counter(p, DEC_CALL_LIMIT); /* Determine how to disconnect */ if (p->owner != ast) { ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n"); ast_mutex_unlock(&p->lock); return 0; } /* If the call is not UP, we need to send CANCEL instead of BYE */ if (ast->_state != AST_STATE_UP) needcancel = 1; /* Disconnect */ if (p->vad) { ast_dsp_free(p->vad); } p->owner = NULL; ast->tech_pvt = NULL; ast_mutex_lock(&usecnt_lock); usecnt--; ast_mutex_unlock(&usecnt_lock); ast_update_use_count(); /* Do not destroy this pvt until we have timeout or get an answer to the BYE or INVITE/CANCEL If we get no answer during retransmit period, drop the call anyway. (Sorry, mother-in-law, you can't deny a hangup by sending 603 declined to BYE...) */ if (ast_test_flag(p, SIP_ALREADYGONE)) needdestroy = 1; /* Set destroy flag at end of this function */ else sip_scheddestroy(p, 32000); /* Start the process if it's not already started */ if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) { if (needcancel) { /* Outgoing call, not up */ if (ast_test_flag(p, SIP_OUTGOING)) { /* stop retransmitting an INVITE that has not received a response */ __sip_pretend_ack(p); /* are we allowed to send CANCEL yet? if not, mark it pending */ if (!ast_test_flag(p, SIP_CAN_BYE)) { ast_set_flag(p, SIP_PENDINGBYE); /* Do we need a timer here if we don't hear from them at all? */ } else { /* Send a new request: CANCEL */ transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0); /* Actually don't destroy us yet, wait for the 487 on our original INVITE, but do set an autodestruct just in case we never get it. */ } if ( p->initid != -1 ) { /* channel still up - reverse dec of inUse counter only if the channel is not auto-congested */ update_call_counter(p, INC_CALL_LIMIT); } } else { /* Incoming call, not up */ char *res; if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) { transmit_response_reliable(p, res, &p->initreq, 1); } else transmit_response_reliable(p, "603 Declined", &p->initreq, 1); } } else { /* Call is in UP state, send BYE */ if (!p->pendinginvite) { /* Send a hangup */ transmit_request_with_auth(p, SIP_BYE, 0, 1, 1); } else { /* Note we will need a BYE when this all settles out but we can't send one while we have "INVITE" outstanding. */ ast_set_flag(p, SIP_PENDINGBYE); ast_clear_flag(p, SIP_NEEDREINVITE); } } } if (needdestroy) ast_set_flag(p, SIP_NEEDDESTROY); ast_mutex_unlock(&p->lock); return 0; } /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */ static void try_suggested_sip_codec(struct sip_pvt *p) { int fmt; char *codec; codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC"); if (!codec) return; fmt = ast_getformatbyname(codec); if (fmt) { ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec); if (p->jointcapability & fmt) { p->jointcapability &= fmt; p->capability &= fmt; } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n"); } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec); return; } /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite * Part of PBX interface */ static int sip_answer(struct ast_channel *ast) { int res = 0; struct sip_pvt *p = ast->tech_pvt; ast_mutex_lock(&p->lock); if (ast->_state != AST_STATE_UP) { #ifdef OSP_SUPPORT time(&p->ospstart); #endif try_suggested_sip_codec(p); ast_setstate(ast, AST_STATE_UP); if (option_debug) ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name); res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1); } ast_mutex_unlock(&p->lock); return res; } /*! \brief sip_write: Send frame to media channel (rtp) ---*/ static int sip_write(struct ast_channel *ast, struct ast_frame *frame) { struct sip_pvt *p = ast->tech_pvt; int res = 0; switch (frame->frametype) { case AST_FRAME_VOICE: if (!(frame->subclass & ast->nativeformats)) { ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n", frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat); return 0; } if (p) { ast_mutex_lock(&p->lock); if (p->rtp) { /* If channel is not up, activate early media session */ if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) { transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0); ast_set_flag(p, SIP_PROGRESS_SENT); } time(&p->lastrtptx); res = ast_rtp_write(p->rtp, frame); } ast_mutex_unlock(&p->lock); } break; case AST_FRAME_VIDEO: if (p) { ast_mutex_lock(&p->lock); if (p->vrtp) { /* Activate video early media */ if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) { transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0); ast_set_flag(p, SIP_PROGRESS_SENT); } time(&p->lastrtptx); res = ast_rtp_write(p->vrtp, frame); } ast_mutex_unlock(&p->lock); } break; case AST_FRAME_IMAGE: return 0; break; default: ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype); return 0; } return res; } /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called. Basically update any ->owner links ----*/ static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan) { struct sip_pvt *p = newchan->tech_pvt; ast_mutex_lock(&p->lock); if (p->owner != oldchan) { ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner); ast_mutex_unlock(&p->lock); return -1; } p->owner = newchan; ast_mutex_unlock(&p->lock); return 0; } /*! \brief sip_senddigit: Send DTMF character on SIP channel */ /* within one call, we're able to transmit in many methods simultaneously */ static int sip_senddigit(struct ast_channel *ast, char digit) { struct sip_pvt *p = ast->tech_pvt; int res = 0; ast_mutex_lock(&p->lock); switch (ast_test_flag(p, SIP_DTMF)) { case SIP_DTMF_INFO: transmit_info_with_digit(p, digit); break; case SIP_DTMF_RFC2833: if (p->rtp) ast_rtp_senddigit(p->rtp, digit); break; case SIP_DTMF_INBAND: res = -1; break; } ast_mutex_unlock(&p->lock); return res; } /*! \brief sip_transfer: Transfer SIP call */ static int sip_transfer(struct ast_channel *ast, const char *dest) { struct sip_pvt *p = ast->tech_pvt; int res; ast_mutex_lock(&p->lock); if (ast->_state == AST_STATE_RING) res = sip_sipredirect(p, dest); else res = transmit_refer(p, dest); ast_mutex_unlock(&p->lock); return res; } /*! \brief sip_indicate: Play indication to user * With SIP a lot of indications is sent as messages, letting the device play the indication - busy signal, congestion etc */ static int sip_indicate(struct ast_channel *ast, int condition) { struct sip_pvt *p = ast->tech_pvt; int res = 0; ast_mutex_lock(&p->lock); switch(condition) { case AST_CONTROL_RINGING: if (ast->_state == AST_STATE_RING) { if (!ast_test_flag(p, SIP_PROGRESS_SENT) || (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) { /* Send 180 ringing if out-of-band seems reasonable */ transmit_response(p, "180 Ringing", &p->initreq); ast_set_flag(p, SIP_RINGING); if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES) break; } else { /* Well, if it's not reasonable, just send in-band */ } } res = -1; break; case AST_CONTROL_BUSY: if (ast->_state != AST_STATE_UP) { transmit_response(p, "486 Busy Here", &p->initreq); ast_set_flag(p, SIP_ALREADYGONE); ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV); break; } res = -1; break; case AST_CONTROL_CONGESTION: if (ast->_state != AST_STATE_UP) { transmit_response(p, "503 Service Unavailable", &p->initreq); ast_set_flag(p, SIP_ALREADYGONE); ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV); break; } res = -1; break; case AST_CONTROL_PROCEEDING: if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) { transmit_response(p, "100 Trying", &p->initreq); break; } res = -1; break; case AST_CONTROL_PROGRESS: if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) { transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0); ast_set_flag(p, SIP_PROGRESS_SENT); break; } res = -1; break; case AST_CONTROL_HOLD: /* The other part of the bridge are put on hold */ if (sipdebug) ast_log(LOG_DEBUG, "Bridged channel now on hold%s\n", p->callid); res = -1; break; case AST_CONTROL_UNHOLD: /* The other part of the bridge are back from hold */ if (sipdebug) ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid); res = -1; break; case AST_CONTROL_VIDUPDATE: /* Request a video frame update */ if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) { transmit_info_with_vidupdate(p); res = 0; } else res = -1; break; case -1: res = -1; break; default: ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition); res = -1; break; } ast_mutex_unlock(&p->lock); return res; } /*! \brief sip_new: Initiate a call in the SIP channel */ /* called from sip_request_call (calls from the pbx ) */ static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title) { struct ast_channel *tmp; struct ast_variable *v = NULL; int fmt; #ifdef OSP_SUPPORT char iabuf[INET_ADDRSTRLEN]; char peer[MAXHOSTNAMELEN]; #endif ast_mutex_unlock(&i->lock); /* Don't hold a sip pvt lock while we allocate a channel */ tmp = ast_channel_alloc(1); ast_mutex_lock(&i->lock); if (!tmp) { ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n"); return NULL; } tmp->tech = &sip_tech; /* Select our native format based on codec preference until we receive something from another device to the contrary. */ if (i->jointcapability) tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1); else if (i->capability) tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1); else tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1); fmt = ast_best_codec(tmp->nativeformats); if (title) snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", title, (int)(long) i); else if (strchr(i->fromdomain,':')) snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':') + 1, (int)(long) i); else snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long) i); tmp->type = channeltype; if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) { i->vad = ast_dsp_new(); ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT); if (relaxdtmf) ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF); } if (i->rtp) { tmp->fds[0] = ast_rtp_fd(i->rtp); tmp->fds[1] = ast_rtcp_fd(i->rtp); } if (i->vrtp) { tmp->fds[2] = ast_rtp_fd(i->vrtp); tmp->fds[3] = ast_rtcp_fd(i->vrtp); } if (state == AST_STATE_RING) tmp->rings = 1; tmp->adsicpe = AST_ADSI_UNAVAILABLE; tmp->writeformat = fmt; tmp->rawwriteformat = fmt; tmp->readformat = fmt; tmp->rawreadformat = fmt; tmp->tech_pvt = i; tmp->callgroup = i->callgroup; tmp->pickupgroup = i->pickupgroup; tmp->cid.cid_pres = i->callingpres; if (!ast_strlen_zero(i->accountcode)) ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)); if (i->amaflags) tmp->amaflags = i->amaflags; if (!ast_strlen_zero(i->language)) ast_copy_string(tmp->language, i->language, sizeof(tmp->language)); if (!ast_strlen_zero(i->musicclass)) ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass)); i->owner = tmp; ast_copy_string(tmp->context, i->context, sizeof(tmp->context)); ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten)); if (!ast_strlen_zero(i->cid_num)) tmp->cid.cid_num = strdup(i->cid_num); if (!ast_strlen_zero(i->cid_name)) tmp->cid.cid_name = strdup(i->cid_name); if (!ast_strlen_zero(i->rdnis)) tmp->cid.cid_rdnis = strdup(i->rdnis); if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) tmp->cid.cid_dnid = strdup(i->exten); tmp->priority = 1; if (!ast_strlen_zero(i->uri)) { pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri); } if (!ast_strlen_zero(i->domain)) { pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain); } if (!ast_strlen_zero(i->useragent)) { pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent); } if (!ast_strlen_zero(i->callid)) { pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid); } #ifdef OSP_SUPPORT snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port)); pbx_builtin_setvar_helper(tmp, "OSPPEER", peer); #endif ast_setstate(tmp, state); if (state != AST_STATE_DOWN) { if (ast_pbx_start(tmp)) { ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name); ast_hangup(tmp); tmp = NULL; } } /* Set channel variables for this call from configuration */ for (v = i->chanvars ; v ; v = v->next) pbx_builtin_setvar_helper(tmp,v->name,v->value); ast_mutex_lock(&usecnt_lock); usecnt++; ast_mutex_unlock(&usecnt_lock); ast_update_use_count(); return tmp; } /*! \brief get_body_by_line: Reads one line of message body */ static char *get_body_by_line(char *line, char *name, int nameLen) { if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') { return ast_skip_blanks(line + nameLen + 1); } return ""; } /*! \brief get_sdp: get a specific line from the SDP */ static char *get_sdp(struct sip_request *req, char *name) { int x; int len = strlen(name); char *r; for (x = req->sdp_start; x < req->sdp_end; x++) { r = get_body_by_line(req->line[x], name, len); if (r[0] != '\0') return r; } return ""; } static void sdpLineNum_iterator_init(int *iterator, struct sip_request *req) { *iterator = req->sdp_start; } static char *get_sdp_iterate(int *iterator, struct sip_request *req, char *name) { int len = strlen(name); char *r; while (*iterator < req->sdp_end) { r = get_body_by_line(req->line[(*iterator)++], name, len); if (r[0] != '\0') return r; } return ""; } /*! \brief get_body: get a specific line from the message body */ static char *get_body(struct sip_request *req, char *name) { int x; int len = strlen(name); char *r; for (x = 0; x < req->lines; x++) { r = get_body_by_line(req->line[x], name, len); if (r[0] != '\0') return r; } return ""; } static char *find_alias(const char *name, char *_default) { int x; for (x=0;xheaders; x++) { if (!strncasecmp(req->header[x], name, len)) { char *r = req->header[x] + len; /* skip name */ if (pedanticsipchecking) r = ast_skip_blanks(r); if (*r == ':') { *start = x+1; return ast_skip_blanks(r+1); } } } if (pass == 0) /* Try aliases */ name = find_alias(name, NULL); } /* Don't return NULL, so get_header is always a valid pointer */ return ""; } /*! \brief get_header: Get header from SIP request ---*/ static char *get_header(struct sip_request *req, char *name) { int start = 0; return __get_header(req, name, &start); } /*! \brief sip_rtp_read: Read RTP from network ---*/ static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p) { /* Retrieve audio/etc from channel. Assumes p->lock is already held. */ struct ast_frame *f; static struct ast_frame null_frame = { AST_FRAME_NULL, }; if (!p->rtp) { /* We have no RTP allocated for this channel */ return &null_frame; } switch(ast->fdno) { case 0: f = ast_rtp_read(p->rtp); /* RTP Audio */ break; case 1: f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */ break; case 2: f = ast_rtp_read(p->vrtp); /* RTP Video */ break; case 3: f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */ break; default: f = &null_frame; } /* Don't forward RFC2833 if we're not supposed to */ if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833)) return &null_frame; if (p->owner) { /* We already hold the channel lock */ if (f->frametype == AST_FRAME_VOICE) { if (f->subclass != p->owner->nativeformats) { ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass); p->owner->nativeformats = f->subclass; ast_set_read_format(p->owner, p->owner->readformat); ast_set_write_format(p->owner, p->owner->writeformat); } if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) { f = ast_dsp_process(p->owner, p->vad, f); if (f && (f->frametype == AST_FRAME_DTMF)) ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass); } } } return f; } /*! \brief sip_read: Read SIP RTP from channel */ static struct ast_frame *sip_read(struct ast_channel *ast) { struct ast_frame *fr; struct sip_pvt *p = ast->tech_pvt; ast_mutex_lock(&p->lock); fr = sip_rtp_read(ast, p); time(&p->lastrtprx); ast_mutex_unlock(&p->lock); return fr; } /*! \brief build_callid: Build SIP CALLID header ---*/ static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain) { int res; int val; int x; char iabuf[INET_ADDRSTRLEN]; for (x=0; x<4; x++) { val = thread_safe_rand(); res = snprintf(callid, len, "%08x", val); len -= res; callid += res; } if (!ast_strlen_zero(fromdomain)) snprintf(callid, len, "@%s", fromdomain); else /* It's not important that we really use our right IP here... */ snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip)); } static void make_our_tag(char *tagbuf, size_t len) { snprintf(tagbuf, len, "as%08x", thread_safe_rand()); } /*! \brief sip_alloc: Allocate SIP_PVT structure and set defaults ---*/ static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method) { struct sip_pvt *p; if (!(p = calloc(1, sizeof(*p)))) return NULL; ast_mutex_init(&p->lock); p->method = intended_method; p->initid = -1; p->autokillid = -1; p->subscribed = NONE; p->stateid = -1; p->prefs = prefs; if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */ p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */ #ifdef OSP_SUPPORT p->osphandle = -1; p->osptimelimit = 0; #endif if (sin) { memcpy(&p->sa, sin, sizeof(p->sa)); if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip)) memcpy(&p->ourip, &__ourip, sizeof(p->ourip)); } else { memcpy(&p->ourip, &__ourip, sizeof(p->ourip)); } p->branch = thread_safe_rand(); make_our_tag(p->tag, sizeof(p->tag)); /* Start with 101 instead of 1 */ p->ocseq = 101; if (sip_methods[intended_method].need_rtp) { p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr); if (videosupport) p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr); if (!p->rtp || (videosupport && !p->vrtp)) { ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n", videosupport ? "and video" : "", strerror(errno)); ast_mutex_destroy(&p->lock); if (p->chanvars) { ast_variables_destroy(p->chanvars); p->chanvars = NULL; } free(p); return NULL; } ast_rtp_settos(p->rtp, tos); if (p->vrtp) ast_rtp_settos(p->vrtp, tos); p->rtptimeout = global_rtptimeout; p->rtpholdtimeout = global_rtpholdtimeout; p->rtpkeepalive = global_rtpkeepalive; } if (useglobal_nat && sin) { /* Setup NAT structure according to global settings if we have an address */ ast_copy_flags(p, &global_flags, SIP_NAT); memcpy(&p->recv, sin, sizeof(p->recv)); if (p->rtp) ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)); if (p->vrtp) ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)); } if (p->method != SIP_REGISTER) ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain)); build_via(p, p->via, sizeof(p->via)); if (!callid) build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain); else ast_copy_string(p->callid, callid, sizeof(p->callid)); ast_copy_flags(p, &global_flags, SIP_FLAGS_TO_COPY); /* Assign default music on hold class */ strcpy(p->musicclass, global_musicclass); p->capability = global_capability; if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO)) p->noncodeccapability |= AST_RTP_DTMF; strcpy(p->context, default_context); /* Add to active dialog list */ ast_mutex_lock(&iflock); p->next = iflist; iflist = p; ast_mutex_unlock(&iflock); if (option_debug) ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP"); return p; } /*! \brief find_call: Connect incoming SIP message to current dialog or create new dialog structure */ /* Called by handle_request, sipsock_read */ static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method) { struct sip_pvt *p; char *callid; char *tag = ""; char totag[128]; char fromtag[128]; callid = get_header(req, "Call-ID"); if (pedanticsipchecking) { /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy we need more to identify a branch - so we have to check branch, from and to tags to identify a call leg. For Asterisk to behave correctly, you need to turn on pedanticsipchecking in sip.conf */ if (gettag(req, "To", totag, sizeof(totag))) ast_set_flag(req, SIP_PKT_WITH_TOTAG); /* Used in handle_request/response */ gettag(req, "From", fromtag, sizeof(fromtag)); if (req->method == SIP_RESPONSE) tag = totag; else tag = fromtag; if (option_debug > 4 ) ast_log(LOG_DEBUG, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag); } ast_mutex_lock(&iflock); p = iflist; while(p) { /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */ int found = 0; if (req->method == SIP_REGISTER) found = (!strcmp(p->callid, callid)); else found = (!strcmp(p->callid, callid) && (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ; if (option_debug > 4) ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag); /* If we get a new request within an existing to-tag - check the to tag as well */ if (pedanticsipchecking && found && req->method != SIP_RESPONSE) { /* SIP Request */ if (p->tag[0] == '\0' && totag[0]) { /* We have no to tag, but they have. Wrong dialog */ found = 0; } else if (totag[0]) { /* Both have tags, compare them */ if (strcmp(totag, p->tag)) { found = 0; /* This is not our packet */ } } if (!found && option_debug > 4) ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text); } if (found) { /* Found the call */ ast_mutex_lock(&p->lock); ast_mutex_unlock(&iflock); return p; } p = p->next; } ast_mutex_unlock(&iflock); p = sip_alloc(callid, sin, 1, intended_method); if (p) ast_mutex_lock(&p->lock); return p; } /*! \brief sip_register: Parse register=> line in sip.conf and add to registry */ static int sip_register(char *value, int lineno) { struct sip_registry *reg; char copy[256]; char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL; char *porta=NULL; char *contact=NULL; char *stringp=NULL; if (!value) return -1; ast_copy_string(copy, value, sizeof(copy)); stringp=copy; username = stringp; hostname = strrchr(stringp, '@'); if (hostname) { *hostname = '\0'; hostname++; } if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) { ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno); return -1; } stringp=username; username = strsep(&stringp, ":"); if (username) { secret = strsep(&stringp, ":"); if (secret) authuser = strsep(&stringp, ":"); } stringp = hostname; hostname = strsep(&stringp, "/"); if (hostname) contact = strsep(&stringp, "/"); if (ast_strlen_zero(contact)) contact = "s"; stringp=hostname; hostname = strsep(&stringp, ":"); porta = strsep(&stringp, ":"); if (porta && !atoi(porta)) { ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno); return -1; } reg = malloc(sizeof(struct sip_registry)); if (!reg) { ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n"); return -1; } memset(reg, 0, sizeof(struct sip_registry)); regobjs++; ASTOBJ_INIT(reg); ast_copy_string(reg->contact, contact, sizeof(reg->contact)); if (username) ast_copy_string(reg->username, username, sizeof(reg->username)); if (hostname) ast_copy_string(reg->hostname, hostname, sizeof(reg->hostname)); if (authuser) ast_copy_string(reg->authuser, authuser, sizeof(reg->authuser)); if (secret) ast_copy_string(reg->secret, secret, sizeof(reg->secret)); reg->expire = -1; reg->timeout = -1; reg->refresh = default_expiry; reg->portno = porta ? atoi(porta) : 0; reg->callid_valid = 0; reg->ocseq = 101; ASTOBJ_CONTAINER_LINK(®l, reg); ASTOBJ_UNREF(reg,sip_registry_destroy); return 0; } /*! \brief lws2sws: Parse multiline SIP headers into one header */ /* This is enabled if pedanticsipchecking is enabled */ static int lws2sws(char *msgbuf, int len) { int h = 0, t = 0; int lws = 0; for (; h < len;) { /* Eliminate all CRs */ if (msgbuf[h] == '\r') { h++; continue; } /* Check for end-of-line */ if (msgbuf[h] == '\n') { /* Check for end-of-message */ if (h + 1 == len) break; /* Check for a continuation line */ if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { /* Merge continuation line */ h++; continue; } /* Propagate LF and start new line */ msgbuf[t++] = msgbuf[h++]; lws = 0; continue; } if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { if (lws) { h++; continue; } msgbuf[t++] = msgbuf[h++]; lws = 1; continue; } msgbuf[t++] = msgbuf[h++]; if (lws) lws = 0; } msgbuf[t] = '\0'; return t; } /*! \brief parse_request: Parse a SIP message ----*/ static void parse_request(struct sip_request *req) { /* Divide fields by NULL's */ char *c; int f = 0; c = req->data; /* First header starts immediately */ req->header[f] = c; while(*c) { if (*c == '\n') { /* We've got a new header */ *c = 0; if (sipdebug && option_debug > 3) ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f])); if (ast_strlen_zero(req->header[f])) { /* Line by itself means we're now in content */ c++; break; } if (f >= SIP_MAX_HEADERS - 1) { ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n"); } else f++; req->header[f] = c + 1; } else if (*c == '\r') { /* Ignore but eliminate \r's */ *c = 0; } c++; } /* Check for last header */ if (!ast_strlen_zero(req->header[f])) { if (sipdebug && option_debug > 3) ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f])); f++; } req->headers = f; /* Now we process any mime content */ f = 0; req->line[f] = c; while(*c) { if (*c == '\n') { /* We've got a new line */ *c = 0; if (sipdebug && option_debug > 3) ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f])); if (f >= SIP_MAX_LINES - 1) { ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n"); } else f++; req->line[f] = c + 1; } else if (*c == '\r') { /* Ignore and eliminate \r's */ *c = 0; } c++; } /* Check for last line */ if (!ast_strlen_zero(req->line[f])) f++; req->lines = f; if (*c) ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c); /* Split up the first line parts */ determine_firstline_parts(req); } /*! \brief Determine whether a SIP message contains an SDP in its body \param req the SIP request to process \return 1 if SDP found, 0 if not found Also updates req->sdp_start and req->sdp_end to indicate where the SDP lives in the message body. */ static int find_sdp(struct sip_request *req) { char *content_type; char *search; char *boundary; unsigned int x; content_type = get_header(req, "Content-Type"); /* if the body contains only SDP, this is easy */ if (!strcasecmp(content_type, "application/sdp")) { req->sdp_start = 0; req->sdp_end = req->lines; return 1; } /* if it's not multipart/mixed, there cannot be an SDP */ if (strncasecmp(content_type, "multipart/mixed", 15)) return 0; /* if there is no boundary marker, it's invalid */ if (!(search = strcasestr(content_type, ";boundary="))) return 0; search += 10; if (ast_strlen_zero(search)) return 0; /* make a duplicate of the string, with two extra characters at the beginning */ boundary = ast_strdupa(search - 2); boundary[0] = boundary[1] = '-'; /* search for the boundary marker, but stop when there are not enough lines left for it, the Content-Type header and at least one line of body */ for (x = 0; x < (req->lines - 2); x++) { if (!strncasecmp(req->line[x], boundary, strlen(boundary)) && !strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) { req->sdp_start = x + 2; /* search for the end of the body part */ for ( ; x < req->lines; x++) { if (!strncasecmp(req->line[x], boundary, strlen(boundary))) break; } req->sdp_end = x; return 1; } } return 0; } /*! \brief process_sdp: Process SIP SDP and activate RTP channels---*/ static int process_sdp(struct sip_pvt *p, struct sip_request *req) { char *m; char *c; char *a; char host[258]; char iabuf[INET_ADDRSTRLEN]; int len = -1; int portno = -1; int vportno = -1; int peercapability, peernoncodeccapability; int vpeercapability=0, vpeernoncodeccapability=0; struct sockaddr_in sin; char *codecs; struct hostent *hp; struct ast_hostent ahp; int codec; int destiterator = 0; int iterator; int sendonly = 0; int x,y; int debug=sip_debug_test_pvt(p); struct ast_channel *bridgepeer = NULL; if (!p->rtp) { ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n"); return -1; } /* Update our last rtprx when we receive an SDP, too */ time(&p->lastrtprx); time(&p->lastrtptx); m = get_sdp(req, "m"); sdpLineNum_iterator_init(&destiterator, req); c = get_sdp_iterate(&destiterator, req, "c"); if (ast_strlen_zero(m) || ast_strlen_zero(c)) { ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c); return -1; } if (sscanf(c, "IN IP4 %256s", host) != 1) { ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c); return -1; } /* XXX This could block for a long time, and block the main thread! XXX */ hp = ast_gethostbyname(host, &ahp); if (!hp) { ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c); return -1; } sdpLineNum_iterator_init(&iterator, req); ast_set_flag(p, SIP_NOVIDEO); while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') { int found = 0; if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2) || (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) { found = 1; portno = x; /* Scan through the RTP payload types specified in a "m=" line: */ ast_rtp_pt_clear(p->rtp); codecs = m + len; while(!ast_strlen_zero(codecs)) { if (sscanf(codecs, "%d%n", &codec, &len) != 1) { ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs); return -1; } if (debug) ast_verbose("Found RTP audio format %d\n", codec); ast_rtp_set_m_type(p->rtp, codec); codecs = ast_skip_blanks(codecs + len); } } if (p->vrtp) ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */ if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) { found = 1; ast_clear_flag(p, SIP_NOVIDEO); vportno = x; /* Scan through the RTP payload types specified in a "m=" line: */ codecs = m + len; while(!ast_strlen_zero(codecs)) { if (sscanf(codecs, "%d%n", &codec, &len) != 1) { ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs); return -1; } if (debug) ast_verbose("Found RTP video format %d\n", codec); ast_rtp_set_m_type(p->vrtp, codec); codecs = ast_skip_blanks(codecs + len); } } if (!found ) ast_log(LOG_WARNING, "Unknown SDP media type in offer: %s\n", m); } if (portno == -1 && vportno == -1) { /* No acceptable offer found in SDP */ return -2; } /* Check for Media-description-level-address for audio */ c = get_sdp_iterate(&destiterator, req, "c"); if (!ast_strlen_zero(c)) { if (sscanf(c, "IN IP4 %256s", host) != 1) { ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c); } else { /* XXX This could block for a long time, and block the main thread! XXX */ hp = ast_gethostbyname(host, &ahp); if (!hp) { ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c); } } } /* RTP addresses and ports for audio and video */ sin.sin_family = AF_INET; memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr)); /* Setup audio port number */ sin.sin_port = htons(portno); if (p->rtp && sin.sin_port) { ast_rtp_set_peer(p->rtp, &sin); if (debug) { ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port)); ast_log(LOG_DEBUG,"Peer audio RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port)); } } /* Check for Media-description-level-address for video */ c = get_sdp_iterate(&destiterator, req, "c"); if (!ast_strlen_zero(c)) { if (sscanf(c, "IN IP4 %256s", host) != 1) { ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c); } else { /* XXX This could block for a long time, and block the main thread! XXX */ hp = ast_gethostbyname(host, &ahp); if (!hp) { ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c); } } } /* Setup video port number */ sin.sin_port = htons(vportno); if (p->vrtp && sin.sin_port) { ast_rtp_set_peer(p->vrtp, &sin); if (debug) { ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port)); ast_log(LOG_DEBUG,"Peer video RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port)); } } /* Next, scan through each "a=rtpmap:" line, noting each * specified RTP payload type (with corresponding MIME subtype): */ sdpLineNum_iterator_init(&iterator, req); while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') { char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */ if (!strcasecmp(a, "sendonly") || !strcasecmp(a, "inactive")) { sendonly = 1; continue; } if (!strcasecmp(a, "sendrecv")) { sendonly = 0; } if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue; if (debug) ast_verbose("Found description format %s\n", mimeSubtype); /* Note: should really look at the 'freq' and '#chans' params too */ ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype); if (p->vrtp) ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype); } /* Now gather all of the codecs that were asked for: */ ast_rtp_get_current_formats(p->rtp, &peercapability, &peernoncodeccapability); if (p->vrtp) ast_rtp_get_current_formats(p->vrtp, &vpeercapability, &vpeernoncodeccapability); p->jointcapability = p->capability & (peercapability | vpeercapability); p->peercapability = (peercapability | vpeercapability); p->noncodeccapability = noncodeccapability & peernoncodeccapability; if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO) { ast_clear_flag(p, SIP_DTMF); if (p->noncodeccapability & AST_RTP_DTMF) { /* XXX Would it be reasonable to drop the DSP at this point? XXX */ ast_set_flag(p, SIP_DTMF_RFC2833); } else { ast_set_flag(p, SIP_DTMF_INBAND); } } if (debug) { /* shame on whoever coded this.... */ const unsigned slen=512; char s1[slen], s2[slen], s3[slen], s4[slen]; ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n", ast_getformatname_multiple(s1, slen, p->capability), ast_getformatname_multiple(s2, slen, peercapability), ast_getformatname_multiple(s3, slen, vpeercapability), ast_getformatname_multiple(s4, slen, p->jointcapability)); ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n", ast_rtp_lookup_mime_multiple(s1, slen, noncodeccapability, 0), ast_rtp_lookup_mime_multiple(s2, slen, peernoncodeccapability, 0), ast_rtp_lookup_mime_multiple(s3, slen, p->noncodeccapability, 0)); } if (!p->jointcapability) { ast_log(LOG_NOTICE, "No compatible codecs!\n"); return -1; } if (!p->owner) /* There's no open channel owning us */ return 0; if (!(p->owner->nativeformats & p->jointcapability)) { const unsigned slen=512; char s1[slen], s2[slen]; ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n", ast_getformatname_multiple(s1, slen, p->jointcapability), ast_getformatname_multiple(s2, slen, p->owner->nativeformats)); p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1); ast_set_read_format(p->owner, p->owner->readformat); ast_set_write_format(p->owner, p->owner->writeformat); } if ((bridgepeer=ast_bridged_channel(p->owner))) { /* We have a bridge */ /* Turn on/off music on hold if we are holding/unholding */ struct ast_frame af = { AST_FRAME_NULL, }; if (sin.sin_addr.s_addr && !sendonly) { ast_moh_stop(bridgepeer); /* Activate a re-invite */ ast_queue_frame(p->owner, &af); } else { /* No address for RTP, we're on hold */ ast_moh_start(bridgepeer, NULL); if (sendonly) ast_rtp_stop(p->rtp); /* Activate a re-invite */ ast_queue_frame(p->owner, &af); } } /* Manager Hold and Unhold events must be generated, if necessary */ if (sin.sin_addr.s_addr && !sendonly) { append_history(p, "Unhold", req->data); if (callevents && ast_test_flag(p, SIP_CALL_ONHOLD)) { manager_event(EVENT_FLAG_CALL, "Unhold", "Channel: %s\r\n" "Uniqueid: %s\r\n", p->owner->name, p->owner->uniqueid); } ast_clear_flag(p, SIP_CALL_ONHOLD); } else { /* No address for RTP, we're on hold */ append_history(p, "Hold", req->data); if (callevents && !ast_test_flag(p, SIP_CALL_ONHOLD)) { manager_event(EVENT_FLAG_CALL, "Hold", "Channel: %s\r\n" "Uniqueid: %s\r\n", p->owner->name, p->owner->uniqueid); } ast_set_flag(p, SIP_CALL_ONHOLD); } return 0; } /*! \brief add_header: Add header to SIP message */ static int add_header(struct sip_request *req, const char *var, const char *value) { int x = 0; if (req->headers == SIP_MAX_HEADERS) { ast_log(LOG_WARNING, "Out of SIP header space\n"); return -1; } if (req->lines) { ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n"); return -1; } if (req->len >= sizeof(req->data) - 4) { ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value); return -1; } req->header[req->headers] = req->data + req->len; if (compactheaders) { for (x = 0; x < (sizeof(aliases) / sizeof(aliases[0])); x++) if (!strcasecmp(aliases[x].fullname, var)) var = aliases[x].shortname; } snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value); req->len += strlen(req->header[req->headers]); req->headers++; return 0; } /*! \brief add_header_contentLen: Add 'Content-Length' header to SIP message */ static int add_header_contentLength(struct sip_request *req, int len) { char clen[10]; snprintf(clen, sizeof(clen), "%d", len); return add_header(req, "Content-Length", clen); } /*! \brief add_blank_header: Add blank header to SIP message */ static int add_blank_header(struct sip_request *req) { if (req->headers == SIP_MAX_HEADERS) { ast_log(LOG_WARNING, "Out of SIP header space\n"); return -1; } if (req->lines) { ast_log(LOG_WARNING, "Can't add more headers when lines have