/* CallWeaver -- An open source telephony toolkit. * * Copyright (C) 1999 - 2005, Digium, Inc. * * Mark Spencer * * See http://www.callweaver.org for more information about * the CallWeaver 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 */ #ifdef HAVE_CONFIG_H #include "confdefs.h" #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "callweaver.h" CALLWEAVER_FILE_VERSION("$HeadURL$", "$Revision$") #include "callweaver/lock.h" #include "callweaver/channel.h" #include "callweaver/config.h" #include "callweaver/logger.h" #include "callweaver/module.h" #include "callweaver/pbx.h" #include "callweaver/options.h" #include "callweaver/lock.h" #include "callweaver/sched.h" #include "callweaver/io.h" #include "callweaver/rtp.h" #include "callweaver/udptl.h" //#include "callweaver/tpkt.h" #include "callweaver/acl.h" #include "callweaver/manager.h" #include "callweaver/phone_no_utils.h" #include "callweaver/cli.h" #include "callweaver/app.h" #include "callweaver/musiconhold.h" #include "callweaver/dsp.h" #include "callweaver/features.h" #include "callweaver/acl.h" #include "callweaver/srv.h" #include "callweaver/callweaver_db.h" #include "callweaver/causes.h" #include "callweaver/utils.h" #include "callweaver/file.h" #include "callweaver/astobj.h" #include "callweaver/devicestate.h" #include "callweaver/linkedlists.h" #include "callweaver/localtime.h" #include "callweaver/udpfromto.h" #include "callweaver/stun.h" #ifdef OSP_SUPPORT #include "callweaver/astosp.h" #endif #ifndef DEFAULT_USERAGENT #define DEFAULT_USERAGENT "CallWeaver" #endif #define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru CW_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 RFC_TIMER_T1 500 /* Default RTT estimate in ms (RFC3261 requires 500ms) */ #define RFC_TIMER_T2 4000 /* Maximum retransmit interval for non-INVITEs in ms (RFC3261 requires 4s) */ #define DEFAULT_RFC_TIMER_B 64 /* INVITE transaction timeout, in units of T1. Default gives 7 attempts (RFC3261 requires termination after 64*T1 ms) */ static int rfc_timer_b = DEFAULT_RFC_TIMER_B; #define RFC_TIMER_F 64 /* non-INVITE transaction timeout, in units of T1 (RFC3261 requires termination after 64*T1 ms) */ #define MAX_AUTHTRIES 3 /* Try authentication three times, then fail */ #define DEBUG_READ 0 /* Recieved data */ #define DEBUG_SEND 1 /* Transmit data */ #include "callweaver/generic_jb.h" static struct cw_jb_conf global_jbconf; 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"; static void *sipheader_function; static const char sipheader_func_name[] = "SIP_HEADER"; static const char sipheader_func_synopsis[] = "Gets or sets the specified SIP header"; static const char sipheader_func_syntax[] = "SIP_HEADER()"; static const char sipheader_func_desc[] = ""; static void *sippeer_function; static const char sippeer_func_name[] = "SIPPEER"; static const char sippeer_func_synopsis[] = "Gets SIP peer information"; static const char sippeer_func_syntax[] = "SIPPEER(peername[, item])"; static const char sippeer_func_desc[] = "Valid items are:\n" "- ip (default) The IP address.\n" "- mailbox The configured mailbox.\n" "- context The configured context.\n" "- expire The epoch time of the next expire.\n" "- dynamic Is it dynamic? (yes/no).\n" "- callerid_name The configured Caller ID name.\n" "- callerid_num The configured Caller ID number.\n" "- codecs The configured codecs.\n" "- status Status (if qualify=yes).\n" "- regexten Registration extension\n" "- limit Call limit (call-limit)\n" "- curcalls Current amount of calls \n" " Only available if call-limit is set\n" "- language Default language for peer\n" "- useragent Current user agent id for peer\n" "- codec[x] Preferred codec index number 'x' (beginning with zero).\n" "\n"; static void *sippeervar_function; static const char sippeervar_func_name[] = "SIPPEERVAR"; static const char sippeervar_func_synopsis[] = "Gets SIP peer variable"; static const char sippeervar_func_syntax[] = "SIPPEERVAR(peername, varname)"; static const char sippeervar_func_desc[] = "Returns the value of varname as specified for the peer in its configuration.\n" "\n"; static void *sipchaninfo_function; static const char sipchaninfo_func_name[] = "SIPCHANINFO"; static const char sipchaninfo_func_synopsis[] = "Gets the specified SIP parameter from the current channel"; static const char sipchaninfo_func_syntax[] = "SIPCHANINFO(item)"; static const char sipchaninfo_func_desc[] = "Valid items are:\n" "- peerip The IP address of the peer.\n" "- recvip The source IP address of the peer.\n" "- from The URI from the From: header.\n" "- uri The URI from the Contact: header.\n" "- useragent The useragent.\n" "- peername The name of the peer.\n"; static void *checksipdomain_function; static const char checksipdomain_func_name[] = "CHECKSIPDOMAIN"; static const char checksipdomain_func_synopsis[] = "Checks if domain is a local domain"; static const char checksipdomain_func_syntax[] = "CHECKSIPDOMAIN()"; static const char checksipdomain_func_desc[] = "This function checks if the domain in the argument is configured\n" "as a local SIP domain that this CallWeaver server is configured to handle.\n" "Returns the domain name if it is locally handled, otherwise an empty string.\n" "Check the domain= configuration in sip.conf\n"; #define RTP 1 #define NO_RTP 0 /* 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 = 0, /* This MUST be 0 - find_sip_method assumes it is */ SIP_RESPONSE = 1, SIP_REGISTER = 2, SIP_OPTIONS = 3, SIP_NOTIFY = 4, SIP_INVITE = 5, SIP_ACK = 6, SIP_PRACK = 7, SIP_BYE = 8, SIP_REFER = 9, SIP_SUBSCRIBE = 10, SIP_MESSAGE = 11, SIP_UPDATE = 12, SIP_INFO = 13, SIP_CANCEL = 14, SIP_PUBLISH = 15, }; enum sip_auth_type { PROXY_AUTH, WWW_AUTH, }; static const struct { int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */ char * const text; int len; int can_create; } sip_methods[] = { #define S(str) str, sizeof(str)-1 [SIP_UNKNOWN] = { RTP, S("-UNKNOWN-"), 2 }, [SIP_RESPONSE] = { NO_RTP, S("SIP/2.0"), 0 }, [SIP_REGISTER] = { NO_RTP, S("REGISTER"), 1 }, [SIP_OPTIONS] = { NO_RTP, S("OPTIONS"), 1 }, [SIP_NOTIFY] = { NO_RTP, S("NOTIFY"), 2 }, [SIP_INVITE] = { RTP, S("INVITE"), 1 }, [SIP_ACK] = { NO_RTP, S("ACK"), 0 }, [SIP_PRACK] = { NO_RTP, S("PRACK"), 2 }, [SIP_BYE] = { NO_RTP, S("BYE"), 0 }, [SIP_REFER] = { NO_RTP, S("REFER"), 2 }, [SIP_SUBSCRIBE] = { NO_RTP, S("SUBSCRIBE"), 1 }, [SIP_MESSAGE] = { NO_RTP, S("MESSAGE"), 1 }, [SIP_UPDATE] = { NO_RTP, S("UPDATE"), 0 }, [SIP_INFO] = { NO_RTP, S("INFO"), 0 }, [SIP_CANCEL] = { NO_RTP, S("CANCEL"), 0 }, [SIP_PUBLISH] = { NO_RTP, S("PUBLISH"), 1 } #undef S }; /*! \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 CallWeaver ? */ 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[CW_MAX_EXTENSION] = DEFAULT_USERAGENT; #define DEFAULT_CONTEXT "default" static char default_context[CW_MAX_CONTEXT] = DEFAULT_CONTEXT; static char default_subscribecontext[CW_MAX_CONTEXT]; #define DEFAULT_VMEXTEN "callweaver" static char global_vmexten[CW_MAX_EXTENSION] = DEFAULT_VMEXTEN; static char default_language[MAX_LANGUAGE] = ""; #define DEFAULT_CALLERID "callweaver" static char default_callerid[CW_MAX_EXTENSION] = DEFAULT_CALLERID; static char default_fromdomain[CW_MAX_EXTENSION] = ""; #define DEFAULT_NOTIFYMIME "application/simple-message-summary" static char default_notifymime[CW_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 cw_flags global_flags = {0}; /*!< global SIP_ flags */ static struct cw_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; CW_MUTEX_DEFINE_STATIC(usecnt_lock); CW_MUTEX_DEFINE_STATIC(rand_lock); /*! \brief Protect the interface list (of sip_pvt's) */ CW_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. */ CW_MUTEX_DEFINE_STATIC(netlock); CW_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 = CW_PTHREADT_NULL; static int restart_monitor(void); /* T.38 channel status */ typedef enum { SIP_T38_OFFER_REJECTED = -1, SIP_T38_STATUS_UNKNOWN = 0, SIP_T38_OFFER_SENT_DIRECT = 1, SIP_T38_OFFER_SENT_REINVITE = 2, SIP_T38_OFFER_RECEIVED_DIRECT = 3, SIP_T38_OFFER_RECEIVED_REINVITE = 4, SIP_T38_NEGOTIATED = 5 } sip_t38_status_t; /* T.38 set of flags */ #define T38FAX_FILL_BIT_REMOVAL (1 << 0) /*!< Default: 0 (unset)*/ #define T38FAX_TRANSCODING_MMR (1 << 1) /*!< Default: 0 (unset)*/ #define T38FAX_TRANSCODING_JBIG (1 << 2) /*!< Default: 0 (unset)*/ /* Rate management */ #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF (0 << 3) #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF (1 << 3) /*!< Unset for transferedTCF (UDPTL), set for localTCF (TPKT) */ /* UDP Error correction */ #define T38FAX_UDP_EC_FEC (1 << 4) /*!< Set for t38UDPFEC */ #define T38FAX_UDP_EC_REDUNDANCY (2 << 4) /*!< Set for t38UDPRedundancy */ /* T38 Spec version */ #define T38FAX_VERSION (3 << 6) /*!< two bits, 2 values so far, up to 4 values max */ #define T38FAX_VERSION_0 (0 << 6) /*!< Version 0 */ #define T38FAX_VERSION_1 (1 << 6) /*!< Version 1 */ /* Maximum Fax Rate */ #define T38FAX_RATE_2400 (1 << 8) /*!< 2400 bps t38FaxRate */ #define T38FAX_RATE_4800 (1 << 9) /*!< 4800 bps t38FaxRate */ #define T38FAX_RATE_7200 (1 << 10) /*!< 7200 bps t38FaxRate */ #define T38FAX_RATE_9600 (1 << 11) /*!< 9600 bps t38FaxRate */ #define T38FAX_RATE_12000 (1 << 12) /*!< 12000 bps t38FaxRate */ #define T38FAX_RATE_14400 (1 << 13) /*!< 14400 bps t38FaxRate */ #define T38FAX_RATE_33600 (1 << 14) /*!< 33600 bps t38FaxRate */ /*! \brief Codecs that we support by default: */ static int global_capability = CW_FORMAT_ULAW | CW_FORMAT_ALAW | CW_FORMAT_GSM | CW_FORMAT_H263; static int noncodeccapability = CW_RTP_DTMF; static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600 | T38FAX_RATE_14400; /* This is default: NO MMR and JBIG trancoding, NO fill bit removal, transfered TCF, UDP FEC, Version 0 and 9600 max fax rate */ 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 t38udptlsupport = 0; static int t38rtpsupport = 0; static int t38tcpsupport = 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 "callweaver.org" static char global_realm[MAXHOSTNAMELEN] = DEFAULT_REALM; /*!< Default realm */ static char regcontext[CW_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; static int *sipsock_read_id; #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 SIP_MAX_LINE_LEN 1024 #define DEC_CALL_LIMIT 0 #define INC_CALL_LIMIT 1 static struct cw_codec_pref prefs; #define STUN_DEV_DEBUG 1 #define SIP_DL_DONTCARE 0 #define SIP_DL_HEAD_CONTENTLENGHT 1 #define SIP_DL_HEAD_CONTACT 2 #define SIP_DL_HEAD_VIA 3 #define SIP_DL_HEAD_CALLID 4 #define SIP_DL_HEAD_FROM 5 #define SIP_DL_HEAD_TO 6 #define SIP_DL_SDP_O 20 #define SIP_DL_SDP_C 21 #define SIP_DL_SDP_M_AUDIO 22 #define SIP_DL_SDP_M_VIDEO 23 #define SIP_DL_SDP_M_T38 24 struct sip_data_line { char content[SIP_MAX_LINE_LEN]; short int type; struct sip_data_line * next; }; /*! \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 */ enum sipmethod 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 */ /* ******* stun rework of request ******** */ struct sip_data_line *head_lines; struct sip_data_line *sdp_lines; }; 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 */ int t38txdetection; /*!< Detect outgoing fax CNG */ }; 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[CW_MAX_EXTENSION]; /*!< Incoming context for this domain */ enum domain_mode mode; /*!< How did we find this domain? */ CW_LIST_ENTRY(domain) list; /*!< List mechanics */ }; static CW_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[CW_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) #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_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 = 120; /*! \brief sip_pvt: PVT structures are used for each SIP conversation, ie. a call */ static struct sip_pvt { cw_mutex_t lock; /*!< Channel private lock */ enum sipmethod method; /*!< SIP method of this packet */ char callid[80]; /*!< Global CallID */ char randdata[80]; /*!< Random data */ struct cw_codec_pref prefs; /*!< codec prefs */ unsigned int ocseq; /*!< Current outgoing seqno */ unsigned int icseq; /*!< Current incoming seqno */ cw_group_t callgroup; /*!< Call group */ cw_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 cw_channel *owner; /*!< Who owns us */ char exten[CW_MAX_EXTENSION]; /*!< Extension where to start */ char refer_to[CW_MAX_EXTENSION]; /*!< Place to store REFER-TO extension */ char referred_by[CW_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */ char refer_contact[CW_MAX_EXTENSION]; /*!< 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[CW_MAX_CONTEXT]; /*!< Context for this call */ char subscribecontext[CW_MAX_CONTEXT]; /*!< Subscribecontext */ char fromdomain[MAXHOSTNAMELEN]; /*!< Domain to show in the from field */ char fromuser[CW_MAX_EXTENSION]; /*!< User to show in the user field */ char fromname[CW_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[256]; /*!< 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[128]; /*!< The Contact: that the UA registers with us */ char accountcode[CW_MAX_ACCOUNT_CODE]; /*!< Account code */ char our_contact[256]; /*!< 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 cw_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 cw_rtp *rtp; /*!< RTP Session */ struct cw_rtp *vrtp; /*!< Video RTP session */ struct sip_pkt *packets; /*!< Packets scheduled for re-transmission */ struct sip_history *history; /*!< History of this SIP dialog */ struct cw_variable *chanvars; /*!< Channel variables to set for call */ struct sip_pvt *next; /*!< Next call in chain */ struct sip_invite_param *options; /*!< Options for INVITE */ struct cw_jb_conf jbconf; char ruri[256]; /*!< REAL Original requested URI */ //struct cw_tpkt *tpkt; /*!< T.38 TPKT session */ cw_udptl_t *udptl; /*!< T.38 UDPTL session */ int t38capability; /*!< Our T38 capability */ int t38peercapability; /*!< Peers T38 capability */ int t38jointcapability; /*!< Supported T38 capability at both ends */ sip_t38_status_t t38state; /*!< T.38 state : 0 - not enabled, 1 - offered from local - direct, 2 - offered from local - reinvite, 3 - offered from peer - direct, 4 - offered from peer - reinvite, 5 - negotiated (enabled) */ struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */ struct cw_dsp *vadtx; /*!< Voice Activation Detection dsp on TX */ int udptl_active; /*!< */ int stun_needed; /*!< Did we request STUN for this call ? */ int ourport; /*!< Our port seen from stun*/ int stun_resreq_id; int stun_retrans_no; rfc3489_trans_id_t stun_transid; } *iflist = NULL; #define STUN_WAIT_RETRY_TIME 100 /*!< ms to wait between every sip packet check for transmission*/ #define STUN_MAX_RETRANSMIT 4*1000/STUN_WAIT_RETRY_TIME /*!< max retrans for a packet before giving up. RFC says 9.5 secs, we use 4 secs */ /* This structure saves all data we need to retransmit a request after we have received stun response */ struct sip_reqresp { int type; struct sip_pvt *p; char callid[80]; struct sip_request req; int reliable; int seqno; rfc3489_request_t *streq; }; #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 */ enum sipmethod 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 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[CW_MAX_CONTEXT]; /*!< Default context for incoming calls */ char subscribecontext[CW_MAX_CONTEXT]; /* Default context for subscriptions */ char cid_num[80]; /*!< Caller ID num */ char cid_name[80]; /*!< Caller ID name */ char accountcode[CW_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 cw_codec_pref prefs; /*!< codec prefs */ cw_group_t callgroup; /*!< Call group */ cw_group_t pickupgroup; /*!< Pickup Group */ unsigned int flags; /*!< SIP flags */ unsigned int sipoptions; /*!< Supported SIP options */ struct cw_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 cw_ha *ha; /*!< ACL setting */ struct cw_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[CW_MAX_CONTEXT]; /*!< Default context for incoming calls */ char subscribecontext[CW_MAX_CONTEXT]; /*!< Default context for subscriptions */ char username[80]; /*!< Temporary username until registration */ char accountcode[CW_MAX_ACCOUNT_CODE]; /*!< Account code */ int amaflags; /*!< AMA Flags (for billing) */ char tohost[MAXHOSTNAMELEN]; /*!< If not dynamic, IP address or hostname */ char proxyhost[MAXHOSTNAMELEN]; /*!< IP address or hostname of proxy (if any) */ char regexten[CW_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[256]; /*!< 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[CW_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/ char mailbox[CW_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 cw_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 cw_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 */ cw_group_t callgroup; /*!< Call group */ cw_group_t pickupgroup; /*!< Pickup group */ 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 */ int noanswer; /*!< How many noanswers we have had in a row */ struct timeval ps; /*!< Ping send time */ struct sockaddr_in defaddr; /*!< Default IP address, used until registration */ struct cw_ha *ha; /*!< Access control list */ struct cw_variable *chanvars; /*!< Variables to set for channel created by user */ int lastmsg; }; CW_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[256]; /*!< 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[80]; /*!< 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 cw_user_list { ASTOBJ_CONTAINER_COMPONENTS(struct sip_user); } userl; /*! \brief The peer list: Peers and Friends */ static struct cw_peer_list { ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer); } peerl; /*! \brief The register list: Other SIP proxys we register with and call */ static struct cw_register_list { ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry); int recheck; } regl; 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 cw_ha *localaddr; /* The list of manual NOTIFY types we know how to send */ struct cw_config *notify_types; static struct sip_auth *authl; /*!< Authentication list */ static int transmit_response_using_temp(char *callid, struct sockaddr_in *sin, int useglobal_nat, const enum sipmethod intended_method, struct sip_request *req, char *msg); 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, enum sipmethod sipmethod, int inc, int reliable, int newbranch); static int transmit_request_with_auth(struct sip_pvt *p, enum sipmethod sipmethod, int inc, int reliable, int newbranch); static int transmit_invite(struct sip_pvt *p, enum sipmethod 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, unsigned int duration); 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, enum sipmethod sipmethod, int init); static void free_old_route(struct sip_route *route); static int build_reply_digest(struct sip_pvt *p, enum sipmethod 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 cw_variable *v, int realtime); static struct sip_user *build_user(const char *name, struct cw_variable *v, int realtime); static int sip_do_reload(void); static int expire_register(void *data); static int callevents = 0; static struct cw_channel *sip_request_call(const char *type, int format, void *data, int *cause); static int sip_devicestate(void *data); static int sip_sendtext(struct cw_channel *ast, const char *text); static int sip_call(struct cw_channel *ast, char *dest); static int sip_hangup(struct cw_channel *ast); static int sip_answer(struct cw_channel *ast); static struct cw_frame *sip_read(struct cw_channel *ast); static int sip_write(struct cw_channel *ast, struct cw_frame *frame); static int sip_indicate(struct cw_channel *ast, int condition); static int sip_transfer(struct cw_channel *ast, const char *dest); static int sip_fixup(struct cw_channel *oldchan, struct cw_channel *newchan); static int sip_senddigit(struct cw_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, int timeout); static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize); static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans); static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p); static int sip_handle_t38_reinvite(struct cw_channel *chan, struct sip_pvt *pvt, int reinvite); /* T38 negotiation helper function */ static enum cw_bridge_result sip_bridge(struct cw_channel *c0, struct cw_channel *c1, int flag, struct cw_frame **fo,struct cw_channel **rc, int timeoutms); /* Function to bridge to SIP channels if T38 support enabled */ static char *nat2str(int nat); static int cw_sip_ouraddrfor(struct in_addr *them, struct in_addr *us, struct sip_pvt *p); static int sip_poke_peer(void *data); /*! \brief Definition of this channel for PBX channel registration */ static const struct cw_channel_tech sip_tech = { .type = channeltype, .description = "Session Initiation Protocol (SIP)", .capabilities = ((CW_FORMAT_MAX_AUDIO << 1) - 1), .properties = CW_CHAN_TP_WANTSJITTER | CW_CHAN_TP_CREATESJITTER, .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 = sip_bridge, // .bridge = cw_rtp_bridge, .send_text = sip_sendtext, }; static void sip_debug_ports(struct sip_pvt *p) { struct sockaddr_in sin; struct sockaddr_in udptlsin; char iabuf[255]; if ( option_debug > 8 ) { if ( p->owner ) cw_log(CW_LOG_DEBUG,"DEBUG PORTS CHANNEL %s\n", p->owner->name); if (p->udptl) { cw_udptl_get_us(p->udptl, &udptlsin); cw_log(CW_LOG_DEBUG,"DEBUG PORTS T.38 UDPTL is at port %s:%d...\n", cw_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(udptlsin.sin_port)); } if (p->rtp) { cw_rtp_get_us(p->rtp, &sin); cw_log(CW_LOG_DEBUG,"DEBUG PORTS rtp is at port %s:%d...\n", cw_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(sin.sin_port)); } } } /*! \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 int thread_safe_cw_random(void) { int val; cw_mutex_lock(&rand_lock); val = rand(); cw_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 */ static enum sipmethod find_sip_method(char *msg) { int i; if (!cw_strlen_zero(msg)) { for (i = 1; i < arraysize(sip_methods); i++) { if (!strcasecmp(sip_methods[i].text, msg)) return i; } } return 0; } /*! \brief parse_sip_options: Parse supported header in incoming packet */ static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported) { char *next = NULL; char *sep = NULL; char *temp = cw_strdupa(supported); int i; unsigned int profile = 0; if (cw_strlen_zero(supported)) return 0; if (option_debug > 2 && sipdebug) cw_log(CW_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) cw_log(CW_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) cw_log(CW_LOG_DEBUG, "Matched SIP option: %s\n", next); } } if (!res) if (option_debug > 2 && sipdebug) cw_log(CW_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) cw_log(CW_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_is_nat_needed: Check if we need NAT or STUN */ static inline int sip_is_nat_needed(struct sip_pvt *p) { int local; local = !cw_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip,p); cw_log(CW_LOG_DEBUG,"Checking nat (local %d = %s)\n", local, nat2str(cw_test_flag(p, SIP_NAT)) ); if ( (cw_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) && local ) { if ( option_debug > 5 ) cw_log(CW_LOG_DEBUG,"Nat is not needed (condition 1)\n"); return 0; } if ( (cw_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) && !local ) { if ( option_debug > 5 ) cw_log(CW_LOG_DEBUG,"Nat is needed (condition 2)\n"); return 1; } if ( (cw_test_flag(p, SIP_NAT) & SIP_NAT_ALWAYS) ) { if ( option_debug > 5 ) cw_log(CW_LOG_DEBUG,"Nat is needed (condition 3)\n"); return 1; } if ( (cw_test_flag(&global_flags, SIP_NAT) & SIP_NAT_ROUTE) && local ) { if ( option_debug > 5 ) cw_log(CW_LOG_DEBUG,"Nat is not needed (condition 4)\n"); return 0; } if ( (cw_test_flag(&global_flags, SIP_NAT) & SIP_NAT_ROUTE) && local) { if ( option_debug > 5 ) cw_log(CW_LOG_DEBUG,"Nat is not needed (condition 5)\n"); return 0; } if (cw_test_flag(&global_flags, SIP_NAT) & SIP_NAT_ALWAYS) { if ( option_debug > 5 ) cw_log(CW_LOG_DEBUG,"Nat is needed (condition 5)\n"); return 1; } return 0; } /*! \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(( sip_is_nat_needed(p) ? &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 (p->peerpoke && p->stun_needed) gettimeofday(&p->peerpoke->ps, NULL); // We set ping time here to make pokepeer calculations correct. Stun introduces lag. if ( sip_is_nat_needed(p) ) res = cw_sendfromto(sipsock, data, len, 0, NULL, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in)); else { struct sockaddr_in from; from.sin_family = AF_INET; memcpy(&from.sin_addr, &p->ourip, sizeof(from.sin_addr)); res=cw_sendfromto(sipsock, data, len, 0, (struct sockaddr *)&from, sizeof(struct sockaddr_in), (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in)); } if (res != len) cw_log(CW_LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, cw_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), res, ntohs(p->sa.sin_port), 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 (cw_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581) snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", cw_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), p->ourport, p->branch); else /* Work around buggy UNIDEN UIP200 firmware */ snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", cw_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), p->ourport, p->branch); } /*! \brief cw_sip_ouraddrfor: NAT fix - decide which IP address to use for CallWeaver.org server? */ /* Only used for outbound registrations */ static int cw_sip_ouraddrfor(struct in_addr *them, struct in_addr *us, struct sip_pvt *p) { /* * 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 */ int res = 0; struct sockaddr_in theirs; theirs.sin_addr = *them; if ((localaddr && cw_apply_ha(localaddr, &theirs)) && (rfc3489_active || externip.sin_addr.s_addr)) { char iabuf[INET_ADDRSTRLEN]; if (externexpire && (time(NULL) >= externexpire)) { struct cw_hostent ahp; struct hostent *hp; time(&externexpire); externexpire += externrefresh; if ((hp = cw_gethostbyname(externhost, &ahp))) memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr)); else cw_log(CW_LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost); } memcpy(us, &externip.sin_addr, sizeof(struct in_addr)); cw_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr); if (!rfc3489_active) { cw_log(CW_LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf); p->stun_needed = 0; res = 1; } else { cw_log(CW_LOG_DEBUG, "Target address %s is not local, substituting externip and enabling stun\n", iabuf); p->stun_needed = 1; res = 1; } } else if (bindaddr.sin_addr.s_addr) { memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr)); } else { res=cw_ouraddrfor(them, us); } return res; } /*! \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; struct sip_history *prev; char *c; if (!recordhistory || !p) return 0; if(!(hist = malloc(sizeof(struct sip_history)))) { cw_log(CW_LOG_WARNING, "Can't allocate memory for history\n"); 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; /* Lock channel */ cw_mutex_lock(&pkt->owner->lock); /* It's possible we just waited while an ack was sent for a reply * to a previous transmission of this packet. If so the ack code * will have changed the method for this packet to unknown to * signal that no further retransmissions are required, however * it is still down to us to dequeue the packet once we're done * looking at it. */ if (pkt->method != SIP_UNKNOWN && ((pkt->method == SIP_INVITE && pkt->timer_a < rfc_timer_b) || (pkt->method != SIP_INVITE && pkt->timer_a < RFC_TIMER_F))) { char buf[(INET_ADDRSTRLEN > 80 ? INET_ADDRSTRLEN : 80)]; int reschedule; /* Re-schedule using timer_a and timer_t1 */ if (!pkt->timer_a) pkt->timer_a = 2 ; else pkt->timer_a = 2 * pkt->timer_a; /* Double each time */ reschedule = pkt->timer_a * pkt->owner->timer_t1; /* For non-invites, a maximum of T2 (normally 4 secs as per RFC3261) */ if (pkt->method != SIP_INVITE && reschedule > RFC_TIMER_T2) reschedule = RFC_TIMER_T2; if (pkt->owner && sip_debug_test_pvt(pkt->owner)) { if ( sip_is_nat_needed(pkt->owner) ) cw_verbose("SIP TIMER: #%d: Retransmitting (NAT) to %s:%d:\n%s\n---\n", pkt->retransid, cw_inet_ntoa(buf, sizeof(buf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data); else cw_verbose("SIP TIMER: #%d: Retransmitting (no NAT) to %s:%d:\n%s\n---\n", pkt->retransid, cw_inet_ntoa(buf, sizeof(buf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data); } if (sipdebug && option_debug > 3) cw_log(CW_LOG_DEBUG, "SIP TIMER: #%d: scheduling retransmission of %s for %d ms (t1 %d ms) \n", pkt->retransid, sip_methods[pkt->method].text, reschedule, pkt->owner->timer_t1); snprintf(buf, sizeof(buf), "ReTx %d", reschedule); append_history(pkt->owner, buf, pkt->data); __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* We reschedule ourself here rather than letting the scheduler do it * because the lock below coordinates with the acking code. Releasing * the lock allows the acking code to process a response and attempt * to deschedule retransmission. If we then come back here, return * and allow the scheduler to reschedule us we're going to send * an unwanted retransmission of a packet that we already acked a * reply for. */ pkt->retransid = cw_sched_modify(sched, pkt->retransid, reschedule, retrans_pkt, pkt); cw_mutex_unlock(&pkt->owner->lock); return 0; } /* Too many retries */ /* Dequeue the packet. It is then exclusively ours even if we drop the * lock thus allowing an attempt to ack a late reply. */ for (prev = &pkt->owner->packets; *prev; prev = &(*prev)->next) { if (*prev == pkt) { *prev = pkt->next; break; } } if (pkt->method != SIP_UNKNOWN) { if (pkt->owner && pkt->method != SIP_OPTIONS) { if (cw_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */ cw_log(CW_LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (cw_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (cw_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request"); } else { if (pkt->method == SIP_OPTIONS && sipdebug) cw_log(CW_LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid); } append_history(pkt->owner, "MaxRetries", (cw_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)"); if (cw_test_flag(pkt, FLAG_FATAL)) { while (pkt->owner->owner && cw_mutex_trylock(&pkt->owner->owner->lock)) { cw_mutex_unlock(&pkt->owner->lock); usleep(1); cw_mutex_lock(&pkt->owner->lock); } if (pkt->owner->owner) { cw_set_flag(pkt->owner, SIP_ALREADYGONE); cw_log(CW_LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid); cw_queue_hangup(pkt->owner->owner); cw_mutex_unlock(&pkt->owner->owner->lock); } else { /* If no channel owner, destroy now */ /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */ if (pkt->method != SIP_OPTIONS) cw_set_flag(pkt->owner, SIP_NEEDDESTROY); } } } cw_mutex_unlock(&pkt->owner->lock); free(pkt); 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, enum sipmethod sipmethod) { struct sip_pkt *pkt; if ((pkt = malloc(sizeof(struct sip_pkt) + len + 1)) == NULL) 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; if (resp) cw_set_flag(pkt, FLAG_RESPONSE); pkt->data[len] = '\0'; if (fatal) cw_set_flag(pkt, FLAG_FATAL); /* Schedule retransmission */ /* Note: The first retransmission is at last RTT plus a bit to allow for (some) jitter * and to avoid sending a retransmit at the exact moment we expect the reply to arrive */ pkt->retransid = cw_sched_add_variable(sched, (p->timer_t1 != RFC_TIMER_T1 ? p->timer_t1 + (p->timer_t1 >> 4) + 1 : RFC_TIMER_T1), retrans_pkt, pkt, 1); if (option_debug > 3 && sipdebug) cw_log(CW_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) { transmit_state_notify(p, CW_EXTENSION_DEACTIVATED, 1, 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; cw_log(CW_LOG_DEBUG, "Auto destroying call '%s'\n", p->callid); append_history(p, "AutoDestroy", ""); if (p->owner) { cw_log(CW_LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid); cw_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)) cw_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) cw_sched_del(sched, p->autokillid); p->autokillid = cw_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) cw_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, enum sipmethod sipmethod) { struct sip_pkt *cur, *prev = NULL; int res = -1; int resetinvite = 0; /* Just in case... */ char *msg; cw_mutex_lock(&p->lock); cur = p->packets; while (cur) { if ((cur->seqno == seqno) && ((cw_test_flag(cur, FLAG_RESPONSE)) == resp) && ((cw_test_flag(cur, FLAG_RESPONSE)) || (sipmethod >= 0 && (!cur->data[sip_methods[sipmethod].len] || isspace(cur->data[sip_methods[sipmethod].len]) && !strncasecmp(sip_methods[sipmethod].text, cur->data, sip_methods[sipmethod].len))))) { if (!resp && (seqno == p->pendinginvite)) { cw_log(CW_LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite); p->pendinginvite = 0; resetinvite = 1; } /* If we can delete the scheduled retransmit we own the packet * and can go ahead and free it. Otherwise the scheduled retransmit * has already fired and is waiting on the lock. In this case we * just set the method to unknown so retrans_pkt will give up once * it acquires the lock. */ if (cur->retransid == -1 || !cw_sched_del(sched, cur->retransid)) { if (sipdebug && option_debug > 3) cw_log(CW_LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid); cur->retransid = -1; if (prev) prev->next = cur->next; else p->packets = cur->next; free(cur); } else cur->method = SIP_UNKNOWN; res = 0; break; } prev = cur; cur = cur->next; } cw_mutex_unlock(&p->lock); cw_log(CW_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) { cw_log(CW_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, (cw_test_flag(p->packets, FLAG_RESPONSE)), cur->method); else { /* Unknown packet type */ char *c; char method[128]; cw_copy_string(method, p->packets->data, sizeof(method)); c = cw_skip_blanks(method); /* XXX what ? */ *c = '\0'; __sip_ack(p, p->packets->seqno, (cw_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, enum sipmethod sipmethod) { struct sip_pkt *cur; int res = -1; cur = p->packets; while (cur) { if ((cur->seqno == seqno) && ((cw_test_flag(cur, FLAG_RESPONSE)) == resp) && ((cw_test_flag(cur, FLAG_RESPONSE)) || ((!cur->data[sip_methods[sipmethod].len] || isspace(cur->data[sip_methods[sipmethod].len])) && !strncasecmp(sip_methods[sipmethod].text, cur->data, sip_methods[sipmethod].len)))) { /* this is our baby */ if (cur->retransid > -1) { if (option_debug > 3 && sipdebug) cw_log(CW_LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text); cw_sched_del(sched, cur->retransid); cur->retransid = -1; } res = 0; break; } cur = cur->next; } cw_log(CW_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(struct sip_request)); memcpy(dst->data, src->data, sizeof(dst->data)); dst->len = src->len; parse_request(dst); } static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain); static int sip_resend_reqresp(void *data); static void sip_dealloc_headsdp_lines(struct sip_request *req) { struct sip_data_line *tmpsdl,*tmprem; if (req == NULL) return; tmpsdl = req->head_lines; while (tmpsdl != NULL) { tmprem=tmpsdl; tmpsdl=tmpsdl->next; //cw_verbose("(-) removing header[%d]: %s\n",tmprem->type, tmprem->content); free(tmprem); } req->head_lines = NULL; tmpsdl = req->sdp_lines; while (tmpsdl != NULL) { tmprem = tmpsdl; tmpsdl = tmpsdl->next; //cw_verbose("(-) removing line[%d]: %s\n",tmprem->type, tmprem->content); free(tmprem); } req->sdp_lines = NULL; return; } static void sip_rebuild_payload(struct sip_pvt *p, struct sip_request *req,int have_stun) { char iabuf[INET_ADDRSTRLEN]; char buf[SIP_MAX_LINE_LEN]; struct sip_data_line *tmpsdl, *tmpsdlcl; char *s; /* First of all, we rebuild the sip message. If SDP il present, it's probably wrong. */ memset(req->data, 0, SIP_MAX_HEADERS); tmpsdl = req->head_lines; while (tmpsdl != NULL) { if (tmpsdl->type == SIP_DL_HEAD_CONTENTLENGHT) { // Must recalculate content length int sdplen = 0; tmpsdlcl = req->sdp_lines; while (tmpsdlcl) { sdplen += strlen(tmpsdlcl->content) + 2; tmpsdlcl = tmpsdlcl->next; } sprintf(tmpsdl->content, "Content-Length: %d", sdplen); } if (p->stun_needed && have_stun) { if (tmpsdl->type == SIP_DL_HEAD_CONTACT) { snprintf(p->our_contact, sizeof(p->our_contact), "", p->exten, cw_strlen_zero(p->exten) ? "" : "@", cw_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), p->ourport); sprintf(tmpsdl->content, "Contact: %s", p->our_contact); } else if (tmpsdl->type == SIP_DL_HEAD_VIA) { snprintf(p->via, SIP_MAX_LINE_LEN, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", cw_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), p->ourport, p->branch); sprintf(tmpsdl->content, "Via: %s", p->via); } else if (tmpsdl->type==SIP_DL_HEAD_CALLID) { //NOT Managed yet. Not a problem } else if (tmpsdl->type==SIP_DL_HEAD_FROM) { //NOT Managed yet. Not a problem } } #if STUN_DEV_DEBUG if (stundebug) cw_log(CW_LOG_DEBUG,"(*) joining header[%d]: %s\n",tmpsdl->type, tmpsdl->content); #endif strcat(req->data, tmpsdl->content); strcat(req->data, "\r\n"); tmpsdl = tmpsdl->next; } // Separator between headers and sdp strcat(req->data, "\r\n"); tmpsdl = req->sdp_lines; #if STUN_DEV_DEBUG if (stundebug) cw_log(CW_LOG_DEBUG,"STUN_NEEDED: %d - HAVE_STUN: %d\n",p->stun_needed, have_stun); #endif while (tmpsdl) { if (p->stun_needed && have_stun) { if (tmpsdl->type == SIP_DL_SDP_O) { } else if (tmpsdl->type == SIP_DL_SDP_C) { } else if (tmpsdl->type==SIP_DL_SDP_M_AUDIO) { struct sockaddr_in port; cw_rtp_get_us(p->rtp,&port); snprintf(buf, SIP_MAX_LINE_LEN, "m=audio %d RTP/AVP %s", ntohs(port.sin_port), ((s = strstr(tmpsdl->content, "RTP/AVP ")) ? s + 8 : "") ); #if STUN_DEV_DEBUG if (stundebug) { cw_log(CW_LOG_DEBUG,"M_AUDIO was: %s\n",tmpsdl->content); cw_log(CW_LOG_DEBUG,"M_AUDIO is : %s\n",buf); } #endif strncpy(tmpsdl->content,buf,SIP_MAX_LINE_LEN-1); } else if (tmpsdl->type == SIP_DL_SDP_M_VIDEO) { struct sockaddr_in port; cw_rtp_get_us(p->vrtp,&port); snprintf(buf, SIP_MAX_LINE_LEN, "m=video %d RTP/AVP %s", ntohs(port.sin_port), ((s = strstr(tmpsdl->content,"RTP/AVP ")) ? s + 8 : "") ); strncpy(tmpsdl->content,buf,SIP_MAX_LINE_LEN-1); } else if (tmpsdl->type == SIP_DL_SDP_M_T38) { struct sockaddr_in port; if (t38udptlsupport) { cw_udptl_get_us(p->udptl, &port); snprintf(tmpsdl->content, SIP_MAX_LINE_LEN, "m=image %d udptl t38", ntohs(port.sin_port)); } } } #if STUN_DEV_DEBUG if (stundebug) cw_log(CW_LOG_DEBUG,"(*) joining sdp[%d]: %s\n",tmpsdl->type, tmpsdl->content); #endif strcat(req->data, tmpsdl->content); strcat(req->data, "\r\n"); tmpsdl = tmpsdl->next; } req->len = strlen(req->data); } static int if_callid_exists(char *callid) { struct sip_pvt *cur; cur = iflist; while (cur) { if (!strcmp(cur->callid, callid)) return 1; cur = cur->next; } return 0; } /*! \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 = 0; char iabuf[INET_ADDRSTRLEN]; struct sip_request tmp; char tmpmsg[80]; if (rfc3489_active && p->stun_needed == 1) { cw_log(CW_LOG_DEBUG,"This call response %s seqno %d really needs STUN - sched %d\n",p->callid,seqno,p->stun_resreq_id); struct sip_reqresp *rr; rr = malloc(sizeof(struct sip_reqresp)); memset(rr, 0, sizeof(struct sip_reqresp)); rr->type = 1; rr->reliable = reliable; rr->seqno = seqno; memcpy(&rr->req, req, sizeof(struct sip_request)); memcpy(&rr->callid, p->callid, sizeof(p->callid)); rr->p = p; rr->p->stun_retrans_no = 0; rr->streq = cw_udp_stun_bindrequest(sipsock, &stunserver_ip, NULL, NULL); if (rr->streq) memcpy(&rr->p->stun_transid, &rr->streq->req_head.id, sizeof(rr->p->stun_transid)); if (p->rtp && !cw_rtp_get_stunstate(p->rtp)) { cw_log(CW_LOG_DEBUG, "Setting NAT on RTP to %d\n", sip_is_nat_needed(p)); cw_rtp_setnat(p->rtp, sip_is_nat_needed(p) ); } if (p->vrtp && !cw_rtp_get_stunstate(p->vrtp)) { cw_log(CW_LOG_DEBUG, "Setting NAT on VRTP to %d\n", sip_is_nat_needed(p)); cw_rtp_setnat(p->vrtp, sip_is_nat_needed(p) ); } if (p->udptl && !cw_udptl_get_stunstate(p->udptl)) { cw_log(CW_LOG_DEBUG, "Setting NAT on UDPTL to %d\n", sip_is_nat_needed(p) ); cw_udptl_setnat(p->udptl, sip_is_nat_needed(p) ); } if (rr->streq) { if (stundebug) cw_log(CW_LOG_DEBUG,"** Sent STUN packet for response %d\n",rr->streq->req_head.id.id[0]); rr->p->stun_resreq_id = cw_sched_add(sched, STUN_WAIT_RETRY_TIME, sip_resend_reqresp, rr); return 0; } else { cw_log(CW_LOG_WARNING, "STUN: couldn't send packet. Trying to revert to old externip mode.\n"); } } else if (p->stun_needed == 2) { if (stundebug) cw_log(CW_LOG_DEBUG,"This transmit response has already a stun %d\n",p->stun_needed); sip_rebuild_payload(p, req, 1); } else { if (stundebug) cw_log(CW_LOG_DEBUG,"This transmit response has stun at %d\n",p->stun_needed); sip_rebuild_payload(p, req, 0); } if (sip_debug_test_pvt(p)) { if ( sip_is_nat_needed(p) ) cw_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", cw_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data); else cw_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", cw_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); } p->stun_needed = 0; sip_dealloc_headsdp_lines(req); 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=0; char iabuf[INET_ADDRSTRLEN]; struct sip_request tmp; char tmpmsg[80]; if (rfc3489_active && p->stun_needed == 1) { cw_log(CW_LOG_DEBUG,"This call request %s seqno %d really needs STUN - sched %d\n",p->callid,seqno,p->stun_resreq_id); struct sip_reqresp *rr; rr = malloc(sizeof(struct sip_reqresp)); memset(rr, 0, sizeof(struct sip_reqresp)); rr->type = 2; rr->reliable = reliable; rr->seqno = seqno; memcpy(&rr->req, req, sizeof(struct sip_request)); memcpy(&rr->callid, p->callid, sizeof(p->callid)); rr->p = p; rr->p->stun_retrans_no = 0; rr->streq = cw_udp_stun_bindrequest(sipsock,&stunserver_ip,NULL,NULL); if (rr->streq) memcpy(&rr->p->stun_transid, &rr->streq->req_head.id, sizeof(rr->p->stun_transid)); if (p->rtp && cw_rtp_get_stunstate(p->rtp) == 0) { cw_log(CW_LOG_DEBUG, "Setting NAT on RTP to %d\n", sip_is_nat_needed(p) ); cw_rtp_setnat(p->rtp, sip_is_nat_needed(p) ); } if (p->vrtp && cw_rtp_get_stunstate(p->vrtp) == 0) { cw_log(CW_LOG_DEBUG, "Setting NAT on VRTP to %d\n", sip_is_nat_needed(p) ); cw_rtp_setnat(p->vrtp, sip_is_nat_needed(p) ); } if (p->udptl && cw_udptl_get_stunstate(p->udptl) == 0) { cw_log(CW_LOG_DEBUG, "Setting NAT on UDPTL to %d\n", sip_is_nat_needed(p) ); cw_udptl_setnat(p->udptl, sip_is_nat_needed(p) ); } if (rr->streq) { if (stundebug) cw_log(CW_LOG_DEBUG,"** Sent STUN packet for request %d\n",rr->streq->req_head.id.id[0]); rr->p->stun_resreq_id=cw_sched_add(sched, STUN_WAIT_RETRY_TIME, sip_resend_reqresp, rr); return 0; } else { cw_log(CW_LOG_WARNING, "STUN: couldn't send packet. Trying to revert to old externip mode.\n"); } } else if (p->stun_needed == 2) { if (stundebug) cw_log(CW_LOG_DEBUG,"This transmit request has already a stun %d\n",p->stun_needed); sip_rebuild_payload(p,req,1); } else { if (stundebug) cw_log(CW_LOG_DEBUG,"This transmit request has stun at %d\n",p->stun_needed); sip_rebuild_payload(p,req,0); } if (sip_debug_test_pvt(p)) { if ( sip_is_nat_needed(p) ) cw_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", cw_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data); else cw_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", cw_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data); } if (reliable && !p->peerpoke) { 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); } p->stun_needed=0; sip_dealloc_headsdp_lines(req); return res; } static int sip_resend_reqresp(void *data) { int res = 0; struct sip_reqresp *rr = data; rfc3489_addr_t *map = NULL; struct sip_pvt *p = rr->p; struct sip_request tmp; struct sockaddr_in msin; if (!rr) return 0; if (!if_callid_exists(rr->callid)) { cw_log(CW_LOG_DEBUG, "REQRESP: callid %s has been destroyed in the meanwhile. \n",rr->callid); sip_dealloc_headsdp_lines(&rr->req); free(data); return 0; } if (rr->streq) { if (stundebug) cw_log(CW_LOG_DEBUG,"** expected stun reqid %d\n",rr->streq->req_head.id.id[0]); } else { if (stundebug) cw_log(CW_LOG_DEBUG,"** deleting transmission retrial 'cause stun request is not set\n"); rr->p->stun_needed=0; sip_dealloc_headsdp_lines(&rr->req); free(data); return 0; } rr->p->stun_retrans_no++; if (rr->p->stun_retrans_no > STUN_MAX_RETRANSMIT) { if (stundebug) cw_log(CW_LOG_DEBUG,"Deleting this request of reqresp (too many time has passed to wait for stun responses (sip %d)\n",rr->p->stun_resreq_id); p->stun_needed = 0; sip_dealloc_headsdp_lines(&rr->req); free(data); return 0; }; if (stundebug) cw_log(CW_LOG_DEBUG,"** Trying to resend a packet after stun request. " "Type %d, seqno %d sched %d, callid %s\n",rr->type,rr->seqno,rr->p->stun_resreq_id, rr->callid); if (p->rtp && cw_rtp_get_stunstate(p->rtp) == 1) cw_rtp_read(p->rtp); /* RTP Stun search */ if (p->vrtp && cw_rtp_get_stunstate(p->vrtp) == 1) cw_rtp_read(p->vrtp); /* VRTP Stun search */ if (p->udptl && cw_udptl_get_stunstate(p->udptl) == 1) cw_udptl_read(p->udptl); /* UDPTL Stun search */ map = cw_stun_find_request(&rr->streq->req_head.id); if (stundebug) { cw_log(CW_LOG_DEBUG,"** STUN: state - sip: %d - sdp ports: rtp:%d vrtp:%d udptl:%d \n", (!map) ? 1 : 2, cw_rtp_get_stunstate(p->rtp), cw_rtp_get_stunstate(p->vrtp), cw_udptl_get_stunstate(p->udptl)); } if (map && cw_rtp_get_stunstate(p->rtp) != 1 && cw_rtp_get_stunstate(p->vrtp) != 1 && cw_udptl_get_stunstate(p->udptl) != 1) { char iabuf[INET_ADDRSTRLEN]; rfc3489_addr_to_sockaddr(&msin, map); memcpy(&p->stun_transid, &rr->streq->req_head.id, sizeof(p->stun_transid)); if (stundebug) cw_log(CW_LOG_DEBUG,"** STUN: Mapped address is %s:%d\n", cw_inet_ntoa(iabuf, sizeof(iabuf), msin.sin_addr), ntohs(map->port)); } else { if (stundebug) cw_log(CW_LOG_DEBUG,"** SIP port stun mapped address not found. STUN state on sdp ports is: rtp:%d vrtp:%d udptl:%d \n", cw_rtp_get_stunstate(p->rtp), cw_rtp_get_stunstate(p->vrtp), cw_udptl_get_stunstate(p->udptl)); rr->p->stun_resreq_id=cw_sched_add(sched, STUN_WAIT_RETRY_TIME, sip_resend_reqresp, rr); return res; } p->ourip = msin.sin_addr; p->ourport = ntohs(map->port); #if STUN_DEV_DEBUG if (stundebug) cw_log(CW_LOG_DEBUG,"** STUN rebuilding payload before sending reqresp\n"); #endif sip_rebuild_payload(rr->p, &rr->req, 1); parse_copy(&tmp,&rr->req); if (rr->type == 1) { if (stundebug) cw_log(CW_LOG_DEBUG,"** STUN Sending response after acquiring STUN\n"); /* This is a send_response*/ rr->p->stun_needed = 2; send_response(rr->p, &rr->req, rr->reliable, rr->seqno); } else if (rr->type == 2) { if (stundebug) cw_log(CW_LOG_DEBUG,"** STUN Sending request after acquiring STUN\n"); /* This is a send_request*/ rr->p->stun_needed = 2; send_request(rr->p, &rr->req, rr->reliable, rr->seqno); } else { if (stundebug) cw_log(CW_LOG_DEBUG, "deleting this request of reqresp %d\n",rr->p->stun_resreq_id); } sip_dealloc_headsdp_lines(&rr->req); stun_remove_request(&rr->streq->req_head.id); free(data); 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) { cw_log(CW_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 { cw_log(CW_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 cw_channel *ast, const char *text) { struct sip_pvt *p = ast->tech_pvt; int debug=sip_debug_test_pvt(p); if (debug) cw_verbose("Sending text %s on %s\n", text, ast->name); if (!p) return -1; if (cw_strlen_zero(text)) return 0; if (debug) cw_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 */ /*! \brief Update peer object in realtime storage If the CallWeaver system name is set in callweaver.conf, we will use that name and store that in the "regserver" field in the sippeers table to facilitate multi-server setups. */ static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expiry, const char *useragent) { char port[10]; char ipaddr[20]; char regseconds[20] = "0"; char *sysname = cw_config_CW_SYSTEM_NAME; char *syslabel = NULL; time_t nowtime; time(&nowtime); nowtime += expiry; snprintf(regseconds, sizeof(regseconds), "%ld", nowtime); /* Expiration time */ cw_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr); snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port)); if (cw_strlen_zero(sysname)) /* No system name, disable this */ sysname = NULL; else syslabel = "regserver"; if (fullcontact) cw_update_realtime( "sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "useragent", useragent, "fullcontact", fullcontact, syslabel, sysname, NULL); else cw_update_realtime( "sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "useragent", useragent, syslabel, sysname, 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 (!cw_strlen_zero(regcontext)) { cw_copy_string(multi, cw_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi)); stringp = multi; while ((ext = strsep(&stringp, "&"))) { if (onoff) cw_add_extension(regcontext, 1, ext, 1, NULL, NULL, "NoOp", strdup(peer->name), free, channeltype); else cw_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->expire > -1) cw_sched_del(sched, peer->expire); if (peer->pokeexpire > -1) cw_sched_del(sched, peer->pokeexpire); if (peer->call) sip_destroy(peer->call); if (peer->chanvars) { cw_variables_destroy(peer->chanvars); peer->chanvars = NULL; } register_peer_exten(peer, 0); cw_free_ha(peer->ha); if (cw_test_flag(peer, SIP_SELFDESTRUCT)) apeerobjs--; else if (cw_test_flag(peer, SIP_REALTIME)) rpeerobjs--; else speerobjs--; clear_realm_authentication(peer->auth); peer->auth = (struct sip_auth *) NULL; free(peer); } /*! \brief update_peer: Update peer data in database (if used) */ static void update_peer(struct sip_peer *p, int expiry) { int rtcachefriends = cw_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS); if (cw_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) && (cw_test_flag(p, SIP_REALTIME) || rtcachefriends)) { realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry, p->useragent); } } /*! \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 cw_variable *var; struct cw_variable *tmp; char *newpeername = (char *) peername; char iabuf[80]; char iabuf2[10]; int port = 0; /* First check on peer name */ if (newpeername) var = cw_load_realtime("sippeers", "name", peername, NULL); else if (sin) { /* Then check on IP address */ cw_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr); port = ntohs(sin->sin_port); snprintf(iabuf2,sizeof(iabuf2),"%d",port); var = cw_load_realtime("sippeers", "host", iabuf, NULL); if (!var) var = cw_load_realtime("sippeers", "ipaddr", iabuf, "port", iabuf2, 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")) { cw_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 */ cw_log(CW_LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf); cw_variables_destroy(var); return (struct sip_peer *) NULL; } /* Peer found in realtime, now build it in memory */ peer = build_peer(newpeername, var, !cw_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)); if (!peer) { cw_variables_destroy(var); return (struct sip_peer *) NULL; } if (cw_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) { /* Cache peer */ cw_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS); if (cw_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) { if (peer->expire > -1) cw_sched_del(sched, peer->expire); peer->expire = cw_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer); } ASTOBJ_CONTAINER_LINK(&peerl,peer); } else { cw_set_flag(peer, SIP_REALTIME); } cw_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) || (cw_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) { cw_free_ha(user->ha); if (user->chanvars) { cw_variables_destroy(user->chanvars); user->chanvars = NULL; } if (cw_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 cw_variable *var; struct cw_variable *tmp; struct sip_user *user = NULL; var = cw_load_realtime("sipusers", "name", username, NULL); if (!var) return NULL; tmp = var; while (tmp) { if (!strcasecmp(tmp->name, "type") && !strcasecmp(tmp->value, "peer")) { cw_variables_destroy(var); return NULL; } tmp = tmp->next; } user = build_user(username, var, !cw_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)); if (!user) { /* No user found */ cw_variables_destroy(var); return NULL; } if (cw_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) { cw_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS); suserobjs++; ASTOBJ_CONTAINER_LINK(&userl,user); } else { /* Move counter from s to r... */ suserobjs--; ruserobjs++; cw_set_flag(user, SIP_REALTIME); } cw_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; } cw_copy_flags(r, peer, SIP_FLAGS_TO_COPY); r->capability = peer->capability; r->prefs = peer->prefs; r->t38capability = global_t38_capability; if (r->udptl) { if (cw_udptl_get_preferred_error_correction_scheme(r->udptl) == UDPTL_ERROR_CORRECTION_FEC) r->t38capability |= T38FAX_UDP_EC_FEC; else if (cw_udptl_get_preferred_error_correction_scheme(r->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY) r->t38capability |= T38FAX_UDP_EC_REDUNDANCY; r->t38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF; cw_log(CW_LOG_DEBUG,"Our T38 capability (%d)\n", r->t38capability); } r->t38jointcapability = r->t38capability; if (r->rtp) { cw_log(CW_LOG_DEBUG, "Setting NAT on RTP to %d\n", sip_is_nat_needed(r) ); cw_rtp_setnat(r->rtp, sip_is_nat_needed(r) ); } if (r->vrtp) { cw_log(CW_LOG_DEBUG, "Setting NAT on VRTP to %d\n", sip_is_nat_needed(r) ); cw_rtp_setnat(r->vrtp, sip_is_nat_needed(r) ); } if (r->udptl) { cw_log(CW_LOG_DEBUG, "Setting NAT on UDPTL to %d\n", sip_is_nat_needed(r) ); cw_udptl_setnat(r->udptl, sip_is_nat_needed(r) ); } cw_copy_string(r->peername, peer->username, sizeof(r->peername)); cw_copy_string(r->authname, peer->username, sizeof(r->authname)); cw_copy_string(r->username, peer->username, sizeof(r->username)); cw_copy_string(r->peersecret, peer->secret, sizeof(r->peersecret)); cw_copy_string(r->peermd5secret, peer->md5secret, sizeof(r->peermd5secret)); cw_copy_string(r->tohost, peer->tohost, sizeof(r->tohost)); cw_copy_string(r->fullcontact, peer->fullcontact, sizeof(r->fullcontact)); if (!r->initreq.headers && !cw_strlen_zero(peer->fromdomain)) { if ((callhost = strchr(r->callid, '@'))) strncpy(callhost + 1, peer->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2); } if (cw_strlen_zero(r->tohost)) { if (peer->addr.sin_addr.s_addr) cw_inet_ntoa(r->tohost, sizeof(r->tohost), peer->addr.sin_addr); else cw_inet_ntoa(r->tohost, sizeof(r->tohost), peer->defaddr.sin_addr); } if (!cw_strlen_zero(peer->fromdomain)) cw_copy_string(r->fromdomain, peer->fromdomain, sizeof(r->fromdomain)); if (!cw_strlen_zero(peer->fromuser)) cw_copy_string(r->fromuser, peer->fromuser, sizeof(r->fromuser)); if (!cw_strlen_zero(peer->language)) cw_copy_string(r->language, peer->language, sizeof(r->language)); 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 ((cw_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (cw_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO)) r->noncodeccapability |= CW_RTP_DTMF; else r->noncodeccapability &= ~CW_RTP_DTMF; cw_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) cw_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 cw_hostent ahp; struct sip_peer *p; char *port; int portno; char host[MAXHOSTNAMELEN], *hostn; char peer[256]; cw_copy_string(peer, opeer, sizeof(peer)); port = strchr(peer, ':'); if (port) { *port = '\0'; port++; } dialog->sa.sin_family = AF_INET; p = find_peer(peer, NULL, 1); if (p) { int ret = create_addr_from_peer(dialog, p); ASTOBJ_UNREF(p, sip_destroy_peer); return ret; } else { 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 = cw_get_srv(NULL, host, sizeof(host), &tportno, service); if (ret > 0) { hostn = host; portno = tportno; } } if ((hp = cw_gethostbyname(hostn, &ahp))) { cw_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 { cw_log(CW_LOG_WARNING, "No such host: %s\n", peer); return -1; } } } /*! \brief auto_congest: Scheduled congestion on a call */ static int auto_congest(void *nothing) { struct sip_pvt *p = nothing; cw_mutex_lock(&p->lock); p->initid = -1; if (p->owner) { if (!cw_mutex_trylock(&p->owner->lock)) { cw_log(CW_LOG_NOTICE, "Auto-congesting %s\n", p->owner->name); cw_queue_control(p->owner, CW_CONTROL_CONGESTION); cw_mutex_unlock(&p->owner->lock); } } cw_mutex_unlock(&p->lock); return 0; } /*! \brief sip_call: Initiate SIP call from PBX * used from the dial() application */ static int sip_call(struct cw_channel *ast, char *dest) { int res; struct sip_pvt *p; #ifdef OSP_SUPPORT char *osphandle = NULL; #endif struct varshead *headp; struct cw_var_t *current; p = ast->tech_pvt; if ((ast->_state != CW_STATE_DOWN) && (ast->_state != CW_STATE_RESERVED)) { cw_log(CW_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; CW_LIST_TRAVERSE(headp,current,entries) { /* Check whether there is a VXML_URL variable */ if (!p->options->vxml_url && !strcasecmp(cw_var_name(current), "VXML_URL")) { p->options->vxml_url = cw_var_value(current); } else if (!p->options->uri_options && !strcasecmp(cw_var_name(current), "SIP_URI_OPTIONS")) { p->options->uri_options = cw_var_value(current); } else if (!p->options->distinctive_ring && !strcasecmp(cw_var_name(current), "ALERT_INFO")) { /* Check whether there is a ALERT_INFO variable */ p->options->distinctive_ring = cw_var_value(current); } else if (!p->options->addsipheaders && !strncasecmp(cw_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) { /* Check whether there is a variable with a name starting with SIPADDHEADER */ p->options->addsipheaders = 1; } else if (!p->options->t38txdetection && !strncasecmp(cw_var_name(current), "T38TXDETECT", strlen("T38TXDETECT"))) { /* Check whether there is a variable with a name starting with SIPADDHEADER */ p->options->t38txdetection = 1; } else if (!strncasecmp(cw_var_name(current), "T38CALL", strlen("T38CALL"))) { /* Check whether there is a variable with a name starting with T38CALL */ p->t38state = SIP_T38_OFFER_SENT_DIRECT; cw_log(CW_LOG_DEBUG,"T38State change to %d on channel %s\n",p->t38state, ast->name); } #ifdef OSP_SUPPORT else if (!p->options->osptoken && !strcasecmp(cw_var_name(current), "OSPTOKEN")) { p->options->osptoken = cw_var_value(current); } else if (!osphandle && !strcasecmp(cw_var_name(current), "OSPHANDLE")) { osphandle = cw_var_value(current); } #endif } res = 0; cw_set_flag(p, SIP_OUTGOING); #ifdef OSP_SUPPORT if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) { /* Force Disable OSP support */ cw_log(CW_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 cw_log(CW_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; p->t38jointcapability = p->t38capability; cw_log(CW_LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38capability, p->t38jointcapability); transmit_invite(p, SIP_INVITE, 1, 2); if (p->maxtime) { /* Initialize auto-congest time */ p->initid = cw_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) cw_sched_del(sched, reg->expire); if (reg->timeout > -1) cw_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)) cw_verbose("Destroying call '%s'\n", p->callid); if (dumphistory) sip_dump_history(p); if (p->options) free(p->options); if (p->stateid > -1) cw_extension_state_del(p->stateid, NULL); if (p->initid > -1) cw_sched_del(sched, p->initid); if (p->autokillid > -1) cw_sched_del(sched, p->autokillid); if (p->rtp) cw_rtp_destroy(p->rtp); if (p->vrtp) cw_rtp_destroy(p->vrtp); if (p->udptl) cw_udptl_destroy(p->udptl); #if 0 if (p->tpkt) cw_tpkt_destroy(p->tpkt); #endif 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) cw_mutex_lock(&p->owner->lock); cw_log(CW_LOG_DEBUG, "Detaching from %s\n", p->owner->name); p->owner->tech_pvt = NULL; if (lockowner) cw_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) { cw_log(CW_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) cw_sched_del(sched, cp->retransid); free(cp); } if (p->chanvars) { cw_variables_destroy(p->chanvars); p->chanvars = NULL; } cw_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 = cw_test_flag(fup, SIP_OUTGOING); struct sip_user *u = NULL; struct sip_peer *p = NULL; if (option_debug > 2) cw_log(CW_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 (!cw_test_flag(fup, SIP_CALL_LIMIT)) return 0; cw_copy_string(name, fup->username, sizeof(name)); /* Check the list of users */ u = find_user(name, 1); if (!outgoing && 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; cw_copy_string(name, fup->peername, sizeof(name)); } else { if (option_debug > 1) cw_log(CW_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 (cw_test_flag(fup,SIP_INC_COUNT)) { (*inuse)--; cw_clear_flag(fup, SIP_INC_COUNT); } } else *inuse = 0; if (option_debug > 1 || sipdebug) cw_log(CW_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) { cw_log(CW_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)++; cw_set_flag(fup,SIP_INC_COUNT); if (option_debug > 1 || sipdebug) cw_log(CW_LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit); break; default: cw_log(CW_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) { cw_mutex_lock(&iflock); __sip_destroy(p, 1); cw_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 CallWeaver 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 CW_CAUSE_CALL_REJECTED; case 404: /* Not found */ return CW_CAUSE_UNALLOCATED; case 408: /* No reaction */ return CW_CAUSE_NO_USER_RESPONSE; case 480: /* No answer */ return CW_CAUSE_NO_ANSWER; case 483: /* Too many hops */ return CW_CAUSE_NO_ANSWER; case 486: /* Busy everywhere */ return CW_CAUSE_BUSY; case 488: /* No codecs approved */ return CW_CAUSE_BEARERCAPABILITY_NOTAVAIL; case 500: /* Server internal failure */ return CW_CAUSE_FAILURE; case 501: /* Call rejected */ return CW_CAUSE_FACILITY_REJECTED; case 502: return CW_CAUSE_DESTINATION_OUT_OF_ORDER; case 503: /* Service unavailable */ return CW_CAUSE_CONGESTION; default: return CW_CAUSE_NORMAL; } /* Never reached */ return 0; } /*! \brief hangup_cause2sip: Convert CallWeaver hangup causes to SIP codes \verbatim Possible values from causes.h CW_CAUSE_NOTDEFINED CW_CAUSE_NORMAL CW_CAUSE_BUSY CW_CAUSE_FAILURE CW_CAUSE_CONGESTION CW_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 CW_CAUSE_UNALLOCATED: /* 1 */ case CW_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */ case CW_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */ return "404 Not Found"; case CW_CAUSE_CONGESTION: /* 34 */ case CW_CAUSE_SWITCH_CONGESTION: /* 42 */ return "503 Service Unavailable"; case CW_CAUSE_NO_USER_RESPONSE: /* 18 */ return "408 Request Timeout"; case CW_CAUSE_NO_ANSWER: /* 19 */ return "480 Temporarily unavailable"; case CW_CAUSE_CALL_REJECTED: /* 21 */ return "403 Forbidden"; case CW_CAUSE_NUMBER_CHANGED: /* 22 */ return "410 Gone"; case CW_CAUSE_NORMAL_UNSPECIFIED: /* 31 */ return "480 Temporarily unavailable"; case CW_CAUSE_INVALID_NUMBER_FORMAT: return "484 Address incomplete"; case CW_CAUSE_USER_BUSY: return "486 Busy here"; case CW_CAUSE_FAILURE: return "500 Server internal failure"; case CW_CAUSE_FACILITY_REJECTED: /* 29 */ return "501 Not Implemented"; case CW_CAUSE_CHAN_NOT_IMPLEMENTED: return "503 Service Unavailable"; /* Used in chan_iax2 */ case CW_CAUSE_DESTINATION_OUT_OF_ORDER: return "502 Bad Gateway"; case CW_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */ return "488 Not Acceptable Here"; case CW_CAUSE_NOTDEFINED: default: cw_log(CW_LOG_DEBUG, "CW 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 cw_hangup */ static int sip_hangup(struct cw_channel *ast) { struct sip_pvt *p = ast->tech_pvt; int needcancel = 0; int needdestroy = 0; //struct cw_flags locflags = {0}; if (!p) { cw_log(CW_LOG_DEBUG, "Asked to hangup channel not connected\n"); return 0; } if (option_debug) cw_log(CW_LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid); cw_mutex_lock(&p->lock); #ifdef OSP_SUPPORT if ((p->osphandle > -1) && (ast->_state == CW_STATE_UP)) { cw_osp_terminate(p->osphandle, CW_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart); } #endif cw_log(CW_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) { cw_log(CW_LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n"); cw_mutex_unlock(&p->lock); return 0; } /* If the call is not UP, we need to send CANCEL instead of BYE */ if (ast->_state != CW_STATE_UP) needcancel = 1; /* Disconnect */ if (p->vad) cw_dsp_free(p->vad); p->owner = NULL; ast->tech_pvt = NULL; cw_mutex_lock(&usecnt_lock); usecnt--; cw_mutex_unlock(&usecnt_lock); /* 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 (cw_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 (!cw_test_flag(p, SIP_ALREADYGONE) && !cw_strlen_zero(p->initreq.data)) { if (needcancel) { /* Outgoing call, not up */ if (cw_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 (!cw_test_flag(p, SIP_CAN_BYE)) { cw_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); } //cw_clear_flag(&locflags, SIP_NEEDDESTROY); //sip_scheddestroy(p, 15000); } 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. */ cw_set_flag(p, SIP_PENDINGBYE); cw_clear_flag(p, SIP_NEEDREINVITE); } } } if (needdestroy) cw_set_flag(p, SIP_NEEDDESTROY); cw_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 = cw_getformatbyname(codec); if (fmt) { cw_log(CW_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 cw_log(CW_LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n"); } else cw_log(CW_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 cw_channel *ast) { int res = 0; struct sip_pvt *p = ast->tech_pvt; cw_mutex_lock(&p->lock); if (ast->_state != CW_STATE_UP) { #ifdef OSP_SUPPORT time(&p->ospstart); #endif try_suggested_sip_codec(p); cw_setstate(ast, CW_STATE_UP); if (option_debug) cw_log(CW_LOG_DEBUG, "sip_answer(%s)\n", ast->name); if (p->t38state == SIP_T38_OFFER_RECEIVED_DIRECT) { p->t38state = SIP_T38_NEGOTIATED; cw_log(CW_LOG_DEBUG,"T38State change to %d on channel %s\n",p->t38state, ast->name); cw_log(CW_LOG_DEBUG,"T38mode enabled for channel %s\n", ast->name); res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, 2); cw_channel_set_t38_status(ast, T38_NEGOTIATED); } else { res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 2); } } cw_mutex_unlock(&p->lock); return res; } /*! \brief sip_write: Send frame to media channel (rtp) */ static int sip_rtp_write(struct cw_channel *ast, struct cw_frame *frame, int *faxdetect) { struct sip_pvt *p = ast->tech_pvt; int res = 0; switch (frame->frametype) { case CW_FRAME_VOICE: if (!(frame->subclass & ast->nativeformats)) { cw_log(CW_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) { cw_mutex_lock(&p->lock); if (p->rtp) { /* If channel is not up, activate early media session */ if ((ast->_state != CW_STATE_UP) && !cw_test_flag(p, SIP_PROGRESS_SENT) && !cw_test_flag(p, SIP_OUTGOING)) { tran