2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Session Initiation Protocol
6 * Copyright (C) 2004 - 2005, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
18 #include "asterisk/lock.h"
19 #include "asterisk/channel.h"
20 #include "asterisk/config.h"
21 #include "asterisk/logger.h"
22 #include "asterisk/module.h"
23 #include "asterisk/pbx.h"
24 #include "asterisk/options.h"
25 #include "asterisk/lock.h"
26 #include "asterisk/sched.h"
27 #include "asterisk/io.h"
28 #include "asterisk/rtp.h"
29 #include "asterisk/acl.h"
30 #include "asterisk/manager.h"
31 #include "asterisk/callerid.h"
32 #include "asterisk/cli.h"
33 #include "asterisk/app.h"
34 #include "asterisk/musiconhold.h"
35 #include "asterisk/dsp.h"
36 #include "asterisk/features.h"
37 #include "asterisk/acl.h"
38 #include "asterisk/srv.h"
39 #include "asterisk/astdb.h"
40 #include "asterisk/causes.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/file.h"
43 #include "asterisk/astobj.h"
44 #include "asterisk/dnsmgr.h"
46 #include "asterisk/astosp.h"
48 #include <sys/socket.h>
49 #include <sys/ioctl.h>
56 #include <arpa/inet.h>
58 #include <sys/signal.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/ip.h>
63 #ifndef DEFAULT_USERAGENT
64 #define DEFAULT_USERAGENT "Asterisk PBX"
67 #define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
69 #define IPTOS_MINCOST 0x02
72 /* #define VOCAL_DATA_HACK */
75 #define DEFAULT_DEFAULT_EXPIRY 120
76 #define DEFAULT_MAX_EXPIRY 3600
77 #define DEFAULT_REGISTRATION_TIMEOUT 20
79 /* guard limit must be larger than guard secs */
80 /* guard min must be < 1000, and should be >= 250 */
81 #define EXPIRY_GUARD_SECS 15 /* How long before expiry do we reregister */
82 #define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of
84 #define EXPIRY_GUARD_MIN 500 /* This is the minimum guard time applied. If
85 GUARD_PCT turns out to be lower than this, it
86 will use this time instead.
87 This is in milliseconds. */
88 #define EXPIRY_GUARD_PCT 0.20 /* Percentage of expires timeout to use when
89 below EXPIRY_GUARD_LIMIT */
91 static int max_expiry = DEFAULT_MAX_EXPIRY;
92 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
95 #define MAX(a,b) ((a) > (b) ? (a) : (b))
98 #define CALLERID_UNKNOWN "Unknown"
102 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
103 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
104 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
106 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
107 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
110 #define DEBUG_READ 0 /* Recieved data */
111 #define DEBUG_SEND 1 /* Transmit data */
113 static const char desc[] = "Session Initiation Protocol (SIP)";
114 static const char channeltype[] = "SIP";
115 static const char config[] = "sip.conf";
116 static const char notify_config[] = "sip_notify.conf";
118 #define SIP_REGISTER 1
119 #define SIP_OPTIONS 2
126 #define SIP_SUBSCRIBE 9
127 #define SIP_MESSAGE 10
128 #define SIP_UPDATE 11
130 #define SIP_CANCEL 13
131 #define SIP_PUBLISH 14
132 #define SIP_RESPONSE 100
136 const struct cfsip_methods {
138 int need_rtp; /* when this is the 'primary' use for a pvt structure, does it need RTP? */
141 { 0, RTP, "-UNKNOWN-" },
142 { SIP_REGISTER, NO_RTP, "REGISTER" },
143 { SIP_OPTIONS, NO_RTP, "OPTIONS" },
144 { SIP_NOTIFY, NO_RTP, "NOTIFY" },
145 { SIP_INVITE, RTP, "INVITE" },
146 { SIP_ACK, NO_RTP, "ACK" },
147 { SIP_PRACK, NO_RTP, "PRACK" },
148 { SIP_BYE, NO_RTP, "BYE" },
149 { SIP_REFER, NO_RTP, "REFER" },
150 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
151 { SIP_MESSAGE, NO_RTP, "MESSAGE" },
152 { SIP_UPDATE, NO_RTP, "UPDATE" },
153 { SIP_INFO, NO_RTP, "INFO" },
154 { SIP_CANCEL, NO_RTP, "CANCEL" },
155 { SIP_PUBLISH, NO_RTP, "PUBLISH" }
158 /* Structure for conversion between compressed SIP and "normal" SIP */
159 static struct cfalias {
163 { "Content-Type", "c" },
164 { "Content-Encoding", "e" },
168 { "Content-Length", "l" },
171 { "Supported", "k" },
173 { "Allow-Events", "u" },
179 #define DEFAULT_SIP_PORT 5060 /* From RFC 3261 (former 2543) */
180 #define SIP_MAX_PACKET 4096 /* Also from RFC 3261 (2543), should sub headers tho */
182 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY"
184 static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
186 #define DEFAULT_CONTEXT "default"
187 static char default_context[AST_MAX_EXTENSION] = DEFAULT_CONTEXT;
189 static char default_language[MAX_LANGUAGE] = "";
191 #define DEFAULT_CALLERID "asterisk"
192 static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
194 static char default_fromdomain[AST_MAX_EXTENSION] = "";
196 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
197 static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
200 static int default_qualify = 0; /* Default Qualify= setting */
202 static struct ast_flags global_flags = {0}; /* global SIP_ flags */
203 static struct ast_flags global_flags_page2 = {0}; /* more global SIP_ flags */
205 static int srvlookup = 0; /* SRV Lookup on or off. Default is off, RFC behavior is on */
207 static int pedanticsipchecking = 0; /* Extra checking ? Default off */
209 static int autocreatepeer = 0; /* Auto creation of peers at registration? Default off. */
211 static int relaxdtmf = 0;
213 static int global_rtptimeout = 0;
215 static int global_rtpholdtimeout = 0;
217 static int global_rtpkeepalive = 0;
219 static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
221 /* Object counters */
222 static int suserobjs = 0;
223 static int ruserobjs = 0;
224 static int speerobjs = 0;
225 static int rpeerobjs = 0;
226 static int apeerobjs = 0;
227 static int regobjs = 0;
229 static int global_allowguest = 1; /* allow unauthenticated users/peers to connect? */
231 #define DEFAULT_MWITIME 10
232 static int global_mwitime = DEFAULT_MWITIME; /* Time between MWI checks for peers */
234 static int usecnt =0;
235 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
238 /* Protect the interface list (of sip_pvt's) */
239 AST_MUTEX_DEFINE_STATIC(iflock);
241 /* Protect the monitoring thread, so only one process can kill or start it, and not
242 when it's doing something critical. */
243 AST_MUTEX_DEFINE_STATIC(netlock);
245 AST_MUTEX_DEFINE_STATIC(monlock);
247 /* This is the thread for the monitor which checks for input on the channels
248 which are not currently in use. */
249 static pthread_t monitor_thread = AST_PTHREADT_NULL;
251 static int restart_monitor(void);
253 /* Codecs that we support by default: */
254 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
255 static int noncodeccapability = AST_RTP_DTMF;
257 static struct in_addr __ourip;
258 static struct sockaddr_in outboundproxyip;
261 static int sipdebug = 0;
262 static struct sockaddr_in debugaddr;
266 static int videosupport = 0;
268 static int compactheaders = 0; /* send compact sip headers */
270 static int recordhistory = 0; /* Record SIP history. Off by default */
272 static char global_musicclass[MAX_LANGUAGE] = ""; /* Global music on hold class */
273 #define DEFAULT_REALM "asterisk"
274 static char global_realm[MAXHOSTNAMELEN] = DEFAULT_REALM; /* Default realm */
275 static char regcontext[AST_MAX_EXTENSION] = ""; /* Context for auto-extensions */
278 #define DEFAULT_EXPIRY 900
279 static int expiry = DEFAULT_EXPIRY;
281 static struct sched_context *sched;
282 static struct io_context *io;
283 /* The private structures of the sip channels are linked for
284 selecting outgoing channels */
286 #define SIP_MAX_HEADERS 64
287 #define SIP_MAX_LINES 64
291 #define DEC_OUT_USE 2
292 #define INC_OUT_USE 3
294 static struct ast_codec_pref prefs;
297 /* sip_request: The data grabbed from the UDP socket */
299 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
300 char *rlPart2; /* The Request URI or Response Status */
301 int len; /* Length */
302 int headers; /* # of SIP Headers */
303 int method; /* Method of this request */
304 char *header[SIP_MAX_HEADERS];
305 int lines; /* SDP Content */
306 char *line[SIP_MAX_LINES];
307 char data[SIP_MAX_PACKET];
313 struct sip_route *next;
317 /* sip_history: Structure for saving transactions within a SIP dialog */
320 struct sip_history *next;
323 /* sip_auth: Creadentials for authentication to other SIP services */
325 char realm[AST_MAX_EXTENSION]; /* Realm in which these credentials are valid */
326 char username[256]; /* Username */
327 char secret[256]; /* Secret */
328 char md5secret[256]; /* MD5Secret */
329 struct sip_auth *next; /* Next auth structure in list */
332 #define SIP_ALREADYGONE (1 << 0) /* Whether or not we've already been destroyed by our peer */
333 #define SIP_NEEDDESTROY (1 << 1) /* if we need to be destroyed */
334 #define SIP_NOVIDEO (1 << 2) /* Didn't get video in invite, don't offer */
335 #define SIP_RINGING (1 << 3) /* Have sent 180 ringing */
336 #define SIP_PROGRESS_SENT (1 << 4) /* Have sent 183 message progress */
337 #define SIP_NEEDREINVITE (1 << 5) /* Do we need to send another reinvite? */
338 #define SIP_PENDINGBYE (1 << 6) /* Need to send bye after we ack? */
339 #define SIP_GOTREFER (1 << 7) /* Got a refer? */
340 #define SIP_PROMISCREDIR (1 << 8) /* Promiscuous redirection */
341 #define SIP_TRUSTRPID (1 << 9) /* Trust RPID headers? */
342 #define SIP_USEREQPHONE (1 << 10) /* Add user=phone to numeric URI. Default off */
343 #define SIP_REALTIME (1 << 11) /* Flag for realtime users */
344 #define SIP_USECLIENTCODE (1 << 12) /* Trust X-ClientCode info message */
345 #define SIP_OUTGOING (1 << 13) /* Is this an outgoing call? */
346 #define SIP_SELFDESTRUCT (1 << 14)
347 #define SIP_DYNAMIC (1 << 15) /* Is this a dynamic peer? */
348 /* --- Choices for DTMF support in SIP channel */
349 #define SIP_DTMF (3 << 16) /* three settings, uses two bits */
350 #define SIP_DTMF_RFC2833 (0 << 16) /* RTP DTMF */
351 #define SIP_DTMF_INBAND (1 << 16) /* Inband audio, only for ULAW/ALAW */
352 #define SIP_DTMF_INFO (2 << 16) /* SIP Info messages */
354 #define SIP_NAT (3 << 18) /* four settings, uses two bits */
355 #define SIP_NAT_NEVER (0 << 18) /* No nat support */
356 #define SIP_NAT_RFC3581 (1 << 18)
357 #define SIP_NAT_ROUTE (2 << 18)
358 #define SIP_NAT_ALWAYS (3 << 18)
359 /* re-INVITE related settings */
360 #define SIP_REINVITE (3 << 20) /* two bits used */
361 #define SIP_CAN_REINVITE (1 << 20) /* allow peers to be reinvited to send media directly p2p */
362 #define SIP_REINVITE_UPDATE (2 << 20) /* use UPDATE (RFC3311) when reinviting this peer */
363 /* "insecure" settings */
364 #define SIP_INSECURE_PORT (1 << 22) /* don't require matching port for incoming requests */
365 #define SIP_INSECURE_INVITE (1 << 23) /* don't require authentication for incoming INVITEs */
366 /* Sending PROGRESS in-band settings */
367 #define SIP_PROG_INBAND (3 << 24) /* three settings, uses two bits */
368 #define SIP_PROG_INBAND_NEVER (0 << 24)
369 #define SIP_PROG_INBAND_NO (1 << 24)
370 #define SIP_PROG_INBAND_YES (2 << 24)
371 /* Open Settlement Protocol authentication */
372 #define SIP_OSPAUTH (3 << 26) /* three settings, uses two bits */
373 #define SIP_OSPAUTH_NO (0 << 26)
374 #define SIP_OSPAUTH_YES (1 << 26)
375 #define SIP_OSPAUTH_EXCLUSIVE (2 << 26)
377 #define SIP_CALL_ONHOLD (1 << 28)
378 #define SIP_CALL_LIMIT (1 << 29)
380 /* a new page of flags for peer */
381 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
382 #define SIP_PAGE2_RTNOUPDATE (1 << 1)
383 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
385 static int global_rtautoclear = 120;
387 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call */
388 static struct sip_pvt {
389 ast_mutex_t lock; /* Channel private lock */
390 int method; /* SIP method of this packet */
391 char callid[80]; /* Global CallID */
392 char randdata[80]; /* Random data */
393 struct ast_codec_pref prefs; /* codec prefs */
394 unsigned int ocseq; /* Current outgoing seqno */
395 unsigned int icseq; /* Current incoming seqno */
396 ast_group_t callgroup; /* Call group */
397 ast_group_t pickupgroup; /* Pickup group */
398 int lastinvite; /* Last Cseq of invite */
399 unsigned int flags; /* SIP_ flags */
400 int capability; /* Special capability (codec) */
401 int jointcapability; /* Supported capability at both ends (codecs ) */
402 int peercapability; /* Supported peer capability */
403 int prefcodec; /* Preferred codec (outbound only) */
404 int noncodeccapability;
405 int callingpres; /* Calling presentation */
406 int authtries; /* Times we've tried to authenticate */
407 int expiry; /* How long we take to expire */
408 int branch; /* One random number */
409 int tag; /* Another random number */
410 int sessionid; /* SDP Session ID */
411 int sessionversion; /* SDP Session Version */
412 struct sockaddr_in sa; /* Our peer */
413 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
414 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
415 int redircodecs; /* Redirect codecs */
416 struct sockaddr_in recv; /* Received as */
417 struct in_addr ourip; /* Our IP */
418 struct ast_channel *owner; /* Who owns us */
419 char exten[AST_MAX_EXTENSION]; /* Extension where to start */
420 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
421 char referred_by[AST_MAX_EXTENSION]; /* Place to store REFERRED-BY extension */
422 char refer_contact[AST_MAX_EXTENSION]; /* Place to store Contact info from a REFER extension */
423 struct sip_pvt *refer_call; /* Call we are referring */
424 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
425 int route_persistant; /* Is this the "real" route? */
426 char from[256]; /* The From: header */
427 char useragent[256]; /* User agent in SIP request */
428 char context[AST_MAX_EXTENSION]; /* Context for this call */
429 char fromdomain[MAXHOSTNAMELEN]; /* Domain to show in the from field */
430 char fromuser[AST_MAX_EXTENSION]; /* User to show in the user field */
431 char fromname[AST_MAX_EXTENSION]; /* Name to show in the user field */
432 char tohost[MAXHOSTNAMELEN]; /* Host we should put in the "to" field */
433 char language[MAX_LANGUAGE]; /* Default language for this call */
434 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
435 char rdnis[256]; /* Referring DNIS */
436 char theirtag[256]; /* Their tag */
437 char username[256]; /* [user] name */
438 char peername[256]; /* [peer] name, not set if [user] */
439 char authname[256]; /* Who we use for authentication */
440 char uri[256]; /* Original requested URI */
441 char okcontacturi[256]; /* URI from the 200 OK on INVITE */
442 char peersecret[256]; /* Password */
443 char peermd5secret[256];
444 struct sip_auth *peerauth; /* Realm authentication */
445 char cid_num[256]; /* Caller*ID */
446 char cid_name[256]; /* Caller*ID */
447 char via[256]; /* Via: header */
448 char fullcontact[128]; /* The Contact: that the UA registers with us */
449 char accountcode[20]; /* Account code */
450 char our_contact[256]; /* Our contact header */
451 char realm[MAXHOSTNAMELEN]; /* Authorization realm */
452 char nonce[256]; /* Authorization nonce */
453 char opaque[256]; /* Opaque nonsense */
454 char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
455 char domain[MAXHOSTNAMELEN]; /* Authorization domain */
456 char lastmsg[256]; /* Last Message sent/received */
457 int amaflags; /* AMA Flags */
458 int pendinginvite; /* Any pending invite */
460 int osphandle; /* OSP Handle for call */
461 time_t ospstart; /* OSP Start time */
463 struct sip_request initreq; /* Initial request */
465 int maxtime; /* Max time for first response */
466 int maxforwards; /* keep the max-forwards info */
467 int initid; /* Auto-congest ID if appropriate */
468 int autokillid; /* Auto-kill ID */
469 time_t lastrtprx; /* Last RTP received */
470 time_t lastrtptx; /* Last RTP sent */
471 int rtptimeout; /* RTP timeout time */
472 int rtpholdtimeout; /* RTP timeout when on hold */
473 int rtpkeepalive; /* Send RTP packets for keepalive */
475 int subscribed; /* Is this call a subscription? */
479 struct ast_dsp *vad; /* Voice Activation Detection dsp */
481 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
482 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
483 struct ast_rtp *rtp; /* RTP Session */
484 struct ast_rtp *vrtp; /* Video RTP session */
485 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
486 struct sip_history *history; /* History of this SIP dialog */
487 struct ast_variable *chanvars; /* Channel variables to set for call */
488 struct sip_pvt *next; /* Next call in chain */
491 #define FLAG_RESPONSE (1 << 0)
492 #define FLAG_FATAL (1 << 1)
494 /* sip packet - read in sipsock_read, transmitted in send_request */
496 struct sip_pkt *next; /* Next packet */
497 int retrans; /* Retransmission number */
498 int seqno; /* Sequence number */
499 unsigned int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
500 struct sip_pvt *owner; /* Owner call */
501 int retransid; /* Retransmission ID */
502 int packetlen; /* Length of packet */
506 /* Structure for SIP user data. User's place calls to us */
508 /* Users who can access various contexts */
509 ASTOBJ_COMPONENTS(struct sip_user);
510 char secret[80]; /* Password */
511 char md5secret[80]; /* Password in md5 */
512 char context[AST_MAX_EXTENSION]; /* Default context for incoming calls */
513 char cid_num[80]; /* Caller ID num */
514 char cid_name[80]; /* Caller ID name */
515 char accountcode[20]; /* Account code */
516 char language[MAX_LANGUAGE]; /* Default language for this user */
517 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
518 char useragent[256]; /* User agent in SIP request */
519 struct ast_codec_pref prefs; /* codec prefs */
520 ast_group_t callgroup; /* Call group */
521 ast_group_t pickupgroup; /* Pickup Group */
522 unsigned int flags; /* SIP_ flags */
523 struct ast_flags flags_page2; /* SIP_PAGE2 flags */
524 int amaflags; /* AMA flags for billing */
525 int callingpres; /* Calling id presentation */
526 int capability; /* Codec capability */
527 int inUse; /* Number of calls in use */
528 int incominglimit; /* Limit of incoming calls */
529 int outUse; /* disabled */
530 int outgoinglimit; /* disabled */
531 struct ast_ha *ha; /* ACL setting */
532 struct ast_variable *chanvars; /* Variables to set for channel created by user */
535 /* Structure for SIP peer data, we place calls to peers if registred or fixed IP address (host) */
537 ASTOBJ_COMPONENTS(struct sip_peer); /* name, refcount, objflags, object pointers */
538 /* peer->name is the unique name of this object */
539 char secret[80]; /* Password */
540 char md5secret[80]; /* Password in MD5 */
541 struct sip_auth *auth; /* Realm authentication list */
542 char context[AST_MAX_EXTENSION]; /* Default context for incoming calls */
543 char username[80]; /* Temporary username until registration */
544 char accountcode[20]; /* Account code */
545 int amaflags; /* AMA Flags (for billing) */
546 char tohost[MAXHOSTNAMELEN]; /* If not dynamic, IP address */
547 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
548 char fromuser[80]; /* From: user when calling this peer */
549 char fromdomain[MAXHOSTNAMELEN]; /* From: domain when calling this peer */
550 char fullcontact[256]; /* Contact registred with us (not in sip.conf) */
551 char cid_num[80]; /* Caller ID num */
552 char cid_name[80]; /* Caller ID name */
553 int callingpres; /* Calling id presentation */
554 int inUse; /* Number of calls in use */
555 int incominglimit; /* Limit of incoming calls */
556 int outUse; /* disabled */
557 int outgoinglimit; /* disabled */
558 char mailbox[AST_MAX_EXTENSION]; /* Mailbox setting for MWI checks */
559 char language[MAX_LANGUAGE]; /* Default language for prompts */
560 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
561 char useragent[256]; /* User agent in SIP request (saved from registration) */
562 struct ast_codec_pref prefs; /* codec prefs */
564 time_t lastmsgcheck; /* Last time we checked for MWI */
565 unsigned int flags; /* SIP_ flags */
566 struct ast_flags flags_page2; /* SIP_PAGE2 flags */
567 int expire; /* When to expire this peer registration */
568 int expiry; /* Duration of registration */
569 int capability; /* Codec capability */
570 int rtptimeout; /* RTP timeout */
571 int rtpholdtimeout; /* RTP Hold Timeout */
572 int rtpkeepalive; /* Send RTP packets for keepalive */
573 ast_group_t callgroup; /* Call group */
574 ast_group_t pickupgroup; /* Pickup group */
575 struct ast_dnsmgr_entry *dnsmgr;/* DNS refresh manager for peer */
576 struct sockaddr_in addr; /* IP address of peer */
580 struct sip_pvt *call; /* Call pointer */
581 int pokeexpire; /* When to expire poke (qualify= checking) */
582 int lastms; /* How long last response took (in ms), or -1 for no response */
583 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
584 struct timeval ps; /* Ping send time */
586 struct sockaddr_in defaddr; /* Default IP address, used until registration */
587 struct ast_ha *ha; /* Access control list */
588 struct ast_variable *chanvars; /* Variables to set for channel created by user */
592 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
593 static int sip_reloading = 0;
595 /* States for outbound registrations (with register= lines in sip.conf */
596 #define REG_STATE_UNREGISTERED 0
597 #define REG_STATE_REGSENT 1
598 #define REG_STATE_AUTHSENT 2
599 #define REG_STATE_REGISTERED 3
600 #define REG_STATE_REJECTED 4
601 #define REG_STATE_TIMEOUT 5
602 #define REG_STATE_NOAUTH 6
605 /* sip_registry: Registrations with other SIP proxies */
606 struct sip_registry {
607 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
608 int portno; /* Optional port override */
609 char username[80]; /* Who we are registering as */
610 char authuser[80]; /* Who we *authenticate* as */
611 char hostname[MAXHOSTNAMELEN]; /* Domain or host we register to */
612 char secret[80]; /* Password or key name in []'s */
614 char contact[256]; /* Contact extension */
616 int expire; /* Sched ID of expiration */
617 int timeout; /* sched id of sip_reg_timeout */
618 int refresh; /* How often to refresh */
619 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
620 int regstate; /* Registration state (see above) */
621 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
622 char callid[80]; /* Global CallID for this registry */
623 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
624 struct sockaddr_in us; /* Who the server thinks we are */
627 char realm[MAXHOSTNAMELEN]; /* Authorization realm */
628 char nonce[256]; /* Authorization nonce */
629 char domain[MAXHOSTNAMELEN]; /* Authorization domain */
630 char opaque[256]; /* Opaque nonsense */
631 char qop[80]; /* Quality of Protection. */
633 char lastmsg[256]; /* Last Message sent/received */
636 /*--- The user list: Users and friends ---*/
637 static struct ast_user_list {
638 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
641 /*--- The peer list: Peers and Friends ---*/
642 static struct ast_peer_list {
643 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
646 /*--- The register list: Other SIP proxys we register with and call ---*/
647 static struct ast_register_list {
648 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
653 static int __sip_do_register(struct sip_registry *r);
655 static int sipsock = -1;
658 static struct sockaddr_in bindaddr;
659 static struct sockaddr_in externip;
660 static char externhost[MAXHOSTNAMELEN] = "";
661 static time_t externexpire = 0;
662 static int externrefresh = 10;
663 static struct ast_ha *localaddr;
665 /* The list of manual NOTIFY types we know how to send */
666 struct ast_config *notify_types;
668 static struct sip_auth *authl; /* Authentication list */
671 static struct ast_frame *sip_read(struct ast_channel *ast);
672 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
673 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
674 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header);
675 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
676 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
677 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, char *osptoken, int addsipheaders, int init);
678 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
679 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
680 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
681 static int transmit_refer(struct sip_pvt *p, const char *dest);
682 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
683 static struct sip_peer *temp_peer(const char *name);
684 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
685 static void free_old_route(struct sip_route *route);
686 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
687 static int update_user_counter(struct sip_pvt *fup, int event);
688 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
689 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
690 static int sip_do_reload(void);
691 static int expire_register(void *data);
692 static int callevents = 0;
694 static struct ast_channel *sip_request(const char *type, int format, void *data, int *cause);
695 static int sip_devicestate(void *data);
696 static int sip_sendtext(struct ast_channel *ast, const char *text);
697 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
698 static int sip_hangup(struct ast_channel *ast);
699 static int sip_answer(struct ast_channel *ast);
700 static struct ast_frame *sip_read(struct ast_channel *ast);
701 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
702 static int sip_indicate(struct ast_channel *ast, int condition);
703 static int sip_transfer(struct ast_channel *ast, const char *dest);
704 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
705 static int sip_senddigit(struct ast_channel *ast, char digit);
706 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
707 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno); /* Add realm authentication in list */
708 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm); /* Find authentication for a specific realm */
710 /* Definition of this channel for channel registration */
711 static const struct ast_channel_tech sip_tech = {
713 .description = "Session Initiation Protocol (SIP)",
714 .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
715 .properties = AST_CHAN_TP_WANTSJITTER,
716 .requester = sip_request,
717 .devicestate = sip_devicestate,
719 .hangup = sip_hangup,
720 .answer = sip_answer,
723 .write_video = sip_write,
724 .indicate = sip_indicate,
725 .transfer = sip_transfer,
727 .send_digit = sip_senddigit,
728 .bridge = ast_rtp_bridge,
729 .send_text = sip_sendtext,
732 /*--- find_sip_method: Find SIP method from header */
733 int find_sip_method(char *msg)
736 /* Strictly speaking, SIP methods are case SENSITIVE, but we don't check */
737 for (i=1;(i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
738 if (!strcasecmp(sip_methods[i].text, msg))
739 res = sip_methods[i].id;
744 /*--- sip_debug_test_addr: See if we pass debug IP filter */
745 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
749 if (debugaddr.sin_addr.s_addr) {
750 if (((ntohs(debugaddr.sin_port) != 0)
751 && (debugaddr.sin_port != addr->sin_port))
752 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
758 /*--- sip_debug_test_pvt: Test PVT for debugging output */
759 static inline int sip_debug_test_pvt(struct sip_pvt *p)
763 return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
767 /*--- __sip_xmit: Transmit SIP message ---*/
768 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
771 char iabuf[INET_ADDRSTRLEN];
773 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
774 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
776 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
778 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));
783 static void sip_destroy(struct sip_pvt *p);
785 /*--- build_via: Build a Via header for a request ---*/
786 static void build_via(struct sip_pvt *p, char *buf, int len)
788 char iabuf[INET_ADDRSTRLEN];
790 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
791 if (ast_test_flag(p, SIP_NAT) != SIP_NAT_NEVER)
792 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
793 else /* Work around buggy UNIDEN UIP200 firmware */
794 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
797 /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
798 /* Only used for outbound registrations */
799 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
802 * Using the localaddr structure built up with localnet statements
803 * apply it to their address to see if we need to substitute our
804 * externip or can get away with our internal bindaddr
806 struct sockaddr_in theirs;
807 theirs.sin_addr = *them;
808 if (localaddr && externip.sin_addr.s_addr &&
809 ast_apply_ha(localaddr, &theirs)) {
810 char iabuf[INET_ADDRSTRLEN];
811 if (externexpire && (time(NULL) >= externexpire)) {
812 struct ast_hostent ahp;
815 externexpire += externrefresh;
816 if ((hp = ast_gethostbyname(externhost, &ahp))) {
817 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
819 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
821 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
822 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
823 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
825 else if (bindaddr.sin_addr.s_addr)
826 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
828 return ast_ouraddrfor(them, us);
832 /*--- append_history: Append to SIP dialog history */
833 /* Always returns 0 */
834 static int append_history(struct sip_pvt *p, char *event, char *data)
836 struct sip_history *hist, *prev;
840 if(!(hist = malloc(sizeof(struct sip_history)))) {
841 ast_log(LOG_WARNING, "Can't allocate memory for history");
844 memset(hist, 0, sizeof(struct sip_history));
845 snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
849 if ((*c == '\r') || (*c == '\n')) {
855 /* Enqueue into history */
867 /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
868 static int retrans_pkt(void *data)
870 struct sip_pkt *pkt=data, *prev, *cur;
872 char iabuf[INET_ADDRSTRLEN];
873 ast_mutex_lock(&pkt->owner->lock);
874 if (pkt->retrans < MAX_RETRANS) {
876 if (sip_debug_test_pvt(pkt->owner)) {
877 if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
878 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);
880 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);
882 append_history(pkt->owner, "ReTx", pkt->data);
883 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
886 ast_log(LOG_WARNING, "Maximum retries exceeded on call %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");
887 append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
889 if (ast_test_flag(pkt, FLAG_FATAL)) {
890 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
891 ast_mutex_unlock(&pkt->owner->lock);
893 ast_mutex_lock(&pkt->owner->lock);
895 if (pkt->owner->owner) {
896 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
897 ast_queue_hangup(pkt->owner->owner);
898 ast_mutex_unlock(&pkt->owner->owner->lock);
900 /* If no owner, destroy now */
901 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
904 /* In any case, go ahead and remove the packet */
906 cur = pkt->owner->packets;
915 prev->next = cur->next;
917 pkt->owner->packets = cur->next;
918 ast_mutex_unlock(&pkt->owner->lock);
922 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
925 ast_mutex_unlock(&pkt->owner->lock);
929 /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
930 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
933 pkt = malloc(sizeof(struct sip_pkt) + len + 1);
936 memset(pkt, 0, sizeof(struct sip_pkt));
937 memcpy(pkt->data, data, len);
938 pkt->packetlen = len;
939 pkt->next = p->packets;
943 pkt->data[len] = '\0';
945 ast_set_flag(pkt, FLAG_FATAL);
946 /* Schedule retransmission */
947 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
948 pkt->next = p->packets;
950 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
951 if (!strncasecmp(pkt->data, "INVITE", 6)) {
952 /* Note this is a pending invite */
953 p->pendinginvite = seqno;
958 /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
959 static int __sip_autodestruct(void *data)
961 struct sip_pvt *p = data;
964 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
965 append_history(p, "AutoDestroy", "");
967 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
968 ast_queue_hangup(p->owner);
975 /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
976 static int sip_scheddestroy(struct sip_pvt *p, int ms)
979 if (sip_debug_test_pvt(p))
980 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
982 snprintf(tmp, sizeof(tmp), "%d ms", ms);
983 append_history(p, "SchedDestroy", tmp);
985 if (p->autokillid > -1)
986 ast_sched_del(sched, p->autokillid);
987 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
991 /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
992 static int sip_cancel_destroy(struct sip_pvt *p)
994 if (p->autokillid > -1)
995 ast_sched_del(sched, p->autokillid);
996 append_history(p, "CancelDestroy", "");
1001 /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
1002 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1004 struct sip_pkt *cur, *prev = NULL;
1006 int resetinvite = 0;
1007 /* Just in case... */
1010 if (sipmethod > 0) {
1011 msg = sip_methods[sipmethod].text;
1013 msg = "___NEVER___";
1016 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1017 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1018 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1019 if (!resp && (seqno == p->pendinginvite)) {
1020 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1021 p->pendinginvite = 0;
1024 /* this is our baby */
1026 prev->next = cur->next;
1028 p->packets = cur->next;
1029 if (cur->retransid > -1)
1030 ast_sched_del(sched, cur->retransid);
1038 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1042 /* Pretend to ack all packets */
1043 static int __sip_pretend_ack(struct sip_pvt *p)
1045 char method[128]="";
1046 struct sip_pkt *cur=NULL;
1049 if (cur == p->packets) {
1050 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up!\n");
1054 ast_copy_string(method, p->packets->data, sizeof(method));
1056 while(*c && (*c < 33)) c++;
1058 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
1063 /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
1064 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1066 struct sip_pkt *cur;
1068 char *msg = sip_methods[sipmethod].text;
1072 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1073 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
1074 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1075 /* this is our baby */
1076 if (cur->retransid > -1)
1077 ast_sched_del(sched, cur->retransid);
1078 cur->retransid = -1;
1084 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");
1088 static void parse(struct sip_request *req);
1089 static char *get_header(struct sip_request *req, char *name);
1090 static void copy_request(struct sip_request *dst,struct sip_request *src);
1092 /*--- parse_copy: Copy SIP request, parse it */
1093 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1095 memset(dst, 0, sizeof(*dst));
1096 memcpy(dst->data, src->data, sizeof(dst->data));
1097 dst->len = src->len;
1101 /*--- send_response: Transmit response on SIP request---*/
1102 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1105 char iabuf[INET_ADDRSTRLEN];
1106 struct sip_request tmp;
1108 if (sip_debug_test_pvt(p)) {
1109 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1110 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);
1112 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);
1115 if (recordhistory) {
1116 parse_copy(&tmp, req);
1117 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1118 append_history(p, "TxRespRel", tmpmsg);
1120 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
1122 if (recordhistory) {
1123 parse_copy(&tmp, req);
1124 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1125 append_history(p, "TxResp", tmpmsg);
1127 res = __sip_xmit(p, req->data, req->len);
1134 /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
1135 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1138 char iabuf[INET_ADDRSTRLEN];
1139 struct sip_request tmp;
1142 if (sip_debug_test_pvt(p)) {
1143 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1144 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);
1146 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);
1149 if (recordhistory) {
1150 parse_copy(&tmp, req);
1151 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1152 append_history(p, "TxReqRel", tmpmsg);
1154 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
1156 if (recordhistory) {
1157 parse_copy(&tmp, req);
1158 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1159 append_history(p, "TxReq", tmpmsg);
1161 res = __sip_xmit(p, req->data, req->len);
1166 /*--- url_decode: Decode SIP URL ---*/
1167 static void url_decode(char *s)
1174 if (strlen(s) > 2) {
1175 if (sscanf(s + 1, "%2x", &tmp) == 1) {
1177 s += 2; /* Will be incremented once more when we break out */
1181 /* Fall through if something wasn't right with the formatting */
1191 /*--- ditch_braces: Pick out text in braces from character string ---*/
1192 static char *ditch_braces(char *tmp)
1197 if ((q = strchr(tmp, '"')) ) {
1199 if ((q = strchr(c, '"')) )
1202 ast_log(LOG_WARNING, "No closing quote in '%s'\n", tmp);
1206 if ((n = strchr(c, '<')) ) {
1208 while(*c && *c != '>') c++;
1210 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
1219 /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
1220 /* Called from PBX core text message functions */
1221 static int sip_sendtext(struct ast_channel *ast, const char *text)
1223 struct sip_pvt *p = ast->tech_pvt;
1224 int debug=sip_debug_test_pvt(p);
1227 ast_verbose("Sending text %s on %s\n", text, ast->name);
1230 if (!text || ast_strlen_zero(text))
1233 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1234 transmit_message_with_text(p, text);
1238 /*--- realtime_update_peer: Update peer object in realtime storage ---*/
1239 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, int expirey)
1242 char ipaddr[20] = "";
1243 char regseconds[20] = "0";
1245 if (expirey) { /* Registration */
1249 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime); /* Expiration time */
1250 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1251 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1253 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1256 /*--- register_peer_exten: Automatically add peer extension to dial plan ---*/
1257 static void register_peer_exten(struct sip_peer *peer, int onoff)
1260 char *stringp, *ext;
1261 if (!ast_strlen_zero(regcontext)) {
1262 ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
1264 while((ext = strsep(&stringp, "&"))) {
1266 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), free, channeltype);
1268 ast_context_remove_extension(regcontext, ext, 1, NULL);
1273 /*--- sip_destroy_peer: Destroy peer object from memory */
1274 static void sip_destroy_peer(struct sip_peer *peer)
1276 /* Delete it, it needs to disappear */
1278 sip_destroy(peer->call);
1279 if (peer->chanvars) {
1280 ast_variables_destroy(peer->chanvars);
1281 peer->chanvars = NULL;
1283 if (peer->expire > -1)
1284 ast_sched_del(sched, peer->expire);
1285 if (peer->pokeexpire > -1)
1286 ast_sched_del(sched, peer->pokeexpire);
1287 register_peer_exten(peer, 0);
1288 ast_free_ha(peer->ha);
1289 if (ast_test_flag(peer, SIP_SELFDESTRUCT))
1291 else if (ast_test_flag(peer, SIP_REALTIME))
1295 clear_realm_authentication(peer->auth);
1296 peer->auth = (struct sip_auth *) NULL;
1298 ast_dnsmgr_release(peer->dnsmgr);
1302 /*--- update_peer: Update peer data in database (if used) ---*/
1303 static void update_peer(struct sip_peer *p, int expiry)
1305 if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_RTNOUPDATE) &&
1306 (ast_test_flag(p, SIP_REALTIME) ||
1307 ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS))) {
1308 if (p->expire == -1)
1309 expiry = 0; /* Unregister realtime peer */
1310 realtime_update_peer(p->name, &p->addr, p->username, expiry);
1315 /*--- realtime_peer: Get peer from realtime storage ---*/
1316 /* Checks the "sippeers" realtime family from extconfig.conf */
1317 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1319 struct sip_peer *peer=NULL;
1320 struct ast_variable *var;
1321 struct ast_variable *tmp;
1322 char *newpeername = (char *) peername;
1323 char iabuf[80] = "";
1325 /* First check on peer name */
1327 var = ast_load_realtime("sippeers", "name", peername, NULL);
1328 else if (sin) { /* Then check on IP address */
1329 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1330 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);
1338 /* If this is type=user, then skip this object. */
1340 if (!strcasecmp(tmp->name, "type") &&
1341 !strcasecmp(tmp->value, "user")) {
1342 ast_variables_destroy(var);
1344 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1345 newpeername = tmp->value;
1350 if (!newpeername) { /* Did not find peer in realtime */
1351 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1352 ast_variables_destroy(var);
1353 return (struct sip_peer *) NULL;
1356 /* Peer found in realtime, now build it in memory */
1357 peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1360 ast_variables_destroy(var);
1361 return (struct sip_peer *) NULL;
1363 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1365 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1366 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
1367 if (peer->expire > -1) {
1368 ast_sched_del(sched, peer->expire);
1370 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1372 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1374 ast_set_flag(peer, SIP_REALTIME);
1376 ast_variables_destroy(var);
1380 /*--- sip_addrcmp: Support routine for find_peer ---*/
1381 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1383 /* We know name is the first field, so we can cast */
1384 struct sip_peer *p = (struct sip_peer *)name;
1385 return !(!inaddrcmp(&p->addr, sin) ||
1386 (ast_test_flag(p, SIP_INSECURE_PORT) &&
1387 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1390 /*--- find_peer: Locate peer by name or ip address */
1391 /* This is used on incoming SIP message to find matching peer on ip
1392 or outgoing message to find matching peer on name */
1393 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1395 struct sip_peer *p = NULL;
1398 p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
1400 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
1402 if (!p && realtime) {
1403 p = realtime_peer(peer, sin);
1409 /*--- sip_destroy_user: Remove user object from in-memory storage ---*/
1410 static void sip_destroy_user(struct sip_user *user)
1412 ast_free_ha(user->ha);
1413 if (user->chanvars) {
1414 ast_variables_destroy(user->chanvars);
1415 user->chanvars = NULL;
1417 if (ast_test_flag(user, SIP_REALTIME))
1424 /*--- realtime_user: Load user from realtime storage ---*/
1425 /* Loads user from "sipusers" category in realtime (extconfig.conf) */
1426 /* Users are matched on From: user name (the domain in skipped) */
1427 static struct sip_user *realtime_user(const char *username)
1429 struct ast_variable *var;
1430 struct ast_variable *tmp;
1431 struct sip_user *user = NULL;
1433 var = ast_load_realtime("sipusers", "name", username, NULL);
1440 if (!strcasecmp(tmp->name, "type") &&
1441 !strcasecmp(tmp->value, "peer")) {
1442 ast_variables_destroy(var);
1450 user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1452 if (!user) { /* No user found */
1453 ast_variables_destroy(var);
1457 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1458 ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1460 ASTOBJ_CONTAINER_LINK(&userl,user);
1462 /* Move counter from s to r... */
1465 ast_set_flag(user, SIP_REALTIME);
1467 ast_variables_destroy(var);
1471 /*--- find_user: Locate user by name ---*/
1472 /* Locates user by name (From: sip uri user name part) first
1473 from in-memory list (static configuration) then from
1474 realtime storage (defined in extconfig.conf) */
1475 static struct sip_user *find_user(const char *name, int realtime)
1477 struct sip_user *u = NULL;
1478 u = ASTOBJ_CONTAINER_FIND(&userl,name);
1479 if (!u && realtime) {
1480 u = realtime_user(name);
1485 /*--- create_addr: create address structure from peer definition ---*/
1486 /* Or, if peer not found, find it in the global DNS */
1487 /* returns TRUE on failure, FALSE on success */
1488 static int create_addr(struct sip_pvt *r, char *opeer)
1491 struct ast_hostent ahp;
1497 char host[MAXHOSTNAMELEN], *hostn;
1500 ast_copy_string(peer, opeer, sizeof(peer));
1501 port = strchr(peer, ':');
1506 r->sa.sin_family = AF_INET;
1507 p = find_peer(peer, NULL, 1);
1511 ast_copy_flags(r, p,
1512 SIP_PROMISCREDIR | SIP_USEREQPHONE | SIP_DTMF | SIP_NAT | SIP_REINVITE |
1513 SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
1514 r->capability = p->capability;
1516 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1517 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1520 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1521 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1523 ast_copy_string(r->peername, p->username, sizeof(r->peername));
1524 ast_copy_string(r->authname, p->username, sizeof(r->authname));
1525 ast_copy_string(r->username, p->username, sizeof(r->username));
1526 ast_copy_string(r->peersecret, p->secret, sizeof(r->peersecret));
1527 ast_copy_string(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret));
1528 ast_copy_string(r->tohost, p->tohost, sizeof(r->tohost));
1529 ast_copy_string(r->fullcontact, p->fullcontact, sizeof(r->fullcontact));
1530 if (!r->initreq.headers && !ast_strlen_zero(p->fromdomain)) {
1531 if ((callhost = strchr(r->callid, '@'))) {
1532 strncpy(callhost + 1, p->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
1535 if (ast_strlen_zero(r->tohost)) {
1536 if (p->addr.sin_addr.s_addr)
1537 ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->addr.sin_addr);
1539 ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->defaddr.sin_addr);
1541 if (!ast_strlen_zero(p->fromdomain))
1542 ast_copy_string(r->fromdomain, p->fromdomain, sizeof(r->fromdomain));
1543 if (!ast_strlen_zero(p->fromuser))
1544 ast_copy_string(r->fromuser, p->fromuser, sizeof(r->fromuser));
1545 r->maxtime = p->maxms;
1546 r->callgroup = p->callgroup;
1547 r->pickupgroup = p->pickupgroup;
1548 if (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833)
1549 r->noncodeccapability |= AST_RTP_DTMF;
1551 r->noncodeccapability &= ~AST_RTP_DTMF;
1552 ast_copy_string(r->context, p->context,sizeof(r->context));
1553 r->rtptimeout = p->rtptimeout;
1554 r->rtpholdtimeout = p->rtpholdtimeout;
1555 r->rtpkeepalive = p->rtpkeepalive;
1556 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1557 (!p->maxms || ((p->lastms >= 0) && (p->lastms <= p->maxms)))) {
1558 if (p->addr.sin_addr.s_addr) {
1559 r->sa.sin_addr = p->addr.sin_addr;
1560 r->sa.sin_port = p->addr.sin_port;
1562 r->sa.sin_addr = p->defaddr.sin_addr;
1563 r->sa.sin_port = p->defaddr.sin_port;
1565 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1567 ASTOBJ_UNREF(p,sip_destroy_peer);
1573 portno = atoi(port);
1575 portno = DEFAULT_SIP_PORT;
1577 char service[MAXHOSTNAMELEN];
1580 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1581 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1587 hp = ast_gethostbyname(hostn, &ahp);
1589 ast_copy_string(r->tohost, peer, sizeof(r->tohost));
1590 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
1591 r->sa.sin_port = htons(portno);
1592 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1595 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1601 ASTOBJ_UNREF(p,sip_destroy_peer);
1606 /*--- auto_congest: Scheduled congestion on a call ---*/
1607 static int auto_congest(void *nothing)
1609 struct sip_pvt *p = nothing;
1610 ast_mutex_lock(&p->lock);
1613 if (!ast_mutex_trylock(&p->owner->lock)) {
1614 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1615 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1616 ast_mutex_unlock(&p->owner->lock);
1619 ast_mutex_unlock(&p->lock);
1626 /*--- sip_call: Initiate SIP call from PBX ---*/
1627 /* used from the dial() application */
1628 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1632 char *vxml_url = NULL;
1633 char *distinctive_ring = NULL;
1634 char *osptoken = NULL;
1636 char *osphandle = NULL;
1638 struct varshead *headp;
1639 struct ast_var_t *current;
1640 int addsipheaders = 0;
1643 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1644 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1647 /* Check whether there is vxml_url, distinctive ring variables */
1649 headp=&ast->varshead;
1650 AST_LIST_TRAVERSE(headp,current,entries) {
1651 /* Check whether there is a VXML_URL variable */
1652 if (!vxml_url && !strcasecmp(ast_var_name(current),"VXML_URL")) {
1653 vxml_url = ast_var_value(current);
1654 } else if (!distinctive_ring && !strcasecmp(ast_var_name(current),"ALERT_INFO")) {
1655 /* Check whether there is a ALERT_INFO variable */
1656 distinctive_ring = ast_var_value(current);
1657 } else if (!addsipheaders && !strncasecmp(ast_var_name(current),"SIPADDHEADER",strlen("SIPADDHEADER"))) {
1658 /* Check whether there is a variable with a name starting with SIPADDHEADER */
1664 else if (!osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
1665 osptoken = ast_var_value(current);
1666 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
1667 osphandle = ast_var_value(current);
1673 ast_set_flag(p, SIP_OUTGOING);
1675 if (!osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
1676 /* Force Disable OSP support */
1677 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", osptoken, osphandle);
1683 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1684 res = update_user_counter(p,INC_OUT_USE);
1686 p->callingpres = ast->cid.cid_pres;
1687 p->jointcapability = p->capability;
1688 transmit_invite(p, SIP_INVITE, 1, NULL, NULL, vxml_url,distinctive_ring, osptoken, addsipheaders, 1);
1690 /* Initialize auto-congest time */
1691 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1697 /*--- sip_registry_destroy: Destroy registry object ---*/
1698 /* Objects created with the register= statement in static configuration */
1699 static void sip_registry_destroy(struct sip_registry *reg)
1703 /* Clear registry before destroying to ensure
1704 we don't get reentered trying to grab the registry lock */
1705 reg->call->registry = NULL;
1706 sip_destroy(reg->call);
1708 if (reg->expire > -1)
1709 ast_sched_del(sched, reg->expire);
1710 if (reg->timeout > -1)
1711 ast_sched_del(sched, reg->timeout);
1717 /*--- __sip_destroy: Execute destrucion of call structure, release memory---*/
1718 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1720 struct sip_pvt *cur, *prev = NULL;
1722 struct sip_history *hist;
1724 if (sip_debug_test_pvt(p))
1725 ast_verbose("Destroying call '%s'\n", p->callid);
1726 if (p->stateid > -1)
1727 ast_extension_state_del(p->stateid, NULL);
1729 ast_sched_del(sched, p->initid);
1730 if (p->autokillid > -1)
1731 ast_sched_del(sched, p->autokillid);
1734 ast_rtp_destroy(p->rtp);
1737 ast_rtp_destroy(p->vrtp);
1740 free_old_route(p->route);
1744 if (p->registry->call == p)
1745 p->registry->call = NULL;
1746 ASTOBJ_UNREF(p->registry,sip_registry_destroy);
1748 /* Unlink us from the owner if we have one */
1751 ast_mutex_lock(&p->owner->lock);
1752 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1753 p->owner->tech_pvt = NULL;
1755 ast_mutex_unlock(&p->owner->lock);
1760 p->history = p->history->next;
1767 prev->next = cur->next;
1776 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
1780 ast_sched_del(sched, p->initid);
1781 while((cp = p->packets)) {
1782 p->packets = p->packets->next;
1783 if (cp->retransid > -1)
1784 ast_sched_del(sched, cp->retransid);
1787 ast_mutex_destroy(&p->lock);
1789 ast_variables_destroy(p->chanvars);
1795 /*--- update_user_counter: Handle incominglimit and outgoinglimit for SIP users ---*/
1796 /* Note: This is going to be replaced by app_groupcount */
1797 /* Thought: For realtime, we should propably update storage with inuse counter... */
1798 static int update_user_counter(struct sip_pvt *fup, int event)
1800 char name[256] = "";
1803 int *inuse, *incominglimit;
1805 /* Test if we need to check call limits, in order to avoid
1806 realtime lookups if we do not need it */
1807 if (!ast_test_flag(fup, SIP_CALL_LIMIT))
1810 ast_copy_string(name, fup->username, sizeof(name));
1812 /* Check the list of users */
1813 u = find_user(name, 1);
1816 incominglimit = &u->incominglimit;
1819 /* Try to find peer */
1820 p = find_peer(fup->peername, NULL, 1);
1823 incominglimit = &p->incominglimit;
1824 ast_copy_string(name, fup->peername, sizeof(name));
1826 if (option_debug > 1)
1827 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
1832 /* incoming and outgoing affects the inUse counter */
1843 if (*incominglimit > 0 ) {
1844 if (*inuse >= *incominglimit) {
1845 ast_log(LOG_ERROR, "Call from %s '%s' rejected due to usage limit of %d\n", u?"user":"peer", name, *incominglimit);
1846 /* inc inUse as well */
1847 if ( event == INC_OUT_USE ) {
1851 ASTOBJ_UNREF(u,sip_destroy_user);
1853 ASTOBJ_UNREF(p,sip_destroy_peer);
1858 ast_log(LOG_DEBUG, "Call from %s '%s' is %d out of %d\n", u?"user":"peer", name, *inuse, *incominglimit);
1860 #ifdef DISABLED_CODE
1861 /* we don't use these anymore */
1863 if ( u->outUse > 0 ) {
1870 if ( u->outgoinglimit > 0 ) {
1871 if ( u->outUse >= u->outgoinglimit ) {
1872 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1873 ast_mutex_unlock(&userl.lock);
1884 ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",name,event);
1887 ASTOBJ_UNREF(u,sip_destroy_user);
1889 ASTOBJ_UNREF(p,sip_destroy_peer);
1893 /*--- sip_destroy: Destroy SIP call structure ---*/
1894 static void sip_destroy(struct sip_pvt *p)
1896 ast_mutex_lock(&iflock);
1897 __sip_destroy(p, 1);
1898 ast_mutex_unlock(&iflock);
1902 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1904 /*--- hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes ---*/
1905 static int hangup_sip2cause(int cause)
1907 /* Possible values taken from causes.h */
1910 case 403: /* Not found */
1911 return AST_CAUSE_CALL_REJECTED;
1912 case 404: /* Not found */
1913 return AST_CAUSE_UNALLOCATED;
1914 case 408: /* No reaction */
1915 return AST_CAUSE_NO_USER_RESPONSE;
1916 case 480: /* No answer */
1917 return AST_CAUSE_FAILURE;
1918 case 483: /* Too many hops */
1919 return AST_CAUSE_NO_ANSWER;
1920 case 486: /* Busy everywhere */
1921 return AST_CAUSE_BUSY;
1922 case 488: /* No codecs approved */
1923 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1924 case 500: /* Server internal failure */
1925 return AST_CAUSE_FAILURE;
1926 case 501: /* Call rejected */
1927 return AST_CAUSE_FACILITY_REJECTED;
1929 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1930 case 503: /* Service unavailable */
1931 return AST_CAUSE_CONGESTION;
1933 return AST_CAUSE_NORMAL;
1940 /*--- hangup_cause2sip: Convert Asterisk hangup causes to SIP codes ---*/
1941 /* Possible values from causes.h
1942 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
1943 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
1945 In addition to these, a lot of PRI codes is defined in causes.h
1946 ...should we take care of them too ?
1950 ISUP Cause value SIP response
1951 ---------------- ------------
1952 1 unallocated number 404 Not Found
1953 2 no route to network 404 Not found
1954 3 no route to destination 404 Not found
1955 16 normal call clearing --- (*)
1956 17 user busy 486 Busy here
1957 18 no user responding 408 Request Timeout
1958 19 no answer from the user 480 Temporarily unavailable
1959 20 subscriber absent 480 Temporarily unavailable
1960 21 call rejected 403 Forbidden (+)
1961 22 number changed (w/o diagnostic) 410 Gone
1962 22 number changed (w/ diagnostic) 301 Moved Permanently
1963 23 redirection to new destination 410 Gone
1964 26 non-selected user clearing 404 Not Found (=)
1965 27 destination out of order 502 Bad Gateway
1966 28 address incomplete 484 Address incomplete
1967 29 facility rejected 501 Not implemented
1968 31 normal unspecified 480 Temporarily unavailable
1970 static char *hangup_cause2sip(int cause)
1974 case AST_CAUSE_UNALLOCATED: /* 1 */
1975 case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
1976 case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
1977 return "404 Not Found";
1978 case AST_CAUSE_CONGESTION: /* 34 */
1979 case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
1980 return "503 Service Unavailable";
1981 case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
1982 return "408 Request Timeout";
1983 case AST_CAUSE_NO_ANSWER: /* 19 */
1984 return "480 Temporarily unavailable";
1985 case AST_CAUSE_CALL_REJECTED: /* 21 */
1986 return "403 Forbidden";
1987 case AST_CAUSE_NUMBER_CHANGED: /* 22 */
1989 case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
1990 return "480 Temporarily unavailable";
1991 case AST_CAUSE_INVALID_NUMBER_FORMAT:
1992 return "484 Address incomplete";
1993 case AST_CAUSE_USER_BUSY:
1994 return "486 Busy here";
1995 case AST_CAUSE_FAILURE:
1996 return "500 Server internal failure";
1997 case AST_CAUSE_FACILITY_REJECTED: /* 29 */
1998 return "501 Not Implemented";
1999 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2000 return "503 Service Unavailable";
2001 /* Used in chan_iax2 */
2002 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2003 return "502 Bad Gateway";
2004 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
2005 return "488 Not Acceptable Here";
2007 case AST_CAUSE_NOTDEFINED:
2009 ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2018 /*--- sip_hangup: Hangup SIP call ---*/
2019 /* Part of PBX interface */
2020 static int sip_hangup(struct ast_channel *ast)
2022 struct sip_pvt *p = ast->tech_pvt;
2024 struct ast_flags locflags = {0};
2027 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
2029 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2032 ast_mutex_lock(&p->lock);
2034 if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
2035 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
2038 if (ast_test_flag(p, SIP_OUTGOING)) {
2039 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
2040 update_user_counter(p, DEC_OUT_USE);
2042 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
2043 update_user_counter(p, DEC_IN_USE);
2045 /* Determine how to disconnect */
2046 if (p->owner != ast) {
2047 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
2048 ast_mutex_unlock(&p->lock);
2051 if (ast->_state != AST_STATE_UP)
2056 ast_dsp_free(p->vad);
2059 ast->tech_pvt = NULL;
2061 ast_mutex_lock(&usecnt_lock);
2063 ast_mutex_unlock(&usecnt_lock);
2064 ast_update_use_count();
2066 ast_set_flag(&locflags, SIP_NEEDDESTROY);
2067 /* Start the process if it's not already started */
2068 if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2070 if (ast_test_flag(p, SIP_OUTGOING)) {
2071 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
2072 /* Actually don't destroy us yet, wait for the 487 on our original
2073 INVITE, but do set an autodestruct just in case we never get it. */
2074 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2075 sip_scheddestroy(p, 15000);
2076 if ( p->initid != -1 ) {
2077 /* channel still up - reverse dec of inUse counter
2078 only if the channel is not auto-congested */
2079 if (ast_test_flag(p, SIP_OUTGOING)) {
2080 update_user_counter(p, INC_OUT_USE);
2083 update_user_counter(p, INC_IN_USE);
2088 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
2089 transmit_response_reliable(p, res, &p->initreq, 1);
2091 transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
2094 if (!p->pendinginvite) {
2096 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
2098 /* Note we will need a BYE when this all settles out
2099 but we can't send one while we have "INVITE" outstanding. */
2100 ast_set_flag(p, SIP_PENDINGBYE);
2101 ast_clear_flag(p, SIP_NEEDREINVITE);
2105 ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);
2106 ast_mutex_unlock(&p->lock);
2110 /*--- sip_answer: Answer SIP call , send 200 OK on Invite ---*/
2111 /* Part of PBX interface */
2112 static int sip_answer(struct ast_channel *ast)
2116 struct sip_pvt *p = ast->tech_pvt;
2118 ast_mutex_lock(&p->lock);
2119 if (ast->_state != AST_STATE_UP) {
2124 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
2126 fmt=ast_getformatbyname(codec);
2128 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
2129 if (p->jointcapability & fmt) {
2130 p->jointcapability &= fmt;
2131 p->capability &= fmt;
2133 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2134 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
2137 ast_setstate(ast, AST_STATE_UP);
2139 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
2140 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
2142 ast_mutex_unlock(&p->lock);
2146 /*--- sip_write: Send frame to media channel (rtp) ---*/
2147 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2149 struct sip_pvt *p = ast->tech_pvt;
2151 switch (frame->frametype) {
2152 case AST_FRAME_VOICE:
2153 if (!(frame->subclass & ast->nativeformats)) {
2154 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2155 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2159 ast_mutex_lock(&p->lock);
2161 /* If channel is not up, activate early media session */
2162 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2163 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2164 ast_set_flag(p, SIP_PROGRESS_SENT);
2166 time(&p->lastrtptx);
2167 res = ast_rtp_write(p->rtp, frame);
2169 ast_mutex_unlock(&p->lock);
2172 case AST_FRAME_VIDEO:
2174 ast_mutex_lock(&p->lock);
2176 /* Activate video early media */
2177 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2178 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2179 ast_set_flag(p, SIP_PROGRESS_SENT);
2181 time(&p->lastrtptx);
2182 res = ast_rtp_write(p->vrtp, frame);
2184 ast_mutex_unlock(&p->lock);
2187 case AST_FRAME_IMAGE:
2191 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2198 /*--- sip_fixup: Fix up a channel: If a channel is consumed, this is called.
2199 Basically update any ->owner links ----*/
2200 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2202 struct sip_pvt *p = newchan->tech_pvt;
2203 ast_mutex_lock(&p->lock);
2204 if (p->owner != oldchan) {
2205 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2206 ast_mutex_unlock(&p->lock);
2210 ast_mutex_unlock(&p->lock);
2214 /*--- sip_senddigit: Send DTMF character on SIP channel */
2215 /* within one call, we're able to transmit in many methods simultaneously */
2216 static int sip_senddigit(struct ast_channel *ast, char digit)
2218 struct sip_pvt *p = ast->tech_pvt;
2220 ast_mutex_lock(&p->lock);
2221 switch (ast_test_flag(p, SIP_DTMF)) {
2223 transmit_info_with_digit(p, digit);
2225 case SIP_DTMF_RFC2833:
2227 ast_rtp_senddigit(p->rtp, digit);
2229 case SIP_DTMF_INBAND:
2233 ast_mutex_unlock(&p->lock);
2238 /*--- sip_transfer: Transfer SIP call */
2239 static int sip_transfer(struct ast_channel *ast, const char *dest)
2241 struct sip_pvt *p = ast->tech_pvt;
2244 ast_mutex_lock(&p->lock);
2245 if (ast->_state == AST_STATE_RING)
2246 res = sip_sipredirect(p, dest);
2248 res = transmit_refer(p, dest);
2249 ast_mutex_unlock(&p->lock);
2253 /*--- sip_indicate: Play indication to user */
2254 /* With SIP a lot of indications is sent as messages, letting the device play
2255 the indication - busy signal, congestion etc */
2256 static int sip_indicate(struct ast_channel *ast, int condition)
2258 struct sip_pvt *p = ast->tech_pvt;
2261 ast_mutex_lock(&p->lock);
2263 case AST_CONTROL_RINGING:
2264 if (ast->_state == AST_STATE_RING) {
2265 if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
2266 (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
2267 /* Send 180 ringing if out-of-band seems reasonable */
2268 transmit_response(p, "180 Ringing", &p->initreq);
2269 ast_set_flag(p, SIP_RINGING);
2270 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2273 /* Well, if it's not reasonable, just send in-band */
2278 case AST_CONTROL_BUSY:
2279 if (ast->_state != AST_STATE_UP) {
2280 transmit_response(p, "486 Busy Here", &p->initreq);
2281 ast_set_flag(p, SIP_ALREADYGONE);
2282 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2287 case AST_CONTROL_CONGESTION:
2288 if (ast->_state != AST_STATE_UP) {
2289 transmit_response(p, "503 Service Unavailable", &p->initreq);
2290 ast_set_flag(p, SIP_ALREADYGONE);
2291 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2296 case AST_CONTROL_PROGRESS:
2297 case AST_CONTROL_PROCEEDING:
2298 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2299 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2300 ast_set_flag(p, SIP_PROGRESS_SENT);
2305 case AST_CONTROL_HOLD: /* We are put on hold */
2306 /* The PBX is providing us with onhold music, but
2307 should we clear the RTP stream with the other
2308 end? Guess we could do that if there's no
2309 musiconhold class defined for this channel
2312 ast_log(LOG_DEBUG, "SIP dialog on hold: %s\n", p->callid);
2314 ast_set_flag(p, SIP_CALL_ONHOLD);
2316 case AST_CONTROL_UNHOLD: /* We are back from hold */
2317 /* Open RTP stream if we decide to close it
2320 ast_log(LOG_DEBUG, "SIP dialog off hold: %s\n", p->callid);
2322 ast_clear_flag(p, SIP_CALL_ONHOLD);
2328 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2332 ast_mutex_unlock(&p->lock);
2338 /*--- sip_new: Initiate a call in the SIP channel */
2339 /* called from sip_request (calls from the pbx ) */
2340 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
2342 struct ast_channel *tmp;
2343 struct ast_variable *v = NULL;
2346 ast_mutex_unlock(&i->lock);
2347 /* Don't hold a sip pvt lock while we allocate a channel */
2348 tmp = ast_channel_alloc(1);
2349 ast_mutex_lock(&i->lock);
2351 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2354 tmp->tech = &sip_tech;
2355 /* Select our native format based on codec preference until we receive
2356 something from another device to the contrary. */
2357 ast_mutex_lock(&i->lock);
2358 if (i->jointcapability)
2359 tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
2360 else if (i->capability)
2361 tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
2363 tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
2364 ast_mutex_unlock(&i->lock);
2365 fmt = ast_best_codec(tmp->nativeformats);
2368 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
2369 else if (strchr(i->fromdomain,':'))
2370 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2372 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2374 tmp->type = channeltype;
2375 if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
2376 i->vad = ast_dsp_new();
2377 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2379 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2381 tmp->fds[0] = ast_rtp_fd(i->rtp);
2382 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2384 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2385 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2387 if (state == AST_STATE_RING)
2389 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2390 tmp->writeformat = fmt;
2391 tmp->rawwriteformat = fmt;
2392 tmp->readformat = fmt;
2393 tmp->rawreadformat = fmt;
2396 tmp->callgroup = i->callgroup;
2397 tmp->pickupgroup = i->pickupgroup;
2398 tmp->cid.cid_pres = i->callingpres;
2399 if (!ast_strlen_zero(i->accountcode))
2400 ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
2402 tmp->amaflags = i->amaflags;
2403 if (!ast_strlen_zero(i->language))
2404 ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
2405 if (!ast_strlen_zero(i->musicclass))
2406 ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
2408 ast_mutex_lock(&usecnt_lock);
2410 ast_mutex_unlock(&usecnt_lock);
2411 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
2412 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
2413 if (!ast_strlen_zero(i->cid_num))
2414 tmp->cid.cid_num = strdup(i->cid_num);
2415 if (!ast_strlen_zero(i->cid_name))
2416 tmp->cid.cid_name = strdup(i->cid_name);
2417 if (!ast_strlen_zero(i->rdnis))
2418 tmp->cid.cid_rdnis = strdup(i->rdnis);
2419 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2420 tmp->cid.cid_dnid = strdup(i->exten);
2422 if (!ast_strlen_zero(i->uri)) {
2423 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2425 if (!ast_strlen_zero(i->domain)) {
2426 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2428 if (!ast_strlen_zero(i->useragent)) {
2429 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2431 if (!ast_strlen_zero(i->callid)) {
2432 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2434 ast_setstate(tmp, state);
2435 if (state != AST_STATE_DOWN) {
2436 if (ast_pbx_start(tmp)) {
2437 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2442 /* Set channel variables for this call from configuration */
2443 for (v = i->chanvars ; v ; v = v->next)
2444 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2449 /*--- get_sdp_by_line: Reads one line of SIP message body */
2450 static char* get_sdp_by_line(char* line, char *name, int nameLen)
2452 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2453 char* r = line + nameLen + 1;
2454 while (*r && (*r < 33))
2461 /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
2462 but the name wrongly applies _only_ sdp */
2463 static char *get_sdp(struct sip_request *req, char *name)
2466 int len = strlen(name);
2469 for (x=0; x<req->lines; x++) {
2470 r = get_sdp_by_line(req->line[x], name, len);
2478 static void sdpLineNum_iterator_init(int* iterator)
2483 static char* get_sdp_iterate(int* iterator,
2484 struct sip_request *req, char *name)
2486 int len = strlen(name);
2489 while (*iterator < req->lines) {
2490 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2497 static char *__get_header(struct sip_request *req, char *name, int *start)
2500 int len = strlen(name);
2502 if (pedanticsipchecking) {
2503 /* Technically you can place arbitrary whitespace both before and after the ':' in
2504 a header, although RFC3261 clearly says you shouldn't before, and place just
2505 one afterwards. If you shouldn't do it, what absolute idiot decided it was
2506 a good idea to say you can do it, and if you can do it, why in the hell would
2507 you say you shouldn't. */
2508 for (x=*start; x<req->headers; x++) {
2509 if (!strncasecmp(req->header[x], name, len)) {
2510 r = req->header[x] + len;
2511 while(*r && (*r < 33))
2515 while(*r && (*r < 33))
2523 /* We probably shouldn't even bother counting whitespace afterwards but
2524 I guess for backwards compatibility we will */
2525 for (x=*start;x<req->headers;x++) {
2526 if (!strncasecmp(req->header[x], name, len) &&
2527 (req->header[x][len] == ':')) {
2528 r = req->header[x] + len + 1;
2529 while(*r && (*r < 33))
2537 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2538 if (!strcasecmp(aliases[x].fullname, name))
2539 return __get_header(req, aliases[x].shortname, start);
2541 /* Don't return NULL, so get_header is always a valid pointer */
2545 /*--- get_header: Get header from SIP request ---*/
2546 static char *get_header(struct sip_request *req, char *name)
2549 return __get_header(req, name, &start);
2552 /*--- sip_rtp_read: Read RTP from network ---*/
2553 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
2555 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
2556 struct ast_frame *f;
2557 static struct ast_frame null_frame = { AST_FRAME_NULL, };
2560 f = ast_rtp_read(p->rtp); /* RTP Audio */
2563 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
2566 f = ast_rtp_read(p->vrtp); /* RTP Video */
2569 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
2574 /* Don't forward RFC2833 if we're not supposed to */
2575 if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
2578 /* We already hold the channel lock */
2579 if (f->frametype == AST_FRAME_VOICE) {
2580 if (f->subclass != p->owner->nativeformats) {
2581 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2582 p->owner->nativeformats = f->subclass;
2583 ast_set_read_format(p->owner, p->owner->readformat);
2584 ast_set_write_format(p->owner, p->owner->writeformat);
2586 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
2587 f = ast_dsp_process(p->owner, p->vad, f);
2588 if (f && (f->frametype == AST_FRAME_DTMF))
2589 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
2596 /*--- sip_read: Read SIP RTP from channel */
2597 static struct ast_frame *sip_read(struct ast_channel *ast)
2599 struct ast_frame *fr;
2600 struct sip_pvt *p = ast->tech_pvt;
2601 ast_mutex_lock(&p->lock);
2602 fr = sip_rtp_read(ast, p);
2603 time(&p->lastrtprx);
2604 ast_mutex_unlock(&p->lock);
2608 /*--- build_callid: Build SIP CALLID header ---*/
2609 static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
2614 char iabuf[INET_ADDRSTRLEN];
2615 for (x=0; x<4; x++) {
2617 res = snprintf(callid, len, "%08x", val);
2621 if (!ast_strlen_zero(fromdomain))
2622 snprintf(callid, len, "@%s", fromdomain);
2624 /* It's not important that we really use our right IP here... */
2625 snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
2628 /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
2629 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method)
2633 p = malloc(sizeof(struct sip_pvt));
2636 /* Keep track of stuff */
2637 memset(p, 0, sizeof(struct sip_pvt));
2638 ast_mutex_init(&p->lock);
2648 memcpy(&p->sa, sin, sizeof(p->sa));
2649 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
2650 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2652 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2657 /* Start with 101 instead of 1 */
2660 if (sip_methods[intended_method].need_rtp) {
2661 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2663 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2665 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
2666 ast_mutex_destroy(&p->lock);
2668 ast_variables_destroy(p->chanvars);
2674 ast_rtp_settos(p->rtp, tos);
2676 ast_rtp_settos(p->vrtp, tos);
2677 p->rtptimeout = global_rtptimeout;
2678 p->rtpholdtimeout = global_rtpholdtimeout;
2679 p->rtpkeepalive = global_rtpkeepalive;
2682 if (useglobal_nat && sin) {
2683 /* Setup NAT structure according to global settings if we have an address */
2684 ast_copy_flags(p, &global_flags, SIP_NAT);
2685 memcpy(&p->recv, sin, sizeof(p->recv));
2687 ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
2689 ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
2692 ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
2693 build_via(p, p->via, sizeof(p->via));
2695 build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
2697 ast_copy_string(p->callid, callid, sizeof(p->callid));
2698 ast_copy_flags(p, (&global_flags), SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_DTMF | SIP_REINVITE | SIP_PROG_INBAND | SIP_OSPAUTH);
2699 /* Assign default music on hold class */
2700 strcpy(p->musicclass, global_musicclass);
2701 p->capability = global_capability;
2702 if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833)
2703 p->noncodeccapability |= AST_RTP_DTMF;
2704 strcpy(p->context, default_context);
2706 /* Add to active dialog list */
2707 ast_mutex_lock(&iflock);
2710 ast_mutex_unlock(&iflock);
2712 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");
2716 /*--- find_call: Connect incoming SIP message to current dialog or create new dialog structure */
2717 /* Called by handle_request ,sipsock_read */
2718 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
2723 char iabuf[INET_ADDRSTRLEN];
2727 callid = get_header(req, "Call-ID");
2729 if (pedanticsipchecking) {
2730 /* In principle Call-ID's uniquely identify a call, however some vendors
2731 (i.e. Pingtel) send multiple calls with the same Call-ID and different
2732 tags in order to simplify billing. The RFC does state that we have to
2733 compare tags in addition to the call-id, but this generate substantially
2734 more overhead which is totally unnecessary for the vast majority of sane
2735 SIP implementations, and thus Asterisk does not enable this behavior
2736 by default. Short version: You'll need this option to support conferencing
2738 ast_copy_string(tmp, req->header[0], sizeof(tmp));
2740 c = strchr(tmp, ' ');
2743 if (!strcasecmp(cmd, "SIP/2.0"))
2744 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
2746 ast_copy_string(tmp, get_header(req, "From"), sizeof(tmp));
2747 tag = ast_strcasestr(tmp, "tag=");
2750 c = strchr(tag, ';');
2757 if (ast_strlen_zero(callid)) {
2758 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
2761 ast_mutex_lock(&iflock);
2764 if (!strcmp(p->callid, callid) &&
2765 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) {
2766 /* Found the call */
2767 ast_mutex_lock(&p->lock);
2768 ast_mutex_unlock(&iflock);
2773 ast_mutex_unlock(&iflock);
2774 p = sip_alloc(callid, sin, 1, intended_method);
2776 ast_mutex_lock(&p->lock);
2780 /*--- sip_register: Parse register=> line in sip.conf and add to registry */
2781 static int sip_register(char *value, int lineno)
2783 struct sip_registry *reg;
2784 char copy[256] = "";
2785 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
2792 ast_copy_string(copy, value, sizeof(copy));
2795 hostname = strrchr(stringp, '@');
2800 if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
2801 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
2805 username = strsep(&stringp, ":");
2807 secret = strsep(&stringp, ":");
2809 authuser = strsep(&stringp, ":");
2812 hostname = strsep(&stringp, "/");
2814 contact = strsep(&stringp, "/");
2815 if (!contact || ast_strlen_zero(contact))
2818 hostname = strsep(&stringp, ":");
2819 porta = strsep(&stringp, ":");
2821 if (porta && !atoi(porta)) {
2822 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
2825 reg = malloc(sizeof(struct sip_registry));
2827 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
2830 memset(reg, 0, sizeof(struct sip_registry));
2833 ast_copy_string(reg->contact, contact, sizeof(reg->contact));
2835 ast_copy_string(reg->username, username, sizeof(reg->username));
2837 ast_copy_string(reg->hostname, hostname, sizeof(reg->hostname));
2839 ast_copy_string(reg->authuser, authuser, sizeof(reg->authuser));
2841 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
2844 reg->refresh = default_expiry;
2845 reg->portno = porta ? atoi(porta) : 0;
2846 reg->callid_valid = 0;
2848 ASTOBJ_CONTAINER_LINK(®l, reg);
2849 ASTOBJ_UNREF(reg,sip_registry_destroy);
2853 /*--- lws2sws: Parse multiline SIP headers into one header */
2854 /* This is enabled if pedanticsipchecking is enabled */
2855 static int lws2sws(char *msgbuf, int len)
2861 /* Eliminate all CRs */
2862 if (msgbuf[h] == '\r') {
2866 /* Check for end-of-line */
2867 if (msgbuf[h] == '\n') {
2868 /* Check for end-of-message */
2871 /* Check for a continuation line */
2872 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
2873 /* Merge continuation line */
2877 /* Propagate LF and start new line */
2878 msgbuf[t++] = msgbuf[h++];
2882 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
2887 msgbuf[t++] = msgbuf[h++];
2891 msgbuf[t++] = msgbuf[h++];
2899 /*--- parse: Parse a SIP message ----*/
2900 static void parse(struct sip_request *req)
2902 /* Divide fields by NULL's */
2907 /* First header starts immediately */
2911 /* We've got a new header */
2915 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2917 if (ast_strlen_zero(req->header[f])) {
2918 /* Line by itself means we're now in content */
2922 if (f >= SIP_MAX_HEADERS - 1) {
2923 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2926 req->header[f] = c + 1;
2927 } else if (*c == '\r') {
2928 /* Ignore but eliminate \r's */
2933 /* Check for last header */
2934 if (!ast_strlen_zero(req->header[f]))
2937 /* Now we process any mime content */
2942 /* We've got a new line */
2945 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2947 if (f >= SIP_MAX_LINES - 1) {
2948 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2951 req->line[f] = c + 1;
2952 } else if (*c == '\r') {
2953 /* Ignore and eliminate \r's */
2958 /* Check for last line */
2959 if (!ast_strlen_zero(req->line[f]))
2963 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2966 /*--- process_sdp: Process SIP SDP and activate RTP channels---*/
2967 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2973 char iabuf[INET_ADDRSTRLEN];
2977 int peercapability, peernoncodeccapability;
2978 int vpeercapability=0, vpeernoncodeccapability=0;
2979 struct sockaddr_in sin;
2982 struct ast_hostent ahp;
2984 int destiterator = 0;
2988 int debug=sip_debug_test_pvt(p);
2989 struct ast_channel *bridgepeer = NULL;
2991 /* Update our last rtprx when we receive an SDP, too */
2992 time(&p->lastrtprx);
2993 time(&p->lastrtptx);
2995 /* Get codec and RTP info from SDP */
2996 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2997 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
3000 m = get_sdp(req, "m");
3001 sdpLineNum_iterator_init(&destiterator);
3002 c = get_sdp_iterate(&destiterator, req, "c");
3003 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
3004 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
3007 if (sscanf(c, "IN IP4 %256s", host) != 1) {
3008 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
3011 /* XXX This could block for a long time, and block the main thread! XXX */
3012 hp = ast_gethostbyname(host, &ahp);
3014 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
3017 sdpLineNum_iterator_init(&iterator);
3018 ast_set_flag(p, SIP_NOVIDEO);
3019 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
3021 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1) ||
3022 (sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2)) {
3025 /* Scan through the RTP payload types specified in a "m=" line: */
3026 ast_rtp_pt_clear(p->rtp);
3028 while(!ast_strlen_zero(codecs)) {
3029 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
3030 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
3034 ast_verbose("Found RTP audio format %d\n", codec);
3035 ast_rtp_set_m_type(p->rtp, codec);
3037 /* Skip over any whitespace */
3038 while(*codecs && (*codecs < 33)) codecs++;
3042 ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
3044 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
3046 ast_clear_flag(p, SIP_NOVIDEO);
3048 /* Scan through the RTP payload types specified in a "m=" line: */
3050 while(!ast_strlen_zero(codecs)) {
3051 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
3052 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
3056 ast_verbose("Found video format %s\n", ast_getformatname(codec));
3057 ast_rtp_set_m_type(p->vrtp, codec);
3059 /* Skip over any whitespace */
3060 while(*codecs && (*codecs < 33)) codecs++;
3064 ast_log(LOG_WARNING, "Unknown SDP media type in offer: %s\n", m);
3066 if (portno == -1 && vportno == -1) {
3067 /* No acceptable offer found in SDP */
3070 /* Check for Media-description-level-address for audio */
3071 if (pedanticsipchecking) {
3072 c = get_sdp_iterate(&destiterator, req, "c");
3073 if (!ast_strlen_zero(c)) {
3074 if (sscanf(c, "IN IP4 %256s", host) != 1) {
3075 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
3077 /* XXX This could block for a long time, and block the main thread! XXX */
3078 hp = ast_gethostbyname(host, &ahp);
3080 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
3085 /* RTP addresses and ports for audio and video */
3086 sin.sin_family = AF_INET;
3087 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
3089 /* Setup audio port number */
3090 sin.sin_port = htons(portno);
3091 if (p->rtp && sin.sin_port) {
3092 ast_rtp_set_peer(p->rtp, &sin);
3094 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3095 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));
3098 /* Check for Media-description-level-address for video */
3099 if (pedanticsipchecking) {
3100 c = get_sdp_iterate(&destiterator, req, "c");
3101 if (!ast_strlen_zero(c)) {
3102 if (sscanf(c, "IN IP4 %256s", host) != 1) {
3103 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
3105 /* XXX This could block for a long time, and block the main thread! XXX */
3106 hp = ast_gethostbyname(host, &ahp);
3108 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
3113 /* Setup video port number */
3114 sin.sin_port = htons(vportno);
3115 if (p->vrtp && sin.sin_port) {
3116 ast_rtp_set_peer(p->vrtp, &sin);
3118 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3119 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));
3123 /* Next, scan through each "a=rtpmap:" line, noting each
3124 * specified RTP payload type (with corresponding MIME subtype):
3126 sdpLineNum_iterator_init(&iterator);
3127 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
3128 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
3129 if (!strcasecmp(a, "sendonly")) {
3133 if (!strcasecmp(a, "sendrecv")) {
3136 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
3138 ast_verbose("Found description format %s\n", mimeSubtype);
3139 /* Note: should really look at the 'freq' and '#chans' params too */
3140 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
3142 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
3145 /* Now gather all of the codecs that were asked for: */
3146 ast_rtp_get_current_formats(p->rtp,
3147 &peercapability, &peernoncodeccapability);
3149 ast_rtp_get_current_formats(p->vrtp,
3150 &vpeercapability, &vpeernoncodeccapability);
3151 p->jointcapability = p->capability & (peercapability | vpeercapability);
3152 p->peercapability = (peercapability | vpeercapability);
3153 p->noncodeccapability = noncodeccapability & peernoncodeccapability;
3156 /* shame on whoever coded this.... */
3157 const unsigned slen=512;
3158 char s1[slen], s2[slen], s3[slen], s4[slen];
3160 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
3161 ast_getformatname_multiple(s1, slen, p->capability),
3162 ast_getformatname_multiple(s2, slen, peercapability),
3163 ast_getformatname_multiple(s3, slen, vpeercapability),
3164 ast_getformatname_multiple(s4, slen, p->jointcapability));
3166 ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
3167 ast_rtp_lookup_mime_multiple(s1, slen, noncodeccapability, 0),
3168 ast_rtp_lookup_mime_multiple(s2, slen, peernoncodeccapability, 0),
3169 ast_rtp_lookup_mime_multiple(s3, slen, p->noncodeccapability, 0));
3171 if (!p->jointcapability) {
3172 ast_log(LOG_NOTICE, "No compatible codecs!\n");
3176 if (!p->owner) /* There's no open channel owning us */
3179 if (!(p->owner->nativeformats & p->jointcapability)) {
3180 const unsigned slen=512;
3181 char s1[slen], s2[slen];
3182 ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n",
3183 ast_getformatname_multiple(s1, slen, p->jointcapability),
3184 ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
3185 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1);
3186 ast_set_read_format(p->owner, p->owner->readformat);
3187 ast_set_write_format(p->owner, p->owner->writeformat);
3189 if ((bridgepeer=ast_bridged_channel(p->owner))) {
3190 /* We have a bridge */
3191 /* Turn on/off music on hold if we are holding/unholding */
3192 if (sin.sin_addr.s_addr && !sendonly) {
3193 ast_moh_stop(bridgepeer);
3194 /* Indicate UNHOLD status to the other channel */
3195 ast_indicate(bridgepeer, AST_CONTROL_UNHOLD);
3196 append_history(p, "Unhold", req->data);
3197 if (callevents && ast_test_flag(p, SIP_CALL_ONHOLD)) {
3198 manager_event(EVENT_FLAG_CALL, "Unhold",
3202 p->owner->uniqueid);
3204 ast_clear_flag(p, SIP_CALL_ONHOLD);
3205 /* Somehow, we need to check if we need to re-invite here */
3206 /* If this call had a external native bridge, it's broken
3207 now and we need to start all over again.
3208 The bridged peer, if SIP, now listens
3209 to RTP from Asterisk instead of from
3212 So IF we had a native bridge before
3213 the HOLD, we need to somehow re-invite
3214 into a NATIVE bridge afterwards...
3219 /* No address for RTP, we're on hold */
3220 append_history(p, "Hold", req->data);
3221 if (callevents && !ast_test_flag(p, SIP_CALL_ONHOLD)) {
3222 manager_event(EVENT_FLAG_CALL, "Hold",
3226 p->owner->uniqueid);
3228 ast_set_flag(p, SIP_CALL_ONHOLD);
3229 /* Indicate HOLD status to the other channel */
3230 ast_indicate(bridgepeer, AST_CONTROL_HOLD);
3231 ast_moh_start(bridgepeer, NULL);
3233 ast_rtp_stop(p->rtp);
3239 /*--- add_header: Add header to SIP message */
3240 static int add_header(struct sip_request *req, char *var, char *value)
3243 char *shortname = "";
3244 if (req->len >= sizeof(req->data) - 4) {
3245 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
3249 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
3253 req->header[req->headers] = req->data + req->len;
3254 if (compactheaders) {
3255 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
3256 if (!strcasecmp(aliases[x].fullname, var))
3257 shortname = aliases[x].shortname;
3259 if (!ast_strlen_zero(shortname)) {
3260 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", shortname, value);
3262 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
3264 req->len += strlen(req->header[req->headers]);
3265 if (req->headers == SIP_MAX_HEADERS) {
3266 ast_log(LOG_WARNING, "Out of SIP header space\n");
3273 /*--- add_blank_header: Add blank header to SIP message */
3274 static int add_blank_header(struct sip_request *req)
3276 if (req->len >= sizeof(req->data) - 4) {
3277 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
3281 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
3284 req->header[req->headers] = req->data + req->len;
3285 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
3286 req->len += strlen(req->header[req->headers]);
3287 if (req->headers == SIP_MAX_HEADERS) {
3288 ast_log(LOG_WARNING, "Out of SIP header space\n");
3295 /*--- add_line: Add content (not header) to SIP message */
3296 static int add_line(struct sip_request *req, const char *line)
3298 if (req->len >= sizeof(req->data) - 4) {
3299 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
3303 /* Add extra empty return */
3304 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
3305 req->len += strlen(req->data + req->len);
3307 req->line[req->lines] = req->data + req->len;
3308 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
3309 req->len += strlen(req->line[req->lines]);
3310 if (req->lines == SIP_MAX_LINES) {
3311 ast_log(LOG_WARNING, "Out of SIP line space\n");
3318 /*--- copy_header: Copy one header field from one request to another */
3319 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
3322 tmp = get_header(orig, field);
3323 if (!ast_strlen_zero(tmp)) {
3324 /* Add what we're responding to */
3325 return add_header(req, field, tmp);
3327 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
3331 /*--- copy_all_header: Copy all headers from one request to another ---*/
3332 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
3338 tmp = __get_header(orig, field, &start);
3339 if (!ast_strlen_zero(tmp)) {
3340 /* Add what we're responding to */
3341 add_header(req, field, tmp);
3346 return copied ? 0 : -1;
3349 /*--- copy_via_headers: Copy SIP VIA Headers from one request to another ---*/
3350 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
3352 char tmp[256]="", *oh, *end;
3356 char iabuf[INET_ADDRSTRLEN];
3358 oh = __get_header(orig, field, &start);
3359 if (!ast_strlen_zero(oh)) {
3361 ast_copy_string(tmp, oh, sizeof(tmp));
3362 oh = strstr(tmp, ";rport");
3364 end = strchr(oh + 1, ';');
3366 memmove(oh, end, strlen(end) + 1);
3370 if (!copied && (ast_test_flag(p, SIP_NAT) == SIP_NAT_ALWAYS)) {
3371 /* Whoo hoo! Now we can indicate port address translation too! Just
3372 another RFC (RFC3581). I'll leave the original comments in for
3374 snprintf(new, sizeof(new), "%s;received=%s;rport=%d", tmp, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
3375 add_header(req, field, new);
3377 /* Add what we're responding to */
3378 add_header(req, field, tmp);
3385 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
3391 /*--- add_route: Add route header into request per learned route ---*/
3392 static void add_route(struct sip_request *req, struct sip_route *route)
3395 int n, rem = sizeof(r);
3401 n = strlen(route->hop);
3402 if ((n+3)>rem) break;
3408 ast_copy_string(p, route->hop, rem); p += n;
3411 route = route->next;
3414 add_header(req, "Route", r);
3417 /*--- set_destination: Set destination from SIP URI ---*/
3418 static void set_destination(struct sip_pvt *p, char *uri)
3420 char *h, *maddr, hostname[256] = "";
3421 char iabuf[INET_ADDRSTRLEN];
3424 struct ast_hostent ahp;
3425 int debug=sip_debug_test_pvt(p);
3427 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
3428 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
3431 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
3433 /* Find and parse hostname */
3434 h = strchr(uri, '@');
3439 if (strncmp(h, "sip:", 4) == 0)
3441 else if (strncmp(h, "sips:", 5) == 0)
3444 hn = strcspn(h, ":;>") + 1;
3445 if (hn > sizeof(hostname)) hn = sizeof(hostname);
3446 ast_copy_string(hostname, h, hn);
3449 /* Is "port" present? if not default to 5060 */
3453 port = strtol(h, &h, 10);
3458 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
3459 maddr = strstr(h, "maddr=");
3462 hn = strspn(maddr, "0123456789.") + 1;
3463 if (hn > sizeof(hostname)) hn = sizeof(hostname);
3464 ast_copy_string(hostname, h, hn);
3467 hp = ast_gethostbyname(hostname, &ahp);
3469 ast_log(LOG_WARNING, "Can't find address for host '%s'\n",