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/md5.h>
35 #include <asterisk/app.h>
36 #include <asterisk/musiconhold.h>
37 #include <asterisk/dsp.h>
38 #include <asterisk/features.h>
39 #include <asterisk/acl.h>
40 #include <asterisk/srv.h>
41 #include <asterisk/astdb.h>
42 #include <asterisk/causes.h>
43 #include <asterisk/utils.h>
44 #include <asterisk/file.h>
45 #include <asterisk/astobj.h>
47 #include <asterisk/astosp.h>
49 #include <sys/socket.h>
50 #include <sys/ioctl.h>
57 #include <arpa/inet.h>
59 #include <sys/signal.h>
60 #include <netinet/in_systm.h>
61 #include <netinet/ip.h>
64 #ifndef DEFAULT_USERAGENT
65 #define DEFAULT_USERAGENT "Asterisk PBX"
68 #define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
70 #define IPTOS_MINCOST 0x02
73 /* #define VOCAL_DATA_HACK */
76 #define DEFAULT_DEFAULT_EXPIRY 120
77 #define DEFAULT_MAX_EXPIRY 3600
78 #define DEFAULT_REGISTRATION_TIMEOUT 20
80 /* guard limit must be larger than guard secs */
81 /* guard min must be < 1000, and should be >= 250 */
82 #define EXPIRY_GUARD_SECS 15 /* How long before expiry do we reregister */
83 #define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of
85 #define EXPIRY_GUARD_MIN 500 /* This is the minimum guard time applied. If
86 GUARD_PCT turns out to be lower than this, it
87 will use this time instead.
88 This is in milliseconds. */
89 #define EXPIRY_GUARD_PCT 0.20 /* Percentage of expires timeout to use when
90 below EXPIRY_GUARD_LIMIT */
92 static int max_expiry = DEFAULT_MAX_EXPIRY;
93 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
96 #define MAX(a,b) ((a) > (b) ? (a) : (b))
99 #define CALLERID_UNKNOWN "Unknown"
103 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
104 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
105 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
107 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
108 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
111 #define DEBUG_READ 0 /* Recieved data */
112 #define DEBUG_SEND 1 /* Transmit data */
114 static char *desc = "Session Initiation Protocol (SIP)";
115 static char *channeltype = "SIP";
116 static char *tdesc = "Session Initiation Protocol (SIP)";
117 static char *config = "sip.conf";
118 static char *notify_config = "sip_notify.conf";
120 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
121 #define SIP_MAX_PACKET 4096 /* Also from RFC 2543, should sub headers tho */
123 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
125 static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
127 #define DEFAULT_CONTEXT "default"
128 static char default_context[AST_MAX_EXTENSION] = DEFAULT_CONTEXT;
130 static char default_language[MAX_LANGUAGE] = "";
132 #define DEFAULT_CALLERID "asterisk"
133 static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
135 static char default_fromdomain[AST_MAX_EXTENSION] = "";
137 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
138 static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
140 static struct ast_flags global_flags = {0}; /* global SIP_ flags */
141 static struct ast_flags global_flags_page2 = {0}; /* more global SIP_ flags */
143 static int srvlookup = 0; /* SRV Lookup on or off. Default is off, RFC behavior is on */
145 static int pedanticsipchecking = 0; /* Extra checking ? Default off */
147 static int autocreatepeer = 0; /* Auto creation of peers at registration? Default off. */
149 static int relaxdtmf = 0;
151 static int global_rtptimeout = 0;
153 static int global_rtpholdtimeout = 0;
155 static int global_rtpkeepalive = 0;
157 static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
159 /* Object counters */
160 static int suserobjs = 0;
161 static int ruserobjs = 0;
162 static int speerobjs = 0;
163 static int rpeerobjs = 0;
164 static int apeerobjs = 0;
165 static int regobjs = 0;
167 static int global_allowguest = 1; /* allow unauthenticated users/peers to connect? */
169 #define DEFAULT_MWITIME 10
170 static int global_mwitime = DEFAULT_MWITIME; /* Time between MWI checks for peers */
172 static int usecnt =0;
173 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
176 /* Protect the interface list (of sip_pvt's) */
177 AST_MUTEX_DEFINE_STATIC(iflock);
179 /* Protect the monitoring thread, so only one process can kill or start it, and not
180 when it's doing something critical. */
181 AST_MUTEX_DEFINE_STATIC(netlock);
183 AST_MUTEX_DEFINE_STATIC(monlock);
185 /* This is the thread for the monitor which checks for input on the channels
186 which are not currently in use. */
187 static pthread_t monitor_thread = AST_PTHREADT_NULL;
189 static int restart_monitor(void);
191 /* Codecs that we support by default: */
192 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
193 static int noncodeccapability = AST_RTP_DTMF;
195 static struct in_addr __ourip;
196 static struct sockaddr_in outboundproxyip;
199 static int sipdebug = 0;
200 static struct sockaddr_in debugaddr;
204 static int videosupport = 0;
206 static int compactheaders = 0; /* send compact sip headers */
208 static int recordhistory = 0; /* Record SIP history. Off by default */
210 static char global_musicclass[MAX_LANGUAGE] = ""; /* Global music on hold class */
211 #define DEFAULT_REALM "asterisk"
212 static char global_realm[AST_MAX_EXTENSION] = DEFAULT_REALM; /* Default realm */
213 static char regcontext[AST_MAX_EXTENSION] = ""; /* Context for auto-extensions */
216 #define DEFAULT_EXPIRY 900
217 static int expiry = DEFAULT_EXPIRY;
219 static struct sched_context *sched;
220 static struct io_context *io;
221 /* The private structures of the sip channels are linked for
222 selecting outgoing channels */
224 #define SIP_MAX_HEADERS 64
225 #define SIP_MAX_LINES 64
229 #define DEC_OUT_USE 2
230 #define INC_OUT_USE 3
232 static struct ast_codec_pref prefs;
235 /* sip_request: The data grabbed from the UDP socket */
237 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
238 char *rlPart2; /* The Request URI or Response Status */
239 int len; /* Length */
240 int headers; /* # of SIP Headers */
241 char *header[SIP_MAX_HEADERS];
242 int lines; /* SDP Content */
243 char *line[SIP_MAX_LINES];
244 char data[SIP_MAX_PACKET];
250 struct sip_route *next;
256 struct sip_history *next;
259 #define SIP_ALREADYGONE (1 << 0) /* Whether or not we've already been destroyed by our peer */
260 #define SIP_NEEDDESTROY (1 << 1) /* if we need to be destroyed */
261 #define SIP_NOVIDEO (1 << 2) /* Didn't get video in invite, don't offer */
262 #define SIP_RINGING (1 << 3) /* Have sent 180 ringing */
263 #define SIP_PROGRESS_SENT (1 << 4) /* Have sent 183 message progress */
264 #define SIP_NEEDREINVITE (1 << 5) /* Do we need to send another reinvite? */
265 #define SIP_PENDINGBYE (1 << 6) /* Need to send bye after we ack? */
266 #define SIP_GOTREFER (1 << 7) /* Got a refer? */
267 #define SIP_PROMISCREDIR (1 << 8) /* Promiscuous redirection */
268 #define SIP_TRUSTRPID (1 << 9) /* Trust RPID headers? */
269 #define SIP_USEREQPHONE (1 << 10) /* Add user=phone to numeric URI. Default off */
270 #define SIP_REALTIME (1 << 11) /* Flag for realtime users */
271 #define SIP_USECLIENTCODE (1 << 12) /* Trust X-ClientCode info message */
272 #define SIP_OUTGOING (1 << 13) /* Is this an outgoing call? */
273 #define SIP_SELFDESTRUCT (1 << 14)
274 #define SIP_DYNAMIC (1 << 15) /* Is this a dynamic peer? */
275 /* --- Choices for DTMF support in SIP channel */
276 #define SIP_DTMF (3 << 16) /* three settings, uses two bits */
277 #define SIP_DTMF_RFC2833 (0 << 16) /* RTP DTMF */
278 #define SIP_DTMF_INBAND (1 << 16) /* Inband audio, only for ULAW/ALAW */
279 #define SIP_DTMF_INFO (2 << 16) /* SIP Info messages */
281 #define SIP_NAT (3 << 18) /* four settings, uses two bits */
282 #define SIP_NAT_NEVER (0 << 18) /* No nat support */
283 #define SIP_NAT_RFC3581 (1 << 18)
284 #define SIP_NAT_ROUTE (2 << 18)
285 #define SIP_NAT_ALWAYS (3 << 18)
286 /* re-INVITE related settings */
287 #define SIP_REINVITE (3 << 20) /* two bits used */
288 #define SIP_CAN_REINVITE (1 << 20) /* allow peers to be reinvited to send media directly p2p */
289 #define SIP_REINVITE_UPDATE (2 << 20) /* use UPDATE (RFC3311) when reinviting this peer */
290 /* "insecure" settings */
291 #define SIP_INSECURE (3 << 22) /* three settings, uses two bits */
292 #define SIP_SECURE (0 << 22)
293 #define SIP_INSECURE_NORMAL (1 << 22)
294 #define SIP_INSECURE_VERY (2 << 22)
295 /* Sending PROGRESS in-band settings */
296 #define SIP_PROG_INBAND (3 << 24) /* three settings, uses two bits */
297 #define SIP_PROG_INBAND_NEVER (0 << 24)
298 #define SIP_PROG_INBAND_NO (1 << 24)
299 #define SIP_PROG_INBAND_YES (2 << 24)
300 /* Open Settlement Protocol authentication */
301 #define SIP_OSPAUTH (3 << 26) /* three settings, uses two bits */
302 #define SIP_OSPAUTH_NO (0 << 26)
303 #define SIP_OSPAUTH_YES (1 << 26)
304 #define SIP_OSPAUTH_EXCLUSIVE (2 << 26)
306 #define SIP_CALL_ONHOLD (1 << 28)
307 #define SIP_CALL_LIMIT (1 << 29)
309 /* a new page of flags for peer */
310 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
311 #define SIP_PAGE2_RTNOUPDATE (1 << 1)
312 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
314 static int global_rtautoclear = 120;
316 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call */
317 static struct sip_pvt {
318 ast_mutex_t lock; /* Channel private lock */
319 char callid[80]; /* Global CallID */
320 char randdata[80]; /* Random data */
321 struct ast_codec_pref prefs; /* codec prefs */
322 unsigned int ocseq; /* Current outgoing seqno */
323 unsigned int icseq; /* Current incoming seqno */
324 ast_group_t callgroup; /* Call group */
325 ast_group_t pickupgroup; /* Pickup group */
326 int lastinvite; /* Last Cseq of invite */
327 unsigned int flags; /* SIP_ flags */
328 int capability; /* Special capability (codec) */
329 int jointcapability; /* Supported capability at both ends (codecs ) */
330 int peercapability; /* Supported peer capability */
331 int prefcodec; /* Preferred codec (outbound only) */
332 int noncodeccapability;
333 int callingpres; /* Calling presentation */
334 int authtries; /* Times we've tried to authenticate */
335 int expiry; /* How long we take to expire */
336 int branch; /* One random number */
337 int tag; /* Another random number */
338 int sessionid; /* SDP Session ID */
339 int sessionversion; /* SDP Session Version */
340 struct sockaddr_in sa; /* Our peer */
341 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
342 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
343 int redircodecs; /* Redirect codecs */
344 struct sockaddr_in recv; /* Received as */
345 struct in_addr ourip; /* Our IP */
346 struct ast_channel *owner; /* Who owns us */
347 char exten[AST_MAX_EXTENSION]; /* Extension where to start */
348 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
349 char referred_by[AST_MAX_EXTENSION]; /* Place to store REFERRED-BY extension */
350 char refer_contact[AST_MAX_EXTENSION]; /* Place to store Contact info from a REFER extension */
351 struct sip_pvt *refer_call; /* Call we are referring */
352 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
353 int route_persistant; /* Is this the "real" route? */
354 char from[256]; /* The From: header */
355 char useragent[256]; /* User agent in SIP request */
356 char context[AST_MAX_EXTENSION]; /* Context for this call */
357 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
358 char fromuser[AST_MAX_EXTENSION]; /* User to show in the user field */
359 char fromname[AST_MAX_EXTENSION]; /* Name to show in the user field */
360 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
361 char language[MAX_LANGUAGE]; /* Default language for this call */
362 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
363 char rdnis[256]; /* Referring DNIS */
364 char theirtag[256]; /* Their tag */
365 char username[256]; /* [user] name */
366 char peername[256]; /* [peer] name, not set if [user] */
367 char authname[256]; /* Who we use for authentication */
368 char uri[256]; /* Original requested URI */
369 char okcontacturi[256]; /* URI from the 200 OK on INVITE */
370 char peersecret[256]; /* Password */
371 char peermd5secret[256];
372 char cid_num[256]; /* Caller*ID */
373 char cid_name[256]; /* Caller*ID */
374 char via[256]; /* Via: header */
375 char fullcontact[128]; /* The Contact: that the UA registers with us */
376 char accountcode[20]; /* Account code */
377 char our_contact[256]; /* Our contact header */
378 char realm[256]; /* Authorization realm */
379 char nonce[256]; /* Authorization nonce */
380 char opaque[256]; /* Opaque nonsense */
381 char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
382 char domain[256]; /* Authorization domain */
383 char lastmsg[256]; /* Last Message sent/received */
384 int amaflags; /* AMA Flags */
385 int pendinginvite; /* Any pending invite */
387 int osphandle; /* OSP Handle for call */
388 time_t ospstart; /* OSP Start time */
390 struct sip_request initreq; /* Initial request */
392 int maxtime; /* Max time for first response */
393 int initid; /* Auto-congest ID if appropriate */
394 int autokillid; /* Auto-kill ID */
395 time_t lastrtprx; /* Last RTP received */
396 time_t lastrtptx; /* Last RTP sent */
397 int rtptimeout; /* RTP timeout time */
398 int rtpholdtimeout; /* RTP timeout when on hold */
399 int rtpkeepalive; /* Send RTP packets for keepalive */
401 int subscribed; /* Is this call a subscription? */
405 struct ast_dsp *vad; /* Voice Activation Detection dsp */
407 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
408 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
409 struct ast_rtp *rtp; /* RTP Session */
410 struct ast_rtp *vrtp; /* Video RTP session */
411 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
412 struct sip_history *history; /* History of this SIP dialog */
413 struct ast_variable *chanvars; /* Channel variables to set for call */
414 struct sip_pvt *next; /* Next call in chain */
417 #define FLAG_RESPONSE (1 << 0)
418 #define FLAG_FATAL (1 << 1)
420 /* sip packet - read in sipsock_read, transmitted in send_request */
422 struct sip_pkt *next; /* Next packet */
423 int retrans; /* Retransmission number */
424 int seqno; /* Sequence number */
425 unsigned int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
426 struct sip_pvt *owner; /* Owner call */
427 int retransid; /* Retransmission ID */
428 int packetlen; /* Length of packet */
432 /* Structure for SIP user data. User's place calls to us */
434 /* Users who can access various contexts */
435 ASTOBJ_COMPONENTS(struct sip_user);
436 char secret[80]; /* Password */
437 char md5secret[80]; /* Password in md5 */
438 char context[80]; /* Default context for incoming calls */
439 char cid_num[80]; /* Caller ID num */
440 char cid_name[80]; /* Caller ID name */
441 char accountcode[20]; /* Account code */
442 char language[MAX_LANGUAGE]; /* Default language for this user */
443 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
444 char useragent[256]; /* User agent in SIP request */
445 struct ast_codec_pref prefs; /* codec prefs */
446 ast_group_t callgroup; /* Call group */
447 ast_group_t pickupgroup; /* Pickup Group */
448 unsigned int flags; /* SIP_ flags */
449 int amaflags; /* AMA flags for billing */
450 int callingpres; /* Calling id presentation */
451 int capability; /* Codec capability */
452 int inUse; /* Number of calls in use */
453 int incominglimit; /* Limit of incoming calls */
454 int outUse; /* disabled */
455 int outgoinglimit; /* disabled */
456 struct ast_ha *ha; /* ACL setting */
457 struct ast_variable *chanvars; /* Variables to set for channel created by user */
460 /* Structure for SIP peer data, we place calls to peers if registred or fixed IP address (host) */
462 ASTOBJ_COMPONENTS(struct sip_peer); /* name, refcount, objflags, object pointers */
463 /* peer->name is the unique name of this object */
464 char secret[80]; /* Password */
465 char md5secret[80]; /* Password in MD5 */
466 char context[80]; /* Default context for incoming calls */
467 char username[80]; /* Temporary username until registration */
468 char accountcode[20]; /* Account code */
469 int amaflags; /* AMA Flags (for billing) */
470 char tohost[80]; /* If not dynamic, IP address */
471 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
472 char fromuser[80]; /* From: user when calling this peer */
473 char fromdomain[80]; /* From: domain when calling this peer */
474 char fullcontact[128]; /* Contact registred with us (not in sip.conf) */
475 char cid_num[80]; /* Caller ID num */
476 char cid_name[80]; /* Caller ID name */
477 int callingpres; /* Calling id presentation */
478 int inUse; /* Number of calls in use */
479 int incominglimit; /* Limit of incoming calls */
480 int outUse; /* disabled */
481 int outgoinglimit; /* disabled */
482 char mailbox[AST_MAX_EXTENSION]; /* Mailbox setting for MWI checks */
483 char language[MAX_LANGUAGE]; /* Default language for prompts */
484 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
485 char useragent[256]; /* User agent in SIP request (saved from registration) */
486 struct ast_codec_pref prefs; /* codec prefs */
488 time_t lastmsgcheck; /* Last time we checked for MWI */
489 unsigned int flags; /* SIP_ flags */
490 struct ast_flags flags_page2; /* SIP_PAGE2 flags */
491 int expire; /* Registration expiration */
493 int capability; /* Codec capability */
494 int rtptimeout; /* RTP timeout */
495 int rtpholdtimeout; /* RTP Hold Timeout */
496 int rtpkeepalive; /* Send RTP packets for keepalive */
497 ast_group_t callgroup; /* Call group */
498 ast_group_t pickupgroup; /* Pickup group */
499 struct sockaddr_in addr; /* IP address of peer */
503 struct sip_pvt *call; /* Call pointer */
504 int pokeexpire; /* When to expire poke (qualify= checking) */
505 int lastms; /* How long last response took (in ms), or -1 for no response */
506 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
507 struct timeval ps; /* Ping send time */
509 struct sockaddr_in defaddr; /* Default IP address, used until registration */
510 struct ast_ha *ha; /* Access control list */
511 struct ast_variable *chanvars; /* Variables to set for channel created by user */
515 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
516 static int sip_reloading = 0;
518 /* States for outbound registrations (with register= lines in sip.conf */
519 #define REG_STATE_UNREGISTERED 0
520 #define REG_STATE_REGSENT 1
521 #define REG_STATE_AUTHSENT 2
522 #define REG_STATE_REGISTERED 3
523 #define REG_STATE_REJECTED 4
524 #define REG_STATE_TIMEOUT 5
525 #define REG_STATE_NOAUTH 6
528 /* sip_registry: Registrations with other SIP proxies */
529 struct sip_registry {
530 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
531 int portno; /* Optional port override */
532 char username[80]; /* Who we are registering as */
533 char authuser[80]; /* Who we *authenticate* as */
534 char hostname[80]; /* Domain or host we register to */
535 char secret[80]; /* Password or key name in []'s */
537 char contact[80]; /* Contact extension */
539 int expire; /* Sched ID of expiration */
540 int timeout; /* sched id of sip_reg_timeout */
541 int refresh; /* How often to refresh */
542 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
543 int regstate; /* Registration state (see above) */
544 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
545 char callid[80]; /* Global CallID for this registry */
546 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
547 struct sockaddr_in us; /* Who the server thinks we are */
550 char realm[256]; /* Authorization realm */
551 char nonce[256]; /* Authorization nonce */
552 char domain[256]; /* Authorization domain */
553 char opaque[256]; /* Opaque nonsense */
554 char qop[80]; /* Quality of Protection. */
556 char lastmsg[256]; /* Last Message sent/received */
559 /*--- The user list: Users and friends ---*/
560 static struct ast_user_list {
561 ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
564 /*--- The peer list: Peers and Friends ---*/
565 static struct ast_peer_list {
566 ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
569 /*--- The register list: Other SIP proxys we register with and call ---*/
570 static struct ast_register_list {
571 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
576 static int __sip_do_register(struct sip_registry *r);
578 static int sipsock = -1;
581 static struct sockaddr_in bindaddr;
582 static struct sockaddr_in externip;
583 static char externhost[256] = "";
584 static time_t externexpire = 0;
585 static int externrefresh = 10;
586 static struct ast_ha *localaddr;
588 /* The list of manual NOTIFY types we know how to send */
589 struct ast_config *notify_types;
591 static struct ast_frame *sip_read(struct ast_channel *ast);
592 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
593 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
594 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header);
595 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
596 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
597 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);
598 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
599 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
600 static int transmit_message_with_text(struct sip_pvt *p, char *text);
601 static int transmit_refer(struct sip_pvt *p, char *dest);
602 static struct sip_peer *temp_peer(char *name);
603 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
604 static void free_old_route(struct sip_route *route);
605 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
606 static int update_user_counter(struct sip_pvt *fup, int event);
607 static void prune_peers(void);
608 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
609 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
610 static int sip_do_reload(void);
611 static int expire_register(void *data);
612 static int callevents = 0;
614 /*--- sip_debug_test_addr: See if we pass debug IP filter */
615 static inline int sip_debug_test_addr(struct sockaddr_in *addr)
619 if (debugaddr.sin_addr.s_addr) {
620 if (((ntohs(debugaddr.sin_port) != 0)
621 && (debugaddr.sin_port != addr->sin_port))
622 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
628 static inline int sip_debug_test_pvt(struct sip_pvt *p)
632 return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
636 /*--- __sip_xmit: Transmit SIP message ---*/
637 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
640 char iabuf[INET_ADDRSTRLEN];
641 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
642 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
644 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
646 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));
651 static void sip_destroy(struct sip_pvt *p);
653 /*--- build_via: Build a Via header for a request ---*/
654 static void build_via(struct sip_pvt *p, char *buf, int len)
656 char iabuf[INET_ADDRSTRLEN];
658 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
659 if (ast_test_flag(p, SIP_NAT) != SIP_NAT_NEVER)
660 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
661 else /* Work around buggy UNIDEN UIP200 firmware */
662 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
665 /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
666 /* Only used for outbound registrations */
667 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
670 * Using the localaddr structure built up with localnet statements
671 * apply it to their address to see if we need to substitute our
672 * externip or can get away with our internal bindaddr
674 struct sockaddr_in theirs;
675 theirs.sin_addr = *them;
676 if (localaddr && externip.sin_addr.s_addr &&
677 ast_apply_ha(localaddr, &theirs)) {
678 char iabuf[INET_ADDRSTRLEN];
679 if (externexpire && (time(NULL) >= externexpire)) {
680 struct ast_hostent ahp;
683 externexpire += externrefresh;
684 if ((hp = ast_gethostbyname(externhost, &ahp))) {
685 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
687 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
689 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
690 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
691 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
693 else if (bindaddr.sin_addr.s_addr)
694 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
696 return ast_ouraddrfor(them, us);
700 static int append_history(struct sip_pvt *p, char *event, char *data)
702 struct sip_history *hist, *prev;
706 hist = malloc(sizeof(struct sip_history));
708 memset(hist, 0, sizeof(struct sip_history));
709 snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
713 if ((*c == '\r') || (*c == '\n')) {
719 /* Enqueue into history */
732 /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
733 static int retrans_pkt(void *data)
735 struct sip_pkt *pkt=data, *prev, *cur;
737 char iabuf[INET_ADDRSTRLEN];
738 ast_mutex_lock(&pkt->owner->lock);
739 if (pkt->retrans < MAX_RETRANS) {
741 if (sip_debug_test_pvt(pkt->owner)) {
742 if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
743 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));
745 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));
747 append_history(pkt->owner, "ReTx", pkt->data);
748 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
751 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");
752 append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
754 if (ast_test_flag(pkt, FLAG_FATAL)) {
755 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
756 ast_mutex_unlock(&pkt->owner->lock);
758 ast_mutex_lock(&pkt->owner->lock);
760 if (pkt->owner->owner) {
761 ast_set_flag(pkt->owner, SIP_ALREADYGONE);
762 ast_queue_hangup(pkt->owner->owner);
763 ast_mutex_unlock(&pkt->owner->owner->lock);
765 /* If no owner, destroy now */
766 ast_set_flag(pkt->owner, SIP_NEEDDESTROY);
769 /* In any case, go ahead and remove the packet */
771 cur = pkt->owner->packets;
780 prev->next = cur->next;
782 pkt->owner->packets = cur->next;
783 ast_mutex_unlock(&pkt->owner->lock);
787 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
790 ast_mutex_unlock(&pkt->owner->lock);
794 /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
795 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
798 pkt = malloc(sizeof(struct sip_pkt) + len + 1);
801 memset(pkt, 0, sizeof(struct sip_pkt));
802 memcpy(pkt->data, data, len);
803 pkt->packetlen = len;
804 pkt->next = p->packets;
808 pkt->data[len] = '\0';
810 ast_set_flag(pkt, FLAG_FATAL);
811 /* Schedule retransmission */
812 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
813 pkt->next = p->packets;
815 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
816 if (!strncasecmp(pkt->data, "INVITE", 6)) {
817 /* Note this is a pending invite */
818 p->pendinginvite = seqno;
823 /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
824 static int __sip_autodestruct(void *data)
826 struct sip_pvt *p = data;
828 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
829 append_history(p, "AutoDestroy", "");
831 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
832 ast_queue_hangup(p->owner);
839 /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
840 static int sip_scheddestroy(struct sip_pvt *p, int ms)
843 if (sip_debug_test_pvt(p))
844 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
846 snprintf(tmp, sizeof(tmp), "%d ms", ms);
847 append_history(p, "SchedDestroy", tmp);
849 if (p->autokillid > -1)
850 ast_sched_del(sched, p->autokillid);
851 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
855 /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
856 static int sip_cancel_destroy(struct sip_pvt *p)
858 if (p->autokillid > -1)
859 ast_sched_del(sched, p->autokillid);
860 append_history(p, "CancelDestroy", "");
865 /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
866 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, const char *msg)
868 struct sip_pkt *cur, *prev = NULL;
871 /* Just in case... */
872 if (!msg) msg = "___NEVER___";
875 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
876 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
877 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
878 if (!resp && (seqno == p->pendinginvite)) {
879 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
880 p->pendinginvite = 0;
883 /* this is our baby */
885 prev->next = cur->next;
887 p->packets = cur->next;
888 if (cur->retransid > -1)
889 ast_sched_del(sched, cur->retransid);
897 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
901 /* Pretend to ack all packets */
902 static int __sip_pretend_ack(struct sip_pvt *p)
905 __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), p->packets->data);
910 /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
911 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, const char *msg)
917 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
918 ((ast_test_flag(cur, FLAG_RESPONSE)) ||
919 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
920 /* this is our baby */
921 if (cur->retransid > -1)
922 ast_sched_del(sched, cur->retransid);
929 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");
933 static void parse(struct sip_request *req);
934 static char *get_header(struct sip_request *req, char *name);
935 static void copy_request(struct sip_request *dst,struct sip_request *src);
937 static void parse_copy(struct sip_request *dst, struct sip_request *src)
939 memset(dst, 0, sizeof(*dst));
940 memcpy(dst->data, src->data, sizeof(dst->data));
944 /*--- send_response: Transmit response on SIP request---*/
945 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
948 char iabuf[INET_ADDRSTRLEN];
949 struct sip_request tmp;
951 if (sip_debug_test_pvt(p)) {
952 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
953 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));
955 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));
959 parse_copy(&tmp, req);
960 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
961 append_history(p, "TxRespRel", tmpmsg);
963 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
966 parse_copy(&tmp, req);
967 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
968 append_history(p, "TxResp", tmpmsg);
970 res = __sip_xmit(p, req->data, req->len);
977 /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
978 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
981 char iabuf[INET_ADDRSTRLEN];
982 struct sip_request tmp;
984 if (sip_debug_test_pvt(p)) {
985 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
986 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));
988 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));
992 parse_copy(&tmp, req);
993 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
994 append_history(p, "TxReqRel", tmpmsg);
996 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
999 parse_copy(&tmp, req);
1000 snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1001 append_history(p, "TxReq", tmpmsg);
1003 res = __sip_xmit(p, req->data, req->len);
1008 /*--- url_decode: Decode SIP URL ---*/
1009 static void url_decode(char *s)
1016 if (strlen(s) > 2) {
1017 if (sscanf(s + 1, "%2x", &tmp) == 1) {
1019 s += 2; /* Will be incremented once more when we break out */
1023 /* Fall through if something wasn't right with the formatting */
1033 /*--- ditch_braces: Pick out text in braces from character string ---*/
1034 static char *ditch_braces(char *tmp)
1039 if ((q = strchr(tmp, '"')) ) {
1041 if ((q = strchr(c, '"')) )
1044 ast_log(LOG_WARNING, "No closing quote in '%s'\n", tmp);
1048 if ((n = strchr(c, '<')) ) {
1050 while(*c && *c != '>') c++;
1052 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
1061 /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
1062 /* Called from PBX core text message functions */
1063 static int sip_sendtext(struct ast_channel *ast, char *text)
1065 struct sip_pvt *p = ast->pvt->pvt;
1066 int debug=sip_debug_test_pvt(p);
1069 ast_verbose("Sending text %s on %s\n", text, ast->name);
1072 if (!text || ast_strlen_zero(text))
1075 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1076 transmit_message_with_text(p, text);
1080 /*--- realtime_update_peer: Update peer object in realtime storage ---*/
1081 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, int expirey)
1085 char regseconds[20];
1090 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
1091 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1092 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1093 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1096 /*--- register_peer_exten: Automatically add peer extension to dial plan ---*/
1097 static void register_peer_exten(struct sip_peer *peer, int onoff)
1099 unsigned char multi[256]="";
1100 char *stringp, *ext;
1101 if (!ast_strlen_zero(regcontext)) {
1102 strncpy(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi) - 1);
1104 while((ext = strsep(&stringp, "&"))) {
1106 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), free, channeltype);
1108 ast_context_remove_extension(regcontext, ext, 1, NULL);
1113 /*--- sip_destroy_peer: Destroy peer object from memory */
1114 static void sip_destroy_peer(struct sip_peer *peer)
1116 /* Delete it, it needs to disappear */
1118 sip_destroy(peer->call);
1119 if(peer->chanvars) {
1120 ast_variables_destroy(peer->chanvars);
1121 peer->chanvars = NULL;
1123 if (peer->expire > -1)
1124 ast_sched_del(sched, peer->expire);
1125 if (peer->pokeexpire > -1)
1126 ast_sched_del(sched, peer->pokeexpire);
1127 register_peer_exten(peer, 0);
1128 ast_free_ha(peer->ha);
1129 if (ast_test_flag(peer, SIP_SELFDESTRUCT))
1131 else if (ast_test_flag(peer, SIP_REALTIME))
1138 /*--- update_peer: Update peer data in database (if used) ---*/
1139 static void update_peer(struct sip_peer *p, int expiry)
1141 if (!ast_test_flag((&global_flags_page2), SIP_PAGE2_RTNOUPDATE) &&
1142 (ast_test_flag(p, SIP_REALTIME) ||
1143 ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS)))
1144 realtime_update_peer(p->name, &p->addr, p->username, expiry);
1148 /*--- realtime_peer: Get peer from realtime storage ---*/
1149 /* Checks the "sippeers" realtime family from extconfig.conf */
1150 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1152 struct sip_peer *peer=NULL;
1153 struct ast_variable *var;
1154 struct ast_variable *tmp;
1156 /* First check on peer name */
1158 var = ast_load_realtime("sippeers", "name", peername, NULL);
1159 else if (sin) { /* Then check on IP address */
1162 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1163 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);
1171 /* If this is type=user, then skip this object. */
1173 if (!strcasecmp(tmp->name, "type") &&
1174 !strcasecmp(tmp->value, "user")) {
1175 ast_variables_destroy(var);
1181 peer = build_peer(peername, var, ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS) ? 0 : 1);
1184 if(ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1185 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1186 if(ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
1187 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1189 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1191 ast_set_flag(peer, SIP_REALTIME);
1194 ast_variables_destroy(var);
1198 /*--- sip_addrcmp: Support routine for find_peer ---*/
1199 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1201 /* We know name is the first field, so we can cast */
1202 struct sip_peer *p = (struct sip_peer *)name;
1203 return !(!inaddrcmp(&p->addr, sin) ||
1204 (ast_test_flag(p, SIP_INSECURE) &&
1205 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1208 /*--- find_peer: Locate peer by name or ip address */
1209 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1211 struct sip_peer *p = NULL;
1214 p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
1216 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
1218 if (!p && realtime) {
1219 p = realtime_peer(peer, sin);
1225 /*--- sip_destroy_user: Remove user object from in-memory storage ---*/
1226 static void sip_destroy_user(struct sip_user *user)
1228 ast_free_ha(user->ha);
1229 if(user->chanvars) {
1230 ast_variables_destroy(user->chanvars);
1231 user->chanvars = NULL;
1233 if (ast_test_flag(user, SIP_REALTIME))
1240 /*--- realtime_user: Load user from realtime storage ---*/
1241 /* Loads user from "sipusers" category in realtime (extconfig.conf) */
1242 /* Users are matched on From: user name (the domain in skipped) */
1243 static struct sip_user *realtime_user(const char *username)
1245 struct ast_variable *var;
1246 struct ast_variable *tmp;
1247 struct sip_user *user = NULL;
1249 var = ast_load_realtime("sipusers", "name", username, NULL);
1256 if (!strcasecmp(tmp->name, "type") &&
1257 !strcasecmp(tmp->value, "peer")) {
1258 ast_variables_destroy(var);
1266 user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1269 /* Add some finishing touches, addresses, etc */
1270 if(ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1273 ASTOBJ_CONTAINER_LINK(&userl,user);
1275 /* Move counter from s to r... */
1278 ast_set_flag(user, SIP_REALTIME);
1281 ast_variables_destroy(var);
1285 /*--- find_user: Locate user by name ---*/
1286 /* Locates user by name (From: sip uri user name part) first
1287 from in-memory list (static configuration) then from
1288 realtime storage (defined in extconfig.conf) */
1289 static struct sip_user *find_user(const char *name, int realtime)
1291 struct sip_user *u = NULL;
1292 u = ASTOBJ_CONTAINER_FIND(&userl,name);
1293 if (!u && realtime) {
1294 u = realtime_user(name);
1299 /*--- create_addr: create address structure from peer definition ---*/
1300 /* Or, if peer not found, find it in the global DNS */
1301 /* returns TRUE on failure, FALSE on success */
1302 static int create_addr(struct sip_pvt *r, char *opeer)
1305 struct ast_hostent ahp;
1311 char host[256], *hostn;
1314 strncpy(peer, opeer, sizeof(peer) - 1);
1315 port = strchr(peer, ':');
1320 r->sa.sin_family = AF_INET;
1321 p = find_peer(peer, NULL, 1);
1325 ast_copy_flags(r, p, SIP_PROMISCREDIR | SIP_USEREQPHONE | SIP_DTMF | SIP_NAT | SIP_REINVITE | SIP_INSECURE);
1326 r->capability = p->capability;
1328 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1329 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1332 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1333 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1335 strncpy(r->peername, p->username, sizeof(r->peername)-1);
1336 strncpy(r->authname, p->username, sizeof(r->authname)-1);
1337 strncpy(r->username, p->username, sizeof(r->username)-1);
1338 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
1339 strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
1340 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
1341 strncpy(r->fullcontact, p->fullcontact, sizeof(r->fullcontact)-1);
1342 if (!r->initreq.headers && !ast_strlen_zero(p->fromdomain)) {
1343 if ((callhost = strchr(r->callid, '@'))) {
1344 strncpy(callhost + 1, p->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
1347 if (ast_strlen_zero(r->tohost)) {
1348 if (p->addr.sin_addr.s_addr)
1349 ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->addr.sin_addr);
1351 ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->defaddr.sin_addr);
1353 if (!ast_strlen_zero(p->fromdomain))
1354 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
1355 if (!ast_strlen_zero(p->fromuser))
1356 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
1357 r->maxtime = p->maxms;
1358 r->callgroup = p->callgroup;
1359 r->pickupgroup = p->pickupgroup;
1360 if (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833)
1361 r->noncodeccapability |= AST_RTP_DTMF;
1363 r->noncodeccapability &= ~AST_RTP_DTMF;
1364 strncpy(r->context, p->context,sizeof(r->context)-1);
1365 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1366 (!p->maxms || ((p->lastms >= 0) && (p->lastms <= p->maxms)))) {
1367 if (p->addr.sin_addr.s_addr) {
1368 r->sa.sin_addr = p->addr.sin_addr;
1369 r->sa.sin_port = p->addr.sin_port;
1371 r->sa.sin_addr = p->defaddr.sin_addr;
1372 r->sa.sin_port = p->defaddr.sin_port;
1374 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1376 ASTOBJ_UNREF(p,sip_destroy_peer);
1382 portno = atoi(port);
1384 portno = DEFAULT_SIP_PORT;
1389 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1390 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1396 hp = ast_gethostbyname(hostn, &ahp);
1398 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
1399 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
1400 r->sa.sin_port = htons(portno);
1401 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1404 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1410 ASTOBJ_UNREF(p,sip_destroy_peer);
1415 /*--- auto_congest: Scheduled congestion on a call ---*/
1416 static int auto_congest(void *nothing)
1418 struct sip_pvt *p = nothing;
1419 ast_mutex_lock(&p->lock);
1422 if (!ast_mutex_trylock(&p->owner->lock)) {
1423 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1424 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1425 ast_mutex_unlock(&p->owner->lock);
1428 ast_mutex_unlock(&p->lock);
1435 /*--- sip_call: Initiate SIP call from PBX ---*/
1436 /* used from the dial() application */
1437 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1441 char *vxml_url = NULL;
1442 char *distinctive_ring = NULL;
1443 char *osptoken = NULL;
1445 char *osphandle = NULL;
1447 struct varshead *headp;
1448 struct ast_var_t *current;
1449 int addsipheaders = 0;
1452 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1453 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1456 /* Check whether there is vxml_url, distinctive ring variables */
1458 headp=&ast->varshead;
1459 AST_LIST_TRAVERSE(headp,current,entries) {
1460 /* Check whether there is a VXML_URL variable */
1461 if (!vxml_url && !strcasecmp(ast_var_name(current),"VXML_URL")) {
1462 vxml_url = ast_var_value(current);
1463 } else if (!distinctive_ring && !strcasecmp(ast_var_name(current),"ALERT_INFO")) {
1464 /* Check whether there is a ALERT_INFO variable */
1465 distinctive_ring = ast_var_value(current);
1466 } else if (!addsipheaders && !strncasecmp(ast_var_name(current),"SIPADDHEADER",strlen("SIPADDHEADER"))) {
1467 /* Check whether there is a variable with a name starting with SIPADDHEADER */
1473 else if (!osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
1474 osptoken = ast_var_value(current);
1475 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
1476 osphandle = ast_var_value(current);
1482 ast_set_flag(p, SIP_OUTGOING);
1484 if (!osptoken || !osphandle || (sscanf(osphandle, "%i", &p->osphandle) != 1)) {
1485 /* Force Disable OSP support */
1486 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", osptoken, osphandle);
1492 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1493 res = update_user_counter(p,INC_OUT_USE);
1495 p->callingpres = ast->cid.cid_pres;
1496 p->jointcapability = p->capability;
1497 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, osptoken, addsipheaders, 1);
1499 /* Initialize auto-congest time */
1500 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1506 /*--- sip_registry_destroy: Destroy registry object ---*/
1507 /* Objects created with the register= statement in static configuration */
1508 static void sip_registry_destroy(struct sip_registry *reg)
1512 /* Clear registry before destroying to ensure
1513 we don't get reentered trying to grab the registry lock */
1514 reg->call->registry = NULL;
1515 sip_destroy(reg->call);
1517 if (reg->expire > -1)
1518 ast_sched_del(sched, reg->expire);
1519 if (reg->timeout > -1)
1520 ast_sched_del(sched, reg->timeout);
1526 /*--- __sip_destroy: Execute destrucion of call structure, release memory---*/
1527 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1529 struct sip_pvt *cur, *prev = NULL;
1531 struct sip_history *hist;
1533 if (sip_debug_test_pvt(p))
1534 ast_verbose("Destroying call '%s'\n", p->callid);
1535 if (p->stateid > -1)
1536 ast_extension_state_del(p->stateid, NULL);
1538 ast_sched_del(sched, p->initid);
1539 if (p->autokillid > -1)
1540 ast_sched_del(sched, p->autokillid);
1543 ast_rtp_destroy(p->rtp);
1546 ast_rtp_destroy(p->vrtp);
1549 free_old_route(p->route);
1553 if (p->registry->call == p)
1554 p->registry->call = NULL;
1555 ASTOBJ_UNREF(p->registry,sip_registry_destroy);
1557 /* Unlink us from the owner if we have one */
1560 ast_mutex_lock(&p->owner->lock);
1561 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1562 p->owner->pvt->pvt = NULL;
1564 ast_mutex_unlock(&p->owner->lock);
1569 p->history = p->history->next;
1576 prev->next = cur->next;
1585 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1588 ast_sched_del(sched, p->initid);
1589 while((cp = p->packets)) {
1590 p->packets = p->packets->next;
1591 if (cp->retransid > -1)
1592 ast_sched_del(sched, cp->retransid);
1595 ast_mutex_destroy(&p->lock);
1597 ast_variables_destroy(p->chanvars);
1604 /*--- update_user_counter: Handle incominglimit and outgoinglimit for SIP users ---*/
1605 /* Note: This is going to be replaced by app_groupcount */
1606 /* Thought: For realtime, we should propably update storage with inuse counter... */
1607 static int update_user_counter(struct sip_pvt *fup, int event)
1609 char name[256] = "";
1612 int *inuse, *incominglimit;
1614 /* Test if we need to check call limits, in order to avoid
1615 realtime lookups if we do not need it */
1616 if (!ast_test_flag(fup, SIP_CALL_LIMIT))
1619 strncpy(name, fup->username, sizeof(name) - 1);
1621 /* Check the list of users */
1622 u = find_user(name, 1);
1625 incominglimit = &u->incominglimit;
1628 /* Try to find peer */
1629 p = find_peer(fup->peername, NULL, 1);
1632 incominglimit = &p->incominglimit;
1633 strncpy(name, fup->peername, sizeof(name) -1);
1635 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1640 /* incoming and outgoing affects the inUse counter */
1651 if (*incominglimit > 0 ) {
1652 if (*inuse >= *incominglimit) {
1653 ast_log(LOG_ERROR, "Call from %s '%s' rejected due to usage limit of %d\n", u?"user":"peer", name, *incominglimit);
1654 /* inc inUse as well */
1655 if ( event == INC_OUT_USE ) {
1659 ASTOBJ_UNREF(u,sip_destroy_user);
1661 ASTOBJ_UNREF(p,sip_destroy_peer);
1666 ast_log(LOG_DEBUG, "Call from %s '%s' is %d out of %d\n", u?"user":"peer", name, *inuse, *incominglimit);
1668 #ifdef DISABLED_CODE
1669 /* we don't use these anymore */
1671 if ( u->outUse > 0 ) {
1678 if ( u->outgoinglimit > 0 ) {
1679 if ( u->outUse >= u->outgoinglimit ) {
1680 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1681 ast_mutex_unlock(&userl.lock);
1692 ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",name,event);
1695 ASTOBJ_UNREF(u,sip_destroy_user);
1697 ASTOBJ_UNREF(p,sip_destroy_peer);
1701 /*--- sip_destroy: Destroy SIP call structure ---*/
1702 static void sip_destroy(struct sip_pvt *p)
1704 ast_mutex_lock(&iflock);
1705 __sip_destroy(p, 1);
1706 ast_mutex_unlock(&iflock);
1710 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1712 /*--- hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes ---*/
1713 static int hangup_sip2cause(int cause)
1715 /* Possible values from causes.h
1716 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
1717 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
1721 case 404: /* Not found */
1722 return AST_CAUSE_UNALLOCATED;
1723 case 483: /* Too many hops */
1724 return AST_CAUSE_FAILURE;
1726 return AST_CAUSE_BUSY;
1728 return AST_CAUSE_NORMAL;
1734 /*--- hangup_cause2sip: Convert Asterisk hangup causes to SIP codes ---*/
1735 static char *hangup_cause2sip(int cause)
1739 case AST_CAUSE_FAILURE:
1740 return "500 Server internal failure";
1741 case AST_CAUSE_CONGESTION:
1742 return "503 Service Unavailable";
1743 case AST_CAUSE_BUSY:
1752 /*--- sip_hangup: Hangup SIP call ---*/
1753 /* Part of PBX interface */
1754 static int sip_hangup(struct ast_channel *ast)
1756 struct sip_pvt *p = ast->pvt->pvt;
1758 struct ast_flags locflags = {0};
1760 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1761 if (!ast->pvt->pvt) {
1762 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1765 ast_mutex_lock(&p->lock);
1767 if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
1768 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
1771 if (ast_test_flag(p, SIP_OUTGOING)) {
1772 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
1773 update_user_counter(p, DEC_OUT_USE);
1775 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
1776 update_user_counter(p, DEC_IN_USE);
1778 /* Determine how to disconnect */
1779 if (p->owner != ast) {
1780 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1781 ast_mutex_unlock(&p->lock);
1784 if (!ast || (ast->_state != AST_STATE_UP))
1789 ast_dsp_free(p->vad);
1792 ast->pvt->pvt = NULL;
1794 ast_mutex_lock(&usecnt_lock);
1796 ast_mutex_unlock(&usecnt_lock);
1797 ast_update_use_count();
1799 ast_set_flag(&locflags, SIP_NEEDDESTROY);
1800 /* Start the process if it's not already started */
1801 if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
1803 if (ast_test_flag(p, SIP_OUTGOING)) {
1804 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
1805 /* Actually don't destroy us yet, wait for the 487 on our original
1806 INVITE, but do set an autodestruct just in case we never get it. */
1807 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
1808 sip_scheddestroy(p, 15000);
1809 if ( p->initid != -1 ) {
1810 /* channel still up - reverse dec of inUse counter
1811 only if the channel is not auto-congested */
1812 if (ast_test_flag(p, SIP_OUTGOING)) {
1813 update_user_counter(p, INC_OUT_USE);
1816 update_user_counter(p, INC_IN_USE);
1821 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1822 transmit_response_reliable(p, res, &p->initreq, 1);
1824 transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
1827 if (!p->pendinginvite) {
1829 transmit_request_with_auth(p, "BYE", 0, 1, 1);
1831 /* Note we will need a BYE when this all settles out
1832 but we can't send one while we have "INVITE" outstanding. */
1833 ast_set_flag(p, SIP_PENDINGBYE);
1834 ast_clear_flag(p, SIP_NEEDREINVITE);
1838 ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);
1839 ast_mutex_unlock(&p->lock);
1843 /*--- sip_answer: Answer SIP call , send 200 OK on Invite ---*/
1844 /* Part of PBX interface */
1845 static int sip_answer(struct ast_channel *ast)
1849 struct sip_pvt *p = ast->pvt->pvt;
1851 ast_mutex_lock(&p->lock);
1852 if (ast->_state != AST_STATE_UP) {
1857 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1859 fmt=ast_getformatbyname(codec);
1861 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1862 if (p->jointcapability & fmt) {
1863 p->jointcapability &= fmt;
1864 p->capability &= fmt;
1866 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
1867 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1870 ast_setstate(ast, AST_STATE_UP);
1872 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1873 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1875 ast_mutex_unlock(&p->lock);
1879 /*--- sip_write: Send response, support audio media ---*/
1880 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1882 struct sip_pvt *p = ast->pvt->pvt;
1884 if (frame->frametype == AST_FRAME_VOICE) {
1885 if (!(frame->subclass & ast->nativeformats)) {
1886 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1887 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1891 ast_mutex_lock(&p->lock);
1893 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
1894 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1895 ast_set_flag(p, SIP_PROGRESS_SENT);
1897 time(&p->lastrtptx);
1898 res = ast_rtp_write(p->rtp, frame);
1900 ast_mutex_unlock(&p->lock);
1902 } else if (frame->frametype == AST_FRAME_VIDEO) {
1904 ast_mutex_lock(&p->lock);
1906 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
1907 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1908 ast_set_flag(p, SIP_PROGRESS_SENT);
1910 time(&p->lastrtptx);
1911 res = ast_rtp_write(p->vrtp, frame);
1913 ast_mutex_unlock(&p->lock);
1915 } else if (frame->frametype == AST_FRAME_IMAGE) {
1918 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1925 /*--- sip_fixup: Fix up a channel: If a channel is consumed, this is called.
1926 Basically update any ->owner links ----*/
1927 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1929 struct sip_pvt *p = newchan->pvt->pvt;
1930 ast_mutex_lock(&p->lock);
1931 if (p->owner != oldchan) {
1932 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1933 ast_mutex_unlock(&p->lock);
1937 ast_mutex_unlock(&p->lock);
1941 /*--- sip_senddigit: Send DTMF character on SIP channel */
1942 /* within one call, we're able to transmit in many methods simultaneously */
1943 static int sip_senddigit(struct ast_channel *ast, char digit)
1945 struct sip_pvt *p = ast->pvt->pvt;
1947 ast_mutex_lock(&p->lock);
1948 switch (ast_test_flag(p, SIP_DTMF)) {
1950 transmit_info_with_digit(p, digit);
1952 case SIP_DTMF_RFC2833:
1954 ast_rtp_senddigit(p->rtp, digit);
1956 case SIP_DTMF_INBAND:
1960 ast_mutex_unlock(&p->lock);
1965 /*--- sip_transfer: Transfer SIP call */
1966 static int sip_transfer(struct ast_channel *ast, char *dest)
1968 struct sip_pvt *p = ast->pvt->pvt;
1971 ast_mutex_lock(&p->lock);
1972 res = transmit_refer(p, dest);
1973 ast_mutex_unlock(&p->lock);
1977 /*--- sip_indicate: Play indication to user */
1978 /* With SIP a lot of indications is sent as messages, letting the device play
1979 the indication - busy signal, congestion etc */
1980 static int sip_indicate(struct ast_channel *ast, int condition)
1982 struct sip_pvt *p = ast->pvt->pvt;
1985 ast_mutex_lock(&p->lock);
1987 case AST_CONTROL_RINGING:
1988 if (ast->_state == AST_STATE_RING) {
1989 if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
1990 (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
1991 /* Send 180 ringing if out-of-band seems reasonable */
1992 transmit_response(p, "180 Ringing", &p->initreq);
1993 ast_set_flag(p, SIP_RINGING);
1994 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
1997 /* Well, if it's not reasonable, just send in-band */
2002 case AST_CONTROL_BUSY:
2003 if (ast->_state != AST_STATE_UP) {
2004 transmit_response(p, "486 Busy Here", &p->initreq);
2005 ast_set_flag(p, SIP_ALREADYGONE);
2006 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2011 case AST_CONTROL_CONGESTION:
2012 if (ast->_state != AST_STATE_UP) {
2013 transmit_response(p, "503 Service Unavailable", &p->initreq);
2014 ast_set_flag(p, SIP_ALREADYGONE);
2015 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2020 case AST_CONTROL_PROGRESS:
2021 case AST_CONTROL_PROCEEDING:
2022 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2023 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2024 ast_set_flag(p, SIP_PROGRESS_SENT);
2033 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2037 ast_mutex_unlock(&p->lock);
2043 /*--- sip_new: Initiate a call in the SIP channel */
2044 /* called from sip_request_call (calls from the pbx ) */
2045 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
2047 struct ast_channel *tmp;
2048 struct ast_variable *v = NULL;
2051 ast_mutex_unlock(&i->lock);
2052 /* Don't hold a sip pvt lock while we allocate a channel */
2053 tmp = ast_channel_alloc(1);
2054 ast_mutex_lock(&i->lock);
2056 /* Select our native format based on codec preference until we receive
2057 something from another device to the contrary. */
2058 ast_mutex_lock(&i->lock);
2059 if (i->jointcapability)
2060 tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
2061 else if (i->capability)
2062 tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
2064 tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
2065 ast_mutex_unlock(&i->lock);
2066 fmt = ast_best_codec(tmp->nativeformats);
2068 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
2070 if (strchr(i->fromdomain,':'))
2072 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2076 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2078 tmp->type = channeltype;
2079 if (ast_test_flag(i, SIP_DTMF) == SIP_DTMF_INBAND) {
2080 i->vad = ast_dsp_new();
2081 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2083 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2085 tmp->fds[0] = ast_rtp_fd(i->rtp);
2086 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2088 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2089 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2091 if (state == AST_STATE_RING)
2093 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2094 tmp->writeformat = fmt;
2095 tmp->pvt->rawwriteformat = fmt;
2096 tmp->readformat = fmt;
2097 tmp->pvt->rawreadformat = fmt;
2099 tmp->pvt->send_text = sip_sendtext;
2100 tmp->pvt->call = sip_call;
2101 tmp->pvt->hangup = sip_hangup;
2102 tmp->pvt->answer = sip_answer;
2103 tmp->pvt->read = sip_read;
2104 tmp->pvt->write = sip_write;
2105 tmp->pvt->write_video = sip_write;
2106 tmp->pvt->indicate = sip_indicate;
2107 tmp->pvt->transfer = sip_transfer;
2108 tmp->pvt->fixup = sip_fixup;
2109 tmp->pvt->send_digit = sip_senddigit;
2111 tmp->pvt->bridge = ast_rtp_bridge;
2113 tmp->callgroup = i->callgroup;
2114 tmp->pickupgroup = i->pickupgroup;
2115 tmp->cid.cid_pres = i->callingpres;
2116 if (!ast_strlen_zero(i->accountcode))
2117 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2119 tmp->amaflags = i->amaflags;
2120 if (!ast_strlen_zero(i->language))
2121 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2122 if (!ast_strlen_zero(i->musicclass))
2123 strncpy(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass)-1);
2125 ast_mutex_lock(&usecnt_lock);
2127 ast_mutex_unlock(&usecnt_lock);
2128 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2129 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2130 if (!ast_strlen_zero(i->cid_num))
2131 tmp->cid.cid_num = strdup(i->cid_num);
2132 if (!ast_strlen_zero(i->cid_name))
2133 tmp->cid.cid_name = strdup(i->cid_name);
2134 if (!ast_strlen_zero(i->rdnis))
2135 tmp->cid.cid_rdnis = strdup(i->rdnis);
2136 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2137 tmp->cid.cid_dnid = strdup(i->exten);
2139 if (!ast_strlen_zero(i->uri)) {
2140 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2142 if (!ast_strlen_zero(i->domain)) {
2143 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2145 if (!ast_strlen_zero(i->useragent)) {
2146 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2148 if (!ast_strlen_zero(i->callid)) {
2149 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2151 ast_setstate(tmp, state);
2152 if (state != AST_STATE_DOWN) {
2153 if (ast_pbx_start(tmp)) {
2154 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2159 /* Set channel variables for this call from configuration */
2160 for (v = i->chanvars ; v ; v = v->next)
2161 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2164 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2168 /* Structure for conversion between compressed SIP and "normal" SIP */
2169 static struct cfalias {
2173 { "Content-Type", "c" },
2174 { "Content-Encoding", "e" },
2178 { "Content-Length", "l" },
2181 { "Supported", "k" },
2182 { "Refer-To", "r" },
2183 { "Allow-Events", "u" },
2188 /*--- get_sdp_by_line: Reads one line of SIP message body */
2189 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
2190 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2191 char* r = line + nameLen + 1;
2192 while (*r && (*r < 33)) ++r;
2199 /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
2200 but the name wrongly applies _only_ sdp */
2201 static char *get_sdp(struct sip_request *req, char *name) {
2203 int len = strlen(name);
2206 for (x=0; x<req->lines; x++) {
2207 r = get_sdp_by_line(req->line[x], name, len);
2208 if (r[0] != '\0') return r;
2214 static void sdpLineNum_iterator_init(int* iterator) {
2218 static char* get_sdp_iterate(int* iterator,
2219 struct sip_request *req, char *name) {
2220 int len = strlen(name);
2222 while (*iterator < req->lines) {
2223 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2224 if (r[0] != '\0') return r;
2229 static char *__get_header(struct sip_request *req, char *name, int *start)
2232 int len = strlen(name);
2234 if (pedanticsipchecking) {
2235 /* Technically you can place arbitrary whitespace both before and after the ':' in
2236 a header, although RFC3261 clearly says you shouldn't before, and place just
2237 one afterwards. If you shouldn't do it, what absolute idiot decided it was
2238 a good idea to say you can do it, and if you can do it, why in the hell would
2239 you say you shouldn't. */
2240 for (x=*start;x<req->headers;x++) {
2241 if (!strncasecmp(req->header[x], name, len)) {
2242 r = req->header[x] + len;
2243 while(*r && (*r < 33))
2247 while(*r && (*r < 33))
2255 /* We probably shouldn't even bother counting whitespace afterwards but
2256 I guess for backwards compatibility we will */
2257 for (x=*start;x<req->headers;x++) {
2258 if (!strncasecmp(req->header[x], name, len) &&
2259 (req->header[x][len] == ':')) {
2260 r = req->header[x] + len + 1;
2261 while(*r && (*r < 33))
2269 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2270 if (!strcasecmp(aliases[x].fullname, name))
2271 return __get_header(req, aliases[x].shortname, start);
2273 /* Don't return NULL, so get_header is always a valid pointer */
2277 /*--- get_header: Get header from SIP request ---*/
2278 static char *get_header(struct sip_request *req, char *name)
2281 return __get_header(req, name, &start);
2284 /*--- sip_rtp_read: Read RTP from network ---*/
2285 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
2287 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
2288 struct ast_frame *f;
2289 static struct ast_frame null_frame = { AST_FRAME_NULL, };
2292 f = ast_rtp_read(p->rtp); /* RTP Audio */
2295 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
2298 f = ast_rtp_read(p->vrtp); /* RTP Video */
2301 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
2306 /* Don't send RFC2833 if we're not supposed to */
2307 if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
2310 /* We already hold the channel lock */
2311 if (f->frametype == AST_FRAME_VOICE) {
2312 if (f->subclass != p->owner->nativeformats) {
2313 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2314 p->owner->nativeformats = f->subclass;
2315 ast_set_read_format(p->owner, p->owner->readformat);
2316 ast_set_write_format(p->owner, p->owner->writeformat);
2318 if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
2319 f = ast_dsp_process(p->owner,p->vad,f);
2320 if (f && (f->frametype == AST_FRAME_DTMF))
2321 ast_log(LOG_DEBUG, "Detected DTMF '%c'\n", f->subclass);
2328 /*--- sip_read: Read SIP RTP from channel */
2329 static struct ast_frame *sip_read(struct ast_channel *ast)
2331 struct ast_frame *fr;
2332 struct sip_pvt *p = ast->pvt->pvt;
2333 ast_mutex_lock(&p->lock);
2334 fr = sip_rtp_read(ast, p);
2335 time(&p->lastrtprx);
2336 ast_mutex_unlock(&p->lock);
2340 /*--- build_callid: Build SIP CALLID header ---*/
2341 static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
2346 char iabuf[INET_ADDRSTRLEN];
2349 res = snprintf(callid, len, "%08x", val);
2353 if (!ast_strlen_zero(fromdomain))
2354 snprintf(callid, len, "@%s", fromdomain);
2356 /* It's not important that we really use our right IP here... */
2357 snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
2360 /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
2361 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat)
2365 p = malloc(sizeof(struct sip_pvt));
2368 /* Keep track of stuff */
2369 memset(p, 0, sizeof(struct sip_pvt));
2370 ast_mutex_init(&p->lock);
2380 memcpy(&p->sa, sin, sizeof(p->sa));
2381 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
2382 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2384 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2386 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2388 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2392 /* Start with 101 instead of 1 */
2395 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
2396 ast_mutex_destroy(&p->lock);
2398 ast_variables_destroy(p->chanvars);
2404 ast_rtp_settos(p->rtp, tos);
2406 ast_rtp_settos(p->vrtp, tos);
2407 if (useglobal_nat && sin) {
2408 /* Setup NAT structure according to global settings if we have an address */
2409 ast_copy_flags(p, &global_flags, SIP_NAT);
2410 memcpy(&p->recv, sin, sizeof(p->recv));
2411 ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
2413 ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
2416 strncpy(p->fromdomain, default_fromdomain, sizeof(p->fromdomain) - 1);
2417 build_via(p, p->via, sizeof(p->via));
2419 build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
2421 strncpy(p->callid, callid, sizeof(p->callid) - 1);
2422 ast_copy_flags(p, (&global_flags), SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_DTMF | SIP_REINVITE | SIP_PROG_INBAND | SIP_OSPAUTH);
2423 /* Assign default music on hold class */
2424 strncpy(p->musicclass, global_musicclass, sizeof(p->musicclass) - 1);
2425 p->rtptimeout = global_rtptimeout;
2426 p->rtpholdtimeout = global_rtpholdtimeout;
2427 p->rtpkeepalive = global_rtpkeepalive;
2428 p->capability = global_capability;
2429 if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833)
2430 p->noncodeccapability |= AST_RTP_DTMF;
2431 strncpy(p->context, default_context, sizeof(p->context) - 1);
2433 ast_mutex_lock(&iflock);
2436 ast_mutex_unlock(&iflock);
2438 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
2442 /*--- find_call: Connect incoming SIP message to current call or create new call structure */
2443 /* Called by handle_request ,sipsock_read */
2444 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
2449 char iabuf[INET_ADDRSTRLEN];
2453 callid = get_header(req, "Call-ID");
2455 if (pedanticsipchecking) {
2456 /* In principle Call-ID's uniquely identify a call, however some vendors
2457 (i.e. Pingtel) send multiple calls with the same Call-ID and different
2458 tags in order to simplify billing. The RFC does state that we have to
2459 compare tags in addition to the call-id, but this generate substantially
2460 more overhead which is totally unnecessary for the vast majority of sane
2461 SIP implementations, and thus Asterisk does not enable this behavior
2462 by default. Short version: You'll need this option to support conferencing
2464 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
2466 c = strchr(tmp, ' ');
2469 if (!strcasecmp(cmd, "SIP/2.0"))
2470 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2472 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
2473 tag = strstr(tmp, "tag=");
2476 c = strchr(tag, ';');
2483 if (ast_strlen_zero(callid)) {
2484 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
2487 ast_mutex_lock(&iflock);
2490 if (!strcmp(p->callid, callid) &&
2491 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) {
2492 /* Found the call */
2493 ast_mutex_lock(&p->lock);
2494 ast_mutex_unlock(&iflock);
2499 ast_mutex_unlock(&iflock);
2500 p = sip_alloc(callid, sin, 1);
2502 ast_mutex_lock(&p->lock);
2506 /*--- sip_register: Parse register=> line in sip.conf and add to registry */
2507 static int sip_register(char *value, int lineno)
2509 struct sip_registry *reg;
2510 char copy[256] = "";
2511 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
2518 strncpy(copy, value, sizeof(copy)-1);
2521 hostname = strrchr(stringp, '@');
2526 if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
2527 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
2531 username = strsep(&stringp, ":");
2533 secret = strsep(&stringp, ":");
2535 authuser = strsep(&stringp, ":");
2538 hostname = strsep(&stringp, "/");
2540 contact = strsep(&stringp, "/");
2541 if (!contact || ast_strlen_zero(contact))
2544 hostname = strsep(&stringp, ":");
2545 porta = strsep(&stringp, ":");
2547 if (porta && !atoi(porta)) {
2548 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
2551 reg = malloc(sizeof(struct sip_registry));
2553 memset(reg, 0, sizeof(struct sip_registry));
2556 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
2558 strncpy(reg->username, username, sizeof(reg->username)-1);
2560 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
2562 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
2564 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
2567 reg->refresh = default_expiry;
2568 reg->portno = porta ? atoi(porta) : 0;
2569 reg->callid_valid = 0;
2571 ASTOBJ_CONTAINER_LINK(®l, reg);
2572 ASTOBJ_UNREF(reg,sip_registry_destroy);
2574 ast_log(LOG_ERROR, "Out of memory\n");
2580 /*--- lws2sws: Parse multiline SIP headers into one header */
2581 /* This is enabled if pedanticsipchecking is enabled */
2582 static int lws2sws(char *msgbuf, int len)
2588 /* Eliminate all CRs */
2589 if (msgbuf[h] == '\r') {
2593 /* Check for end-of-line */
2594 if (msgbuf[h] == '\n') {
2595 /* Check for end-of-message */
2598 /* Check for a continuation line */
2599 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
2600 /* Merge continuation line */
2604 /* Propagate LF and start new line */
2605 msgbuf[t++] = msgbuf[h++];
2609 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
2614 msgbuf[t++] = msgbuf[h++];
2618 msgbuf[t++] = msgbuf[h++];
2626 /*--- parse: Parse a SIP message ----*/
2627 static void parse(struct sip_request *req)
2629 /* Divide fields by NULL's */
2634 /* First header starts immediately */
2638 /* We've got a new header */
2642 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2644 if (ast_strlen_zero(req->header[f])) {
2645 /* Line by itself means we're now in content */
2649 if (f >= SIP_MAX_HEADERS - 1) {
2650 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2653 req->header[f] = c + 1;
2654 } else if (*c == '\r') {
2655 /* Ignore but eliminate \r's */
2660 /* Check for last header */
2661 if (!ast_strlen_zero(req->header[f]))
2664 /* Now we process any mime content */
2669 /* We've got a new line */
2672 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2674 if (f >= SIP_MAX_LINES - 1) {
2675 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2678 req->line[f] = c + 1;
2679 } else if (*c == '\r') {
2680 /* Ignore and eliminate \r's */
2685 /* Check for last line */
2686 if (!ast_strlen_zero(req->line[f]))
2690 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2693 /*--- process_sdp: Process SIP SDP ---*/
2694 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2700 char iabuf[INET_ADDRSTRLEN];
2704 int peercapability, peernoncodeccapability;
2705 int vpeercapability=0, vpeernoncodeccapability=0;
2706 struct sockaddr_in sin;
2709 struct ast_hostent ahp;
2711 int destiterator = 0;
2715 int debug=sip_debug_test_pvt(p);
2717 /* Update our last rtprx when we receive an SDP, too */
2718 time(&p->lastrtprx);
2719 time(&p->lastrtptx);
2721 /* Get codec and RTP info from SDP */
2722 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2723 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2726 m = get_sdp(req, "m");
2727 sdpLineNum_iterator_init(&destiterator);
2728 c = get_sdp_iterate(&destiterator, req, "c");
2729 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
2730 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2733 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2734 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2737 /* XXX This could block for a long time, and block the main thread! XXX */
2738 hp = ast_gethostbyname(host, &ahp);
2740 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2743 sdpLineNum_iterator_init(&iterator);
2744 ast_set_flag(p, SIP_NOVIDEO);
2745 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2746 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1) ||
2747 (sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2)) {
2749 /* Scan through the RTP payload types specified in a "m=" line: */
2750 ast_rtp_pt_clear(p->rtp);
2752 while(!ast_strlen_zero(codecs)) {
2753 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2754 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2758 ast_verbose("Found RTP audio format %d\n", codec);
2759 ast_rtp_set_m_type(p->rtp, codec);
2761 /* Skip over any whitespace */
2762 while(*codecs && (*codecs < 33)) codecs++;
2766 ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
2768 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2769 ast_clear_flag(p, SIP_NOVIDEO);
2771 /* Scan through the RTP payload types specified in a "m=" line: */
2773 while(!ast_strlen_zero(codecs)) {
2774 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2775 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2779 ast_verbose("Found video format %s\n", ast_getformatname(codec));
2780 ast_rtp_set_m_type(p->vrtp, codec);
2782 /* Skip over any whitespace */
2783 while(*codecs && (*codecs < 33)) codecs++;
2787 /* Check for Media-description-level-address for audio */
2788 if (pedanticsipchecking) {
2789 c = get_sdp_iterate(&destiterator, req, "c");
2790 if (!ast_strlen_zero(c)) {
2791 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2792 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
2794 /* XXX This could block for a long time, and block the main thread! XXX */
2795 hp = ast_gethostbyname(host, &ahp);
2797 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
2802 /* RTP addresses and ports for audio and video */
2803 sin.sin_family = AF_INET;
2804 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2806 /* Setup audio port number */
2807 sin.sin_port = htons(portno);
2808 if (p->rtp && sin.sin_port) {
2809 ast_rtp_set_peer(p->rtp, &sin);
2811 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2812 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));
2815 /* Check for Media-description-level-address for video */
2816 if (pedanticsipchecking) {
2817 c = get_sdp_iterate(&destiterator, req, "c");
2818 if (!ast_strlen_zero(c)) {
2819 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2820 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
2822 /* XXX This could block for a long time, and block the main thread! XXX */
2823 hp = ast_gethostbyname(host, &ahp);
2825 ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
2830 /* Setup video port number */
2831 sin.sin_port = htons(vportno);
2832 if (p->vrtp && sin.sin_port) {
2833 ast_rtp_set_peer(p->vrtp, &sin);
2835 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2836 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));
2840 /* Next, scan through each "a=rtpmap:" line, noting each
2841 * specified RTP payload type (with corresponding MIME subtype):
2843 sdpLineNum_iterator_init(&iterator);
2844 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2845 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2846 if (!strcasecmp(a, "sendonly")) {
2850 if (!strcasecmp(a, "sendrecv")) {
2853 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2855 ast_verbose("Found description format %s\n", mimeSubtype);
2856 /* Note: should really look at the 'freq' and '#chans' params too */
2857 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2859 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2862 /* Now gather all of the codecs that were asked for: */
2863 ast_rtp_get_current_formats(p->rtp,
2864 &peercapability, &peernoncodeccapability);
2866 ast_rtp_get_current_formats(p->vrtp,
2867 &vpeercapability, &vpeernoncodeccapability);
2868 p->jointcapability = p->capability & (peercapability | vpeercapability);
2869 p->peercapability = (peercapability | vpeercapability);
2870 p->noncodeccapability = noncodeccapability & peernoncodeccapability;
2873 /* shame on whoever coded this.... */
2874 const unsigned slen=512;
2875 char s1[slen], s2[slen], s3[slen], s4[slen];
2877 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
2878 ast_getformatname_multiple(s1, slen, p->capability),
2879 ast_getformatname_multiple(s2, slen, peercapability),
2880 ast_getformatname_multiple(s3, slen, vpeercapability),
2881 ast_getformatname_multiple(s4, slen, p->jointcapability));
2883 ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
2884 ast_getformatname_multiple(s1, slen, noncodeccapability),
2885 ast_getformatname_multiple(s2, slen, peernoncodeccapability),
2886 ast_getformatname_multiple(s3, slen, p->noncodeccapability));
2888 if (!p->jointcapability) {
2889 ast_log(LOG_NOTICE, "No compatible codecs!\n");
2893 if (!(p->owner->nativeformats & p->jointcapability)) {
2894 const unsigned slen=512;
2895 char s1[slen], s2[slen];
2896 ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n",
2897 ast_getformatname_multiple(s1, slen, p->jointcapability),
2898 ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
2899 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1);
2900 ast_set_read_format(p->owner, p->owner->readformat);
2901 ast_set_write_format(p->owner, p->owner->writeformat);
2903 if (ast_bridged_channel(p->owner)) {
2904 /* Turn on/off music on hold if we are holding/unholding */
2905 if (sin.sin_addr.s_addr && !sendonly) {
2906 ast_moh_stop(ast_bridged_channel(p->owner));
2907 if (callevents && ast_test_flag(p, SIP_CALL_ONHOLD)) {
2908 manager_event(EVENT_FLAG_CALL, "Unhold",
2912 p->owner->uniqueid);
2913 ast_clear_flag(p, SIP_CALL_ONHOLD);
2916 if (callevents && !ast_test_flag(p, SIP_CALL_ONHOLD)) {
2917 manager_event(EVENT_FLAG_CALL, "Hold",
2921 p->owner->uniqueid);
2922 ast_set_flag(p, SIP_CALL_ONHOLD);
2924 ast_moh_start(ast_bridged_channel(p->owner), NULL);
2926 ast_rtp_stop(p->rtp);
2934 /*--- add_header: Add header to SIP message */
2935 static int add_header(struct sip_request *req, char *var, char *value)
2938 char *shortname = "";
2939 if (req->len >= sizeof(req->data) - 4) {
2940 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2944 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2948 req->header[req->headers] = req->data + req->len;
2949 if (compactheaders) {
2950 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
2951 if (!strcasecmp(aliases[x].fullname, var))
2952 shortname = aliases[x].shortname;
2954 if(!ast_strlen_zero(shortname)) {
2955 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", shortname, value);
2957 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2959 req->len += strlen(req->header[req->headers]);
2960 if (req->headers < SIP_MAX_HEADERS)
2963 ast_log(LOG_WARNING, "Out of header space\n");
2969 /*--- add_blank_header: Add blank header to SIP message */
2970 static int add_blank_header(struct sip_request *req)
2972 if (req->len >= sizeof(req->data) - 4) {
2973 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2977 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2980 req->header[req->headers] = req->data + req->len;
2981 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2982 req->len += strlen(req->header[req->headers]);
2983 if (req->headers < SIP_MAX_HEADERS)
2986 ast_log(LOG_WARNING, "Out of header space\n");
2992 /*--- add_line: Add content (not header) to SIP message */
2993 static int add_line(struct sip_request *req, char *line)
2995 if (req->len >= sizeof(req->data) - 4) {
2996 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
3000 /* Add extra empty return */
3001 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
3002 req->len += strlen(req->data + req->len);
3004 req->line[req->lines] = req->data + req->len;
3005 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
3006 req->len += strlen(req->line[req->lines]);
3007 if (req->lines < SIP_MAX_LINES)
3010 ast_log(LOG_WARNING, "Out of line space\n");