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/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <asterisk/lock.h>
27 #include <asterisk/sched.h>
28 #include <asterisk/io.h>
29 #include <asterisk/rtp.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/manager.h>
32 #include <asterisk/callerid.h>
33 #include <asterisk/cli.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <asterisk/features.h>
38 #include <asterisk/acl.h>
39 #include <asterisk/srv.h>
40 #include <asterisk/astdb.h>
41 #include <asterisk/causes.h>
42 #include <asterisk/utils.h>
43 #include <asterisk/file.h>
44 #include <asterisk/astobj.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 char *desc = "Session Initiation Protocol (SIP)";
114 static char *channeltype = "SIP";
115 static char *tdesc = "Session Initiation Protocol (SIP)";
116 static char *config = "sip.conf";
117 static char *notify_config = "sip_notify.conf";
119 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
120 #define SIP_MAX_PACKET 4096 /* Also from RFC 2543, should sub headers tho */
122 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
124 static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
126 #define DEFAULT_CONTEXT "default"
127 static char default_context[AST_MAX_EXTENSION] = DEFAULT_CONTEXT;
129 static char default_language[MAX_LANGUAGE] = "";
131 #define DEFAULT_CALLERID "asterisk"
132 static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
134 static char default_fromdomain[AST_MAX_EXTENSION] = "";
136 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
137 static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
140 static int default_qualify = 0; /* Default Qualify= setting */
142 static struct ast_flags global_flags = {0}; /* global SIP_ flags */
143 static struct ast_flags global_flags_page2 = {0}; /* more global SIP_ flags */
145 static int srvlookup = 0; /* SRV Lookup on or off. Default is off, RFC behavior is on */
147 static int pedanticsipchecking = 0; /* Extra checking ? Default off */
149 static int autocreatepeer = 0; /* Auto creation of peers at registration? Default off. */
151 static int relaxdtmf = 0;
153 static int global_rtptimeout = 0;
155 static int global_rtpholdtimeout = 0;
157 static int global_rtpkeepalive = 0;
159 static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
161 /* Object counters */
162 static int suserobjs = 0;
163 static int ruserobjs = 0;
164 static int speerobjs = 0;
165 static int rpeerobjs = 0;
166 static int apeerobjs = 0;
167 static int regobjs = 0;
169 static int global_allowguest = 1; /* allow unauthenticated users/peers to connect? */
171 #define DEFAULT_MWITIME 10
172 static int global_mwitime = DEFAULT_MWITIME; /* Time between MWI checks for peers */
174 static int usecnt =0;
175 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
178 /* Protect the interface list (of sip_pvt's) */
179 AST_MUTEX_DEFINE_STATIC(iflock);
181 /* Protect the monitoring thread, so only one process can kill or start it, and not
182 when it's doing something critical. */
183 AST_MUTEX_DEFINE_STATIC(netlock);
185 AST_MUTEX_DEFINE_STATIC(monlock);
187 /* This is the thread for the monitor which checks for input on the channels
188 which are not currently in use. */
189 static pthread_t monitor_thread = AST_PTHREADT_NULL;
191 static int restart_monitor(void);
193 /* Codecs that we support by default: */
194 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
195 static int noncodeccapability = AST_RTP_DTMF;
197 static struct in_addr __ourip;
198 static struct sockaddr_in outboundproxyip;
201 static int sipdebug = 0;
202 static struct sockaddr_in debugaddr;
206 static int videosupport = 0;
208 static int compactheaders = 0; /* send compact sip headers */
210 static int recordhistory = 0; /* Record SIP history. Off by default */
212 static char global_musicclass[MAX_LANGUAGE] = ""; /* Global music on hold class */
213 #define DEFAULT_REALM "asterisk"
214 static char global_realm[AST_MAX_EXTENSION] = DEFAULT_REALM; /* Default realm */
215 static char regcontext[AST_MAX_EXTENSION] = ""; /* Context for auto-extensions */
218 #define DEFAULT_EXPIRY 900
219 static int expiry = DEFAULT_EXPIRY;
221 static struct sched_context *sched;
222 static struct io_context *io;
223 /* The private structures of the sip channels are linked for
224 selecting outgoing channels */
226 #define SIP_MAX_HEADERS 64
227 #define SIP_MAX_LINES 64
231 #define DEC_OUT_USE 2
232 #define INC_OUT_USE 3
234 static struct ast_codec_pref prefs;
237 /* sip_request: The data grabbed from the UDP socket */
239 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
240 char *rlPart2; /* The Request URI or Response Status */
241 int len; /* Length */
242 int headers; /* # of SIP Headers */
243 char *header[SIP_MAX_HEADERS];
244 int lines; /* SDP Content */
245 char *line[SIP_MAX_LINES];
246 char data[SIP_MAX_PACKET];
252 struct sip_route *next;
258 struct sip_history *next;
261 #define SIP_ALREADYGONE (1 << 0) /* Whether or not we've already been destroyed by our peer */
262 #define SIP_NEEDDESTROY (1 << 1) /* if we need to be destroyed */
263 #define SIP_NOVIDEO (1 << 2) /* Didn't get video in invite, don't offer */
264 #define SIP_RINGING (1 << 3) /* Have sent 180 ringing */
265 #define SIP_PROGRESS_SENT (1 << 4) /* Have sent 183 message progress */
266 #define SIP_NEEDREINVITE (1 << 5) /* Do we need to send another reinvite? */
267 #define SIP_PENDINGBYE (1 << 6) /* Need to send bye after we ack? */
268 #define SIP_GOTREFER (1 << 7) /* Got a refer? */
269 #define SIP_PROMISCREDIR (1 << 8) /* Promiscuous redirection */
270 #define SIP_TRUSTRPID (1 << 9) /* Trust RPID headers? */
271 #define SIP_USEREQPHONE (1 << 10) /* Add user=phone to numeric URI. Default off */
272 #define SIP_REALTIME (1 << 11) /* Flag for realtime users */
273 #define SIP_USECLIENTCODE (1 << 12) /* Trust X-ClientCode info message */
274 #define SIP_OUTGOING (1 << 13) /* Is this an outgoing call? */
275 #define SIP_SELFDESTRUCT (1 << 14)
276 #define SIP_DYNAMIC (1 << 15) /* Is this a dynamic peer? */
277 /* --- Choices for DTMF support in SIP channel */
278 #define SIP_DTMF (3 << 16) /* three settings, uses two bits */
279 #define SIP_DTMF_RFC2833 (0 << 16) /* RTP DTMF */
280 #define SIP_DTMF_INBAND (1 << 16) /* Inband audio, only for ULAW/ALAW */
281 #define SIP_DTMF_INFO (2 << 16) /* SIP Info messages */
283 #define SIP_NAT (3 << 18) /* four settings, uses two bits */
284 #define SIP_NAT_NEVER (0 << 18) /* No nat support */
285 #define SIP_NAT_RFC3581 (1 << 18)
286 #define SIP_NAT_ROUTE (2 << 18)
287 #define SIP_NAT_ALWAYS (3 << 18)
288 /* re-INVITE related settings */
289 #define SIP_REINVITE (3 << 20) /* two bits used */
290 #define SIP_CAN_REINVITE (1 << 20) /* allow peers to be reinvited to send media directly p2p */
291 #define SIP_REINVITE_UPDATE (2 << 20) /* use UPDATE (RFC3311) when reinviting this peer */
292 /* "insecure" settings */
293 #define SIP_INSECURE (3 << 22) /* three settings, uses two bits */
294 #define SIP_SECURE (0 << 22)
295 #define SIP_INSECURE_NORMAL (1 << 22)
296 #define SIP_INSECURE_VERY (2 << 22)
297 /* Sending PROGRESS in-band settings */
298 #define SIP_PROG_INBAND (3 << 24) /* three settings, uses two bits */
299 #define SIP_PROG_INBAND_NEVER (0 << 24)
300 #define SIP_PROG_INBAND_NO (1 << 24)
301 #define SIP_PROG_INBAND_YES (2 << 24)
302 /* Open Settlement Protocol authentication */
303 #define SIP_OSPAUTH (3 << 26) /* three settings, uses two bits */
304 #define SIP_OSPAUTH_NO (0 << 26)
305 #define SIP_OSPAUTH_YES (1 << 26)
306 #define SIP_OSPAUTH_EXCLUSIVE (2 << 26)
308 #define SIP_CALL_ONHOLD (1 << 28)
309 #define SIP_CALL_LIMIT (1 << 29)
311 /* a new page of flags for peer */
312 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
313 #define SIP_PAGE2_RTNOUPDATE (1 << 1)
314 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
316 static int global_rtautoclear = 120;
318 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call */
319 static struct sip_pvt {
320 ast_mutex_t lock; /* Channel private lock */
321 char callid[80]; /* Global CallID */
322 char randdata[80]; /* Random data */
323 struct ast_codec_pref prefs; /* codec prefs */
324 unsigned int ocseq; /* Current outgoing seqno */
325 unsigned int icseq; /* Current incoming seqno */
326 ast_group_t callgroup; /* Call group */
327 ast_group_t pickupgroup; /* Pickup group */
328 int lastinvite; /* Last Cseq of invite */
329 unsigned int flags; /* SIP_ flags */
330 int capability; /* Special capability (codec) */
331 int jointcapability; /* Supported capability at both ends (codecs ) */
332 int peercapability; /* Supported peer capability */
333 int prefcodec; /* Preferred codec (outbound only) */
334 int noncodeccapability;
335 int callingpres; /* Calling presentation */
336 int authtries; /* Times we've tried to authenticate */
337 int expiry; /* How long we take to expire */
338 int branch; /* One random number */
339 int tag; /* Another random number */
340 int sessionid; /* SDP Session ID */
341 int sessionversion; /* SDP Session Version */
342 struct sockaddr_in sa; /* Our peer */
343 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
344 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
345 int redircodecs; /* Redirect codecs */
346 struct sockaddr_in recv; /* Received as */
347 struct in_addr ourip; /* Our IP */
348 struct ast_channel *owner; /* Who owns us */
349 char exten[AST_MAX_EXTENSION]; /* Extension where to start */
350 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
351 char referred_by[AST_MAX_EXTENSION]; /* Place to store REFERRED-BY extension */
352 char refer_contact[AST_MAX_EXTENSION]; /* Place to store Contact info from a REFER extension */
353 struct sip_pvt *refer_call; /* Call we are referring */
354 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
355 int route_persistant; /* Is this the "real" route? */
356 char from[256]; /* The From: header */
357 char useragent[256]; /* User agent in SIP request */
358 char context[AST_MAX_EXTENSION]; /* Context for this call */
359 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
360 char fromuser[AST_MAX_EXTENSION]; /* User to show in the user field */
361 char fromname[AST_MAX_EXTENSION]; /* Name to show in the user field */
362 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
363 char language[MAX_LANGUAGE]; /* Default language for this call */
364 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
365 char rdnis[256]; /* Referring DNIS */
366 char theirtag[256]; /* Their tag */
367 char username[256]; /* [user] name */
368 char peername[256]; /* [peer] name, not set if [user] */
369 char authname[256]; /* Who we use for authentication */
370 char uri[256]; /* Original requested URI */
371 char okcontacturi[256]; /* URI from the 200 OK on INVITE */
372 char peersecret[256]; /* Password */
373 char peermd5secret[256];
374 char cid_num[256]; /* Caller*ID */
375 char cid_name[256]; /* Caller*ID */
376 char via[256]; /* Via: header */
377 char fullcontact[128]; /* The Contact: that the UA registers with us */
378 char accountcode[20]; /* Account code */
379 char our_contact[256]; /* Our contact header */
380 char realm[256]; /* Authorization realm */
381 char nonce[256]; /* Authorization nonce */
382 char opaque[256]; /* Opaque nonsense */
383 char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
384 char domain[256]; /* Authorization domain */
385 char lastmsg[256]; /* Last Message sent/received */
386 int amaflags; /* AMA Flags */
387 int pendinginvite; /* Any pending invite */
389 int osphandle; /* OSP Handle for call */
390 time_t ospstart; /* OSP Start time */
392 struct sip_request initreq; /* Initial request */
394 int maxtime; /* Max time for first response */
395 int maxforwards; /* keep the max-forwards info */
396 int initid; /* Auto-congest ID if appropriate */
397 int autokillid; /* Auto-kill ID */
398 time_t lastrtprx; /* Last RTP received */
399 time_t lastrtptx; /* Last RTP sent */
400 int rtptimeout; /* RTP timeout time */
401 int rtpholdtimeout; /* RTP timeout when on hold */
402 int rtpkeepalive; /* Send RTP packets for keepalive */
404 int subscribed; /* Is this call a subscription? */
408 struct ast_dsp *vad; /* Voice Activation Detection dsp */
410 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
411 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
412 struct ast_rtp *rtp; /* RTP Session */
413 struct ast_rtp *vrtp; /* Video RTP session */
414 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
415 struct sip_history *history; /* History of this SIP dialog */
416 struct ast_variable *chanvars; /* Channel variables to set for call */
417 struct sip_pvt *next; /* Next call in chain */
420 #define FLAG_RESPONSE (1 << 0)
421 #define FLAG_FATAL (1 << 1)
423 /* sip packet - read in sipsock_read, transmitted in send_request */
425 struct sip_pkt *next; /* Next packet */
426 int retrans; /* Retransmission number */
427 int seqno; /* Sequence number */
428 unsigned int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
429 struct sip_pvt *owner; /* Owner call */
430 int retransid; /* Retransmission ID */
431 int packetlen; /* Length of packet */
435 /* Structure for SIP user data. User's place calls to us */
437 /* Users who can access various contexts */
438 ASTOBJ_COMPONENTS(struct sip_user);
439 char secret[80]; /* Password */
440 char md5secret[80]; /* Password in md5 */
441 char context[80]; /* Default context for incoming calls */
442 char cid_num[80]; /* Caller ID num */
443 char cid_name[80]; /* Caller ID name */
444 char accountcode[20]; /* Account code */
445 char language[MAX_LANGUAGE]; /* Default language for this user */
446 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
447 char useragent[256]; /* User agent in SIP request */
448 struct ast_codec_pref prefs; /* codec prefs */
449 ast_group_t callgroup; /* Call group */
450 ast_group_t pickupgroup; /* Pickup Group */
451 unsigned int flags; /* SIP_ flags */
452 int amaflags; /* AMA flags for billing */
453 int callingpres; /* Calling id presentation */
454 int capability; /* Codec capability */
455 int inUse; /* Number of calls in use */
456 int incominglimit; /* Limit of incoming calls */
457 int outUse; /* disabled */
458 int outgoinglimit; /* disabled */
459 struct ast_ha *ha; /* ACL setting */
460 struct ast_variable *chanvars; /* Variables to set for channel created by user */
463 /* Structure for SIP peer data, we place calls to peers if registred or fixed IP address (host) */
465 ASTOBJ_COMPONENTS(struct sip_peer); /* name, refcount, objflags, object pointers */
466 /* peer->name is the unique name of this object */
467 char secret[80]; /* Password */
468 char md5secret[80]; /* Password in MD5 */
469 char context[80]; /* Default context for incoming calls */
470 char username[80]; /* Temporary username until registration */
471 char accountcode[20]; /* Account code */
472 int amaflags; /* AMA Flags (for billing) */
473 char tohost[80]; /* If not dynamic, IP address */
474 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
475 char fromuser[80]; /* From: user when calling this peer */
476 char fromdomain[80]; /* From: domain when calling this peer */
477 char fullcontact[128]; /* Contact registred with us (not in sip.conf) */
478 char cid_num[80]; /* Caller ID num */
479 char cid_name[80]; /* Caller ID name */
480 int callingpres; /* Calling id presentation */
481 int inUse; /* Number of calls in use */
482 int incominglimit; /* Limit of incoming calls */
483 int outUse; /* disabled */
484 int outgoinglimit; /* disabled */
485 char mailbox[AST_MAX_EXTENSION]; /* Mailbox setting for MWI checks */
486 char language[MAX_LANGUAGE]; /* Default language for prompts */
487 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
488 char useragent[256]; /* User agent in SIP request (saved from registration) */
489 struct ast_codec_pref prefs; /* codec prefs */
491 time_t lastmsgcheck; /* Last time we checked for MWI */
492 unsigned int flags; /* SIP_ flags */
493 struct ast_flags flags_page2; /* SIP_PAGE2 flags */
494 int expire; /* Registration expiration */
496 int capability; /* Codec capability */
497 int rtptimeout; /* RTP timeout */
498 int rtpholdtimeout; /* RTP Hold Timeout */
499 int rtpkeepalive; /* Send RTP packets for keepalive */
500 ast_group_t callgroup; /* Call group */
501 ast_group_t pickupgroup; /* Pickup group */
502 struct sockaddr_in addr; /* IP address of peer */
506 struct sip_pvt *call; /* Call pointer */
507 int pokeexpire; /* When to expire poke (qualify= checking) */
508 int lastms; /* How long last response took (in ms), or -1 for no response */
509 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
510 struct timeval ps; /* Ping send time */
512 struct sockaddr_in defaddr; /* Default IP address, used until registration */
513 struct ast_ha *ha; /* Access control list */
514 struct ast_variable *chanvars; /* Variables to set for channel created by user */
518 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
519 static int sip_reloading = 0;
521 /* States for outbound registrations (with register= lines in sip.conf */
522 #define REG_STATE_UNREGISTERED 0
523 #define REG_STATE_REGSENT 1
524 #define REG_STATE_AUTHSENT 2
525 #define REG_STATE_REGISTERED 3
526 #define REG_STATE_REJECTED 4
527 #define REG_STATE_TIMEOUT 5
528 #define REG_STATE_NOAUTH 6
531 /* sip_registry: Registrations with other SIP proxies */
532 struct sip_registry {
533 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
534 int portno; /* Optional port override */
535 char username[80]; /* Who we are registering as */
536 char authuser[80]; /* Who we *authenticate* as */
537 char hostname[80]; /* Domain or host we register to */
538 char secret[80]; /* Password or key name in []'s */
540 char contact[80]; /* Contact extension */
542 int expire; /* Sched ID of expiration */
543 int timeout; /* sched id of sip_reg_timeout */
544 int refresh; /* How often to refresh */
545 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
546 int regstate; /* Registration state (see above) */
547 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
548 char callid[80]; /* Global CallID for this registry */
549 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
550 struct sockaddr_in us; /* Who the server thinks we are */
553 char realm[256]; /* Authorization realm */
554 char nonce[256]; /* Authorization nonce */
555 char domain[256]; /* Authorization domain */
556 char opaque[256]; /* Opaque nonsense */
557 char qop[80]; /* Quality of Protection. */
559 char lastmsg[256]; /* Last Message sent/received */
562 /*--- The user list: Users and friends ---*/
563 static struct ast_user_list {
564 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
567 /*--- The peer list: Peers and Friends ---*/
568 static struct ast_peer_list {
569 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
572 /*--- The register list: Other SIP proxys we register with and call ---*/
573 static struct ast_register_list {
574 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
579 static int __sip_do_register(struct sip_registry *r);
581 static int sipsock = -1;
584 static struct sockaddr_in bindaddr;
585 static struct sockaddr_in externip;
586 static char externhost[256] = "";
587 static time_t externexpire = 0;
588 static int externrefresh = 10;
589 static struct ast_ha *localaddr;
591 /* The list of manual NOTIFY types we know how to send */
592 struct ast_config *notify_types;
594 static struct ast_frame *sip_read(struct ast_channel *ast);
595 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
596 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
597 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header);
598 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
599 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
600 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, char *osptoken, int addsipheaders, int init);
601 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
602 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
603 static int transmit_message_with_text(struct sip_pvt *p, char *text);
604 static int transmit_refer(struct sip_pvt *p, char *dest);
605 static int sip_sipredirect(struct sip_pvt *p, char *dest);
606 static struct sip_peer *temp_peer(char *name);
607 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
608 static void free_old_route(struct sip_route *route);
609 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
610 static int update_user_counter(struct sip_pvt *fup, int event);
611 static void prune_peers(void);
612 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
613 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
614 static int sip_do_reload(void);
615 static int expire_register(void *data);
616 static int callevents = 0;
618 /*--- sip_debug_test_addr: See if we pass debug IP filter */
619 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
623 if (debugaddr.sin_addr.s_addr) {
624 if (((ntohs(debugaddr.sin_port) != 0)
625 && (debugaddr.sin_port != addr->sin_port))
626 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
632 static inline int sip_debug_test_pvt(struct sip_pvt *p)
636 return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
640 /*--- __sip_xmit: Transmit SIP message ---*/
641 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
644 char iabuf[INET_ADDRSTRLEN];
645 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
646 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
648 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
650 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));
655 static void sip_destroy(struct sip_pvt *p);
657 /*--- build_via: Build a Via header for a request ---*/
658 static void build_via(struct sip_pvt *p, char *buf, int len)
660 char iabuf[INET_ADDRSTRLEN];
662 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
663 if (ast_test_flag(p, SIP_NAT) != SIP_NAT_NEVER)
664 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
665 else /* Work around buggy UNIDEN UIP200 firmware */
666 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
669 /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
670 /* Only used for outbound registrations */
671 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
674 * Using the localaddr structure built up with localnet statements
675 * apply it to their address to see if we need to substitute our
676 * externip or can get away with our internal bindaddr
678 struct sockaddr_in theirs;
679 theirs.sin_addr = *them;
680 if (localaddr && externip.sin_addr.s_addr &&
681 ast_apply_ha(localaddr, &theirs)) {
682 char iabuf[INET_ADDRSTRLEN];
683 if (externexpire && (time(NULL) >= externexpire)) {
684 struct ast_hostent ahp;
687 externexpire += externrefresh;
688 if ((hp = ast_gethostbyname(externhost, &ahp))) {
689 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
691 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
693 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
694 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
695 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
697 else if (bindaddr.sin_addr.s_addr)
698 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
700 return ast_ouraddrfor(them, us);
704 static int append_history(struct sip_pvt *p, char *event, char *data)
706 struct sip_history *hist, *prev;
710 hist = malloc(sizeof(struct sip_history));
712 memset(hist, 0, sizeof(struct sip_history));
713 snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
717 if ((*c == '\r') || (*c == '\n')) {
723 /* Enqueue into history */
736 /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
737 static int retrans_pkt(void *data)
739 struct sip_pkt *pkt=data, *prev, *cur;
741 char iabuf[INET_ADDRSTRLEN];
742 ast_mutex_lock(&pkt->owner->lock);
743 if (pkt->retrans < MAX_RETRANS) {
745 if (sip_debug_test_pvt(pkt->owner)) {
746 if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
747 ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
749 ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
751 append_history(pkt->owner, "ReTx", pkt->data);
752 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
755 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");
756 append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
758 if (ast_test_flag(pkt, FLAG_FATAL)) {
759 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
760 ast_mutex_unlock(&pkt->owner->lock);
762 ast_mutex_lock(&pkt->owner->lock);
764 if (pkt->owner->owner) {
765 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
766 ast_queue_hangup(pkt->owner->owner);
767 ast_mutex_unlock(&pkt->owner->owner->lock);
769 /* If no owner, destroy now */
770 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
773 /* In any case, go ahead and remove the packet */
775 cur = pkt->owner->packets;
784 prev->next = cur->next;
786 pkt->owner->packets = cur->next;
787 ast_mutex_unlock(&pkt->owner->lock);
791 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
794 ast_mutex_unlock(&pkt->owner->lock);
798 /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
799 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
802 pkt = malloc(sizeof(struct sip_pkt) + len + 1);
805 memset(pkt, 0, sizeof(struct sip_pkt));
806 memcpy(pkt->data, data, len);
807 pkt->packetlen = len;
808 pkt->next = p->packets;
812 pkt->data[len] = '\0';
814 ast_set_flag(pkt, FLAG_FATAL);
815 /* Schedule retransmission */
816 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
817 pkt->next = p->packets;
819 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
820 if (!strncasecmp(pkt->data, "INVITE", 6)) {
821 /* Note this is a pending invite */
822 p->pendinginvite = seqno;
827 /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
828 static int __sip_autodestruct(void *data)
830 struct sip_pvt *p = data;
832 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
833 append_history(p, "AutoDestroy", "");
835 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
836 ast_queue_hangup(p->owner);
843 /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
844 static int sip_scheddestroy(struct sip_pvt *p, int ms)
847 if (sip_debug_test_pvt(p))
848 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
850 snprintf(tmp, sizeof(tmp), "%d ms", ms);
851 append_history(p, "SchedDestroy", tmp);
853 if (p->autokillid > -1)
854 ast_sched_del(sched, p->autokillid);
855 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
859 /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
860 static int sip_cancel_destroy(struct sip_pvt *p)
862 if (p->autokillid > -1)
863 ast_sched_del(sched, p->autokillid);
864 append_history(p, "CancelDestroy", "");
869 /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
870 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, const char *msg)
872 struct sip_pkt *cur, *prev = NULL;
875 /* Just in case... */
876 if (!msg) msg = "___NEVER___";
879 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
880 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
881 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
882 if (!resp && (seqno == p->pendinginvite)) {
883 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
884 p->pendinginvite = 0;
887 /* this is our baby */
889 prev->next = cur->next;
891 p->packets = cur->next;
892 if (cur->retransid > -1)
893 ast_sched_del(sched, cur->retransid);
901 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
905 /* Pretend to ack all packets */
906 static int __sip_pretend_ack(struct sip_pvt *p)
909 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), p->packets->data);
914 /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
915 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, const char *msg)
921 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
922 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
923 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
924 /* this is our baby */
925 if (cur->retransid > -1)
926 ast_sched_del(sched, cur->retransid);
933 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");
937 static void parse(struct sip_request *req);
938 static char *get_header(struct sip_request *req, char *name);
939 static void copy_request(struct sip_request *dst,struct sip_request *src);
941 static void parse_copy(struct sip_request *dst, struct sip_request *src)
943 memset(dst, 0, sizeof(*dst));
944 memcpy(dst->data, src->data, sizeof(dst->data));
948 /*--- send_response: Transmit response on SIP request---*/
949 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
952 char iabuf[INET_ADDRSTRLEN];
953 struct sip_request tmp;
955 if (sip_debug_test_pvt(p)) {
956 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
957 ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
959 ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
963 parse_copy(&tmp, req);
964 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
965 append_history(p, "TxRespRel", tmpmsg);
967 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
970 parse_copy(&tmp, req);
971 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
972 append_history(p, "TxResp", tmpmsg);
974 res = __sip_xmit(p, req->data, req->len);
981 /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
982 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
985 char iabuf[INET_ADDRSTRLEN];
986 struct sip_request tmp;
988 if (sip_debug_test_pvt(p)) {
989 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
990 ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
992 ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
996 parse_copy(&tmp, req);
997 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
998 append_history(p, "TxReqRel", tmpmsg);
1000 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
1002 if (recordhistory) {
1003 parse_copy(&tmp, req);
1004 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1005 append_history(p, "TxReq", tmpmsg);
1007 res = __sip_xmit(p, req->data, req->len);
1012 /*--- url_decode: Decode SIP URL ---*/
1013 static void url_decode(char *s)
1020 if (strlen(s) > 2) {
1021 if (sscanf(s + 1, "%2x", &tmp) == 1) {
1023 s += 2; /* Will be incremented once more when we break out */
1027 /* Fall through if something wasn't right with the formatting */
1037 /*--- ditch_braces: Pick out text in braces from character string ---*/
1038 static char *ditch_braces(char *tmp)
1043 if ((q = strchr(tmp, '"')) ) {
1045 if ((q = strchr(c, '"')) )
1048 ast_log(LOG_WARNING, "No closing quote in '%s'\n", tmp);
1052 if ((n = strchr(c, '<')) ) {
1054 while(*c && *c != '>') c++;
1056 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
1065 /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
1066 /* Called from PBX core text message functions */
1067 static int sip_sendtext(struct ast_channel *ast, char *text)
1069 struct sip_pvt *p = ast->pvt->pvt;
1070 int debug=sip_debug_test_pvt(p);
1073 ast_verbose("Sending text %s on %s\n", text, ast->name);
1076 if (!text || ast_strlen_zero(text))
1079 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1080 transmit_message_with_text(p, text);
1084 /*--- realtime_update_peer: Update peer object in realtime storage ---*/
1085 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, int expirey)
1089 char regseconds[20];
1094 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
1095 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1096 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1097 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1100 /*--- register_peer_exten: Automatically add peer extension to dial plan ---*/
1101 static void register_peer_exten(struct sip_peer *peer, int onoff)
1103 unsigned char multi[256]="";
1104 char *stringp, *ext;
1105 if (!ast_strlen_zero(regcontext)) {
1106 strncpy(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi) - 1);
1108 while((ext = strsep(&stringp, "&"))) {
1110 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), free, channeltype);
1112 ast_context_remove_extension(regcontext, ext, 1, NULL);
1117 /*--- sip_destroy_peer: Destroy peer object from memory */
1118 static void sip_destroy_peer(struct sip_peer *peer)
1120 /* Delete it, it needs to disappear */
1122 sip_destroy(peer->call);
1123 if(peer->chanvars) {
1124 ast_variables_destroy(peer->chanvars);
1125 peer->chanvars = NULL;
1127 if (peer->expire > -1)
1128 ast_sched_del(sched, peer->expire);
1129 if (peer->pokeexpire > -1)
1130 ast_sched_del(sched, peer->pokeexpire);
1131 register_peer_exten(peer, 0);
1132 ast_free_ha(peer->ha);
1133 if (ast_test_flag(peer, SIP_SELFDESTRUCT))
1135 else if (ast_test_flag(peer, SIP_REALTIME))
1142 /*--- update_peer: Update peer data in database (if used) ---*/
1143 static void update_peer(struct sip_peer *p, int expiry)
1145 if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_RTNOUPDATE) &&
1146 (ast_test_flag(p, SIP_REALTIME) ||
1147 ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)))
1148 realtime_update_peer(p->name, &p->addr, p->username, expiry);
1152 /*--- realtime_peer: Get peer from realtime storage ---*/
1153 /* Checks the "sippeers" realtime family from extconfig.conf */
1154 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1156 struct sip_peer *peer=NULL;
1157 struct ast_variable *var;
1158 struct ast_variable *tmp;
1160 /* First check on peer name */
1162 var = ast_load_realtime("sippeers", "name", peername, NULL);
1163 else if (sin) { /* Then check on IP address */
1166 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1167 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);
1175 /* If this is type=user, then skip this object. */
1177 if (!strcasecmp(tmp->name, "type") &&
1178 !strcasecmp(tmp->value, "user")) {
1179 ast_variables_destroy(var);
1185 peer = build_peer(peername, var, ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS) ? 0 : 1);
1188 if(ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1189 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1190 if(ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
1191 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1193 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1195 ast_set_flag(peer, SIP_REALTIME);
1198 ast_variables_destroy(var);
1202 /*--- sip_addrcmp: Support routine for find_peer ---*/
1203 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1205 /* We know name is the first field, so we can cast */
1206 struct sip_peer *p = (struct sip_peer *)name;
1207 return !(!inaddrcmp(&p->addr, sin) ||
1208 (ast_test_flag(p, SIP_INSECURE) &&
1209 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1212 /*--- find_peer: Locate peer by name or ip address */
1213 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1215 struct sip_peer *p = NULL;
1218 p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
1220 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
1222 if (!p && realtime) {
1223 p = realtime_peer(peer, sin);
1229 /*--- sip_destroy_user: Remove user object from in-memory storage ---*/
1230 static void sip_destroy_user(struct sip_user *user)
1232 ast_free_ha(user->ha);
1233 if(user->chanvars) {
1234 ast_variables_destroy(user->chanvars);
1235 user->chanvars = NULL;
1237 if (ast_test_flag(user, SIP_REALTIME))
1244 /*--- realtime_user: Load user from realtime storage ---*/
1245 /* Loads user from "sipusers" category in realtime (extconfig.conf) */
1246 /* Users are matched on From: user name (the domain in skipped) */
1247 static struct sip_user *realtime_user(const char *username)
1249 struct ast_variable *var;
1250 struct ast_variable *tmp;
1251 struct sip_user *user = NULL;
1253 var = ast_load_realtime("sipusers", "name", username, NULL);
1260 if (!strcasecmp(tmp->name, "type") &&
1261 !strcasecmp(tmp->value, "peer")) {
1262 ast_variables_destroy(var);
1270 user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1273 /* Add some finishing touches, addresses, etc */
1274 if(ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1277 ASTOBJ_CONTAINER_LINK(&userl,user);
1279 /* Move counter from s to r... */
1282 ast_set_flag(user, SIP_REALTIME);
1285 ast_variables_destroy(var);
1289 /*--- find_user: Locate user by name ---*/
1290 /* Locates user by name (From: sip uri user name part) first
1291 from in-memory list (static configuration) then from
1292 realtime storage (defined in extconfig.conf) */
1293 static struct sip_user *find_user(const char *name, int realtime)
1295 struct sip_user *u = NULL;
1296 u = ASTOBJ_CONTAINER_FIND(&userl,name);
1297 if (!u && realtime) {
1298 u = realtime_user(name);
1303 /*--- create_addr: create address structure from peer definition ---*/
1304 /* Or, if peer not found, find it in the global DNS */
1305 /* returns TRUE on failure, FALSE on success */
1306 static int create_addr(struct sip_pvt *r, char *opeer)
1309 struct ast_hostent ahp;
1315 char host[256], *hostn;
1318 strncpy(peer, opeer, sizeof(peer) - 1);
1319 port = strchr(peer, ':');
1324 r->sa.sin_family = AF_INET;
1325 p = find_peer(peer, NULL, 1);
1329 ast_copy_flags(r, p, SIP_PROMISCREDIR | SIP_USEREQPHONE | SIP_DTMF | SIP_NAT | SIP_REINVITE | SIP_INSECURE);
1330 r->capability = p->capability;
1332 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1333 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1336 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1337 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1339 strncpy(r->peername, p->username, sizeof(r->peername)-1);
1340 strncpy(r->authname, p->username, sizeof(r->authname)-1);
1341 strncpy(r->username, p->username, sizeof(r->username)-1);
1342 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
1343 strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
1344 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
1345 strncpy(r->fullcontact, p->fullcontact, sizeof(r->fullcontact)-1);
1346 if (!r->initreq.headers && !ast_strlen_zero(p->fromdomain)) {
1347 if ((callhost = strchr(r->callid, '@'))) {
1348 strncpy(callhost + 1, p->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
1351 if (ast_strlen_zero(r->tohost)) {
1352 if (p->addr.sin_addr.s_addr)
1353 ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->addr.sin_addr);
1355 ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->defaddr.sin_addr);
1357 if (!ast_strlen_zero(p->fromdomain))
1358 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
1359 if (!ast_strlen_zero(p->fromuser))
1360 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
1361 r->maxtime = p->maxms;
1362 r->callgroup = p->callgroup;
1363 r->pickupgroup = p->pickupgroup;
1364 if (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833)
1365 r->noncodeccapability |= AST_RTP_DTMF;
1367 r->noncodeccapability &= ~AST_RTP_DTMF;
1368 strncpy(r->context, p->context,sizeof(r->context)-1);
1369 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1370 (!p->maxms || ((p->lastms >= 0) && (p->lastms <= p->maxms)))) {
1371 if (p->addr.sin_addr.s_addr) {
1372 r->sa.sin_addr = p->addr.sin_addr;
1373 r->sa.sin_port = p->addr.sin_port;
1375 r->sa.sin_addr = p->defaddr.sin_addr;
1376 r->sa.sin_port = p->defaddr.sin_port;
1378 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1380 ASTOBJ_UNREF(p,sip_destroy_peer);
1386 portno = atoi(port);
1388 portno = DEFAULT_SIP_PORT;
1393 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1394 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1400 hp = ast_gethostbyname(hostn, &ahp);
1402 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
1403 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
1404 r->sa.sin_port = htons(portno);
1405 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1408 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1414 ASTOBJ_UNREF(p,sip_destroy_peer);
1419 /*--- auto_congest: Scheduled congestion on a call ---*/
1420 static int auto_congest(void *nothing)
1422 struct sip_pvt *p = nothing;
1423 ast_mutex_lock(&p->lock);
1426 if (!ast_mutex_trylock(&p->owner->lock)) {
1427 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1428 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1429 ast_mutex_unlock(&p->owner->lock);
1432 ast_mutex_unlock(&p->lock);
1439 /*--- sip_call: Initiate SIP call from PBX ---*/
1440 /* used from the dial() application */
1441 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1445 char *vxml_url = NULL;
1446 char *distinctive_ring = NULL;
1447 char *osptoken = NULL;
1449 char *osphandle = NULL;
1451 struct varshead *headp;
1452 struct ast_var_t *current;
1453 int addsipheaders = 0;
1456 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1457 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1460 /* Check whether there is vxml_url, distinctive ring variables */
1462 headp=&ast->varshead;
1463 AST_LIST_TRAVERSE(headp,current,entries) {
1464 /* Check whether there is a VXML_URL variable */
1465 if (!vxml_url && !strcasecmp(ast_var_name(current),"VXML_URL")) {
1466 vxml_url = ast_var_value(current);
1467 } else if (!distinctive_ring && !strcasecmp(ast_var_name(current),"ALERT_INFO")) {
1468 /* Check whether there is a ALERT_INFO variable */
1469 distinctive_ring = ast_var_value(current);
1470 } else if (!addsipheaders && !strncasecmp(ast_var_name(current),"SIPADDHEADER",strlen("SIPADDHEADER"))) {
1471 /* Check whether there is a variable with a name starting with SIPADDHEADER */
1477 else if (!osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
1478 osptoken = ast_var_value(current);
1479 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
1480 osphandle = ast_var_value(current);
1486 ast_set_flag(p, SIP_OUTGOING);
1488 if (!osptoken || !osphandle || (sscanf(osphandle, "%i", &p->osphandle) != 1)) {
1489 /* Force Disable OSP support */
1490 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", osptoken, osphandle);
1496 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1497 res = update_user_counter(p,INC_OUT_USE);
1499 p->callingpres = ast->cid.cid_pres;
1500 p->jointcapability = p->capability;
1501 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, osptoken, addsipheaders, 1);
1503 /* Initialize auto-congest time */
1504 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1510 /*--- sip_registry_destroy: Destroy registry object ---*/
1511 /* Objects created with the register= statement in static configuration */
1512 static void sip_registry_destroy(struct sip_registry *reg)
1516 /* Clear registry before destroying to ensure
1517 we don't get reentered trying to grab the registry lock */
1518 reg->call->registry = NULL;
1519 sip_destroy(reg->call);
1521 if (reg->expire > -1)
1522 ast_sched_del(sched, reg->expire);
1523 if (reg->timeout > -1)
1524 ast_sched_del(sched, reg->timeout);
1530 /*--- __sip_destroy: Execute destrucion of call structure, release memory---*/
1531 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1533 struct sip_pvt *cur, *prev = NULL;
1535 struct sip_history *hist;
1537 if (sip_debug_test_pvt(p))
1538 ast_verbose("Destroying call '%s'\n", p->callid);
1539 if (p->stateid > -1)
1540 ast_extension_state_del(p->stateid, NULL);
1542 ast_sched_del(sched, p->initid);
1543 if (p->autokillid > -1)
1544 ast_sched_del(sched, p->autokillid);
1547 ast_rtp_destroy(p->rtp);
1550 ast_rtp_destroy(p->vrtp);
1553 free_old_route(p->route);
1557 if (p->registry->call == p)
1558 p->registry->call = NULL;
1559 ASTOBJ_UNREF(p->registry,sip_registry_destroy);
1561 /* Unlink us from the owner if we have one */
1564 ast_mutex_lock(&p->owner->lock);
1565 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1566 p->owner->pvt->pvt = NULL;
1568 ast_mutex_unlock(&p->owner->lock);
1573 p->history = p->history->next;
1580 prev->next = cur->next;
1589 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1592 ast_sched_del(sched, p->initid);
1593 while((cp = p->packets)) {
1594 p->packets = p->packets->next;
1595 if (cp->retransid > -1)
1596 ast_sched_del(sched, cp->retransid);
1599 ast_mutex_destroy(&p->lock);
1601 ast_variables_destroy(p->chanvars);
1608 /*--- update_user_counter: Handle incominglimit and outgoinglimit for SIP users ---*/
1609 /* Note: This is going to be replaced by app_groupcount */
1610 /* Thought: For realtime, we should propably update storage with inuse counter... */
1611 static int update_user_counter(struct sip_pvt *fup, int event)
1613 char name[256] = "";
1616 int *inuse, *incominglimit;
1618 /* Test if we need to check call limits, in order to avoid
1619 realtime lookups if we do not need it */
1620 if (!ast_test_flag(fup, SIP_CALL_LIMIT))
1623 strncpy(name, fup->username, sizeof(name) - 1);
1625 /* Check the list of users */
1626 u = find_user(name, 1);
1629 incominglimit = &u->incominglimit;
1632 /* Try to find peer */
1633 p = find_peer(fup->peername, NULL, 1);
1636 incominglimit = &p->incominglimit;
1637 strncpy(name, fup->peername, sizeof(name) -1);
1639 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1644 /* incoming and outgoing affects the inUse counter */
1655 if (*incominglimit > 0 ) {
1656 if (*inuse >= *incominglimit) {
1657 ast_log(LOG_ERROR, "Call from %s '%s' rejected due to usage limit of %d\n", u?"user":"peer", name, *incominglimit);
1658 /* inc inUse as well */
1659 if ( event == INC_OUT_USE ) {
1663 ASTOBJ_UNREF(u,sip_destroy_user);
1665 ASTOBJ_UNREF(p,sip_destroy_peer);
1670 ast_log(LOG_DEBUG, "Call from %s '%s' is %d out of %d\n", u?"user":"peer", name, *inuse, *incominglimit);
1672 #ifdef DISABLED_CODE
1673 /* we don't use these anymore */
1675 if ( u->outUse > 0 ) {
1682 if ( u->outgoinglimit > 0 ) {
1683 if ( u->outUse >= u->outgoinglimit ) {
1684 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1685 ast_mutex_unlock(&userl.lock);
1696 ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",name,event);
1699 ASTOBJ_UNREF(u,sip_destroy_user);
1701 ASTOBJ_UNREF(p,sip_destroy_peer);
1705 /*--- sip_destroy: Destroy SIP call structure ---*/
1706 static void sip_destroy(struct sip_pvt *p)
1708 ast_mutex_lock(&iflock);
1709 __sip_destroy(p, 1);
1710 ast_mutex_unlock(&iflock);
1714 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1716 /*--- hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes ---*/
1717 static int hangup_sip2cause(int cause)
1719 /* Possible values from causes.h
1720 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
1721 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
1725 case 404: /* Not found */
1726 return AST_CAUSE_UNALLOCATED;
1727 case 483: /* Too many hops */
1728 return AST_CAUSE_FAILURE;
1730 return AST_CAUSE_BUSY;
1732 return AST_CAUSE_NORMAL;
1738 /*--- hangup_cause2sip: Convert Asterisk hangup causes to SIP codes ---*/
1739 static char *hangup_cause2sip(int cause)
1743 case AST_CAUSE_FAILURE:
1744 return "500 Server internal failure";
1745 case AST_CAUSE_CONGESTION:
1746 return "503 Service Unavailable";
1747 case AST_CAUSE_BUSY:
1756 /*--- sip_hangup: Hangup SIP call ---*/
1757 /* Part of PBX interface */
1758 static int sip_hangup(struct ast_channel *ast)
1760 struct sip_pvt *p = ast->pvt->pvt;
1762 struct ast_flags locflags = {0};
1764 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1765 if (!ast->pvt->pvt) {
1766 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1769 ast_mutex_lock(&p->lock);
1771 if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
1772 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
1775 if (ast_test_flag(p, SIP_OUTGOING)) {
1776 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
1777 update_user_counter(p, DEC_OUT_USE);
1779 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
1780 update_user_counter(p, DEC_IN_USE);
1782 /* Determine how to disconnect */
1783 if (p->owner != ast) {
1784 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1785 ast_mutex_unlock(&p->lock);
1788 if (!ast || (ast->_state != AST_STATE_UP))
1793 ast_dsp_free(p->vad);
1796 ast->pvt->pvt = NULL;
1798 ast_mutex_lock(&usecnt_lock);
1800 ast_mutex_unlock(&usecnt_lock);
1801 ast_update_use_count();
1803 ast_set_flag(&locflags, SIP_NEEDDESTROY);
1804 /* Start the process if it's not already started */
1805 if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
1807 if (ast_test_flag(p, SIP_OUTGOING)) {
1808 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
1809 /* Actually don't destroy us yet, wait for the 487 on our original
1810 INVITE, but do set an autodestruct just in case we never get it. */
1811 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
1812 sip_scheddestroy(p, 15000);
1813 if ( p->initid != -1 ) {
1814 /* channel still up - reverse dec of inUse counter
1815 only if the channel is not auto-congested */
1816 if (ast_test_flag(p, SIP_OUTGOING)) {
1817 update_user_counter(p, INC_OUT_USE);
1820 update_user_counter(p, INC_IN_USE);
1825 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1826 transmit_response_reliable(p, res, &p->initreq, 1);
1828 transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
1831 if (!p->pendinginvite) {
1833 transmit_request_with_auth(p, "BYE", 0, 1, 1);
1835 /* Note we will need a BYE when this all settles out
1836 but we can't send one while we have "INVITE" outstanding. */
1837 ast_set_flag(p, SIP_PENDINGBYE);
1838 ast_clear_flag(p, SIP_NEEDREINVITE);
1842 ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);
1843 ast_mutex_unlock(&p->lock);
1847 /*--- sip_answer: Answer SIP call , send 200 OK on Invite ---*/
1848 /* Part of PBX interface */
1849 static int sip_answer(struct ast_channel *ast)
1853 struct sip_pvt *p = ast->pvt->pvt;
1855 ast_mutex_lock(&p->lock);
1856 if (ast->_state != AST_STATE_UP) {
1861 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1863 fmt=ast_getformatbyname(codec);
1865 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1866 if (p->jointcapability & fmt) {
1867 p->jointcapability &= fmt;
1868 p->capability &= fmt;
1870 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
1871 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1874 ast_setstate(ast, AST_STATE_UP);
1876 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1877 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1879 ast_mutex_unlock(&p->lock);
1883 /*--- sip_write: Send response, support audio media ---*/
1884 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1886 struct sip_pvt *p = ast->pvt->pvt;
1888 if (frame->frametype == AST_FRAME_VOICE) {
1889 if (!(frame->subclass & ast->nativeformats)) {
1890 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1891 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1895 ast_mutex_lock(&p->lock);
1897 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
1898 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1899 ast_set_flag(p, SIP_PROGRESS_SENT);
1901 time(&p->lastrtptx);
1902 res = ast_rtp_write(p->rtp, frame);
1904 ast_mutex_unlock(&p->lock);
1906 } else if (frame->frametype == AST_FRAME_VIDEO) {
1908 ast_mutex_lock(&p->lock);
1910 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
1911 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1912 ast_set_flag(p, SIP_PROGRESS_SENT);
1914 time(&p->lastrtptx);
1915 res = ast_rtp_write(p->vrtp, frame);
1917 ast_mutex_unlock(&p->lock);
1919 } else if (frame->frametype == AST_FRAME_IMAGE) {
1922 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1929 /*--- sip_fixup: Fix up a channel: If a channel is consumed, this is called.
1930 Basically update any ->owner links ----*/
1931 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1933 struct sip_pvt *p = newchan->pvt->pvt;
1934 ast_mutex_lock(&p->lock);
1935 if (p->owner != oldchan) {
1936 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1937 ast_mutex_unlock(&p->lock);
1941 ast_mutex_unlock(&p->lock);
1945 /*--- sip_senddigit: Send DTMF character on SIP channel */
1946 /* within one call, we're able to transmit in many methods simultaneously */
1947 static int sip_senddigit(struct ast_channel *ast, char digit)
1949 struct sip_pvt *p = ast->pvt->pvt;
1951 ast_mutex_lock(&p->lock);
1952 switch (ast_test_flag(p, SIP_DTMF)) {
1954 transmit_info_with_digit(p, digit);
1956 case SIP_DTMF_RFC2833:
1958 ast_rtp_senddigit(p->rtp, digit);
1960 case SIP_DTMF_INBAND:
1964 ast_mutex_unlock(&p->lock);
1969 /*--- sip_transfer: Transfer SIP call */
1970 static int sip_transfer(struct ast_channel *ast, char *dest)
1972 struct sip_pvt *p = ast->pvt->pvt;
1975 ast_mutex_lock(&p->lock);
1976 if (ast->_state == AST_STATE_RING)
1977 res = sip_sipredirect(p, dest);
1979 res = transmit_refer(p, dest);
1980 res = transmit_refer(p, dest);
1981 ast_mutex_unlock(&p->lock);
1985 /*--- sip_indicate: Play indication to user */
1986 /* With SIP a lot of indications is sent as messages, letting the device play
1987 the indication - busy signal, congestion etc */
1988 static int sip_indicate(struct ast_channel *ast, int condition)
1990 struct sip_pvt *p = ast->pvt->pvt;
1993 ast_mutex_lock(&p->lock);
1995 case AST_CONTROL_RINGING:
1996 if (ast->_state == AST_STATE_RING) {
1997 if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
1998 (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
1999 /* Send 180 ringing if out-of-band seems reasonable */
2000 transmit_response(p, "180 Ringing", &p->initreq);
2001 ast_set_flag(p, SIP_RINGING);
2002 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2005 /* Well, if it's not reasonable, just send in-band */
2010 case AST_CONTROL_BUSY:
2011 if (ast->_state != AST_STATE_UP) {
2012 transmit_response(p, "486 Busy Here", &p->initreq);
2013 ast_set_flag(p, SIP_ALREADYGONE);
2014 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2019 case AST_CONTROL_CONGESTION:
2020 if (ast->_state != AST_STATE_UP) {
2021 transmit_response(p, "503 Service Unavailable", &p->initreq);
2022 ast_set_flag(p, SIP_ALREADYGONE);
2023 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2028 case AST_CONTROL_PROGRESS:
2029 case AST_CONTROL_PROCEEDING:
2030 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2031 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2032 ast_set_flag(p, SIP_PROGRESS_SENT);
2041 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2045 ast_mutex_unlock(&p->lock);
2051 /*--- sip_new: Initiate a call in the SIP channel */
2052 /* called from sip_request_call (calls from the pbx ) */
2053 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
2055 struct ast_channel *tmp;
2056 struct ast_variable *v = NULL;
2059 ast_mutex_unlock(&i->lock);
2060 /* Don't hold a sip pvt lock while we allocate a channel */
2061 tmp = ast_channel_alloc(1);
2062 ast_mutex_lock(&i->lock);
2064 /* Select our native format based on codec preference until we receive
2065 something from another device to the contrary. */
2066 ast_mutex_lock(&i->lock);
2067 if (i->jointcapability)
2068 tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
2069 else if (i->capability)
2070 tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
2072 tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
2073 ast_mutex_unlock(&i->lock);
2074 fmt = ast_best_codec(tmp->nativeformats);
2076 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
2078 if (strchr(i->fromdomain,':'))
2080 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2084 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2086 tmp->type = channeltype;
2087 if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
2088 i->vad = ast_dsp_new();
2089 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2091 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2093 tmp->fds[0] = ast_rtp_fd(i->rtp);
2094 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2096 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2097 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2099 if (state == AST_STATE_RING)
2101 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2102 tmp->writeformat = fmt;
2103 tmp->pvt->rawwriteformat = fmt;
2104 tmp->readformat = fmt;
2105 tmp->pvt->rawreadformat = fmt;
2107 tmp->pvt->send_text = sip_sendtext;
2108 tmp->pvt->call = sip_call;
2109 tmp->pvt->hangup = sip_hangup;
2110 tmp->pvt->answer = sip_answer;
2111 tmp->pvt->read = sip_read;
2112 tmp->pvt->write = sip_write;
2113 tmp->pvt->write_video = sip_write;
2114 tmp->pvt->indicate = sip_indicate;
2115 tmp->pvt->transfer = sip_transfer;
2116 tmp->pvt->fixup = sip_fixup;
2117 tmp->pvt->send_digit = sip_senddigit;
2119 tmp->pvt->bridge = ast_rtp_bridge;
2121 tmp->callgroup = i->callgroup;
2122 tmp->pickupgroup = i->pickupgroup;
2123 tmp->cid.cid_pres = i->callingpres;
2124 if (!ast_strlen_zero(i->accountcode))
2125 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2127 tmp->amaflags = i->amaflags;
2128 if (!ast_strlen_zero(i->language))
2129 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2130 if (!ast_strlen_zero(i->musicclass))
2131 strncpy(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass)-1);
2133 ast_mutex_lock(&usecnt_lock);
2135 ast_mutex_unlock(&usecnt_lock);
2136 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2137 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2138 if (!ast_strlen_zero(i->cid_num))
2139 tmp->cid.cid_num = strdup(i->cid_num);
2140 if (!ast_strlen_zero(i->cid_name))
2141 tmp->cid.cid_name = strdup(i->cid_name);
2142 if (!ast_strlen_zero(i->rdnis))
2143 tmp->cid.cid_rdnis = strdup(i->rdnis);
2144 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2145 tmp->cid.cid_dnid = strdup(i->exten);
2147 if (!ast_strlen_zero(i->uri)) {
2148 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2150 if (!ast_strlen_zero(i->domain)) {
2151 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2153 if (!ast_strlen_zero(i->useragent)) {
2154 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2156 if (!ast_strlen_zero(i->callid)) {
2157 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2159 ast_setstate(tmp, state);
2160 if (state != AST_STATE_DOWN) {
2161 if (ast_pbx_start(tmp)) {
2162 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2167 /* Set channel variables for this call from configuration */
2168 for (v = i->chanvars ; v ; v = v->next)
2169 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2172 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2176 /* Structure for conversion between compressed SIP and "normal" SIP */
2177 static struct cfalias {
2181 { "Content-Type", "c" },
2182 { "Content-Encoding", "e" },
2186 { "Content-Length", "l" },
2189 { "Supported", "k" },
2190 { "Refer-To", "r" },
2191 { "Allow-Events", "u" },
2196 /*--- get_sdp_by_line: Reads one line of SIP message body */
2197 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
2198 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2199 char* r = line + nameLen + 1;
2200 while (*r && (*r < 33)) ++r;
2207 /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
2208 but the name wrongly applies _only_ sdp */
2209 static char *get_sdp(struct sip_request *req, char *name) {
2211 int len = strlen(name);
2214 for (x=0; x<req->lines; x++) {
2215 r = get_sdp_by_line(req->line[x], name, len);
2216 if (r[0] != '\0') return r;
2222 static void sdpLineNum_iterator_init(int* iterator) {
2226 static char* get_sdp_iterate(int* iterator,
2227 struct sip_request *req, char *name) {
2228 int len = strlen(name);
2230 while (*iterator < req->lines) {
2231 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2232 if (r[0] != '\0') return r;
2237 static char *__get_header(struct sip_request *req, char *name, int *start)
2240 int len = strlen(name);
2242 if (pedanticsipchecking) {
2243 /* Technically you can place arbitrary whitespace both before and after the ':' in
2244 a header, although RFC3261 clearly says you shouldn't before, and place just
2245 one afterwards. If you shouldn't do it, what absolute idiot decided it was
2246 a good idea to say you can do it, and if you can do it, why in the hell would
2247 you say you shouldn't. */
2248 for (x=*start;x<req->headers;x++) {
2249 if (!strncasecmp(req->header[x], name, len)) {
2250 r = req->header[x] + len;
2251 while(*r && (*r < 33))
2255 while(*r && (*r < 33))
2263 /* We probably shouldn't even bother counting whitespace afterwards but
2264 I guess for backwards compatibility we will */
2265 for (x=*start;x<req->headers;x++) {
2266 if (!strncasecmp(req->header[x], name, len) &&
2267 (req->header[x][len] == ':')) {
2268 r = req->header[x] + len + 1;
2269 while(*r && (*r < 33))
2277 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2278 if (!strcasecmp(aliases[x].fullname, name))
2279 return __get_header(req, aliases[x].shortname, start);
2281 /* Don't return NULL, so get_header is always a valid pointer */
2285 /*--- get_header: Get header from SIP request ---*/
2286 static char *get_header(struct sip_request *req, char *name)
2289 return __get_header(req, name, &start);
2292 /*--- sip_rtp_read: Read RTP from network ---*/
2293 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
2295 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
2296 struct ast_frame *f;
2297 static struct ast_frame null_frame = { AST_FRAME_NULL, };
2300 f = ast_rtp_read(p->rtp); /* RTP Audio */
2303 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
2306 f = ast_rtp_read(p->vrtp); /* RTP Video */
2309 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
2314 /* Don't send RFC2833 if we're not supposed to */
2315 if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
2318 /* We already hold the channel lock */
2319 if (f->frametype == AST_FRAME_VOICE) {
2320 if (f->subclass != p->owner->nativeformats) {
2321 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2322 p->owner->nativeformats = f->subclass;
2323 ast_set_read_format(p->owner, p->owner->readformat);
2324 ast_set_write_format(p->owner, p->owner->writeformat);
2326 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
2327 f = ast_dsp_process(p->owner,p->vad,f);
2328 if (f && (f->frametype == AST_FRAME_DTMF))
2329 ast_log(LOG_DEBUG, "Detected DTMF '%c'\n", f->subclass);
2336 /*--- sip_read: Read SIP RTP from channel */
2337 static struct ast_frame *sip_read(struct ast_channel *ast)
2339 struct ast_frame *fr;
2340 struct sip_pvt *p = ast->pvt->pvt;
2341 ast_mutex_lock(&p->lock);
2342 fr = sip_rtp_read(ast, p);
2343 time(&p->lastrtprx);
2344 ast_mutex_unlock(&p->lock);
2348 /*--- build_callid: Build SIP CALLID header ---*/
2349 static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
2354 char iabuf[INET_ADDRSTRLEN];
2357 res = snprintf(callid, len, "%08x", val);
2361 if (!ast_strlen_zero(fromdomain))
2362 snprintf(callid, len, "@%s", fromdomain);
2364 /* It's not important that we really use our right IP here... */
2365 snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
2368 /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
2369 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat)
2373 p = malloc(sizeof(struct sip_pvt));
2376 /* Keep track of stuff */
2377 memset(p, 0, sizeof(struct sip_pvt));
2378 ast_mutex_init(&p->lock);
2388 memcpy(&p->sa, sin, sizeof(p->sa));
2389 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
2390 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2392 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2394 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2396 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2400 /* Start with 101 instead of 1 */
2403 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
2404 ast_mutex_destroy(&p->lock);
2406 ast_variables_destroy(p->chanvars);
2412 ast_rtp_settos(p->rtp, tos);
2414 ast_rtp_settos(p->vrtp, tos);
2415 if (useglobal_nat && sin) {
2416 /* Setup NAT structure according to global settings if we have an address */
2417 ast_copy_flags(p, &global_flags, SIP_NAT);
2418 memcpy(&p->recv, sin, sizeof(p->recv));
2419 ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
2421 ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
2424 strncpy(p->fromdomain, default_fromdomain, sizeof(p->fromdomain) - 1);
2425 build_via(p, p->via, sizeof(p->via));
2427 build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
2429 strncpy(p->callid, callid, sizeof(p->callid) - 1);
2430 ast_copy_flags(p, (&global_flags), SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_DTMF | SIP_REINVITE | SIP_PROG_INBAND | SIP_OSPAUTH);
2431 /* Assign default music on hold class */
2432 strncpy(p->musicclass, global_musicclass, sizeof(p->musicclass) - 1);
2433 p->rtptimeout = global_rtptimeout;
2434 p->rtpholdtimeout = global_rtpholdtimeout;
2435 p->rtpkeepalive = global_rtpkeepalive;
2436 p->capability = global_capability;
2437 if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833)
2438 p->noncodeccapability |= AST_RTP_DTMF;
2439 strncpy(p->context, default_context, sizeof(p->context) - 1);
2441 ast_mutex_lock(&iflock);
2444 ast_mutex_unlock(&iflock);
2446 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
2450 /*--- find_call: Connect incoming SIP message to current call or create new call structure */
2451 /* Called by handle_request ,sipsock_read */
2452 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
2457 char iabuf[INET_ADDRSTRLEN];
2461 callid = get_header(req, "Call-ID");
2463 if (pedanticsipchecking) {
2464 /* In principle Call-ID's uniquely identify a call, however some vendors
2465 (i.e. Pingtel) send multiple calls with the same Call-ID and different
2466 tags in order to simplify billing. The RFC does state that we have to
2467 compare tags in addition to the call-id, but this generate substantially
2468 more overhead which is totally unnecessary for the vast majority of sane
2469 SIP implementations, and thus Asterisk does not enable this behavior
2470 by default. Short version: You'll need this option to support conferencing
2472 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
2474 c = strchr(tmp, ' ');
2477 if (!strcasecmp(cmd, "SIP/2.0"))
2478 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2480 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
2481 tag = strstr(tmp, "tag=");
2484 c = strchr(tag, ';');
2491 if (ast_strlen_zero(callid)) {
2492 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
2495 ast_mutex_lock(&iflock);
2498 if (!strcmp(p->callid, callid) &&
2499 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) {
2500 /* Found the call */
2501 ast_mutex_lock(&p->lock);
2502 ast_mutex_unlock(&iflock);
2507 ast_mutex_unlock(&iflock);
2508 p = sip_alloc(callid, sin, 1);
2510 ast_mutex_lock(&p->lock);
2514 /*--- sip_register: Parse register=> line in sip.conf and add to registry */
2515 static int sip_register(char *value, int lineno)
2517 struct sip_registry *reg;
2518 char copy[256] = "";
2519 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
2526 strncpy(copy, value, sizeof(copy)-1);
2529 hostname = strrchr(stringp, '@');
2534 if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
2535 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
2539 username = strsep(&stringp, ":");
2541 secret = strsep(&stringp, ":");
2543 authuser = strsep(&stringp, ":");
2546 hostname = strsep(&stringp, "/");
2548 contact = strsep(&stringp, "/");
2549 if (!contact || ast_strlen_zero(contact))
2552 hostname = strsep(&stringp, ":");
2553 porta = strsep(&stringp, ":");
2555 if (porta && !atoi(porta)) {
2556 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
2559 reg = malloc(sizeof(struct sip_registry));
2561 memset(reg, 0, sizeof(struct sip_registry));
2564 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
2566 strncpy(reg->username, username, sizeof(reg->username)-1);
2568 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
2570 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
2572 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
2575 reg->refresh = default_expiry;
2576 reg->portno = porta ? atoi(porta) : 0;
2577 reg->callid_valid = 0;
2579 ASTOBJ_CONTAINER_LINK(®l, reg);
2580 ASTOBJ_UNREF(reg,sip_registry_destroy);
2582 ast_log(LOG_ERROR, "Out of memory\n");
2588 /*--- lws2sws: Parse multiline SIP headers into one header */
2589 /* This is enabled if pedanticsipchecking is enabled */
2590 static int lws2sws(char *msgbuf, int len)
2596 /* Eliminate all CRs */
2597 if (msgbuf[h] == '\r') {
2601 /* Check for end-of-line */
2602 if (msgbuf[h] == '\n') {
2603 /* Check for end-of-message */
2606 /* Check for a continuation line */
2607 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
2608 /* Merge continuation line */
2612 /* Propagate LF and start new line */
2613 msgbuf[t++] = msgbuf[h++];
2617 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
2622 msgbuf[t++] = msgbuf[h++];
2626 msgbuf[t++] = msgbuf[h++];
2634 /*--- parse: Parse a SIP message ----*/
2635 static void parse(struct sip_request *req)
2637 /* Divide fields by NULL's */
2642 /* First header starts immediately */
2646 /* We've got a new header */
2650 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2652 if (ast_strlen_zero(req->header[f])) {
2653 /* Line by itself means we're now in content */
2657 if (f >= SIP_MAX_HEADERS - 1) {
2658 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2661 req->header[f] = c + 1;
2662 } else if (*c == '\r') {
2663 /* Ignore but eliminate \r's */
2668 /* Check for last header */
2669 if (!ast_strlen_zero(req->header[f]))
2672 /* Now we process any mime content */
2677 /* We've got a new line */
2680 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2682 if (f >= SIP_MAX_LINES - 1) {
2683 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2686 req->line[f] = c + 1;
2687 } else if (*c == '\r') {
2688 /* Ignore and eliminate \r's */
2693 /* Check for last line */
2694 if (!ast_strlen_zero(req->line[f]))
2698 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2701 /*--- process_sdp: Process SIP SDP ---*/
2702 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2708 char iabuf[INET_ADDRSTRLEN];
2712 int peercapability, peernoncodeccapability;
2713 int vpeercapability=0, vpeernoncodeccapability=0;
2714 struct sockaddr_in sin;
2717 struct ast_hostent ahp;
2719 int destiterator = 0;
2723 int debug=sip_debug_test_pvt(p);
2725 /* Update our last rtprx when we receive an SDP, too */
2726 time(&p->lastrtprx);
2727 time(&p->lastrtptx);
2729 /* Get codec and RTP info from SDP */
2730 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2731 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2734 m = get_sdp(req, "m");
2735 sdpLineNum_iterator_init(&destiterator);
2736 c = get_sdp_iterate(&destiterator, req, "c");
2737 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
2738 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2741 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2742 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2745 /* XXX This could block for a long time, and block the main thread! XXX */
2746 hp = ast_gethostbyname(host, &ahp);
2748 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2751 sdpLineNum_iterator_init(&iterator);
2752 ast_set_flag(p, SIP_NOVIDEO);
2753 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2754 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1) ||
2755 (sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2)) {
2757 /* Scan through the RTP payload types specified in a "m=" line: */
2758 ast_rtp_pt_clear(p->rtp);
2760 while(!ast_strlen_zero(codecs)) {
2761 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2762 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2766 ast_verbose("Found RTP audio format %d\n", codec);
2767 ast_rtp_set_m_type(p->rtp, codec);
2769 /* Skip over any whitespace */
2770 while(*codecs && (*codecs < 33)) codecs++;
2774 ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
2776 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2777 ast_clear_flag(p, SIP_NOVIDEO);
2779 /* Scan through the RTP payload types specified in a "m=" line: */
2781 while(!ast_strlen_zero(codecs)) {
2782 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2783 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2787 ast_verbose("Found video format %s\n", ast_getformatname(codec));
2788 ast_rtp_set_m_type(p->vrtp, codec);
2790 /* Skip over any whitespace */
2791 while(*codecs && (*codecs < 33)) codecs++;
2795 /* Check for Media-description-level-address for audio */
2796 if (pedanticsipchecking) {
2797 c = get_sdp_iterate(&destiterator, req, "c");
2798 if (!ast_strlen_zero(c)) {
2799 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2800 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
2802 /* XXX This could block for a long time, and block the main thread! XXX */
2803 hp = ast_gethostbyname(host, &ahp);
2805 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
2810 /* RTP addresses and ports for audio and video */
2811 sin.sin_family = AF_INET;
2812 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2814 /* Setup audio port number */
2815 sin.sin_port = htons(portno);
2816 if (p->rtp && sin.sin_port) {
2817 ast_rtp_set_peer(p->rtp, &sin);
2819 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2820 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));
2823 /* Check for Media-description-level-address for video */
2824 if (pedanticsipchecking) {
2825 c = get_sdp_iterate(&destiterator, req, "c");
2826 if (!ast_strlen_zero(c)) {
2827 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2828 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
2830 /* XXX This could block for a long time, and block the main thread! XXX */
2831 hp = ast_gethostbyname(host, &ahp);
2833 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
2838 /* Setup video port number */
2839 sin.sin_port = htons(vportno);
2840 if (p->vrtp && sin.sin_port) {
2841 ast_rtp_set_peer(p->vrtp, &sin);
2843 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2844 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));
2848 /* Next, scan through each "a=rtpmap:" line, noting each
2849 * specified RTP payload type (with corresponding MIME subtype):
2851 sdpLineNum_iterator_init(&iterator);
2852 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2853 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2854 if (!strcasecmp(a, "sendonly")) {
2858 if (!strcasecmp(a, "sendrecv")) {
2861 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2863 ast_verbose("Found description format %s\n", mimeSubtype);
2864 /* Note: should really look at the 'freq' and '#chans' params too */
2865 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2867 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2870 /* Now gather all of the codecs that were asked for: */
2871 ast_rtp_get_current_formats(p->rtp,
2872 &peercapability, &peernoncodeccapability);
2874 ast_rtp_get_current_formats(p->vrtp,
2875 &vpeercapability, &vpeernoncodeccapability);
2876 p->jointcapability = p->capability & (peercapability | vpeercapability);
2877 p->peercapability = (peercapability | vpeercapability);
2878 p->noncodeccapability = noncodeccapability & peernoncodeccapability;
2881 /* shame on whoever coded this.... */
2882 const unsigned slen=512;
2883 char s1[slen], s2[slen], s3[slen], s4[slen];
2885 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
2886 ast_getformatname_multiple(s1, slen, p->capability),
2887 ast_getformatname_multiple(s2, slen, peercapability),
2888 ast_getformatname_multiple(s3, slen, vpeercapability),
2889 ast_getformatname_multiple(s4, slen, p->jointcapability));
2891 ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
2892 ast_getformatname_multiple(s1, slen, noncodeccapability),
2893 ast_getformatname_multiple(s2, slen, peernoncodeccapability),
2894 ast_getformatname_multiple(s3, slen, p->noncodeccapability));
2896 if (!p->jointcapability) {
2897 ast_log(LOG_NOTICE, "No compatible codecs!\n");
2901 if (!(p->owner->nativeformats & p->jointcapability)) {
2902 const unsigned slen=512;
2903 char s1[slen], s2[slen];
2904 ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n",
2905 ast_getformatname_multiple(s1, slen, p->jointcapability),
2906 ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
2907 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1);
2908 ast_set_read_format(p->owner, p->owner->readformat);
2909 ast_set_write_format(p->owner, p->owner->writeformat);
2911 if (ast_bridged_channel(p->owner)) {
2912 /* Turn on/off music on hold if we are holding/unholding */
2913 if (sin.sin_addr.s_addr && !sendonly) {
2914 ast_moh_stop(ast_bridged_channel(p->owner));
2915 if (callevents && ast_test_flag(p, SIP_CALL_ONHOLD)) {
2916 manager_event(EVENT_FLAG_CALL, "Unhold",
2920 p->owner->uniqueid);
2921 ast_clear_flag(p, SIP_CALL_ONHOLD);
2924 if (callevents && !ast_test_flag(p, SIP_CALL_ONHOLD)) {
2925 manager_event(EVENT_FLAG_CALL, "Hold",
2929 p->owner->uniqueid);
2930 ast_set_flag(p, SIP_CALL_ONHOLD);
2932 ast_moh_start(ast_bridged_channel(p->owner), NULL);
2934 ast_rtp_stop(p->rtp);
2942 /*--- add_header: Add header to SIP message */
2943 static int add_header(struct sip_request *req, char *var, char *value)
2946 char *shortname = "";
2947 if (req->len >= sizeof(req->data) - 4) {
2948 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2952 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2956 req->header[req->headers] = req->data + req->len;
2957 if (compactheaders) {
2958 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2959 if (!strcasecmp(aliases[x].fullname, var))
2960 shortname = aliases[x].shortname;
2962 if(!ast_strlen_zero(shortname)) {
2963 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", shortname, value);
2965 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2967 req->len += strlen(req->header[req->headers]);
2968 if (req->headers < SIP_MAX_HEADERS)
2971 ast_log(LOG_WARNING, "Out of header space\n");
2977 /*--- add_blank_header: Add blank header to SIP message */
2978 static int add_blank_header(struct sip_request *req)
2980 if (req->len >= sizeof(req->data) - 4) {
2981 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2985 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2988 req->header[req->headers] = req->data + req->len;
2989 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2990 req->len += strlen(req->header[req->headers]);
2991 if (req->headers < SIP_MAX_HEADERS)
2994 ast_log(LOG_WARNING, "Out of header space\n");
3000 /*--- add_line: Add content (not header) to SIP message */
3001 static int add_line(struct sip_request *req, char *line)
3003 if (req->len >= sizeof(req->data) - 4) {
3004 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
3008 /* Add extra empty return */
3009 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
3010 req->len += strlen(req->data + req->len);
3012 req->line[req->lines] = req->data + req->len;
3013 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
3014 req->len += strlen(req->line[req->lines]);
3015 if (req->lines < SIP_MAX_LINES)
3018 ast_log(LOG_WARNING, "Out of line space\n");
3024 /*--- copy_header: Copy one header field from one request to another */
3025 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
3028 tmp = get_header(orig, field);
3029 if (!ast_strlen_zero(tmp)) {
3030 /* Add what we're responding to */
3031 return add_header(req, field, tmp);
3033 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
3037 /*--- copy_all_header: Copy all headers from one request to another ---*/
3038 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
3044 tmp = __get_header(orig, field, &start);
3045 if (!ast_strlen_zero(tmp)) {
3046 /* Add what we're responding to */
3047 add_header(req, field, tmp);
3052 return copied ? 0 : -1;
3055 /*--- copy_via_headers: Copy SIP VIA Headers from one request to another ---*/
3056 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
3058 char tmp[256]="", *oh, *end;
3062 char iabuf[INET_ADDRSTRLEN];
3064 oh = __get_header(orig, field, &start);
3065 if (!ast_strlen_zero(oh)) {
3067 strncpy(tmp, oh, sizeof(tmp) - 1);
3068 oh = strstr(tmp, ";rport");
3070 end = strchr(oh + 1, ';');
3072 memmove(oh, end, strlen(end) + 1);
3076 if (!copied && (ast_test_flag(p, SIP_NAT) == SIP_NAT_ALWAYS)) {
3077 /* Whoo hoo! Now we can indicate port address translation too! Just
3078 another RFC (RFC3581). I'll leave the original comments in for
3080 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));
3081 add_header(req, field, new);
3083 /* Add what we're responding to */
3084 add_header(req, field, tmp);
3091 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
3097 /*--- add_route: Add route header into request per learned route ---*/
3098 static void add_route(struct sip_request *req, struct sip_route *route)
3101 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
3107 n = strlen(route->hop);
3108 if ((n+3)>rem) break;
3114 strncpy(p, route->hop, rem); p += n;
3117 route = route->next;
3120 add_header(req, "Route", r);
3123 /*--- set_destination: Set destination from SIP URI ---*/
3124 static void set_destination(struct sip_pvt *p, char *uri)
3126 char *h, *maddr, hostname[256] = "";
3127 char iabuf[INET_ADDRSTRLEN];
3130 struct ast_hostent ahp;
3131 int debug=sip_debug_test_pvt(p);
3133 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
3134 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
3137 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
3139 /* Find and parse hostname */
3140 h = strchr(uri, '@');
3145 if (strncmp(h, "sip:", 4) == 0)
3147 else if (strncmp(h, "sips:", 5) == 0)
3150 hn = strcspn(h, ":;>");
3151 if (hn > (sizeof(hostname) - 1)) hn = sizeof(hostname) - 1;
3152 strncpy(hostname, h, hn); hostname[hn] = '\0'; /* safe */
3155 /* Is "port" present? if not default to 5060 */
3159 port = strtol(h, &h, 10);
3164 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
3165 maddr = strstr(h, "maddr=");
3168 hn = strspn(maddr, "0123456789.");
3169 if (hn > (sizeof(hostname) - 1)) hn = sizeof(hostname) - 1;
3170 strncpy(hostname, maddr, hn); hostname[hn] = '\0'; /* safe */
3173 hp = ast_gethostbyname(hostname, &ahp);
3175 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
3178 p->sa.sin_family = AF_INET;
3179 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
3180 p->sa.sin_port = htons(port);
3182 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), port);
3185 /*--- init_resp: Initialize SIP response, based on SIP request ---*/
3186 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
3188 /* Initialize a response */
3189 if (req->headers || req->len) {
3190 ast_log(LOG_WARNING, "Request already initialized?!?\n");
3193 req->header[req->headers] = req->data + req->len;
3194 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
3195 req->len += strlen(req->header[req->headers]);
3196 if (req->headers < SIP_MAX_HEADERS)
3199 ast_log(LOG_WARNING, "Out of header space\n");
3203 /*--- init_req: Initialize SIP request ---*/
3204 static int init_req(struct sip_request *req, char *resp, char *recip)
3206 /* Initialize a response */
3207 if (req->headers || req->len) {
3208 ast_log(LOG_WARNING, "Request already initialized?!?\n");
3211 req->header[req->headers] = req->data + req->len;
3212 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
3213 req->len += strlen(req->header[req->headers]);
3214 if (req->headers < SIP_MAX_HEADERS)
3217 ast_log(LOG_WARNING, "Out of header space\n");
3222 /*--- respprep: Prepare SIP response packet ---*/
3223 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
3225 char newto[256] = "", *ot;
3227 memset(resp, 0, sizeof(*resp));
3228 init_resp(resp, msg, req);
3229 copy_via_headers(p, resp, req, "Via");
3231 copy_all_header(resp, req, "Record-Route");
3232 copy_header(resp, req, "From");
3233 ot = get_header(req, "To");
3234 if (!strstr(ot, "tag=")) {
3235 /* Add the proper tag if we don't have it already. If they have specified
3236 their tag, use it. Otherwise, use our own tag */
3237 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(p, SIP_OUTGOING))
3238 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
3239 else if (p->tag && !ast_test_flag(p, SIP_OUTGOING))
3240 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
3242 strncpy(newto, ot, sizeof(newto) - 1);
3243 newto[sizeof(newto) - 1] = '\0';
3247 add_header(resp, "To", ot);
3248 copy_header(resp, req, "Call-ID");
3249 copy_header(resp, req, "CSeq");
3250 add_header(resp, "User-Agent", default_useragent);
3251 add_header(resp, "Allow", ALLOWED_METHODS);
3253 /* For registration responses, we also need expiry and
3257 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
3258 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
3259 add_header(resp, "Expires", tmp);
3260 add_header(resp, "Contact", contact);
3262 add_header(resp, "Contact", p->our_contact);
3264 if (p->maxforwards) {
3266 snprintf(tmp, sizeof(tmp), "%d", p->maxforwards);
3267 add_header(resp, "Max-Forwards", tmp);
3272 /*--- reqprep: Initialize a SIP request packet ---*/
3273 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno, int newbranch)
3275 struct sip_request *orig = &p->initreq;
3276 char stripped[80] ="";
3282 memset(req, 0, sizeof(struct sip_request));
3284 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
3292 p->branch ^= rand();
3293 build_via(p, p->via, sizeof(p->via));
3295 if (!strcasecmp(msg, "CANCEL")) {
3296 c = p->initreq.rlPart2; /* Use original URI */
3297 } else if (!strcasecmp(msg, "ACK")) {
3298 /* Use URI from Contact: in 200 OK (if INVITE)
3299 (we only have the contacturi on INVITEs) */
3300 if (!ast_strlen_zero(p->okcontacturi))
3301 c = p->okcontacturi;
3303 c = p->initreq.rlPart2;
3304 } else if (!ast_strlen_zero(p->okcontacturi)) {
3305 c = p->okcontacturi; /* Use for BYE or REINVITE */
3306 } else if (!ast_strlen_zero(p->uri)) {
3309 /* We have no URI, use To: or From: header as URI (depending on direction) */
3310 if (ast_test_flag(p, SIP_OUTGOING))
3311 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
3313 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
3315 c = strchr(stripped, '<');
3327 init_req(req, msg, c);
3329 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
3331 add_header(req, "Via", p->via);
3333 set_destination(p, p->route->hop);
3334 add_route(req, p->route->next);
3337 ot = get_header(orig, "To");
3338 of = get_header(orig, "From");
3340 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
3341 as our original request, including tag (or presumably lack thereof) */
3342 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
3343 /* Add the proper tag if we don't have it already. If they have specified
3344 their tag, use it. Otherwise, use our own tag */
3345 if (ast_test_flag(p, SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
3346 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
3347 else if (!ast_test_flag(p, SIP_OUTGOING))
3348 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
3350 snprintf(newto, sizeof(newto), "%s", ot);
3354 if (ast_test_flag(p, SIP_OUTGOING)) {
3355 add_header(req, "From", of);
3356 add_header(req, "To", ot);
3358 add_header(req, "From", ot);
3359 add_header(req, "To", of);
3361 add_header(req, "Contact", p->our_contact);
3362 copy_header(req, orig, "Call-ID");
3363 add_header(req, "CSeq", tmp);
3365 add_header(req, "User-Agent", default_useragent);
3369 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
3371 struct sip_request resp;
3373 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
3374 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
3377 respprep(&resp, p, msg, req);
3378 add_header(&resp, "Content-Length", "0");
3379 add_blank_header(&resp);
3380 return send_response(p, &resp, reliable, seqno);
3383 /*--- transmit_response: Transmit response, no retransmits */
3384 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
3386 return __transmit_response(p, msg, req, 0);
3389 /*--- transmit_response: Transmit response, Make sure you get a reply */
3390 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
3392 return __transmit_response(p, msg, req, fatal ? 2 : 1);
3395 /*--- append_date: Append date to SIP message ---*/
3396 static void append_date(struct sip_request *req)
3403 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
3404 add_header(req, "Date", tmpdat);
3407 /*--- transmit_response_with_date: Append date and content length before transmitting response ---*/
3408 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
3410 struct sip_request resp;
3411 respprep(&resp, p, msg, req);
3413 add_header(&resp, "Content-Length", "0");
3414 add_blank_header(&resp);
3415 return send_response(p, &resp, 0, 0);
3418 /*--- transmit_response_with_allow: Append Accept header, content length before transmitting response ---*/
3419 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
3421 struct sip_request resp;
3422 respprep(&resp, p, msg, req);
3423 add_header(&resp, "Accept", "application/sdp");
3424 add_header(&resp, "Content-Length", "0");
3425 add_blank_header(&resp);
3426 return send_response(p, &resp, reliable, 0);
3429 /* transmit_response_with_auth: Respond with authorization request */
3430 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable, char *header)
3432 struct sip_request resp;
3435 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
3436 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
3439 snprintf(tmp, sizeof(tmp), "Digest realm=\"%s\", nonce=\"%s\"", global_realm, randdata);
3440 respprep(&resp, p, msg, req);
3441 add_header(&resp, header, tmp);
3442 add_header(&resp, "Content-Length", "0");
3443 add_blank_header(&resp);
3444 return send_response(p, &resp, reliable, seqno);
3447 /*--- add_text: Add text body to SIP message ---*/
3448 static int add_text(struct sip_request *req, char *text)
3450 /* XXX Convert \n's to \r\n's XXX */
3451 int len = strlen(text);
3453 snprintf(clen, sizeof(clen), "%d", len);
3454 add_header(req, "Content-Type", "text/plain");
3455 add_header(req, "Content-Length", clen);
3456 add_line(req, text);
3460 /*--- add_digit: add DTMF INFO tone to sip message ---*/
3461 /* Always adds default duration 250 ms, regardless of what came in over the line */
3462 static int add_digit(struct sip_request *req, char digit)