2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * Implementation of Session Initiation Protocol
30 #include <sys/socket.h>
31 #include <sys/ioctl.h>
38 #include <sys/signal.h>
39 #include <netinet/in.h>
40 #include <netinet/in_systm.h>
41 #include <arpa/inet.h>
42 #include <netinet/ip.h>
47 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
49 #include "asterisk/lock.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/config.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/module.h"
54 #include "asterisk/pbx.h"
55 #include "asterisk/options.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/sched.h"
58 #include "asterisk/io.h"
59 #include "asterisk/rtp.h"
60 #include "asterisk/acl.h"
61 #include "asterisk/manager.h"
62 #include "asterisk/callerid.h"
63 #include "asterisk/cli.h"
64 #include "asterisk/app.h"
65 #include "asterisk/musiconhold.h"
66 #include "asterisk/dsp.h"
67 #include "asterisk/features.h"
68 #include "asterisk/acl.h"
69 #include "asterisk/srv.h"
70 #include "asterisk/astdb.h"
71 #include "asterisk/causes.h"
72 #include "asterisk/utils.h"
73 #include "asterisk/file.h"
74 #include "asterisk/astobj.h"
75 #include "asterisk/dnsmgr.h"
76 #include "asterisk/devicestate.h"
77 #include "asterisk/linkedlists.h"
80 #include "asterisk/astosp.h"
83 #ifndef DEFAULT_USERAGENT
84 #define DEFAULT_USERAGENT "Asterisk PBX"
87 #define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
89 #define IPTOS_MINCOST 0x02
92 /* #define VOCAL_DATA_HACK */
95 #define DEFAULT_DEFAULT_EXPIRY 120
96 #define DEFAULT_MAX_EXPIRY 3600
97 #define DEFAULT_REGISTRATION_TIMEOUT 20
98 #define DEFAULT_REGATTEMPTS_MAX 10
100 /* guard limit must be larger than guard secs */
101 /* guard min must be < 1000, and should be >= 250 */
102 #define EXPIRY_GUARD_SECS 15 /* How long before expiry do we reregister */
103 #define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of
105 #define EXPIRY_GUARD_MIN 500 /* This is the minimum guard time applied. If
106 GUARD_PCT turns out to be lower than this, it
107 will use this time instead.
108 This is in milliseconds. */
109 #define EXPIRY_GUARD_PCT 0.20 /* Percentage of expires timeout to use when
110 below EXPIRY_GUARD_LIMIT */
112 static int max_expiry = DEFAULT_MAX_EXPIRY;
113 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
116 #define MAX(a,b) ((a) > (b) ? (a) : (b))
119 #define CALLERID_UNKNOWN "Unknown"
123 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
124 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
125 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
127 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
128 /* 2 * 500 ms in RFC 3261 */
129 #define MAX_RETRANS 6 /* Try only 6 times for retransmissions, a total of 7 transmissions */
130 #define MAX_AUTHTRIES 3 /* Try authentication three times, then fail */
133 #define DEBUG_READ 0 /* Recieved data */
134 #define DEBUG_SEND 1 /* Transmit data */
136 static const char desc[] = "Session Initiation Protocol (SIP)";
137 static const char channeltype[] = "SIP";
138 static const char config[] = "sip.conf";
139 static const char notify_config[] = "sip_notify.conf";
144 /* Do _NOT_ make any changes to this enum, or the array following it;
145 if you think you are doing the right thing, you are probably
146 not doing the right thing. If you think there are changes
147 needed, get someone else to review them first _before_
148 submitting a patch. If these two lists do not match properly
149 bad things will happen.
152 enum subscriptiontype {
161 static const struct cfsubscription_types {
162 enum subscriptiontype type;
163 const char * const event;
164 const char * const mediatype;
165 const char * const text;
166 } subscription_types[] = {
167 { NONE, "-", "unknown", "unknown" },
168 /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
169 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
170 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
171 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
172 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" } /* Pre-RFC 3863 with MS additions */
199 static const struct cfsip_methods {
201 int need_rtp; /* when this is the 'primary' use for a pvt structure, does it need RTP? */
204 { SIP_UNKNOWN, RTP, "-UNKNOWN-" },
205 { SIP_RESPONSE, NO_RTP, "SIP/2.0" },
206 { SIP_REGISTER, NO_RTP, "REGISTER" },
207 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
208 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
209 { SIP_INVITE, RTP, "INVITE" },
210 { SIP_ACK, NO_RTP, "ACK" },
211 { SIP_PRACK, NO_RTP, "PRACK" },
212 { SIP_BYE, NO_RTP, "BYE" },
213 { SIP_REFER, NO_RTP, "REFER" },
214 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
215 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
216 { SIP_UPDATE, NO_RTP, "UPDATE" },
217 { SIP_INFO, NO_RTP, "INFO" },
218 { SIP_CANCEL, NO_RTP, "CANCEL" },
219 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
222 /* Structure for conversion between compressed SIP and "normal" SIP */
223 static const struct cfalias {
224 char * const fullname;
225 char * const shortname;
227 { "Content-Type", "c" },
228 { "Content-Encoding", "e" },
232 { "Content-Length", "l" },
235 { "Supported", "k" },
237 { "Referred-By", "b" },
238 { "Allow-Events", "u" },
241 { "Accept-Contact", "a" },
242 { "Reject-Contact", "j" },
243 { "Request-Disposition", "d" },
244 { "Session-Expires", "x" },
247 /* Define SIP option tags, used in Require: and Supported: headers */
248 /* We need to be aware of these properties in the phones to use
249 the replace: header. We should not do that without knowing
250 that the other end supports it...
251 This is nothing we can configure, we learn by the dialog
252 Supported: header on the REGISTER (peer) or the INVITE
254 We are not using many of these today, but will in the future.
255 This is documented in RFC 3261
258 #define NOT_SUPPORTED 0
260 #define SIP_OPT_REPLACES (1 << 0)
261 #define SIP_OPT_100REL (1 << 1)
262 #define SIP_OPT_TIMER (1 << 2)
263 #define SIP_OPT_EARLY_SESSION (1 << 3)
264 #define SIP_OPT_JOIN (1 << 4)
265 #define SIP_OPT_PATH (1 << 5)
266 #define SIP_OPT_PREF (1 << 6)
267 #define SIP_OPT_PRECONDITION (1 << 7)
268 #define SIP_OPT_PRIVACY (1 << 8)
269 #define SIP_OPT_SDP_ANAT (1 << 9)
270 #define SIP_OPT_SEC_AGREE (1 << 10)
271 #define SIP_OPT_EVENTLIST (1 << 11)
272 #define SIP_OPT_GRUU (1 << 12)
273 #define SIP_OPT_TARGET_DIALOG (1 << 13)
275 /* List of well-known SIP options. If we get this in a require,
276 we should check the list and answer accordingly. */
277 static const struct cfsip_options {
278 int id; /* Bitmap ID */
279 int supported; /* Supported by Asterisk ? */
280 char * const text; /* Text id, as in standard */
282 /* Replaces: header for transfer */
283 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
284 /* RFC3262: PRACK 100% reliability */
285 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
286 /* SIP Session Timers */
287 { SIP_OPT_TIMER, NOT_SUPPORTED, "timer" },
288 /* RFC3959: SIP Early session support */
289 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
290 /* SIP Join header support */
291 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
292 /* RFC3327: Path support */
293 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
294 /* RFC3840: Callee preferences */
295 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
296 /* RFC3312: Precondition support */
297 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
298 /* RFC3323: Privacy with proxies*/
299 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
300 /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
301 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
302 /* RFC3329: Security agreement mechanism */
303 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
304 /* SIMPLE events: draft-ietf-simple-event-list-07.txt */
305 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
306 /* GRUU: Globally Routable User Agent URI's */
307 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
308 /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
309 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "target-dialog" },
313 /* SIP Methods we support */
314 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
316 /* SIP Extensions we support */
317 #define SUPPORTED_EXTENSIONS "replaces"
319 #define DEFAULT_SIP_PORT 5060 /* From RFC 3261 (former 2543) */
320 #define SIP_MAX_PACKET 4096 /* Also from RFC 3261 (2543), should sub headers tho */
322 static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
324 #define DEFAULT_CONTEXT "default"
325 static char default_context[AST_MAX_CONTEXT] = DEFAULT_CONTEXT;
326 static char default_subscribecontext[AST_MAX_CONTEXT];
328 #define DEFAULT_VMEXTEN "asterisk"
329 static char global_vmexten[AST_MAX_EXTENSION] = DEFAULT_VMEXTEN;
331 static char default_language[MAX_LANGUAGE] = "";
333 #define DEFAULT_CALLERID "asterisk"
334 static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
336 static char default_fromdomain[AST_MAX_EXTENSION] = "";
338 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
339 static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
341 static int global_notifyringing = 1; /* Send notifications on ringing */
343 static int default_qualify = 0; /* Default Qualify= setting */
345 static struct ast_flags global_flags = {0}; /* global SIP_ flags */
346 static struct ast_flags global_flags_page2 = {0}; /* more global SIP_ flags */
348 static int srvlookup = 0; /* SRV Lookup on or off. Default is off, RFC behavior is on */
350 static int pedanticsipchecking = 0; /* Extra checking ? Default off */
352 static int autocreatepeer = 0; /* Auto creation of peers at registration? Default off. */
354 static int relaxdtmf = 0;
356 static int global_rtptimeout = 0;
358 static int global_rtpholdtimeout = 0;
360 static int global_rtpkeepalive = 0;
362 static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
363 static int global_regattempts_max = DEFAULT_REGATTEMPTS_MAX;
365 /* Object counters */
366 static int suserobjs = 0;
367 static int ruserobjs = 0;
368 static int speerobjs = 0;
369 static int rpeerobjs = 0;
370 static int apeerobjs = 0;
371 static int regobjs = 0;
373 static int global_allowguest = 1; /* allow unauthenticated users/peers to connect? */
375 #define DEFAULT_MWITIME 10
376 static int global_mwitime = DEFAULT_MWITIME; /* Time between MWI checks for peers */
378 static int usecnt =0;
379 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
382 /* Protect the interface list (of sip_pvt's) */
383 AST_MUTEX_DEFINE_STATIC(iflock);
385 /* Protect the monitoring thread, so only one process can kill or start it, and not
386 when it's doing something critical. */
387 AST_MUTEX_DEFINE_STATIC(netlock);
389 AST_MUTEX_DEFINE_STATIC(monlock);
391 /* This is the thread for the monitor which checks for input on the channels
392 which are not currently in use. */
393 static pthread_t monitor_thread = AST_PTHREADT_NULL;
395 static int restart_monitor(void);
397 /* Codecs that we support by default: */
398 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
399 static int noncodeccapability = AST_RTP_DTMF;
401 static struct in_addr __ourip;
402 static struct sockaddr_in outboundproxyip;
405 #define SIP_DEBUG_CONFIG 1 << 0
406 #define SIP_DEBUG_CONSOLE 1 << 1
407 static int sipdebug = 0;
408 static struct sockaddr_in debugaddr;
412 static int videosupport = 0;
414 static int compactheaders = 0; /* send compact sip headers */
416 static int recordhistory = 0; /* Record SIP history. Off by default */
417 static int dumphistory = 0; /* Dump history to verbose before destroying SIP dialog */
419 static char global_musicclass[MAX_MUSICCLASS] = ""; /* Global music on hold class */
420 #define DEFAULT_REALM "asterisk"
421 static char global_realm[MAXHOSTNAMELEN] = DEFAULT_REALM; /* Default realm */
422 static char regcontext[AST_MAX_CONTEXT] = ""; /* Context for auto-extensions */
425 #define DEFAULT_EXPIRY 900
426 static int expiry = DEFAULT_EXPIRY;
428 static struct sched_context *sched;
429 static struct io_context *io;
430 /* The private structures of the sip channels are linked for
431 selecting outgoing channels */
433 #define SIP_MAX_HEADERS 64
434 #define SIP_MAX_LINES 64
436 #define DEC_CALL_LIMIT 0
437 #define INC_CALL_LIMIT 1
439 static struct ast_codec_pref prefs;
442 /* sip_request: The data grabbed from the UDP socket */
444 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
445 char *rlPart2; /* The Request URI or Response Status */
446 int len; /* Length */
447 int headers; /* # of SIP Headers */
448 int method; /* Method of this request */
449 char *header[SIP_MAX_HEADERS];
450 int lines; /* SDP Content */
451 char *line[SIP_MAX_LINES];
452 char data[SIP_MAX_PACKET];
453 int debug; /* Debug flag for this packet */
458 /* Parameters to the transmit_invite function */
459 struct sip_invite_param {
460 char *distinctive_ring;
467 enum sip_auth_type auth_type;
471 struct sip_route *next;
481 char domain[MAXHOSTNAMELEN];
482 char context[AST_MAX_EXTENSION];
483 enum domain_mode mode;
484 AST_LIST_ENTRY(domain) list;
487 static AST_LIST_HEAD_STATIC(domain_list, domain);
489 int allow_external_domains;
491 /* sip_history: Structure for saving transactions within a SIP dialog */
494 struct sip_history *next;
497 /* sip_auth: Creadentials for authentication to other SIP services */
499 char realm[AST_MAX_EXTENSION]; /* Realm in which these credentials are valid */
500 char username[256]; /* Username */
501 char secret[256]; /* Secret */
502 char md5secret[256]; /* MD5Secret */
503 struct sip_auth *next; /* Next auth structure in list */
506 #define SIP_ALREADYGONE (1 << 0) /* Whether or not we've already been destroyed by our peer */
507 #define SIP_NEEDDESTROY (1 << 1) /* if we need to be destroyed */
508 #define SIP_NOVIDEO (1 << 2) /* Didn't get video in invite, don't offer */
509 #define SIP_RINGING (1 << 3) /* Have sent 180 ringing */
510 #define SIP_PROGRESS_SENT (1 << 4) /* Have sent 183 message progress */
511 #define SIP_NEEDREINVITE (1 << 5) /* Do we need to send another reinvite? */
512 #define SIP_PENDINGBYE (1 << 6) /* Need to send bye after we ack? */
513 #define SIP_GOTREFER (1 << 7) /* Got a refer? */
514 #define SIP_PROMISCREDIR (1 << 8) /* Promiscuous redirection */
515 #define SIP_TRUSTRPID (1 << 9) /* Trust RPID headers? */
516 #define SIP_USEREQPHONE (1 << 10) /* Add user=phone to numeric URI. Default off */
517 #define SIP_REALTIME (1 << 11) /* Flag for realtime users */
518 #define SIP_USECLIENTCODE (1 << 12) /* Trust X-ClientCode info message */
519 #define SIP_OUTGOING (1 << 13) /* Is this an outgoing call? */
520 #define SIP_SELFDESTRUCT (1 << 14)
521 #define SIP_DYNAMIC (1 << 15) /* Is this a dynamic peer? */
522 /* --- Choices for DTMF support in SIP channel */
523 #define SIP_DTMF (3 << 16) /* three settings, uses two bits */
524 #define SIP_DTMF_RFC2833 (0 << 16) /* RTP DTMF */
525 #define SIP_DTMF_INBAND (1 << 16) /* Inband audio, only for ULAW/ALAW */
526 #define SIP_DTMF_INFO (2 << 16) /* SIP Info messages */
527 #define SIP_DTMF_AUTO (3 << 16) /* AUTO switch between rfc2833 and in-band DTMF */
529 #define SIP_NAT (3 << 18) /* four settings, uses two bits */
530 #define SIP_NAT_NEVER (0 << 18) /* No nat support */
531 #define SIP_NAT_RFC3581 (1 << 18)
532 #define SIP_NAT_ROUTE (2 << 18)
533 #define SIP_NAT_ALWAYS (3 << 18)
534 /* re-INVITE related settings */
535 #define SIP_REINVITE (3 << 20) /* two bits used */
536 #define SIP_CAN_REINVITE (1 << 20) /* allow peers to be reinvited to send media directly p2p */
537 #define SIP_REINVITE_UPDATE (2 << 20) /* use UPDATE (RFC3311) when reinviting this peer */
538 /* "insecure" settings */
539 #define SIP_INSECURE_PORT (1 << 22) /* don't require matching port for incoming requests */
540 #define SIP_INSECURE_INVITE (1 << 23) /* don't require authentication for incoming INVITEs */
541 /* Sending PROGRESS in-band settings */
542 #define SIP_PROG_INBAND (3 << 24) /* three settings, uses two bits */
543 #define SIP_PROG_INBAND_NEVER (0 << 24)
544 #define SIP_PROG_INBAND_NO (1 << 24)
545 #define SIP_PROG_INBAND_YES (2 << 24)
546 /* Open Settlement Protocol authentication */
547 #define SIP_OSPAUTH (3 << 26) /* four settings, uses two bits */
548 #define SIP_OSPAUTH_NO (0 << 26)
549 #define SIP_OSPAUTH_GATEWAY (1 << 26)
550 #define SIP_OSPAUTH_PROXY (2 << 26)
551 #define SIP_OSPAUTH_EXCLUSIVE (3 << 26)
553 #define SIP_CALL_ONHOLD (1 << 28)
554 #define SIP_CALL_LIMIT (1 << 29)
555 /* Remote Party-ID Support */
556 #define SIP_SENDRPID (1 << 30)
558 #define SIP_FLAGS_TO_COPY \
559 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
560 SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
561 SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
563 /* a new page of flags for peer */
564 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
565 #define SIP_PAGE2_RTUPDATE (1 << 1)
566 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
567 #define SIP_PAGE2_RTIGNOREREGEXPIRE (1 << 3)
569 static int global_rtautoclear = 120;
571 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call */
572 static struct sip_pvt {
573 ast_mutex_t lock; /* Channel private lock */
574 int method; /* SIP method of this packet */
575 char callid[80]; /* Global CallID */
576 char randdata[80]; /* Random data */
577 struct ast_codec_pref prefs; /* codec prefs */
578 unsigned int ocseq; /* Current outgoing seqno */
579 unsigned int icseq; /* Current incoming seqno */
580 ast_group_t callgroup; /* Call group */
581 ast_group_t pickupgroup; /* Pickup group */
582 int lastinvite; /* Last Cseq of invite */
583 unsigned int flags; /* SIP_ flags */
584 int timer_t1; /* SIP timer T1, ms rtt */
585 unsigned int sipoptions; /* Supported SIP sipoptions on the other end */
586 int capability; /* Special capability (codec) */
587 int jointcapability; /* Supported capability at both ends (codecs ) */
588 int peercapability; /* Supported peer capability */
589 int prefcodec; /* Preferred codec (outbound only) */
590 int noncodeccapability;
591 int callingpres; /* Calling presentation */
592 int authtries; /* Times we've tried to authenticate */
593 int expiry; /* How long we take to expire */
594 int branch; /* One random number */
595 char tag[11]; /* Another random number */
596 int sessionid; /* SDP Session ID */
597 int sessionversion; /* SDP Session Version */
598 struct sockaddr_in sa; /* Our peer */
599 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
600 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
601 int redircodecs; /* Redirect codecs */
602 struct sockaddr_in recv; /* Received as */
603 struct in_addr ourip; /* Our IP */
604 struct ast_channel *owner; /* Who owns us */
605 char exten[AST_MAX_EXTENSION]; /* Extension where to start */
606 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
607 char referred_by[AST_MAX_EXTENSION]; /* Place to store REFERRED-BY extension */
608 char refer_contact[AST_MAX_EXTENSION]; /* Place to store Contact info from a REFER extension */
609 struct sip_pvt *refer_call; /* Call we are referring */
610 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
611 int route_persistant; /* Is this the "real" route? */
612 char from[256]; /* The From: header */
613 char useragent[256]; /* User agent in SIP request */
614 char context[AST_MAX_CONTEXT]; /* Context for this call */
615 char subscribecontext[AST_MAX_CONTEXT]; /* Subscribecontext */
616 char fromdomain[MAXHOSTNAMELEN]; /* Domain to show in the from field */
617 char fromuser[AST_MAX_EXTENSION]; /* User to show in the user field */
618 char fromname[AST_MAX_EXTENSION]; /* Name to show in the user field */
619 char tohost[MAXHOSTNAMELEN]; /* Host we should put in the "to" field */
620 char language[MAX_LANGUAGE]; /* Default language for this call */
621 char musicclass[MAX_MUSICCLASS]; /* Music on Hold class */
622 char rdnis[256]; /* Referring DNIS */
623 char theirtag[256]; /* Their tag */
624 char username[256]; /* [user] name */
625 char peername[256]; /* [peer] name, not set if [user] */
626 char authname[256]; /* Who we use for authentication */
627 char uri[256]; /* Original requested URI */
628 char okcontacturi[256]; /* URI from the 200 OK on INVITE */
629 char peersecret[256]; /* Password */
630 char peermd5secret[256];
631 struct sip_auth *peerauth; /* Realm authentication */
632 char cid_num[256]; /* Caller*ID */
633 char cid_name[256]; /* Caller*ID */
634 char via[256]; /* Via: header */
635 char fullcontact[128]; /* The Contact: that the UA registers with us */
636 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
637 char our_contact[256]; /* Our contact header */
638 char *rpid; /* Our RPID header */
639 char *rpid_from; /* Our RPID From header */
640 char realm[MAXHOSTNAMELEN]; /* Authorization realm */
641 char nonce[256]; /* Authorization nonce */
642 int noncecount; /* Nonce-count */
643 char opaque[256]; /* Opaque nonsense */
644 char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
645 char domain[MAXHOSTNAMELEN]; /* Authorization domain */
646 char lastmsg[256]; /* Last Message sent/received */
647 int amaflags; /* AMA Flags */
648 int pendinginvite; /* Any pending invite */
650 int osphandle; /* OSP Handle for call */
651 time_t ospstart; /* OSP Start time */
652 unsigned int osptimelimit; /* OSP call duration limit */
654 struct sip_request initreq; /* Initial request */
656 int maxtime; /* Max time for first response */
657 int maxforwards; /* keep the max-forwards info */
658 int initid; /* Auto-congest ID if appropriate */
659 int autokillid; /* Auto-kill ID */
660 time_t lastrtprx; /* Last RTP received */
661 time_t lastrtptx; /* Last RTP sent */
662 int rtptimeout; /* RTP timeout time */
663 int rtpholdtimeout; /* RTP timeout when on hold */
664 int rtpkeepalive; /* Send RTP packets for keepalive */
665 enum subscriptiontype subscribed; /* Is this call a subscription? */
667 int laststate; /* Last known extension state */
670 struct ast_dsp *vad; /* Voice Activation Detection dsp */
672 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
673 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
674 struct ast_rtp *rtp; /* RTP Session */
675 struct ast_rtp *vrtp; /* Video RTP session */
676 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
677 struct sip_history *history; /* History of this SIP dialog */
678 struct ast_variable *chanvars; /* Channel variables to set for call */
679 struct sip_pvt *next; /* Next call in chain */
680 struct sip_invite_param *options; /* Options for INVITE */
683 #define FLAG_RESPONSE (1 << 0)
684 #define FLAG_FATAL (1 << 1)
686 /* sip packet - read in sipsock_read, transmitted in send_request */
688 struct sip_pkt *next; /* Next packet */
689 int retrans; /* Retransmission number */
690 int method; /* SIP method for this packet */
691 int seqno; /* Sequence number */
692 unsigned int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
693 struct sip_pvt *owner; /* Owner call */
694 int retransid; /* Retransmission ID */
695 int timer_a; /* SIP timer A, retransmission timer */
696 int timer_t1; /* SIP Timer T1, estimated RTT or 500 ms */
697 int packetlen; /* Length of packet */
701 /* Structure for SIP user data. User's place calls to us */
703 /* Users who can access various contexts */
704 ASTOBJ_COMPONENTS(struct sip_user);
705 char secret[80]; /* Password */
706 char md5secret[80]; /* Password in md5 */
707 char context[AST_MAX_CONTEXT]; /* Default context for incoming calls */
708 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
709 char cid_num[80]; /* Caller ID num */
710 char cid_name[80]; /* Caller ID name */
711 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
712 char language[MAX_LANGUAGE]; /* Default language for this user */
713 char musicclass[MAX_MUSICCLASS];/* Music on Hold class */
714 char useragent[256]; /* User agent in SIP request */
715 struct ast_codec_pref prefs; /* codec prefs */
716 ast_group_t callgroup; /* Call group */
717 ast_group_t pickupgroup; /* Pickup Group */
718 unsigned int flags; /* SIP flags */
719 unsigned int sipoptions; /* Supported SIP options */
720 struct ast_flags flags_page2; /* SIP_PAGE2 flags */
721 int amaflags; /* AMA flags for billing */
722 int callingpres; /* Calling id presentation */
723 int capability; /* Codec capability */
724 int inUse; /* Number of calls in use */
725 int call_limit; /* Limit of concurrent calls */
726 struct ast_ha *ha; /* ACL setting */
727 struct ast_variable *chanvars; /* Variables to set for channel created by user */
730 /* Structure for SIP peer data, we place calls to peers if registered or fixed IP address (host) */
732 ASTOBJ_COMPONENTS(struct sip_peer); /* name, refcount, objflags, object pointers */
733 /* peer->name is the unique name of this object */
734 char secret[80]; /* Password */
735 char md5secret[80]; /* Password in MD5 */
736 struct sip_auth *auth; /* Realm authentication list */
737 char context[AST_MAX_CONTEXT]; /* Default context for incoming calls */
738 char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
739 char username[80]; /* Temporary username until registration */
740 char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
741 int amaflags; /* AMA Flags (for billing) */
742 char tohost[MAXHOSTNAMELEN]; /* If not dynamic, IP address */
743 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
744 char fromuser[80]; /* From: user when calling this peer */
745 char fromdomain[MAXHOSTNAMELEN]; /* From: domain when calling this peer */
746 char fullcontact[256]; /* Contact registered with us (not in sip.conf) */
747 char cid_num[80]; /* Caller ID num */
748 char cid_name[80]; /* Caller ID name */
749 int callingpres; /* Calling id presentation */
750 int inUse; /* Number of calls in use */
751 int call_limit; /* Limit of concurrent calls */
752 char vmexten[AST_MAX_EXTENSION]; /* Dialplan extension for MWI notify message*/
753 char mailbox[AST_MAX_EXTENSION]; /* Mailbox setting for MWI checks */
754 char language[MAX_LANGUAGE]; /* Default language for prompts */
755 char musicclass[MAX_MUSICCLASS];/* Music on Hold class */
756 char useragent[256]; /* User agent in SIP request (saved from registration) */
757 struct ast_codec_pref prefs; /* codec prefs */
759 time_t lastmsgcheck; /* Last time we checked for MWI */
760 unsigned int flags; /* SIP flags */
761 unsigned int sipoptions; /* Supported SIP options */
762 struct ast_flags flags_page2; /* SIP_PAGE2 flags */
763 int expire; /* When to expire this peer registration */
764 int capability; /* Codec capability */
765 int rtptimeout; /* RTP timeout */
766 int rtpholdtimeout; /* RTP Hold Timeout */
767 int rtpkeepalive; /* Send RTP packets for keepalive */
768 ast_group_t callgroup; /* Call group */
769 ast_group_t pickupgroup; /* Pickup group */
770 struct ast_dnsmgr_entry *dnsmgr;/* DNS refresh manager for peer */
771 struct sockaddr_in addr; /* IP address of peer */
774 struct sip_pvt *call; /* Call pointer */
775 int pokeexpire; /* When to expire poke (qualify= checking) */
776 int lastms; /* How long last response took (in ms), or -1 for no response */
777 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
778 struct timeval ps; /* Ping send time */
780 struct sockaddr_in defaddr; /* Default IP address, used until registration */
781 struct ast_ha *ha; /* Access control list */
782 struct ast_variable *chanvars; /* Variables to set for channel created by user */
786 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
787 static int sip_reloading = 0;
789 /* States for outbound registrations (with register= lines in sip.conf */
790 #define REG_STATE_UNREGISTERED 0
791 #define REG_STATE_REGSENT 1
792 #define REG_STATE_AUTHSENT 2
793 #define REG_STATE_REGISTERED 3
794 #define REG_STATE_REJECTED 4
795 #define REG_STATE_TIMEOUT 5
796 #define REG_STATE_NOAUTH 6
797 #define REG_STATE_FAILED 7
800 /* sip_registry: Registrations with other SIP proxies */
801 struct sip_registry {
802 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
803 int portno; /* Optional port override */
804 char username[80]; /* Who we are registering as */
805 char authuser[80]; /* Who we *authenticate* as */
806 char hostname[MAXHOSTNAMELEN]; /* Domain or host we register to */
807 char secret[80]; /* Password or key name in []'s */
809 char contact[256]; /* Contact extension */
811 int expire; /* Sched ID of expiration */
812 int regattempts; /* Number of attempts (since the last success) */
813 int timeout; /* sched id of sip_reg_timeout */
814 int refresh; /* How often to refresh */
815 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
816 int regstate; /* Registration state (see above) */
817 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
818 char callid[80]; /* Global CallID for this registry */
819 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
820 struct sockaddr_in us; /* Who the server thinks we are */
823 char realm[MAXHOSTNAMELEN]; /* Authorization realm */
824 char nonce[256]; /* Authorization nonce */
825 char domain[MAXHOSTNAMELEN]; /* Authorization domain */
826 char opaque[256]; /* Opaque nonsense */
827 char qop[80]; /* Quality of Protection. */
828 int noncecount; /* Nonce-count */
830 char lastmsg[256]; /* Last Message sent/received */
833 /*--- The user list: Users and friends ---*/
834 static struct ast_user_list {
835 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
838 /*--- The peer list: Peers and Friends ---*/
839 static struct ast_peer_list {
840 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
843 /*--- The register list: Other SIP proxys we register with and call ---*/
844 static struct ast_register_list {
845 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
850 static int __sip_do_register(struct sip_registry *r);
852 static int sipsock = -1;
855 static struct sockaddr_in bindaddr;
856 static struct sockaddr_in externip;
857 static char externhost[MAXHOSTNAMELEN] = "";
858 static time_t externexpire = 0;
859 static int externrefresh = 10;
860 static struct ast_ha *localaddr;
862 /* The list of manual NOTIFY types we know how to send */
863 struct ast_config *notify_types;
865 static struct sip_auth *authl; /* Authentication list */
868 static struct ast_frame *sip_read(struct ast_channel *ast);
869 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
870 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
871 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
872 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header, int stale);
873 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
874 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
875 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
876 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
877 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
878 static int transmit_info_with_vidupdate(struct sip_pvt *p);
879 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
880 static int transmit_refer(struct sip_pvt *p, const char *dest);
881 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
882 static struct sip_peer *temp_peer(const char *name);
883 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
884 static void free_old_route(struct sip_route *route);
885 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
886 static int update_call_counter(struct sip_pvt *fup, int event);
887 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
888 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
889 static int sip_do_reload(void);
890 static int expire_register(void *data);
891 static int callevents = 0;
893 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
894 static int sip_devicestate(void *data);
895 static int sip_sendtext(struct ast_channel *ast, const char *text);
896 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
897 static int sip_hangup(struct ast_channel *ast);
898 static int sip_answer(struct ast_channel *ast);
899 static struct ast_frame *sip_read(struct ast_channel *ast);
900 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
901 static int sip_indicate(struct ast_channel *ast, int condition);
902 static int sip_transfer(struct ast_channel *ast, const char *dest);
903 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
904 static int sip_senddigit(struct ast_channel *ast, char digit);
905 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
906 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
907 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm); /* Find authentication for a specific realm */
908 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
909 static void append_date(struct sip_request *req); /* Append date to SIP packet */
910 static int determine_firstline_parts(struct sip_request *req);
911 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
912 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
913 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate);
915 /* Definition of this channel for channel registration */
916 static const struct ast_channel_tech sip_tech = {
918 .description = "Session Initiation Protocol (SIP)",
919 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
920 .properties = AST_CHAN_TP_WANTSJITTER,
921 .requester = sip_request_call,
922 .devicestate = sip_devicestate,
924 .hangup = sip_hangup,
925 .answer = sip_answer,
928 .write_video = sip_write,
929 .indicate = sip_indicate,
930 .transfer = sip_transfer,
932 .send_digit = sip_senddigit,
933 .bridge = ast_rtp_bridge,
934 .send_text = sip_sendtext,
937 /*--- find_sip_method: Find SIP method from header */
938 int find_sip_method(char *msg)
942 if (!msg || ast_strlen_zero(msg))
945 /* Strictly speaking, SIP methods are case SENSITIVE, but we don't check */
946 /* following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
947 for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
948 if (!strcasecmp(sip_methods[i].text, msg))
949 res = sip_methods[i].id;
954 /*--- parse_sip_options: Parse supported header in incoming packet */
955 unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
959 char *temp = ast_strdupa(supported);
961 unsigned int profile = 0;
963 if (!supported || ast_strlen_zero(supported) )
966 if (option_debug > 2 && sipdebug)
967 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
972 if ( (sep = strchr(next, ',')) != NULL) {
976 while (*next == ' ') /* Skip spaces */
978 if (option_debug > 2 && sipdebug)
979 ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
980 for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
981 if (!strcasecmp(next, sip_options[i].text)) {
982 profile |= sip_options[i].id;
984 if (option_debug > 2 && sipdebug)
985 ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
989 if (option_debug > 2 && sipdebug)
990 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
994 pvt->sipoptions = profile;
996 ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
1001 /*--- sip_debug_test_addr: See if we pass debug IP filter */
1002 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
1006 if (debugaddr.sin_addr.s_addr) {
1007 if (((ntohs(debugaddr.sin_port) != 0)
1008 && (debugaddr.sin_port != addr->sin_port))
1009 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1015 /*--- sip_debug_test_pvt: Test PVT for debugging output */
1016 static inline int sip_debug_test_pvt(struct sip_pvt *p)
1020 return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
1024 /*--- __sip_xmit: Transmit SIP message ---*/
1025 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1028 char iabuf[INET_ADDRSTRLEN];
1030 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1031 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
1033 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
1035 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), res, strerror(errno));
1040 static void sip_destroy(struct sip_pvt *p);
1042 /*--- build_via: Build a Via header for a request ---*/
1043 static void build_via(struct sip_pvt *p, char *buf, int len)
1045 char iabuf[INET_ADDRSTRLEN];
1047 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1048 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581)
1049 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
1050 else /* Work around buggy UNIDEN UIP200 firmware */
1051 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
1054 /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
1055 /* Only used for outbound registrations */
1056 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1059 * Using the localaddr structure built up with localnet statements
1060 * apply it to their address to see if we need to substitute our
1061 * externip or can get away with our internal bindaddr
1063 struct sockaddr_in theirs;
1064 theirs.sin_addr = *them;
1065 if (localaddr && externip.sin_addr.s_addr &&
1066 ast_apply_ha(localaddr, &theirs)) {
1067 char iabuf[INET_ADDRSTRLEN];
1068 if (externexpire && (time(NULL) >= externexpire)) {
1069 struct ast_hostent ahp;
1071 time(&externexpire);
1072 externexpire += externrefresh;
1073 if ((hp = ast_gethostbyname(externhost, &ahp))) {
1074 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1076 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1078 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
1079 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1080 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1082 else if (bindaddr.sin_addr.s_addr)
1083 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
1085 return ast_ouraddrfor(them, us);
1089 /*--- append_history: Append to SIP dialog history */
1090 /* Always returns 0 */
1091 static int append_history(struct sip_pvt *p, const char *event, const char *data)
1093 struct sip_history *hist, *prev;
1096 if (!recordhistory || !p)
1098 if(!(hist = malloc(sizeof(struct sip_history)))) {
1099 ast_log(LOG_WARNING, "Can't allocate memory for history");
1102 memset(hist, 0, sizeof(struct sip_history));
1103 snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
1104 /* Trim up nicely */
1107 if ((*c == '\r') || (*c == '\n')) {
1113 /* Enqueue into history */
1125 /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
1126 static int retrans_pkt(void *data)
1128 struct sip_pkt *pkt=data, *prev, *cur = NULL;
1129 char iabuf[INET_ADDRSTRLEN];
1130 int reschedule = DEFAULT_RETRANS;
1133 ast_mutex_lock(&pkt->owner->lock);
1135 if (pkt->retrans < MAX_RETRANS) {
1139 if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
1140 if (sipdebug && option_debug > 3)
1141 ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
1145 if (sipdebug && option_debug > 3)
1146 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1150 pkt->timer_a = 2 * pkt->timer_a;
1152 /* For non-invites, a maximum of 4 secs */
1153 siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
1154 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1157 /* Reschedule re-transmit */
1158 reschedule = siptimer_a;
1159 if (option_debug > 3)
1160 ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
1163 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1164 if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
1165 ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
1167 ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
1169 snprintf(buf, sizeof(buf), "ReTx %d", reschedule);
1171 append_history(pkt->owner, buf, pkt->data);
1172 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1173 ast_mutex_unlock(&pkt->owner->lock);
1176 /* Too many retries */
1177 if (pkt->owner && pkt->method != SIP_OPTIONS) {
1178 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1179 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
1181 if (pkt->method == SIP_OPTIONS && sipdebug)
1182 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1184 append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1186 pkt->retransid = -1;
1188 if (ast_test_flag(pkt, FLAG_FATAL)) {
1189 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1190 ast_mutex_unlock(&pkt->owner->lock);
1192 ast_mutex_lock(&pkt->owner->lock);
1194 if (pkt->owner->owner) {
1195 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
1196 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1197 ast_queue_hangup(pkt->owner->owner);
1198 ast_mutex_unlock(&pkt->owner->owner->lock);
1200 /* If no channel owner, destroy now */
1201 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
1204 /* In any case, go ahead and remove the packet */
1206 cur = pkt->owner->packets;
1215 prev->next = cur->next;
1217 pkt->owner->packets = cur->next;
1218 ast_mutex_unlock(&pkt->owner->lock);
1222 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1224 ast_mutex_unlock(&pkt->owner->lock);
1228 /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
1229 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1231 struct sip_pkt *pkt;
1232 int siptimer_a = DEFAULT_RETRANS;
1234 pkt = malloc(sizeof(struct sip_pkt) + len + 1);
1237 memset(pkt, 0, sizeof(struct sip_pkt));
1238 memcpy(pkt->data, data, len);
1239 pkt->method = sipmethod;
1240 pkt->packetlen = len;
1241 pkt->next = p->packets;
1245 pkt->data[len] = '\0';
1246 pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
1248 ast_set_flag(pkt, FLAG_FATAL);
1250 siptimer_a = pkt->timer_t1 * 2;
1252 /* Schedule retransmission */
1253 pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1254 if (option_debug > 3 && sipdebug)
1255 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id #%d\n", pkt->retransid);
1256 pkt->next = p->packets;
1259 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen); /* Send packet */
1260 if (sipmethod == SIP_INVITE) {
1261 /* Note this is a pending invite */
1262 p->pendinginvite = seqno;
1267 /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
1268 static int __sip_autodestruct(void *data)
1270 struct sip_pvt *p = data;
1274 /* If this is a subscription, tell the phone that we got a timeout */
1275 if (p->subscribed) {
1276 p->subscribed = TIMEOUT;
1277 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, 1); /* Send first notification */
1278 p->subscribed = NONE;
1279 append_history(p, "Subscribestatus", "timeout");
1280 return 10000; /* Reschedule this destruction so that we know that it's gone */
1282 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1283 append_history(p, "AutoDestroy", "");
1285 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
1286 ast_queue_hangup(p->owner);
1293 /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
1294 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1297 if (sip_debug_test_pvt(p))
1298 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
1299 if (recordhistory) {
1300 snprintf(tmp, sizeof(tmp), "%d ms", ms);
1301 append_history(p, "SchedDestroy", tmp);
1304 if (p->autokillid > -1)
1305 ast_sched_del(sched, p->autokillid);
1306 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1310 /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
1311 static int sip_cancel_destroy(struct sip_pvt *p)
1313 if (p->autokillid > -1)
1314 ast_sched_del(sched, p->autokillid);
1315 append_history(p, "CancelDestroy", "");
1320 /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
1321 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1323 struct sip_pkt *cur, *prev = NULL;
1325 int resetinvite = 0;
1326 /* Just in case... */
1329 msg = sip_methods[sipmethod].text;
1333 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1334 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1335 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1336 ast_mutex_lock(&p->lock);
1337 if (!resp && (seqno == p->pendinginvite)) {
1338 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1339 p->pendinginvite = 0;
1342 /* this is our baby */
1344 prev->next = cur->next;
1346 p->packets = cur->next;
1347 if (cur->retransid > -1) {
1348 if (sipdebug && option_debug > 3)
1349 ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1350 ast_sched_del(sched, cur->retransid);
1353 ast_mutex_unlock(&p->lock);
1360 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1364 /* Pretend to ack all packets */
1365 static int __sip_pretend_ack(struct sip_pvt *p)
1367 struct sip_pkt *cur=NULL;
1370 if (cur == p->packets) {
1371 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1376 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
1377 else { /* Unknown packet type */
1380 ast_copy_string(method, p->packets->data, sizeof(method));
1381 c = ast_skip_blanks(method); /* XXX what ? */
1383 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
1389 /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
1390 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1392 struct sip_pkt *cur;
1394 char *msg = sip_methods[sipmethod].text;
1398 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1399 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1400 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1401 /* this is our baby */
1402 if (cur->retransid > -1) {
1403 if (option_debug > 3 && sipdebug)
1404 ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
1405 ast_sched_del(sched, cur->retransid);
1407 cur->retransid = -1;
1413 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1417 static void parse_request(struct sip_request *req);
1418 static char *get_header(struct sip_request *req, char *name);
1419 static void copy_request(struct sip_request *dst,struct sip_request *src);
1421 /*--- parse_copy: Copy SIP request, parse it */
1422 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1424 memset(dst, 0, sizeof(*dst));
1425 memcpy(dst->data, src->data, sizeof(dst->data));
1426 dst->len = src->len;
1430 /*--- send_response: Transmit response on SIP request---*/
1431 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1434 char iabuf[INET_ADDRSTRLEN];
1435 struct sip_request tmp;
1438 if (sip_debug_test_pvt(p)) {
1439 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1440 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1442 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1445 if (recordhistory) {
1446 parse_copy(&tmp, req);
1447 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1448 append_history(p, "TxRespRel", tmpmsg);
1450 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1), req->method);
1452 if (recordhistory) {
1453 parse_copy(&tmp, req);
1454 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1455 append_history(p, "TxResp", tmpmsg);
1457 res = __sip_xmit(p, req->data, req->len);
1464 /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
1465 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1468 char iabuf[INET_ADDRSTRLEN];
1469 struct sip_request tmp;
1472 if (sip_debug_test_pvt(p)) {
1473 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1474 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1476 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1479 if (recordhistory) {
1480 parse_copy(&tmp, req);
1481 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1482 append_history(p, "TxReqRel", tmpmsg);
1484 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method);
1486 if (recordhistory) {
1487 parse_copy(&tmp, req);
1488 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1489 append_history(p, "TxReq", tmpmsg);
1491 res = __sip_xmit(p, req->data, req->len);
1496 /*--- get_in_brackets: Pick out text in brackets from character string ---*/
1497 /* returns pointer to terminated stripped string. modifies input string. */
1498 static char *get_in_brackets(char *tmp)
1502 char *first_bracket;
1503 char *second_bracket;
1508 first_quote = strchr(parse, '"');
1509 first_bracket = strchr(parse, '<');
1510 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1512 for (parse = first_quote + 1; *parse; parse++) {
1513 if ((*parse == '"') && (last_char != '\\'))
1518 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1524 if (first_bracket) {
1525 second_bracket = strchr(first_bracket + 1, '>');
1526 if (second_bracket) {
1527 *second_bracket = '\0';
1528 return first_bracket + 1;
1530 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1538 /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
1539 /* Called from PBX core text message functions */
1540 static int sip_sendtext(struct ast_channel *ast, const char *text)
1542 struct sip_pvt *p = ast->tech_pvt;
1543 int debug=sip_debug_test_pvt(p);
1546 ast_verbose("Sending text %s on %s\n", text, ast->name);
1549 if (!text || ast_strlen_zero(text))
1552 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1553 transmit_message_with_text(p, text);
1557 /*--- realtime_update_peer: Update peer object in realtime storage ---*/
1558 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, int expirey)
1562 char regseconds[20] = "0";
1564 if (expirey) { /* Registration */
1568 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime); /* Expiration time */
1569 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1570 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1572 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1575 /*--- register_peer_exten: Automatically add peer extension to dial plan ---*/
1576 static void register_peer_exten(struct sip_peer *peer, int onoff)
1579 char *stringp, *ext;
1580 if (!ast_strlen_zero(regcontext)) {
1581 ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
1583 while((ext = strsep(&stringp, "&"))) {
1585 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), free, channeltype);
1587 ast_context_remove_extension(regcontext, ext, 1, NULL);
1592 /*--- sip_destroy_peer: Destroy peer object from memory */
1593 static void sip_destroy_peer(struct sip_peer *peer)
1595 /* Delete it, it needs to disappear */
1597 sip_destroy(peer->call);
1598 if (peer->chanvars) {
1599 ast_variables_destroy(peer->chanvars);
1600 peer->chanvars = NULL;
1602 if (peer->expire > -1)
1603 ast_sched_del(sched, peer->expire);
1604 if (peer->pokeexpire > -1)
1605 ast_sched_del(sched, peer->pokeexpire);
1606 register_peer_exten(peer, 0);
1607 ast_free_ha(peer->ha);
1608 if (ast_test_flag(peer, SIP_SELFDESTRUCT))
1610 else if (ast_test_flag(peer, SIP_REALTIME))
1614 clear_realm_authentication(peer->auth);
1615 peer->auth = (struct sip_auth *) NULL;
1617 ast_dnsmgr_release(peer->dnsmgr);
1621 /*--- update_peer: Update peer data in database (if used) ---*/
1622 static void update_peer(struct sip_peer *p, int expiry)
1624 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) &&
1625 (ast_test_flag(p, SIP_REALTIME) ||
1626 ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS))) {
1627 realtime_update_peer(p->name, &p->addr, p->username, expiry);
1632 /*--- realtime_peer: Get peer from realtime storage ---*/
1633 /* Checks the "sippeers" realtime family from extconfig.conf */
1634 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1636 struct sip_peer *peer=NULL;
1637 struct ast_variable *var;
1638 struct ast_variable *tmp;
1639 char *newpeername = (char *) peername;
1642 /* First check on peer name */
1644 var = ast_load_realtime("sippeers", "name", peername, NULL);
1645 else if (sin) { /* Then check on IP address */
1646 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1647 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);
1655 /* If this is type=user, then skip this object. */
1657 if (!strcasecmp(tmp->name, "type") &&
1658 !strcasecmp(tmp->value, "user")) {
1659 ast_variables_destroy(var);
1661 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1662 newpeername = tmp->value;
1667 if (!newpeername) { /* Did not find peer in realtime */
1668 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1669 ast_variables_destroy(var);
1670 return (struct sip_peer *) NULL;
1673 /* Peer found in realtime, now build it in memory */
1674 peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1677 ast_variables_destroy(var);
1678 return (struct sip_peer *) NULL;
1680 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1682 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1683 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
1684 if (peer->expire > -1) {
1685 ast_sched_del(sched, peer->expire);
1687 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1689 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1691 ast_set_flag(peer, SIP_REALTIME);
1693 ast_variables_destroy(var);
1697 /*--- sip_addrcmp: Support routine for find_peer ---*/
1698 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1700 /* We know name is the first field, so we can cast */
1701 struct sip_peer *p = (struct sip_peer *)name;
1702 return !(!inaddrcmp(&p->addr, sin) ||
1703 (ast_test_flag(p, SIP_INSECURE_PORT) &&
1704 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1707 /*--- find_peer: Locate peer by name or ip address */
1708 /* This is used on incoming SIP message to find matching peer on ip
1709 or outgoing message to find matching peer on name */
1710 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1712 struct sip_peer *p = NULL;
1715 p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
1717 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
1719 if (!p && realtime) {
1720 p = realtime_peer(peer, sin);
1726 /*--- sip_destroy_user: Remove user object from in-memory storage ---*/
1727 static void sip_destroy_user(struct sip_user *user)
1729 ast_free_ha(user->ha);
1730 if (user->chanvars) {
1731 ast_variables_destroy(user->chanvars);
1732 user->chanvars = NULL;
1734 if (ast_test_flag(user, SIP_REALTIME))
1741 /*--- realtime_user: Load user from realtime storage ---*/
1742 /* Loads user from "sipusers" category in realtime (extconfig.conf) */
1743 /* Users are matched on From: user name (the domain in skipped) */
1744 static struct sip_user *realtime_user(const char *username)
1746 struct ast_variable *var;
1747 struct ast_variable *tmp;
1748 struct sip_user *user = NULL;
1750 var = ast_load_realtime("sipusers", "name", username, NULL);
1757 if (!strcasecmp(tmp->name, "type") &&
1758 !strcasecmp(tmp->value, "peer")) {
1759 ast_variables_destroy(var);
1767 user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1769 if (!user) { /* No user found */
1770 ast_variables_destroy(var);
1774 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1775 ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1777 ASTOBJ_CONTAINER_LINK(&userl,user);
1779 /* Move counter from s to r... */
1782 ast_set_flag(user, SIP_REALTIME);
1784 ast_variables_destroy(var);
1788 /*--- find_user: Locate user by name ---*/
1789 /* Locates user by name (From: sip uri user name part) first
1790 from in-memory list (static configuration) then from
1791 realtime storage (defined in extconfig.conf) */
1792 static struct sip_user *find_user(const char *name, int realtime)
1794 struct sip_user *u = NULL;
1795 u = ASTOBJ_CONTAINER_FIND(&userl,name);
1796 if (!u && realtime) {
1797 u = realtime_user(name);
1802 /*--- create_addr_from_peer: create address structure from peer reference ---*/
1803 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
1807 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
1808 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
1809 if (peer->addr.sin_addr.s_addr) {
1810 r->sa.sin_family = peer->addr.sin_family;
1811 r->sa.sin_addr = peer->addr.sin_addr;
1812 r->sa.sin_port = peer->addr.sin_port;
1814 r->sa.sin_family = peer->defaddr.sin_family;
1815 r->sa.sin_addr = peer->defaddr.sin_addr;
1816 r->sa.sin_port = peer->defaddr.sin_port;
1818 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1823 ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY);
1824 r->capability = peer->capability;
1825 r->prefs = peer->prefs;
1827 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1828 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1831 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1832 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1834 ast_copy_string(r->peername, peer->username, sizeof(r->peername));
1835 ast_copy_string(r->authname, peer->username, sizeof(r->authname));
1836 ast_copy_string(r->username, peer->username, sizeof(r->username));
1837 ast_copy_string(r->peersecret, peer->secret, sizeof(r->peersecret));
1838 ast_copy_string(r->peermd5secret, peer->md5secret, sizeof(r->peermd5secret));
1839 ast_copy_string(r->tohost, peer->tohost, sizeof(r->tohost));
1840 ast_copy_string(r->fullcontact, peer->fullcontact, sizeof(r->fullcontact));
1841 if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
1842 if ((callhost = strchr(r->callid, '@'))) {
1843 strncpy(callhost + 1, peer->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
1846 if (ast_strlen_zero(r->tohost)) {
1847 if (peer->addr.sin_addr.s_addr)
1848 ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->addr.sin_addr);
1850 ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->defaddr.sin_addr);
1852 if (!ast_strlen_zero(peer->fromdomain))
1853 ast_copy_string(r->fromdomain, peer->fromdomain, sizeof(r->fromdomain));
1854 if (!ast_strlen_zero(peer->fromuser))
1855 ast_copy_string(r->fromuser, peer->fromuser, sizeof(r->fromuser));
1856 r->maxtime = peer->maxms;
1857 r->callgroup = peer->callgroup;
1858 r->pickupgroup = peer->pickupgroup;
1859 /* Set timer T1 to RTT for this peer (if known by qualify=) */
1860 if (peer->maxms && peer->lastms)
1861 r->timer_t1 = peer->lastms;
1862 if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO))
1863 r->noncodeccapability |= AST_RTP_DTMF;
1865 r->noncodeccapability &= ~AST_RTP_DTMF;
1866 ast_copy_string(r->context, peer->context,sizeof(r->context));
1867 r->rtptimeout = peer->rtptimeout;
1868 r->rtpholdtimeout = peer->rtpholdtimeout;
1869 r->rtpkeepalive = peer->rtpkeepalive;
1870 if (peer->call_limit)
1871 ast_set_flag(r, SIP_CALL_LIMIT);
1876 /*--- create_addr: create address structure from peer name ---*/
1877 /* Or, if peer not found, find it in the global DNS */
1878 /* returns TRUE (-1) on failure, FALSE on success */
1879 static int create_addr(struct sip_pvt *dialog, char *opeer)
1882 struct ast_hostent ahp;
1887 char host[MAXHOSTNAMELEN], *hostn;
1890 ast_copy_string(peer, opeer, sizeof(peer));
1891 port = strchr(peer, ':');
1896 dialog->sa.sin_family = AF_INET;
1897 dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
1898 p = find_peer(peer, NULL, 1);
1902 if (create_addr_from_peer(dialog, p))
1903 ASTOBJ_UNREF(p, sip_destroy_peer);
1911 portno = atoi(port);
1913 portno = DEFAULT_SIP_PORT;
1915 char service[MAXHOSTNAMELEN];
1918 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1919 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1925 hp = ast_gethostbyname(hostn, &ahp);
1927 ast_copy_string(dialog->tohost, peer, sizeof(dialog->tohost));
1928 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
1929 dialog->sa.sin_port = htons(portno);
1930 memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
1933 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1937 ASTOBJ_UNREF(p, sip_destroy_peer);
1942 /*--- auto_congest: Scheduled congestion on a call ---*/
1943 static int auto_congest(void *nothing)
1945 struct sip_pvt *p = nothing;
1946 ast_mutex_lock(&p->lock);
1949 if (!ast_mutex_trylock(&p->owner->lock)) {
1950 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1951 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1952 ast_mutex_unlock(&p->owner->lock);
1955 ast_mutex_unlock(&p->lock);
1962 /*--- sip_call: Initiate SIP call from PBX ---*/
1963 /* used from the dial() application */
1964 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1969 char *osphandle = NULL;
1971 struct varshead *headp;
1972 struct ast_var_t *current;
1977 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1978 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1983 /* Check whether there is vxml_url, distinctive ring variables */
1985 headp=&ast->varshead;
1986 AST_LIST_TRAVERSE(headp,current,entries) {
1987 /* Check whether there is a VXML_URL variable */
1988 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
1989 p->options->vxml_url = ast_var_value(current);
1990 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
1991 p->options->uri_options = ast_var_value(current);
1992 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
1993 /* Check whether there is a ALERT_INFO variable */
1994 p->options->distinctive_ring = ast_var_value(current);
1995 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
1996 /* Check whether there is a variable with a name starting with SIPADDHEADER */
1997 p->options->addsipheaders = 1;
2002 else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
2003 p->options->osptoken = ast_var_value(current);
2004 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
2005 osphandle = ast_var_value(current);
2011 ast_set_flag(p, SIP_OUTGOING);
2013 if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
2014 /* Force Disable OSP support */
2015 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
2016 p->options->osptoken = NULL;
2021 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2022 res = update_call_counter(p, INC_CALL_LIMIT);
2024 p->callingpres = ast->cid.cid_pres;
2025 p->jointcapability = p->capability;
2026 transmit_invite(p, SIP_INVITE, 1, 2);
2028 /* Initialize auto-congest time */
2029 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2035 /*--- sip_registry_destroy: Destroy registry object ---*/
2036 /* Objects created with the register= statement in static configuration */
2037 static void sip_registry_destroy(struct sip_registry *reg)
2041 /* Clear registry before destroying to ensure
2042 we don't get reentered trying to grab the registry lock */
2043 reg->call->registry = NULL;
2044 sip_destroy(reg->call);
2046 if (reg->expire > -1)
2047 ast_sched_del(sched, reg->expire);
2048 if (reg->timeout > -1)
2049 ast_sched_del(sched, reg->timeout);
2055 /*--- __sip_destroy: Execute destrucion of call structure, release memory---*/
2056 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2058 struct sip_pvt *cur, *prev = NULL;
2060 struct sip_history *hist;
2062 if (sip_debug_test_pvt(p))
2063 ast_verbose("Destroying call '%s'\n", p->callid);
2066 sip_dump_history(p);
2071 if (p->stateid > -1)
2072 ast_extension_state_del(p->stateid, NULL);
2074 ast_sched_del(sched, p->initid);
2075 if (p->autokillid > -1)
2076 ast_sched_del(sched, p->autokillid);
2079 ast_rtp_destroy(p->rtp);
2082 ast_rtp_destroy(p->vrtp);
2085 free_old_route(p->route);
2089 if (p->registry->call == p)
2090 p->registry->call = NULL;
2091 ASTOBJ_UNREF(p->registry,sip_registry_destroy);
2100 /* Unlink us from the owner if we have one */
2103 ast_mutex_lock(&p->owner->lock);
2104 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2105 p->owner->tech_pvt = NULL;
2107 ast_mutex_unlock(&p->owner->lock);
2112 p->history = p->history->next;
2120 prev->next = cur->next;
2129 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2133 ast_sched_del(sched, p->initid);
2135 while((cp = p->packets)) {
2136 p->packets = p->packets->next;
2137 if (cp->retransid > -1) {
2138 ast_sched_del(sched, cp->retransid);
2143 ast_variables_destroy(p->chanvars);
2146 ast_mutex_destroy(&p->lock);
2150 /*--- update_call_counter: Handle call_limit for SIP users ---*/
2151 /* Note: This is going to be replaced by app_groupcount */
2152 /* Thought: For realtime, we should propably update storage with inuse counter... */
2153 static int update_call_counter(struct sip_pvt *fup, int event)
2156 int *inuse, *call_limit;
2157 int outgoing = ast_test_flag(fup, SIP_OUTGOING);
2158 struct sip_user *u = NULL;
2159 struct sip_peer *p = NULL;
2161 if (option_debug > 2)
2162 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2163 /* Test if we need to check call limits, in order to avoid
2164 realtime lookups if we do not need it */
2165 if (!ast_test_flag(fup, SIP_CALL_LIMIT))
2168 ast_copy_string(name, fup->username, sizeof(name));
2170 /* Check the list of users */
2171 u = find_user(name, 1);
2174 call_limit = &u->call_limit;
2177 /* Try to find peer */
2179 p = find_peer(fup->peername, NULL, 1);
2182 call_limit = &p->call_limit;
2183 ast_copy_string(name, fup->peername, sizeof(name));
2185 if (option_debug > 1)
2186 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2191 /* incoming and outgoing affects the inUse counter */
2192 case DEC_CALL_LIMIT:
2198 if (option_debug > 1 || sipdebug) {
2199 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2202 case INC_CALL_LIMIT:
2203 if (*call_limit > 0 ) {
2204 if (*inuse >= *call_limit) {
2205 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2206 /* inc inUse as well */
2207 if ( event == INC_CALL_LIMIT ) {
2211 ASTOBJ_UNREF(u,sip_destroy_user);
2213 ASTOBJ_UNREF(p,sip_destroy_peer);
2218 if (option_debug > 1 || sipdebug) {
2219 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2223 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2226 ASTOBJ_UNREF(u,sip_destroy_user);
2228 ASTOBJ_UNREF(p,sip_destroy_peer);
2232 /*--- sip_destroy: Destroy SIP call structure ---*/
2233 static void sip_destroy(struct sip_pvt *p)
2235 ast_mutex_lock(&iflock);
2236 __sip_destroy(p, 1);
2237 ast_mutex_unlock(&iflock);
2241 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
2243 /*--- hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes ---*/
2244 static int hangup_sip2cause(int cause)
2246 /* Possible values taken from causes.h */
2249 case 403: /* Not found */
2250 return AST_CAUSE_CALL_REJECTED;
2251 case 404: /* Not found */
2252 return AST_CAUSE_UNALLOCATED;
2253 case 408: /* No reaction */
2254 return AST_CAUSE_NO_USER_RESPONSE;
2255 case 480: /* No answer */
2256 return AST_CAUSE_FAILURE;
2257 case 483: /* Too many hops */
2258 return AST_CAUSE_NO_ANSWER;
2259 case 486: /* Busy everywhere */
2260 return AST_CAUSE_BUSY;
2261 case 488: /* No codecs approved */
2262 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2263 case 500: /* Server internal failure */
2264 return AST_CAUSE_FAILURE;
2265 case 501: /* Call rejected */
2266 return AST_CAUSE_FACILITY_REJECTED;
2268 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2269 case 503: /* Service unavailable */
2270 return AST_CAUSE_CONGESTION;
2272 return AST_CAUSE_NORMAL;
2279 /*--- hangup_cause2sip: Convert Asterisk hangup causes to SIP codes ---*/
2280 /* Possible values from causes.h
2281 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
2282 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
2284 In addition to these, a lot of PRI codes is defined in causes.h
2285 ...should we take care of them too ?
2289 ISUP Cause value SIP response
2290 ---------------- ------------
2291 1 unallocated number 404 Not Found
2292 2 no route to network 404 Not found
2293 3 no route to destination 404 Not found
2294 16 normal call clearing --- (*)
2295 17 user busy 486 Busy here
2296 18 no user responding 408 Request Timeout
2297 19 no answer from the user 480 Temporarily unavailable
2298 20 subscriber absent 480 Temporarily unavailable
2299 21 call rejected 403 Forbidden (+)
2300 22 number changed (w/o diagnostic) 410 Gone
2301 22 number changed (w/ diagnostic) 301 Moved Permanently
2302 23 redirection to new destination 410 Gone
2303 26 non-selected user clearing 404 Not Found (=)
2304 27 destination out of order 502 Bad Gateway
2305 28 address incomplete 484 Address incomplete
2306 29 facility rejected 501 Not implemented
2307 31 normal unspecified 480 Temporarily unavailable
2309 static char *hangup_cause2sip(int cause)
2313 case AST_CAUSE_UNALLOCATED: /* 1 */
2314 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
2315 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
2316 return "404 Not Found";
2317 case AST_CAUSE_CONGESTION: /* 34 */
2318 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
2319 return "503 Service Unavailable";
2320 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
2321 return "408 Request Timeout";
2322 case AST_CAUSE_NO_ANSWER: /* 19 */
2323 return "480 Temporarily unavailable";
2324 case AST_CAUSE_CALL_REJECTED: /* 21 */
2325 return "403 Forbidden";
2326 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
2328 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
2329 return "480 Temporarily unavailable";
2330 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2331 return "484 Address incomplete";
2332 case AST_CAUSE_USER_BUSY:
2333 return "486 Busy here";
2334 case AST_CAUSE_FAILURE:
2335 return "500 Server internal failure";
2336 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
2337 return "501 Not Implemented";
2338 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2339 return "503 Service Unavailable";
2340 /* Used in chan_iax2 */
2341 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2342 return "502 Bad Gateway";
2343 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
2344 return "488 Not Acceptable Here";
2346 case AST_CAUSE_NOTDEFINED:
2348 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2357 /*--- sip_hangup: Hangup SIP call ---*/
2358 /* Part of PBX interface */
2359 static int sip_hangup(struct ast_channel *ast)
2361 struct sip_pvt *p = ast->tech_pvt;
2363 struct ast_flags locflags = {0};
2366 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2370 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2372 ast_mutex_lock(&p->lock);
2374 if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
2375 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
2378 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter\n", p->username);
2379 update_call_counter(p, DEC_CALL_LIMIT);
2380 /* Determine how to disconnect */
2381 if (p->owner != ast) {
2382 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
2383 ast_mutex_unlock(&p->lock);
2386 /* If the call is not UP, we need to send CANCEL instead of BYE */
2387 if (ast->_state != AST_STATE_UP)
2393 ast_dsp_free(p->vad);
2396 ast->tech_pvt = NULL;
2398 ast_mutex_lock(&usecnt_lock);
2400 ast_mutex_unlock(&usecnt_lock);
2401 ast_update_use_count();
2403 ast_set_flag(&locflags, SIP_NEEDDESTROY);
2405 /* Start the process if it's not already started */
2406 if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2407 if (needcancel) { /* Outgoing call, not up */
2408 if (ast_test_flag(p, SIP_OUTGOING)) {
2409 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
2410 /* Actually don't destroy us yet, wait for the 487 on our original
2411 INVITE, but do set an autodestruct just in case we never get it. */
2412 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2413 sip_scheddestroy(p, 15000);
2414 /* stop retransmitting an INVITE that has not received a response */
2415 __sip_pretend_ack(p);
2416 if ( p->initid != -1 ) {
2417 /* channel still up - reverse dec of inUse counter
2418 only if the channel is not auto-congested */
2419 update_call_counter(p, INC_CALL_LIMIT);
2421 } else { /* Incoming call, not up */
2423 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
2424 transmit_response_reliable(p, res, &p->initreq, 1);
2426 transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
2428 } else { /* Call is in UP state, send BYE */
2429 if (!p->pendinginvite) {
2431 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
2433 /* Note we will need a BYE when this all settles out
2434 but we can't send one while we have "INVITE" outstanding. */
2435 ast_set_flag(p, SIP_PENDINGBYE);
2436 ast_clear_flag(p, SIP_NEEDREINVITE);
2440 ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);
2441 ast_mutex_unlock(&p->lock);
2445 /*--- sip_answer: Answer SIP call , send 200 OK on Invite ---*/
2446 /* Part of PBX interface */
2447 static int sip_answer(struct ast_channel *ast)
2451 struct sip_pvt *p = ast->tech_pvt;
2453 ast_mutex_lock(&p->lock);
2454 if (ast->_state != AST_STATE_UP) {
2459 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
2461 fmt=ast_getformatbyname(codec);
2463 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
2464 if (p->jointcapability & fmt) {
2465 p->jointcapability &= fmt;
2466 p->capability &= fmt;
2468 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2469 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
2472 ast_setstate(ast, AST_STATE_UP);
2474 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
2475 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
2477 ast_mutex_unlock(&p->lock);
2481 /*--- sip_write: Send frame to media channel (rtp) ---*/
2482 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2484 struct sip_pvt *p = ast->tech_pvt;
2486 switch (frame->frametype) {
2487 case AST_FRAME_VOICE:
2488 if (!(frame->subclass & ast->nativeformats)) {
2489 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2490 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2494 ast_mutex_lock(&p->lock);
2496 /* If channel is not up, activate early media session */
2497 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2498 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2499 ast_set_flag(p, SIP_PROGRESS_SENT);
2501 time(&p->lastrtptx);
2502 res = ast_rtp_write(p->rtp, frame);
2504 ast_mutex_unlock(&p->lock);
2507 case AST_FRAME_VIDEO:
2509 ast_mutex_lock(&p->lock);
2511 /* Activate video early media */
2512 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2513 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2514 ast_set_flag(p, SIP_PROGRESS_SENT);
2516 time(&p->lastrtptx);
2517 res = ast_rtp_write(p->vrtp, frame);
2519 ast_mutex_unlock(&p->lock);
2522 case AST_FRAME_IMAGE:
2526 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2533 /*--- sip_fixup: Fix up a channel: If a channel is consumed, this is called.
2534 Basically update any ->owner links ----*/
2535 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2537 struct sip_pvt *p = newchan->tech_pvt;
2538 ast_mutex_lock(&p->lock);
2539 if (p->owner != oldchan) {
2540 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2541 ast_mutex_unlock(&p->lock);
2545 ast_mutex_unlock(&p->lock);
2549 /*--- sip_senddigit: Send DTMF character on SIP channel */
2550 /* within one call, we're able to transmit in many methods simultaneously */
2551 static int sip_senddigit(struct ast_channel *ast, char digit)
2553 struct sip_pvt *p = ast->tech_pvt;
2555 ast_mutex_lock(&p->lock);
2556 switch (ast_test_flag(p, SIP_DTMF)) {
2558 transmit_info_with_digit(p, digit);
2560 case SIP_DTMF_RFC2833:
2562 ast_rtp_senddigit(p->rtp, digit);
2564 case SIP_DTMF_INBAND:
2568 ast_mutex_unlock(&p->lock);
2572 #define DEFAULT_MAX_FORWARDS 70
2575 /*--- sip_transfer: Transfer SIP call */
2576 static int sip_transfer(struct ast_channel *ast, const char *dest)
2578 struct sip_pvt *p = ast->tech_pvt;
2581 ast_mutex_lock(&p->lock);
2582 if (ast->_state == AST_STATE_RING)
2583 res = sip_sipredirect(p, dest);
2585 res = transmit_refer(p, dest);
2586 ast_mutex_unlock(&p->lock);
2590 /*--- sip_indicate: Play indication to user */
2591 /* With SIP a lot of indications is sent as messages, letting the device play
2592 the indication - busy signal, congestion etc */
2593 static int sip_indicate(struct ast_channel *ast, int condition)
2595 struct sip_pvt *p = ast->tech_pvt;
2598 ast_mutex_lock(&p->lock);
2600 case AST_CONTROL_RINGING:
2601 if (ast->_state == AST_STATE_RING) {
2602 if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
2603 (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
2604 /* Send 180 ringing if out-of-band seems reasonable */
2605 transmit_response(p, "180 Ringing", &p->initreq);
2606 ast_set_flag(p, SIP_RINGING);
2607 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2610 /* Well, if it's not reasonable, just send in-band */
2615 case AST_CONTROL_BUSY:
2616 if (ast->_state != AST_STATE_UP) {
2617 transmit_response(p, "486 Busy Here", &p->initreq);
2618 ast_set_flag(p, SIP_ALREADYGONE);
2619 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2624 case AST_CONTROL_CONGESTION:
2625 if (ast->_state != AST_STATE_UP) {
2626 transmit_response(p, "503 Service Unavailable", &p->initreq);
2627 ast_set_flag(p, SIP_ALREADYGONE);
2628 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2633 case AST_CONTROL_PROGRESS:
2634 case AST_CONTROL_PROCEEDING:
2635 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2636 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2637 ast_set_flag(p, SIP_PROGRESS_SENT);
2642 case AST_CONTROL_HOLD: /* The other part of the bridge are put on hold */
2644 ast_log(LOG_DEBUG, "Bridged channel now on hold%s\n", p->callid);
2647 case AST_CONTROL_UNHOLD: /* The other part of the bridge are back from hold */
2649 ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
2652 case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
2653 if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) {
2654 transmit_info_with_vidupdate(p);
2663 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2667 ast_mutex_unlock(&p->lock);
2673 /*--- sip_new: Initiate a call in the SIP channel */
2674 /* called from sip_request_call (calls from the pbx ) */
2675 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
2677 struct ast_channel *tmp;
2678 struct ast_variable *v = NULL;
2681 char iabuf[INET_ADDRSTRLEN];
2682 char peer[MAXHOSTNAMELEN];
2685 ast_mutex_unlock(&i->lock);
2686 /* Don't hold a sip pvt lock while we allocate a channel */
2687 tmp = ast_channel_alloc(1);
2688 ast_mutex_lock(&i->lock);
2690 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2693 tmp->tech = &sip_tech;
2694 /* Select our native format based on codec preference until we receive
2695 something from another device to the contrary. */
2696 ast_mutex_lock(&i->lock);
2697 if (i->jointcapability)
2698 tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
2699 else if (i->capability)
2700 tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
2702 tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
2703 ast_mutex_unlock(&i->lock);
2704 fmt = ast_best_codec(tmp->nativeformats);
2707 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
2708 else if (strchr(i->fromdomain,':'))
2709 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2711 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2713 tmp->type = channeltype;
2714 if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
2715 i->vad = ast_dsp_new();
2716 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2718 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2721 tmp->fds[0] = ast_rtp_fd(i->rtp);
2722 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2725 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2726 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2728 if (state == AST_STATE_RING)
2730 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2731 tmp->writeformat = fmt;
2732 tmp->rawwriteformat = fmt;
2733 tmp->readformat = fmt;
2734 tmp->rawreadformat = fmt;
2737 tmp->callgroup = i->callgroup;
2738 tmp->pickupgroup = i->pickupgroup;
2739 tmp->cid.cid_pres = i->callingpres;
2740 if (!ast_strlen_zero(i->accountcode))
2741 ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
2743 tmp->amaflags = i->amaflags;
2744 if (!ast_strlen_zero(i->language))
2745 ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
2746 if (!ast_strlen_zero(i->musicclass))
2747 ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
2749 ast_mutex_lock(&usecnt_lock);
2751 ast_mutex_unlock(&usecnt_lock);
2752 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
2753 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
2754 if (!ast_strlen_zero(i->cid_num))
2755 tmp->cid.cid_num = strdup(i->cid_num);
2756 if (!ast_strlen_zero(i->cid_name))
2757 tmp->cid.cid_name = strdup(i->cid_name);
2758 if (!ast_strlen_zero(i->rdnis))
2759 tmp->cid.cid_rdnis = strdup(i->rdnis);
2760 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2761 tmp->cid.cid_dnid = strdup(i->exten);
2763 if (!ast_strlen_zero(i->uri)) {
2764 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2766 if (!ast_strlen_zero(i->domain)) {
2767 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2769 if (!ast_strlen_zero(i->useragent)) {
2770 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2772 if (!ast_strlen_zero(i->callid)) {
2773 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2776 snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
2777 pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
2779 ast_setstate(tmp, state);
2780 if (state != AST_STATE_DOWN) {
2781 if (ast_pbx_start(tmp)) {
2782 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2787 /* Set channel variables for this call from configuration */
2788 for (v = i->chanvars ; v ; v = v->next)
2789 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2794 /*--- get_sdp_by_line: Reads one line of SIP message body */
2795 static char* get_sdp_by_line(char* line, char *name, int nameLen)
2797 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2798 return ast_skip_blanks(line + nameLen + 1);
2803 /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
2804 but the name wrongly applies _only_ sdp */
2805 static char *get_sdp(struct sip_request *req, char *name)
2808 int len = strlen(name);
2811 for (x=0; x<req->lines; x++) {
2812 r = get_sdp_by_line(req->line[x], name, len);
2820 static void sdpLineNum_iterator_init(int* iterator)
2825 static char* get_sdp_iterate(int* iterator,
2826 struct sip_request *req, char *name)
2828 int len = strlen(name);
2831 while (*iterator < req->lines) {
2832 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2839 static char *find_alias(const char *name, char *_default)
2842 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2843 if (!strcasecmp(aliases[x].fullname, name))
2844 return aliases[x].shortname;
2848 static char *__get_header(struct sip_request *req, char *name, int *start)
2853 * Technically you can place arbitrary whitespace both before and after the ':' in
2854 * a header, although RFC3261 clearly says you shouldn't before, and place just
2855 * one afterwards. If you shouldn't do it, what absolute idiot decided it was
2856 * a good idea to say you can do it, and if you can do it, why in the hell would.
2857 * you say you shouldn't.
2858 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
2859 * and we always allow spaces after that for compatibility.
2861 for (pass = 0; name && pass < 2;pass++) {
2862 int x, len = strlen(name);
2863 for (x=*start; x<req->headers; x++) {
2864 if (!strncasecmp(req->header[x], name, len)) {
2865 char *r = req->header[x] + len; /* skip name */
2866 if (pedanticsipchecking)
2867 r = ast_skip_blanks(r);
2871 return ast_skip_blanks(r+1);
2875 if (pass == 0) /* Try aliases */
2876 name = find_alias(name, NULL);
2879 /* Don't return NULL, so get_header is always a valid pointer */
2883 /*--- get_header: Get header from SIP request ---*/
2884 static char *get_header(struct sip_request *req, char *name)
2887 return __get_header(req, name, &start);
2890 /*--- sip_rtp_read: Read RTP from network ---*/
2891 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
2893 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
2894 struct ast_frame *f;
2895 static struct ast_frame null_frame = { AST_FRAME_NULL, };
2898 /* We have no RTP allocated for this channel */
2904 f = ast_rtp_read(p->rtp); /* RTP Audio */
2907 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
2910 f = ast_rtp_read(p->vrtp); /* RTP Video */
2913 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
2918 /* Don't forward RFC2833 if we're not supposed to */
2919 if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
2922 /* We already hold the channel lock */
2923 if (f->frametype == AST_FRAME_VOICE) {
2924 if (f->subclass != p->owner->nativeformats) {
2925 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2926 p->owner->nativeformats = f->subclass;
2927 ast_set_read_format(p->owner, p->owner->readformat);
2928 ast_set_write_format(p->owner, p->owner->writeformat);
2930 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
2931 f = ast_dsp_process(p->owner, p->vad, f);
2932 if (f && (f->frametype == AST_FRAME_DTMF))
2933 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
2940 /*--- sip_read: Read SIP RTP from channel */
2941 static struct ast_frame *sip_read(struct ast_channel *ast)
2943 struct ast_frame *fr;
2944 struct sip_pvt *p = ast->tech_pvt;
2945 ast_mutex_lock(&p->lock);
2946 fr = sip_rtp_read(ast, p);
2947 time(&p->lastrtprx);
2948 ast_mutex_unlock(&p->lock);
2952 /*--- build_callid: Build SIP CALLID header ---*/
2953 static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
2958 char iabuf[INET_ADDRSTRLEN];
2959 for (x=0; x<4; x++) {
2961 res = snprintf(callid, len, "%08x", val);
2965 if (!ast_strlen_zero(fromdomain))
2966 snprintf(callid, len, "@%s", fromdomain);
2968 /* It's not important that we really use our right IP here... */
2969 snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
2972 static void make_our_tag(char *tagbuf, size_t len)
2974 snprintf(tagbuf, len, "as%08x", rand());
2977 /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
2978 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method)
2982 if (!(p = calloc(1, sizeof(*p))))
2985 ast_mutex_init(&p->lock);
2987 p->method = intended_method;
2990 p->subscribed = NONE;
2993 if (intended_method != SIP_OPTIONS) /* Peerpoke has it's own system */
2994 p->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2997 p->osptimelimit = 0;
3000 memcpy(&p->sa, sin, sizeof(p->sa));
3001 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
3002 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
3004 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
3008 make_our_tag(p->tag, sizeof(p->tag));
3009 /* Start with 101 instead of 1 */
3012 if (sip_methods[intended_method].need_rtp) {
3013 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3015 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3016 if (!p->rtp || (videosupport && !p->vrtp)) {
3017 ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n", videosupport ? "and video" : "", strerror(errno));
3018 ast_mutex_destroy(&p->lock);
3020 ast_variables_destroy(p->chanvars);
3026 ast_rtp_settos(p->rtp, tos);
3028 ast_rtp_settos(p->vrtp, tos);
3029 p->rtptimeout = global_rtptimeout;
3030 p->rtpholdtimeout = global_rtpholdtimeout;
3031 p->rtpkeepalive = global_rtpkeepalive;
3034 if (useglobal_nat && sin) {
3035 /* Setup NAT structure according to global settings if we have an address */
3036 ast_copy_flags(p, &global_flags, SIP_NAT);
3037 memcpy(&p->recv, sin, sizeof(p->recv));
3039 ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
3041 ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
3044 if (p->method != SIP_REGISTER)
3045 ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
3046 build_via(p, p->via, sizeof(p->via));
3048 build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
3050 ast_copy_string(p->callid, callid, sizeof(p->callid));
3051 ast_copy_flags(p, &global_flags, SIP_FLAGS_TO_COPY);
3052 /* Assign default music on hold class */
3053 strcpy(p->musicclass, global_musicclass);
3054 p->capability = global_capability;
3055 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
3056 p->noncodeccapability |= AST_RTP_DTMF;
3057 strcpy(p->context, default_context);
3059 /* Add to active dialog list */
3060 ast_mutex_lock(&iflock);
3063 ast_mutex_unlock(&iflock);
3065 ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
3069 /*--- find_call: Connect incoming SIP message to current dialog or create new dialog structure */
3070 /* Called by handle_request ,sipsock_read */
3071 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
3078 callid = get_header(req, "Call-ID");
3080 if (pedanticsipchecking) {
3081 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
3082 we need more to identify a branch - so we have to check branch, from
3083 and to tags to identify a call leg.
3084 For Asterisk to behave correctly, you need to turn on pedanticsipchecking
3087 if (req->method == SIP_RESPONSE)
3088 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
3090 ast_copy_string(tmp, get_header(req, "From"), sizeof(tmp));
3091 tag = strcasestr(tmp, "tag=");
3094 c = strchr(tag, ';');
3101 ast_mutex_lock(&iflock);
3105 if (req->method == SIP_REGISTER)
3106 found = (!strcmp(p->callid, callid));
3108 found = (!strcmp(p->callid, callid) &&
3109 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
3111 /* Found the call */
3112 ast_mutex_lock(&p->lock);
3113 ast_mutex_unlock(&iflock);
3118 ast_mutex_unlock(&iflock);
3119 p = sip_alloc(callid, sin, 1, intended_method);
3121 ast_mutex_lock(&p->lock);
3125 /*--- sip_register: Parse register=> line in sip.conf and add to registry */
3126 static int sip_register(char *value, int lineno)
3128 struct sip_registry *reg;
3130 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
3137 ast_copy_string(copy, value, sizeof(copy));
3140 hostname = strrchr(stringp, '@');
3145 if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
3146 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
3150 username = strsep(&stringp, ":");
3152 secret = strsep(&stringp, ":");
3154 authuser = strsep(&stringp, ":");
3157 hostname = strsep(&stringp, "/");
3159 contact = strsep(&stringp, "/");
3160 if (!contact || ast_strlen_zero(contact))
3163 hostname = strsep(&stringp, ":");
3164 porta = strsep(&stringp, ":");
3166 if (porta && !atoi(porta)) {
3167 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3170 reg = malloc(sizeof(struct sip_registry));
3172 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
3175 memset(reg, 0, sizeof(struct sip_registry));
3178 ast_copy_string(reg->contact, contact, sizeof(reg->contact));
3180 ast_copy_string(reg->username, username, sizeof(reg->username));
3182 ast_copy_string(reg->hostname, hostname, sizeof(reg->hostname));
3184 ast_copy_string(reg->authuser, authuser, sizeof(reg->authuser));
3186 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
3189 reg->refresh = default_expiry;
3190 reg->portno = porta ? atoi(porta) : 0;
3191 reg->callid_valid = 0;
3193 ASTOBJ_CONTAINER_LINK(®l, reg);
3194 ASTOBJ_UNREF(reg,sip_registry_destroy);
3198 /*--- lws2sws: Parse multiline SIP headers into one header */
3199 /* This is enabled if pedanticsipchecking is enabled */
3200 static int lws2sws(char *msgbuf, int len)
3206 /* Eliminate all CRs */
3207 if (msgbuf[h] == '\r') {
3211 /* Check for end-of-line */
3212 if (msgbuf[h] == '\n') {
3213 /* Check for end-of-message */
3216 /* Check for a continuation line */
3217 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
3218 /* Merge continuation line */
3222 /* Propagate LF and start new line */
3223 msgbuf[t++] = msgbuf[h++];
3227 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
3232 msgbuf[t++] = msgbuf[h++];
3236 msgbuf[t++] = msgbuf[h++];
3244 /*--- parse_request: Parse a SIP message ----*/
3245 static void parse_request(struct sip_request *req)
3247 /* Divide fields by NULL's */
3253 /* First header starts immediately */
3257 /* We've got a new header */
3260 if (sipdebug && option_debug > 3)
3261 ast_log(LOG_DEBUG, "Header: %s (%d)\n", req->header[f], (int) strlen(req->header[f]));
3262 if (ast_strlen_zero(req->header[f])) {
3263 /* Line by itself means we're now in content */
3267 if (f >= SIP_MAX_HEADERS - 1) {
3268 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
3271 req->header[f] = c + 1;
3272 } else if (*c == '\r') {
3273 /* Ignore but eliminate \r's */
3278 /* Check for last header */
3279 if (!ast_strlen_zero(req->header[f]))
3282 /* Now we process any mime content */
3287 /* We've got a new line */
3289 if (sipdebug && option_debug > 3)
3290 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
3291 if (f >= SIP_MAX_LINES - 1) {
3292 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
3295 req->line[f] = c + 1;
3296 } else if (*c == '\r') {
3297 /* Ignore and eliminate \r's */
3302 /* Check for last line */
3303 if (!ast_strlen_zero(req->line[f]))
3307 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
3308 /* Split up the first line parts */
3309 determine_firstline_parts(req);
3312 /*--- process_sdp: Process SIP SDP and activate RTP channels---*/
3313 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
3319 char iabuf[INET_ADDRSTRLEN];
3323 int peercapability, peernoncodeccapability;
3324 int vpeercapability=0, vpeernoncodeccapability=0;
3325 struct sockaddr_in sin;
3328 struct ast_hostent ahp;
3330 int destiterator = 0;
3334 int debug=sip_debug_test_pvt(p);
3335 struct ast_channel *bridgepeer = NULL;
3338 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
3342 /* Update our last rtprx when we receive an SDP, too */
3343 time(&p->lastrtprx);
3344 time(&p->lastrtptx);
3346 /* Get codec and RTP info from SDP */
3347 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
3348 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
3351 m = get_sdp(req, "m");
3352 sdpLineNum_iterator_init(&destiterator);
3353 c = get_sdp_iterate(&destiterator, req, "c");
3354 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
3355 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
3358 if (sscanf(c, "IN IP4 %256s", host) != 1) {
3359 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
3362 /* XXX This could block for a long time, and block the main thread! XXX */
3363 hp = ast_gethostbyname(host, &ahp);
3365 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
3368 sdpLineNum_iterator_init(&iterator);
3369 ast_set_flag(p, SIP_NOVIDEO);
3370 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
3372 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1) ||
3373 (sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2)) {
3376 /* Scan through the RTP payload types specified in a "m=" line: */
3377 ast_rtp_pt_clear(p->rtp);
3379 while(!ast_strlen_zero(codecs)) {
3380 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
3381 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
3385 ast_verbose("Found RTP audio format %d\n", codec);
3386 ast_rtp_set_m_type(p->rtp, codec);
3387 codecs = ast_skip_blanks(codecs + len);
3391 ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
3393 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
3395 ast_clear_flag(p, SIP_NOVIDEO);
3397 /* Scan through the RTP payload types specified in a "m=" line: */
3399 while(!ast_strlen_zero(codecs)) {
3400 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
3401 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
3405 ast_verbose("Found video format %s\n", ast_getformatname(codec));
3406 ast_rtp_set_m_type(p->vrtp, codec);
3407 codecs = ast_skip_blanks(codecs + len);
3411 ast_log(LOG_WARNING, "Unknown SDP media type in offer: %s\n", m);
3413 if (portno == -1 && vportno == -1) {
3414 /* No acceptable offer found in SDP */
3417 /* Check for Media-description-level-address for audio */
3418 if (pedanticsipchecking) {
3419 c = get_sdp_iterate(&destiterator, req, "c");
3420 if (!ast_strlen_zero(c)) {
3421 if (sscanf(c, "IN IP4 %256s", host) != 1) {
3422 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
3424 /* XXX This could block for a long time, and block the main thread! XXX */
3425 hp = ast_gethostbyname(host, &ahp);
3427 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
3432 /* RTP addresses and ports for audio and video */
3433 sin.sin_family = AF_INET;
3434 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
3436 /* Setup audio port number */
3437 sin.sin_port = htons(portno);
3438 if (p->rtp && sin.sin_port) {
3439 ast_rtp_set_peer(p->rtp, &sin);
3441 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3442 ast_log(LOG_DEBUG,"Peer audio RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3445 /* Check for Media-description-level-address for video */
3446 if (pedanticsipchecking) {
3447 c = get_sdp_iterate(&destiterator, req, "c");
3448 if (!ast_strlen_zero(c)) {
3449 if (sscanf(c, "IN IP4 %256s", host) != 1) {
3450 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
3452 /* XXX This could block for a long time, and block the main thread! XXX */
3453 hp = ast_gethostbyname(host, &ahp);
3455 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
3460 /* Setup video port number */
3461 sin.sin_port = htons(vportno);
3462 if (p->vrtp && sin.sin_port) {
3463 ast_rtp_set_peer(p->vrtp, &sin);
3465 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3466 ast_log(LOG_DEBUG,"Peer video RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3470 /* Next, scan through each "a=rtpmap:" line, noting each
3471 * specified RTP payload type (with corresponding MIME subtype):
3473 sdpLineNum_iterator_init(&iterator);
3474 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
3475 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
3476 if (!strcasecmp(a, "sendonly")) {
3480 if (!strcasecmp(a, "sendrecv")) {
3483 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
3485 ast_verbose("Found description format %s\n", mimeSubtype);
3486 /* Note: should really look at the 'freq' and '#chans' params too */
3487 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
3489 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
3492 /* Now gather all of the codecs that were asked for: */
3493 ast_rtp_get_current_formats(p->rtp,
3494 &peercapability, &peernoncodeccapability);
3496 ast_rtp_get_current_formats(p->vrtp,