2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Session Initiation Protocol
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
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/callerid.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/md5.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <asterisk/parking.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 <sys/socket.h>
44 #include <sys/ioctl.h>
51 #include <arpa/inet.h>
54 #include <sys/signal.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/ip.h>
58 #ifdef SIP_MYSQL_FRIENDS
60 #include <mysql/mysql.h>
63 #define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
65 #define IPTOS_MINCOST 0x02
68 /* #define VOCAL_DATA_HACK */
71 #define DEFAULT_DEFAULT_EXPIRY 120
72 #define DEFAULT_MAX_EXPIRY 3600
74 /* guard limit must be larger than guard secs */
75 /* guard min must be < 1000, and should be >= 250 */
76 #define EXPIRY_GUARD_SECS 15 /* How long before expiry do we reregister */
77 #define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of EXPIRY_GUARD_SECS */
78 #define EXPIRY_GUARD_MIN 500 /* This is the minimum guard time applied. If GUARD_PCT turns out
79 to be lower than this, it will use this time instead. This is in
81 #define EXPIRY_GUARD_PCT 0.20 /* Percentage of expires timeout to use when below EXPIRY_GUARD_LIMIT */
84 #define MAX(a,b) ((a) > (b) ? (a) : (b))
87 #define CALLERID_UNKNOWN "Unknown"
89 /* --- Choices for DTMF support in SIP channel */
90 #define SIP_DTMF_RFC2833 (1 << 0)
91 #define SIP_DTMF_INBAND (1 << 1)
92 #define SIP_DTMF_INFO (1 << 2)
94 static int max_expiry = DEFAULT_MAX_EXPIRY;
95 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
97 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
98 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
99 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
101 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
102 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
104 /* MYSQL_FRIENDS: Check if peer exists in database and read some configuration
105 from databse (not all options supported though) */
107 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
109 static char mydbuser[80];
110 static char mydbpass[80];
111 static char mydbhost[80];
112 static char mydbname[80];
116 #define DEBUG_READ 0 /* Recieved data */
117 #define DEBUG_SEND 1 /* Transmit data */
119 static char *desc = "Session Initiation Protocol (SIP)";
120 static char *type = "SIP";
121 static char *tdesc = "Session Initiation Protocol (SIP)";
122 static char *config = "sip.conf";
124 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
125 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
127 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
129 static char context[AST_MAX_EXTENSION] = "default";
131 static char language[MAX_LANGUAGE] = "";
133 static char callerid[AST_MAX_EXTENSION] = "asterisk";
135 static char fromdomain[AST_MAX_EXTENSION] = "";
137 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
139 static int srvlookup = 0;
141 static int pedanticsipchecking = 0;
143 static int autocreatepeer = 0;
145 static int relaxdtmf = 0;
147 static int usecnt =0;
148 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
150 /* Protect the interface list (of sip_pvt's) */
151 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
153 /* Protect the monitoring thread, so only one process can kill or start it, and not
154 when it's doing something critical. */
155 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
157 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
159 /* This is the thread for the monitor which checks for input on the channels
160 which are not currently in use. */
161 static pthread_t monitor_thread = AST_PTHREADT_NULL;
163 static int restart_monitor(void);
165 /* Codecs that we support by default: */
166 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
167 static int noncodeccapability = AST_RTP_DTMF;
169 static char ourhost[256];
170 static struct in_addr __ourip;
173 static int sipdebug = 0;
174 static struct sockaddr_in debugaddr;
178 static int videosupport = 0;
180 static int globaldtmfmode = SIP_DTMF_RFC2833; /* DTMF mode default */
181 static int recordhistory = 0;
183 static char globalmusicclass[MAX_LANGUAGE] = ""; /* Global music on hold class */
184 static char global_realm[AST_MAX_EXTENSION] = "asterisk"; /* Default realm */
187 static int expiry = 900;
189 static struct sched_context *sched;
190 static struct io_context *io;
191 /* The private structures of the sip channels are linked for
192 selecting outgoing channels */
194 #define SIP_MAX_HEADERS 64
195 #define SIP_MAX_LINES 64
199 #define DEC_OUT_USE 2
200 #define INC_OUT_USE 3
202 static struct sip_codec_pref {
204 struct sip_codec_pref *next;
207 /* sip_request: The data grabbed from the UDP socket */
209 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
210 char *rlPart2; /* The Request URI or Response Status */
212 int headers; /* SIP Headers */
213 char *header[SIP_MAX_HEADERS];
214 int lines; /* SDP Content */
215 char *line[SIP_MAX_LINES];
216 char data[SIP_MAX_PACKET];
222 struct sip_route *next;
228 struct sip_history *next;
231 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call */
232 static struct sip_pvt {
233 ast_mutex_t lock; /* Channel private lock */
234 char callid[80]; /* Global CallID */
235 char randdata[80]; /* Random data */
236 unsigned int ocseq; /* Current outgoing seqno */
237 unsigned int icseq; /* Current incoming seqno */
238 unsigned int callgroup; /* Call group */
239 unsigned int pickupgroup; /* Pickup group */
240 int lastinvite; /* Last Cseq of invite */
241 int alreadygone; /* Whether or not we've already been destroyed by or peer */
242 int needdestroy; /* if we need to be destroyed */
243 int capability; /* Special capability (codec) */
244 int jointcapability; /* Supported capability at both ends (codecs ) */
245 int prefcodec; /* Preferred codec (outbound only) */
246 int noncodeccapability;
247 int outgoing; /* Outgoing or incoming call? */
248 int authtries; /* Times we've tried to authenticate */
249 int insecure; /* Don't check source port/ip */
250 int expiry; /* How long we take to expire */
251 int branch; /* One random number */
252 int canreinvite; /* Do we support reinvite */
253 int ringing; /* Have sent 180 ringing */
254 int progress; /* Have sent 183 message progress */
255 int tag; /* Another random number */
256 int nat; /* Whether to try to support NAT */
257 int sessionid; /* SDP Session ID */
258 int sessionversion; /* SDP Session Version */
259 struct sockaddr_in sa; /* Our peer */
260 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
261 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
262 struct sockaddr_in recv; /* Received as */
263 struct in_addr ourip; /* Our IP */
264 struct ast_channel *owner; /* Who owns us */
265 char exten[AST_MAX_EXTENSION]; /* Extension where to start */
266 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
267 char referred_by[AST_MAX_EXTENSION]; /* Place to store REFERRED-BY extension */
268 char refer_contact[AST_MAX_EXTENSION]; /* Place to store Contact info from a REFER extension */
269 struct sip_pvt *refer_call; /* Call we are referring */
270 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
271 int route_persistant; /* Is this the "real" route? */
272 char remote_party_id[256];
273 char from[256]; /* The From: header */
274 char useragent[256]; /* User agent in SIP request */
275 char context[AST_MAX_EXTENSION]; /* Context for this call */
276 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
277 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
278 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
279 char language[MAX_LANGUAGE]; /* Default language for this call */
280 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
281 char rdnis[256]; /* Referring DNIS */
282 char theirtag[256]; /* Their tag */
285 char authname[256]; /* Who we use for authentication */
286 char uri[256]; /* Original requested URI */
287 char peersecret[256];
288 char peermd5secret[256];
289 char callerid[256]; /* Caller*ID */
290 int restrictcid; /* hide presentation from remote user */
292 char accountcode[20]; /* Account code */
293 char our_contact[256]; /* Our contact header */
294 char realm[256]; /* Authorization realm */
295 char nonce[256]; /* Authorization nonce */
296 char opaque[256]; /* Opaque nonsense */
297 char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
298 char domain[256]; /* Authorization nonce */
299 char lastmsg[256]; /* Last Message sent/received */
300 int amaflags; /* AMA Flags */
301 int pendinginvite; /* Any pending invite */
302 int pendingbye; /* Need to send bye after we ack? */
303 int gotrefer; /* Got a refer? */
304 struct sip_request initreq; /* Initial request */
306 int maxtime; /* Max time for first response */
307 int initid; /* Auto-congest ID if appropriate */
308 int autokillid; /* Auto-kill ID */
317 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
318 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
319 struct ast_rtp *rtp; /* RTP Session */
320 struct ast_rtp *vrtp; /* Video RTP session */
321 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
322 struct sip_history *history; /* History of this SIP dialog */
323 struct sip_pvt *next; /* Next call in chain */
326 #define FLAG_RESPONSE (1 << 0)
327 #define FLAG_FATAL (1 << 1)
329 /* sip packet - read in sipsock_read, transmitted in send_request */
331 struct sip_pkt *next; /* Next packet */
332 int retrans; /* Retransmission number */
333 int seqno; /* Sequence number */
334 int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
335 struct sip_pvt *owner; /* Owner call */
336 int retransid; /* Retransmission ID */
337 int packetlen; /* Length of packet */
341 /* Structure for SIP user data. User's place calls to us */
343 /* Users who can access various contexts */
349 char accountcode[20];
350 char language[MAX_LANGUAGE];
351 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
352 char useragent[256]; /* User agent in SIP request */
353 unsigned int callgroup;
354 unsigned int pickupgroup;
368 struct sip_user *next;
371 /* Structure for SIP peer data, we place calls to peers if registred or fixed IP address (host) */
376 char context[80]; /* JK02: peers need context too to allow parking etc */
381 char mailbox[AST_MAX_EXTENSION];
382 char language[MAX_LANGUAGE];
383 char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
384 char useragent[256]; /* User agent in SIP request */
394 unsigned int callgroup;
395 unsigned int pickupgroup;
397 struct sockaddr_in addr;
401 struct sip_pvt *call; /* Call pointer */
402 int pokeexpire; /* When to expire poke */
403 int lastms; /* How long last response took (in ms), or -1 for no response */
404 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
405 struct timeval ps; /* Ping send time */
407 struct sockaddr_in defaddr;
413 struct sip_peer *next;
416 static ast_mutex_t sip_reload_lock = AST_MUTEX_INITIALIZER;
417 static int sip_reloading = 0;
419 #define REG_STATE_UNREGISTERED 0
420 #define REG_STATE_REGSENT 1
421 #define REG_STATE_AUTHSENT 2
422 #define REG_STATE_REGISTERED 3
423 #define REG_STATE_REJECTED 4
424 #define REG_STATE_TIMEOUT 5
425 #define REG_STATE_NOAUTH 6
427 /* sip_registry: Registrations with other SIP proxies */
428 struct sip_registry {
429 struct sockaddr_in addr; /* Who we connect to for registration purposes */
430 char username[80]; /* Who we are registering as */
431 char authuser[80]; /* Who we *authenticate* as */
433 char secret[80]; /* Password or key name in []'s */
435 char contact[80]; /* Contact extension */
437 int expire; /* Sched ID of expiration */
438 int timeout; /* sched id of sip_reg_timeout */
439 int refresh; /* How often to refresh */
440 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
442 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
443 char callid[80]; /* Global CallID for this registry */
444 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
445 struct sockaddr_in us; /* Who the server thinks we are */
446 struct sip_registry *next;
449 /*--- The user list: Users and friends ---*/
450 static struct ast_user_list {
451 struct sip_user *users;
453 } userl = { NULL, AST_MUTEX_INITIALIZER };
455 /*--- The peer list: Peers and Friends ---*/
456 static struct ast_peer_list {
457 struct sip_peer *peers;
459 } peerl = { NULL, AST_MUTEX_INITIALIZER };
461 /*--- The register list: Other SIP proxys we register with and call ---*/
462 static struct ast_register_list {
463 struct sip_registry *registrations;
466 } regl = { NULL, AST_MUTEX_INITIALIZER };
469 #define REINVITE_INVITE 1
470 #define REINVITE_UPDATE 2
472 static int __sip_do_register(struct sip_registry *r);
474 static int sipsock = -1;
475 static int globalnat = 0;
476 static int globalcanreinvite = REINVITE_INVITE;
479 static struct sockaddr_in bindaddr;
480 static struct sockaddr_in externip;
481 static struct ast_ha *localaddr;
483 static struct ast_frame *sip_read(struct ast_channel *ast);
484 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
485 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
486 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
487 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
488 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
489 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
490 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
491 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
492 static int transmit_message_with_text(struct sip_pvt *p, char *text);
493 static int transmit_refer(struct sip_pvt *p, char *dest);
494 static struct sip_peer *temp_peer(char *name);
495 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
496 static void free_old_route(struct sip_route *route);
497 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
498 static int update_user_counter(struct sip_pvt *fup, int event);
499 static void prune_peers(void);
500 static int sip_do_reload(void);
501 static int sip_debug_test_addr(struct sockaddr_in *addr);
502 static int sip_debug_test_pvt(struct sip_pvt *p);
504 /*--- __sip_xmit: Transmit SIP message ---*/
505 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
509 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
511 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
513 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, inet_ntoa(p->sa.sin_addr), res, strerror(errno));
518 static void sip_destroy(struct sip_pvt *p);
520 /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
521 /* Only used for outbound registrations */
522 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
525 * Using the localaddr structure built up with localnet statements
526 * apply it to their address to see if we need to substitute our
527 * externip or can get away with our internal bindaddr
529 struct sockaddr_in theirs;
530 theirs.sin_addr = *them;
531 if (localaddr && externip.sin_addr.s_addr &&
532 ast_apply_ha(localaddr, &theirs)) {
534 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
535 strcpy(t, inet_ntoa(*(struct in_addr *)&them->s_addr));
536 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", t);
538 else if (bindaddr.sin_addr.s_addr)
539 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
541 return ast_ouraddrfor(them, us);
545 static int append_history(struct sip_pvt *p, char *event, char *data)
547 struct sip_history *hist, *prev;
551 hist = malloc(sizeof(struct sip_history));
553 memset(hist, 0, sizeof(struct sip_history));
554 snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
558 if ((*c == '\r') || (*c == '\n')) {
564 /* Enqueue into history */
577 /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
578 static int retrans_pkt(void *data)
580 struct sip_pkt *pkt=data;
582 ast_mutex_lock(&pkt->owner->lock);
583 if (pkt->retrans < MAX_RETRANS) {
585 if (sip_debug_test_pvt(pkt->owner)) {
587 ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
589 ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
591 append_history(pkt->owner, "ReTx", pkt->data);
592 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
595 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (pkt->flags & FLAG_FATAL) ? "Critical" : "Non-critical", (pkt->flags & FLAG_RESPONSE) ? "Response" : "Request");
596 append_history(pkt->owner, "MaxRetries", pkt->flags & FLAG_FATAL ? "(Critical)" : "(Non-critical)");
598 if (pkt->flags & FLAG_FATAL) {
599 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
600 ast_mutex_unlock(&pkt->owner->lock);
602 ast_mutex_lock(&pkt->owner->lock);
604 if (pkt->owner->owner) {
605 /* XXX Potential deadlocK?? XXX */
606 ast_queue_hangup(pkt->owner->owner);
607 ast_mutex_unlock(&pkt->owner->owner->lock);
609 /* If no owner, destroy now */
610 pkt->owner->needdestroy = 1;
613 /* Okay, it's not fatal, just continue. XXX If we were nice, we'd free it now, rather than wait for the
614 end of the call XXX */
618 ast_mutex_unlock(&pkt->owner->lock);
622 /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
623 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
626 pkt = malloc(sizeof(struct sip_pkt) + len);
629 memset(pkt, 0, sizeof(struct sip_pkt));
630 memcpy(pkt->data, data, len);
631 pkt->packetlen = len;
632 pkt->next = p->packets;
637 pkt->flags |= FLAG_FATAL;
638 /* Schedule retransmission */
639 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
640 pkt->next = p->packets;
642 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
643 if (!strncasecmp(pkt->data, "INVITE", 6)) {
644 /* Note this is a pending invite */
645 p->pendinginvite = seqno;
650 /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
651 static int __sip_autodestruct(void *data)
653 struct sip_pvt *p = data;
655 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
656 append_history(p, "AutoDestroy", "");
658 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
659 ast_queue_hangup(p->owner);
666 /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
667 static int sip_scheddestroy(struct sip_pvt *p, int ms)
670 if (sip_debug_test_pvt(p))
671 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
673 snprintf(tmp, sizeof(tmp), "%d ms", ms);
674 append_history(p, "SchedDestroy", tmp);
676 if (p->autokillid > -1)
677 ast_sched_del(sched, p->autokillid);
678 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
682 /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
683 static int sip_cancel_destroy(struct sip_pvt *p)
685 if (p->autokillid > -1)
686 ast_sched_del(sched, p->autokillid);
687 append_history(p, "CancelDestroy", "");
692 /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
693 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
695 struct sip_pkt *cur, *prev = NULL;
700 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
701 if (!resp && (seqno == p->pendinginvite)) {
702 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
703 p->pendinginvite = 0;
706 /* this is our baby */
708 prev->next = cur->next;
710 p->packets = cur->next;
711 if (cur->retransid > -1)
712 ast_sched_del(sched, cur->retransid);
720 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
724 /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
725 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
731 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
732 /* this is our baby */
733 if (cur->retransid > -1)
734 ast_sched_del(sched, cur->retransid);
741 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");
745 /*--- send_response: Transmit response on SIP request---*/
746 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
749 if (sip_debug_test_pvt(p)) {
751 ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
753 ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
756 append_history(p, "TxRespRel", req->data);
757 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
759 append_history(p, "TxResp", req->data);
760 res = __sip_xmit(p, req->data, req->len);
767 /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
768 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
771 if (sip_debug_test_pvt(p)) {
773 ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
775 ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
778 append_history(p, "TxReqRel", req->data);
779 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
781 append_history(p, "TxReq", req->data);
782 res = __sip_xmit(p, req->data, req->len);
787 /*--- ditch_braces: Pick out text in braces from character string ---*/
788 static char *ditch_braces(char *tmp)
792 if ((n = strchr(tmp, '<')) ) {
794 while(*c && *c != '>') c++;
796 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
805 /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
806 /* Called from PBX core text message functions */
807 static int sip_sendtext(struct ast_channel *ast, char *text)
809 struct sip_pvt *p = ast->pvt->pvt;
810 if (sip_debug_test_pvt(p))
811 ast_verbose("Sending text %s on %s\n", text, ast->name);
814 if (!text || ast_strlen_zero(text))
816 if (sip_debug_test_pvt(p))
817 ast_verbose("Really sending text %s on %s\n", text, ast->name);
818 transmit_message_with_text(p, text);
824 /*--- mysql_update_peer: Update peer from database ---*/
825 /* This function adds registration state to database */
826 static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
828 if (mysql && (strlen(peer) < 128)) {
833 name = alloca(strlen(peer) * 2 + 1);
834 uname = alloca(strlen(username) * 2 + 1);
836 mysql_real_escape_string(mysql, name, peer, strlen(peer));
837 mysql_real_escape_string(mysql, uname, username, strlen(username));
838 snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"",
839 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
840 ast_mutex_lock(&mysqllock);
841 if (mysql_real_query(mysql, query, strlen(query)))
842 ast_log(LOG_WARNING, "Unable to update database\n");
844 ast_mutex_unlock(&mysqllock);
848 /*--- mysql_peer: Get peer from database ---*/
849 static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
854 p = malloc(sizeof(struct sip_peer));
855 memset(p, 0, sizeof(struct sip_peer));
856 if (mysql && (!peer || (strlen(peer) < 128))) {
861 time_t regseconds, nowtime;
866 name = alloca(strlen(peer) * 2 + 1);
867 mysql_real_escape_string(mysql, name, peer, strlen(peer));
870 snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
872 snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE name=\"%s\"", name);
873 ast_mutex_lock(&mysqllock);
874 mysql_query(mysql, query);
875 if ((result = mysql_store_result(mysql))) {
876 if ((rowval = mysql_fetch_row(result))) {
877 numfields = mysql_num_fields(result);
878 fields = mysql_fetch_fields(result);
880 p->addr.sin_family = AF_INET;
881 for (x=0;x<numfields;x++) {
883 if (!strcasecmp(fields[x].name, "secret")) {
884 strncpy(p->secret, rowval[x], sizeof(p->secret));
885 } else if (!strcasecmp(fields[x].name, "name")) {
886 strncpy(p->name, rowval[x], sizeof(p->name) - 1);
887 } else if (!strcasecmp(fields[x].name, "context")) {
888 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
889 } else if (!strcasecmp(fields[x].name, "username")) {
890 strncpy(p->username, rowval[x], sizeof(p->username) - 1);
891 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
892 inet_aton(rowval[x], &p->addr.sin_addr);
893 } else if (!strcasecmp(fields[x].name, "port")) {
894 if (sscanf(rowval[x], "%i", &port) != 1)
896 p->addr.sin_port = htons(port);
897 } else if (!strcasecmp(fields[x].name, "regseconds")) {
898 if (sscanf(rowval[x], "%li", ®seconds) != 1)
904 if (nowtime > regseconds)
905 memset(&p->addr, 0, sizeof(p->addr));
907 mysql_free_result(result);
910 ast_mutex_unlock(&mysqllock);
917 p->capability = capability;
919 p->dtmfmode = globaldtmfmode;
927 #endif /* MYSQL_FRIENDS */
929 /*--- update_peer: Update peer data in database (if used) ---*/
930 static void update_peer(struct sip_peer *p, int expiry)
934 mysql_update_peer(p->name, &p->addr, p->username, expiry);
939 /*--- find_peer: Locate peer by name or ip address */
940 static struct sip_peer *find_peer(char *peer, struct sockaddr_in *sin)
942 struct sip_peer *p = NULL;
946 /* Find by peer name */
948 if (!strcasecmp(p->name, peer)) {
957 if (!inaddrcmp(&p->addr, sin) ||
959 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))) {
968 p = mysql_peer(peer, sin);
975 /*--- find_user: Locate user by name */
976 static struct sip_user *find_user(char *name)
978 struct sip_user *u = NULL;
982 if (!strcasecmp(u->name, name)) {
991 /*--- sip_debug_test_addr: See if we pass debug IP filter */
992 static int sip_debug_test_addr(struct sockaddr_in *addr) {
993 if (sipdebug == 0) return 0;
994 if (debugaddr.sin_addr.s_addr) {
995 if (((ntohs(debugaddr.sin_port) != 0) &&
996 (debugaddr.sin_port != addr->sin_port)) ||
997 (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1003 static int sip_debug_test_pvt(struct sip_pvt *p) {
1004 return (sipdebug && sip_debug_test_addr((p->nat ? &p->recv : &p->sa)));
1007 /*--- create_addr: create address structure from peer definition ---*/
1008 /* Or, if peer not found, find it in the global DNS */
1009 /* returns TRUE on failure, FALSE on success */
1010 static int create_addr(struct sip_pvt *r, char *peer)
1013 struct ast_hostent ahp;
1018 char host[256], *hostn;
1020 r->sa.sin_family = AF_INET;
1021 ast_mutex_lock(&peerl.lock);
1022 p = find_peer(peer, NULL);
1026 r->capability = p->capability;
1029 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
1030 ast_rtp_setnat(r->rtp, r->nat);
1033 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
1034 ast_rtp_setnat(r->vrtp, r->nat);
1036 strncpy(r->peername, p->username, sizeof(r->peername)-1);
1037 strncpy(r->authname, p->username, sizeof(r->authname)-1);
1038 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
1039 strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
1040 strncpy(r->username, p->username, sizeof(r->username)-1);
1041 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
1042 if (ast_strlen_zero(r->tohost)) {
1043 if (p->addr.sin_addr.s_addr)
1044 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
1046 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
1048 if (!ast_strlen_zero(p->fromdomain))
1049 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
1050 if (!ast_strlen_zero(p->fromuser))
1051 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
1052 r->insecure = p->insecure;
1053 r->canreinvite = p->canreinvite;
1054 r->maxtime = p->maxms;
1055 r->callgroup = p->callgroup;
1056 r->pickupgroup = p->pickupgroup;
1058 r->dtmfmode = p->dtmfmode;
1059 if (r->dtmfmode & SIP_DTMF_RFC2833)
1060 r->noncodeccapability |= AST_RTP_DTMF;
1062 r->noncodeccapability &= ~AST_RTP_DTMF;
1064 strncpy(r->context, p->context,sizeof(r->context)-1);
1065 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1066 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1067 if (p->addr.sin_addr.s_addr) {
1068 r->sa.sin_addr = p->addr.sin_addr;
1069 r->sa.sin_port = p->addr.sin_port;
1071 r->sa.sin_addr = p->defaddr.sin_addr;
1072 r->sa.sin_port = p->defaddr.sin_port;
1074 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1085 ast_mutex_unlock(&peerl.lock);
1087 if ((port=strchr(peer, ':'))) {
1093 portno = atoi(port);
1095 portno = DEFAULT_SIP_PORT;
1100 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1101 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1107 hp = ast_gethostbyname(hostn, &ahp);
1109 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
1110 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
1111 r->sa.sin_port = htons(portno);
1112 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1115 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1131 /*--- auto_congest: Scheduled congestion on a call ---*/
1132 static int auto_congest(void *nothing)
1134 struct sip_pvt *p = nothing;
1135 ast_mutex_lock(&p->lock);
1138 if (!ast_mutex_trylock(&p->owner->lock)) {
1139 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1140 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1141 ast_mutex_unlock(&p->owner->lock);
1144 ast_mutex_unlock(&p->lock);
1148 /*--- sip_prefs_free: Free codec list in preference structure ---*/
1149 static void sip_prefs_free(void)
1151 struct sip_codec_pref *cur, *next;
1161 /*--- sip_pref_remove: Remove codec from pref list ---*/
1162 static void sip_pref_remove(int format)
1164 struct sip_codec_pref *cur, *prev=NULL;
1167 if (cur->codec == format) {
1169 prev->next = cur->next;
1180 /*--- sip_pref_append: Append codec to list ---*/
1181 static int sip_pref_append(int format)
1183 struct sip_codec_pref *cur, *tmp;
1184 sip_pref_remove(format);
1185 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
1188 memset(tmp, 0, sizeof(struct sip_codec_pref));
1189 tmp->codec = format;
1200 /*--- sip_codec_choose: Pick a codec ---*/
1201 static int sip_codec_choose(int formats)
1203 struct sip_codec_pref *cur;
1204 formats &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1207 if (formats & cur->codec)
1211 return ast_best_codec(formats);
1214 /*--- sip_call: Initiate SIP call from PBX ---*/
1215 /* used from the dial() application */
1216 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1220 char *vxml_url = NULL;
1221 char *distinctive_ring = NULL;
1222 struct varshead *headp;
1223 struct ast_var_t *current;
1226 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1227 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1230 /* Check whether there is vxml_url, distinctive ring variables */
1232 headp=&ast->varshead;
1233 AST_LIST_TRAVERSE(headp,current,entries) {
1234 /* Check whether there is a VXML_URL variable */
1235 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
1237 vxml_url = ast_var_value(current);
1240 /* Check whether there is a ALERT_INFO variable */
1241 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
1243 distinctive_ring = ast_var_value(current);
1250 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1251 res = update_user_counter(p,INC_OUT_USE);
1253 p->restrictcid = ast->restrictcid;
1254 p->jointcapability = p->capability;
1255 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
1257 /* Initialize auto-congest time */
1258 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1264 /*--- __sip_destroy: Execute destrucion of call structure, release memory---*/
1265 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1267 struct sip_pvt *cur, *prev = NULL;
1269 struct sip_history *hist;
1270 if (sip_debug_test_pvt(p))
1271 ast_verbose("Destroying call '%s'\n", p->callid);
1272 if (p->stateid > -1)
1273 ast_extension_state_del(p->stateid, NULL);
1275 ast_sched_del(sched, p->initid);
1276 if (p->autokillid > -1)
1277 ast_sched_del(sched, p->autokillid);
1280 ast_rtp_destroy(p->rtp);
1283 ast_rtp_destroy(p->vrtp);
1286 free_old_route(p->route);
1290 /* Carefully unlink from registry */
1291 struct sip_registry *reg;
1292 ast_mutex_lock(®l.lock);
1293 reg = regl.registrations;
1295 if ((reg == p->registry) && (p->registry->call == p))
1296 p->registry->call=NULL;
1299 ast_mutex_unlock(®l.lock);
1301 /* Unlink us from the owner if we have one */
1304 ast_mutex_lock(&p->owner->lock);
1305 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1306 p->owner->pvt->pvt = NULL;
1308 ast_mutex_unlock(&p->owner->lock);
1313 p->history = p->history->next;
1320 prev->next = cur->next;
1329 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1332 ast_sched_del(sched, p->initid);
1333 while((cp = p->packets)) {
1334 p->packets = p->packets->next;
1335 if (cp->retransid > -1)
1336 ast_sched_del(sched, cp->retransid);
1343 /*--- update_user_counter: Handle incominglimit and outgoinglimit for SIP users ---*/
1344 /* Note: This is going to be replaced by app_groupcount */
1345 static int update_user_counter(struct sip_pvt *fup, int event)
1347 char name[256] = "";
1349 strncpy(name, fup->username, sizeof(name) - 1);
1350 ast_mutex_lock(&userl.lock);
1351 u = find_user(name);
1353 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1354 ast_mutex_unlock(&userl.lock);
1358 /* incoming and outgoing affects the inUse counter */
1361 if ( u->inUse > 0 ) {
1369 if (u->incominglimit > 0 ) {
1370 if (u->inUse >= u->incominglimit) {
1371 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
1372 /* inc inUse as well */
1373 if ( event == INC_OUT_USE ) {
1376 ast_mutex_unlock(&userl.lock);
1381 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1383 /* we don't use these anymore
1385 if ( u->outUse > 0 ) {
1392 if ( u->outgoinglimit > 0 ) {
1393 if ( u->outUse >= u->outgoinglimit ) {
1394 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1395 ast_mutex_unlock(&userl.lock);
1403 ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",u->name,event);
1405 ast_mutex_unlock(&userl.lock);
1409 /*--- sip_destroy: Destroy SIP call structure ---*/
1410 static void sip_destroy(struct sip_pvt *p)
1412 ast_mutex_lock(&iflock);
1413 __sip_destroy(p, 1);
1414 ast_mutex_unlock(&iflock);
1418 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1420 static int hangup_sip2cause(int cause)
1422 /* Possible values from causes.h
1423 AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
1424 AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
1428 case 404: /* Not found */
1429 return AST_CAUSE_UNALLOCATED;
1430 case 483: /* Too many hops */
1431 return AST_CAUSE_FAILURE;
1433 return AST_CAUSE_BUSY;
1435 return AST_CAUSE_NORMAL;
1441 static char *hangup_cause2sip(int cause)
1445 case AST_CAUSE_FAILURE:
1446 return "500 Server internal failure";
1447 case AST_CAUSE_CONGESTION:
1448 return "503 Service Unavailable";
1449 case AST_CAUSE_BUSY:
1458 /*--- sip_hangup: Hangup SIP call */
1459 static int sip_hangup(struct ast_channel *ast)
1461 struct sip_pvt *p = ast->pvt->pvt;
1463 int needdestroy = 0;
1465 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1466 if (!ast->pvt->pvt) {
1467 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1470 ast_mutex_lock(&p->lock);
1471 if ( p->outgoing ) {
1472 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
1473 update_user_counter(p, DEC_OUT_USE);
1475 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
1476 update_user_counter(p, DEC_IN_USE);
1478 /* Determine how to disconnect */
1479 if (p->owner != ast) {
1480 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1481 ast_mutex_unlock(&p->lock);
1484 if (!ast || (ast->_state != AST_STATE_UP))
1489 ast_dsp_free(p->vad);
1492 ast->pvt->pvt = NULL;
1494 ast_mutex_lock(&usecnt_lock);
1496 ast_mutex_unlock(&usecnt_lock);
1497 ast_update_use_count();
1500 /* Start the process if it's not already started */
1501 if (!p->alreadygone && !ast_strlen_zero(p->initreq.data)) {
1504 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
1505 /* Actually don't destroy us yet, wait for the 487 on our original
1506 INVITE, but do set an autodestruct just in case. */
1508 sip_scheddestroy(p, 15000);
1509 if ( p->initid != -1 ) {
1510 /* channel still up - reverse dec of inUse counter
1511 only if the channel is not auto-congested */
1512 if ( p->outgoing ) {
1513 update_user_counter(p, INC_OUT_USE);
1516 update_user_counter(p, INC_IN_USE);
1521 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1522 transmit_response_reliable(p, res, &p->initreq, 1);
1524 transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
1527 if (!p->pendinginvite) {
1529 transmit_request_with_auth(p, "BYE", 0, 1, 1);
1531 /* Note we will need a BYE when this all settles out
1532 but we can't send one while we have "INVITE" outstanding. */
1537 p->needdestroy = needdestroy;
1538 ast_mutex_unlock(&p->lock);
1542 /*--- sip_answer: Answer SIP call , send 200 OK on Invite */
1543 static int sip_answer(struct ast_channel *ast)
1547 struct sip_pvt *p = ast->pvt->pvt;
1550 if (ast->_state != AST_STATE_UP) {
1554 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1556 fmt=ast_getformatbyname(codec);
1558 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1559 p->jointcapability=fmt;
1560 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1563 ast_setstate(ast, AST_STATE_UP);
1565 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1566 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1571 /*--- sip_write: Send response, support audio media ---*/
1572 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1574 struct sip_pvt *p = ast->pvt->pvt;
1576 if (frame->frametype == AST_FRAME_VOICE) {
1577 if (!(frame->subclass & ast->nativeformats)) {
1578 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1579 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1583 ast_mutex_lock(&p->lock);
1585 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1586 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1589 res = ast_rtp_write(p->rtp, frame);
1591 ast_mutex_unlock(&p->lock);
1593 } else if (frame->frametype == AST_FRAME_VIDEO) {
1595 ast_mutex_lock(&p->lock);
1597 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1598 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1601 res = ast_rtp_write(p->vrtp, frame);
1603 ast_mutex_unlock(&p->lock);
1605 } else if (frame->frametype == AST_FRAME_IMAGE) {
1608 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1615 /*--- sip_fixup: Fix up a channel: If a channel is consumed, this is called.
1616 Basically update any ->owner links ----*/
1617 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1619 struct sip_pvt *p = newchan->pvt->pvt;
1620 ast_mutex_lock(&p->lock);
1621 if (p->owner != oldchan) {
1622 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1623 ast_mutex_unlock(&p->lock);
1627 ast_mutex_unlock(&p->lock);
1631 /*--- sip_senddigit: Send DTMF character on SIP channel */
1632 /* within one call, we're able to transmit in many methods simultaneously */
1633 static int sip_senddigit(struct ast_channel *ast, char digit)
1635 struct sip_pvt *p = ast->pvt->pvt;
1636 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1637 transmit_info_with_digit(p, digit);
1639 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1640 ast_rtp_senddigit(p->rtp, digit);
1642 /* If in-band DTMF is desired, send that */
1643 if (p->dtmfmode & SIP_DTMF_INBAND)
1649 /*--- sip_transfer: Transfer SIP call */
1650 static int sip_transfer(struct ast_channel *ast, char *dest)
1652 struct sip_pvt *p = ast->pvt->pvt;
1654 res = transmit_refer(p, dest);
1658 /*--- sip_indicate: Play indication to user */
1659 /* With SIP a lot of indications is sent as messages, letting the device play
1660 the indication - busy signal, congestion etc */
1661 static int sip_indicate(struct ast_channel *ast, int condition)
1663 struct sip_pvt *p = ast->pvt->pvt;
1665 case AST_CONTROL_RINGING:
1666 if (ast->_state == AST_STATE_RING) {
1668 transmit_response(p, "180 Ringing", &p->initreq);
1672 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1676 case AST_CONTROL_BUSY:
1677 if (ast->_state != AST_STATE_UP) {
1678 transmit_response(p, "486 Busy Here", &p->initreq);
1680 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1684 case AST_CONTROL_CONGESTION:
1685 if (ast->_state != AST_STATE_UP) {
1686 transmit_response(p, "503 Service Unavailable", &p->initreq);
1688 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1692 case AST_CONTROL_PROGRESS:
1693 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1694 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1702 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1710 /*--- sip_new: Initiate a call in the SIP channel */
1711 /* called from sip_request_call (calls from the pbx ) */
1712 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1714 struct ast_channel *tmp;
1716 tmp = ast_channel_alloc(1);
1718 /* Select our native format based on codec preference until we receive
1719 something from another device to the contrary. */
1720 if (i->jointcapability)
1721 tmp->nativeformats = sip_codec_choose(i->jointcapability);
1722 else if (i->capability)
1723 tmp->nativeformats = sip_codec_choose(i->capability);
1725 tmp->nativeformats = sip_codec_choose(capability);
1726 fmt = ast_best_codec(tmp->nativeformats);
1728 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1730 if (strchr(i->fromdomain,':'))
1732 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1736 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1739 if (i->dtmfmode & SIP_DTMF_INBAND) {
1740 i->vad = ast_dsp_new();
1741 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1743 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
1745 tmp->fds[0] = ast_rtp_fd(i->rtp);
1746 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1748 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1749 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1751 if (state == AST_STATE_RING)
1753 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1754 tmp->writeformat = fmt;
1755 tmp->pvt->rawwriteformat = fmt;
1756 tmp->readformat = fmt;
1757 tmp->pvt->rawreadformat = fmt;
1759 tmp->pvt->send_text = sip_sendtext;
1760 tmp->pvt->call = sip_call;
1761 tmp->pvt->hangup = sip_hangup;
1762 tmp->pvt->answer = sip_answer;
1763 tmp->pvt->read = sip_read;
1764 tmp->pvt->write = sip_write;
1765 tmp->pvt->write_video = sip_write;
1766 tmp->pvt->indicate = sip_indicate;
1767 tmp->pvt->transfer = sip_transfer;
1768 tmp->pvt->fixup = sip_fixup;
1769 tmp->pvt->send_digit = sip_senddigit;
1771 tmp->pvt->bridge = ast_rtp_bridge;
1773 tmp->callgroup = i->callgroup;
1774 tmp->pickupgroup = i->pickupgroup;
1775 tmp->restrictcid = i->restrictcid;
1776 if (!ast_strlen_zero(i->accountcode))
1777 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1779 tmp->amaflags = i->amaflags;
1780 if (!ast_strlen_zero(i->language))
1781 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1782 if (!ast_strlen_zero(i->musicclass))
1783 strncpy(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass)-1);
1785 ast_mutex_lock(&usecnt_lock);
1787 ast_mutex_unlock(&usecnt_lock);
1788 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1789 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1790 if (!ast_strlen_zero(i->callerid))
1791 tmp->callerid = strdup(i->callerid);
1792 if (!ast_strlen_zero(i->rdnis))
1793 tmp->rdnis = strdup(i->rdnis);
1794 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
1795 tmp->dnid = strdup(i->exten);
1797 if (!ast_strlen_zero(i->domain)) {
1798 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1800 if (!ast_strlen_zero(i->useragent)) {
1801 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
1803 if (!ast_strlen_zero(i->callid)) {
1804 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
1806 ast_setstate(tmp, state);
1807 if (state != AST_STATE_DOWN) {
1808 if (ast_pbx_start(tmp)) {
1809 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1815 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1819 static struct cfalias {
1823 { "Content-Type", "c" },
1824 { "Content-Encoding", "e" },
1828 { "Content-Length", "l" },
1831 { "Supported", "k" },
1832 { "Refer-To", "r" },
1833 { "Allow-Events", "u" },
1838 /*--- get_sdp_by_line: Reads one line of SIP message body */
1839 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1840 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1841 char* r = line + nameLen + 1;
1842 while (*r && (*r < 33)) ++r;
1849 /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
1850 but the name wrongly applies _only_ sdp */
1851 static char *get_sdp(struct sip_request *req, char *name) {
1853 int len = strlen(name);
1856 for (x=0; x<req->lines; x++) {
1857 r = get_sdp_by_line(req->line[x], name, len);
1858 if (r[0] != '\0') return r;
1864 static void sdpLineNum_iterator_init(int* iterator) {
1868 static char* get_sdp_iterate(int* iterator,
1869 struct sip_request *req, char *name) {
1870 int len = strlen(name);
1872 while (*iterator < req->lines) {
1873 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1874 if (r[0] != '\0') return r;
1879 static char *__get_header(struct sip_request *req, char *name, int *start)
1882 int len = strlen(name);
1884 for (x=*start;x<req->headers;x++) {
1885 if (!strncasecmp(req->header[x], name, len) &&
1886 (req->header[x][len] == ':')) {
1887 r = req->header[x] + len + 1;
1888 while(*r && (*r < 33))
1895 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1896 if (!strcasecmp(aliases[x].fullname, name))
1897 return __get_header(req, aliases[x].shortname, start);
1899 /* Don't return NULL, so get_header is always a valid pointer */
1903 /*--- get_header: Get header from SIP request ---*/
1904 static char *get_header(struct sip_request *req, char *name)
1907 return __get_header(req, name, &start);
1910 /*--- sip_rtp_read: Read RTP from network ---*/
1911 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1913 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1914 struct ast_frame *f;
1915 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1918 f = ast_rtp_read(p->rtp); /* RTP Audio */
1921 f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
1924 f = ast_rtp_read(p->vrtp); /* RTP Video */
1927 f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
1932 /* Don't send RFC2833 if we're not supposed to */
1933 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1936 /* We already hold the channel lock */
1937 if (f->frametype == AST_FRAME_VOICE) {
1938 if (f->subclass != p->owner->nativeformats) {
1939 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1940 p->owner->nativeformats = f->subclass;
1941 ast_set_read_format(p->owner, p->owner->readformat);
1942 ast_set_write_format(p->owner, p->owner->writeformat);
1944 if ((p->dtmfmode & SIP_DTMF_INBAND) && p->vad) {
1945 f = ast_dsp_process(p->owner,p->vad,f);
1946 if (f && (f->frametype == AST_FRAME_DTMF))
1947 ast_log(LOG_DEBUG, "Detected DTMF '%c'\n", f->subclass);
1954 /*--- sip_read: Read SIP RTP from channel */
1955 static struct ast_frame *sip_read(struct ast_channel *ast)
1957 struct ast_frame *fr;
1958 struct sip_pvt *p = ast->pvt->pvt;
1959 ast_mutex_lock(&p->lock);
1960 fr = sip_rtp_read(ast, p);
1961 ast_mutex_unlock(&p->lock);
1965 /*--- build_callid: Build SIP CALLID header ---*/
1966 static void build_callid(char *callid, int len, struct in_addr ourip)
1973 res = snprintf(callid, len, "%08x", val);
1977 /* It's not important that we really use our right IP here... */
1978 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1981 /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
1982 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1986 p = malloc(sizeof(struct sip_pvt));
1989 /* Keep track of stuff */
1990 memset(p, 0, sizeof(struct sip_pvt));
1994 p->rtp = ast_rtp_new(sched, io, 1, 0);
1996 p->vrtp = ast_rtp_new(sched, io, 1, 0);
2000 /* Start with 101 instead of 1 */
2003 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
2007 ast_rtp_settos(p->rtp, tos);
2009 ast_rtp_settos(p->vrtp, tos);
2010 if (useglobalnat && sin) {
2011 /* Setup NAT structure according to global settings if we have an address */
2013 memcpy(&p->recv, sin, sizeof(p->recv));
2014 ast_rtp_setnat(p->rtp, p->nat);
2016 ast_rtp_setnat(p->vrtp, p->nat);
2018 ast_mutex_init(&p->lock);
2021 memcpy(&p->sa, sin, sizeof(p->sa));
2022 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
2023 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2025 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2027 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2028 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2030 build_callid(p->callid, sizeof(p->callid), p->ourip);
2032 strncpy(p->callid, callid, sizeof(p->callid) - 1);
2033 /* Assume reinvite OK and via INVITE */
2034 p->canreinvite = globalcanreinvite;
2035 /* Assign default music on hold class */
2036 strncpy(p->musicclass, globalmusicclass, sizeof(p->musicclass));
2037 p->dtmfmode = globaldtmfmode;
2038 p->capability = capability;
2039 if (p->dtmfmode & SIP_DTMF_RFC2833)
2040 p->noncodeccapability |= AST_RTP_DTMF;
2041 strncpy(p->context, context, sizeof(p->context) - 1);
2042 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
2044 ast_mutex_lock(&iflock);
2047 ast_mutex_unlock(&iflock);
2049 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
2053 /*--- find_call: Connect incoming SIP message to current call or create new call structure */
2054 /* Called by handle_request ,sipsock_read */
2055 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
2063 callid = get_header(req, "Call-ID");
2065 if (pedanticsipchecking) {
2066 /* In principle Call-ID's uniquely identify a call, however some vendors
2067 (i.e. Pingtel) send multiple calls with the same Call-ID and different
2068 tags in order to simplify billing. The RFC does state that we have to
2069 compare tags in addition to the call-id, but this generate substantially
2070 more overhead which is totally unnecessary for the vast majority of sane
2071 SIP implementations, and thus Asterisk does not enable this behavior
2072 by default. Short version: You'll need this option to support conferencing
2074 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
2076 c = strchr(tmp, ' ');
2079 if (!strcasecmp(cmd, "SIP/2.0")) {
2085 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
2087 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2088 tag = strstr(tmp, "tag=");
2091 c = strchr(tag, ';');
2098 if (ast_strlen_zero(callid)) {
2099 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
2102 ast_mutex_lock(&iflock);
2105 if (!strcmp(p->callid, callid) &&
2106 (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) {
2107 /* Found the call */
2108 ast_mutex_lock(&p->lock);
2109 ast_mutex_unlock(&iflock);
2114 ast_mutex_unlock(&iflock);
2115 p = sip_alloc(callid, sin, 1);
2117 ast_mutex_lock(&p->lock);
2121 /*--- sip_register: Parse register=> line in sip.conf and add to registry */
2122 static int sip_register(char *value, int lineno)
2124 struct sip_registry *reg;
2125 char copy[256] = "";
2126 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
2132 struct ast_hostent ahp;
2135 strncpy(copy, value, sizeof(copy)-1);
2138 hostname = strrchr(stringp, '@');
2143 if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
2144 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
2148 username = strsep(&stringp, ":");
2150 secret = strsep(&stringp, ":");
2152 authuser = strsep(&stringp, ":");
2155 hostname = strsep(&stringp, "/");
2157 contact = strsep(&stringp, "/");
2158 if (!contact || ast_strlen_zero(contact))
2161 hostname = strsep(&stringp, ":");
2162 porta = strsep(&stringp, ":");
2164 if (porta && !atoi(porta)) {
2165 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
2168 hp = ast_gethostbyname(hostname, &ahp);
2170 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
2173 reg = malloc(sizeof(struct sip_registry));
2175 memset(reg, 0, sizeof(struct sip_registry));
2176 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
2178 strncpy(reg->username, username, sizeof(reg->username)-1);
2180 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
2182 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
2184 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
2187 reg->refresh = default_expiry;
2188 reg->addr.sin_family = AF_INET;
2189 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
2190 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
2191 reg->callid_valid = 0;
2193 ast_mutex_lock(®l.lock);
2194 reg->next = regl.registrations;
2195 regl.registrations = reg;
2196 ast_mutex_unlock(®l.lock);
2198 ast_log(LOG_ERROR, "Out of memory\n");
2204 /*--- lws2sws: Parse multiline SIP headers into one header */
2205 /* This is enabled if pedanticsipchecking is enabled */
2206 static int lws2sws(char *msgbuf, int len)
2212 /* Eliminate all CRs */
2213 if (msgbuf[h] == '\r') {
2217 /* Check for end-of-line */
2218 if (msgbuf[h] == '\n') {
2219 /* Check for end-of-message */
2222 /* Check for a continuation line */
2223 if (msgbuf[h + 1] == ' ') {
2224 /* Merge continuation line */
2228 /* Propagate LF and start new line */
2229 msgbuf[t++] = msgbuf[h++];
2234 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
2239 msgbuf[t++] = msgbuf[h++];
2243 msgbuf[t++] = msgbuf[h++];
2251 /*--- parse: Parse a SIP message ----*/
2252 static void parse(struct sip_request *req)
2254 /* Divide fields by NULL's */
2259 /* First header starts immediately */
2263 /* We've got a new header */
2267 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2269 if (ast_strlen_zero(req->header[f])) {
2270 /* Line by itself means we're now in content */
2274 if (f >= SIP_MAX_HEADERS - 1) {
2275 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2278 req->header[f] = c + 1;
2279 } else if (*c == '\r') {
2280 /* Ignore but eliminate \r's */
2285 /* Check for last header */
2286 if (!ast_strlen_zero(req->header[f]))
2289 /* Now we process any mime content */
2294 /* We've got a new line */
2297 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2299 if (f >= SIP_MAX_LINES - 1) {
2300 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2303 req->line[f] = c + 1;
2304 } else if (*c == '\r') {
2305 /* Ignore and eliminate \r's */
2310 /* Check for last line */
2311 if (!ast_strlen_zero(req->line[f]))
2315 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2318 /*--- process_sdp: Process SIP SDP ---*/
2319 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2328 int peercapability, peernoncodeccapability;
2329 int vpeercapability=0, vpeernoncodeccapability=0;
2330 struct sockaddr_in sin;
2333 struct ast_hostent ahp;
2339 /* Get codec and RTP info from SDP */
2340 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2341 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2344 m = get_sdp(req, "m");
2345 c = get_sdp(req, "c");
2346 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
2347 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2350 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2351 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2354 /* XXX This could block for a long time, and block the main thread! XXX */
2355 hp = ast_gethostbyname(host, &ahp);
2357 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2360 sdpLineNum_iterator_init(&iterator);
2361 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2362 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
2364 /* Scan through the RTP payload types specified in a "m=" line: */
2365 ast_rtp_pt_clear(p->rtp);
2367 while(!ast_strlen_zero(codecs)) {
2368 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2369 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2372 if (sip_debug_test_pvt(p))
2373 ast_verbose("Found RTP audio format %d\n", codec);
2374 ast_rtp_set_m_type(p->rtp, codec);
2376 /* Skip over any whitespace */
2377 while(*codecs && (*codecs < 33)) codecs++;
2381 ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
2383 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2385 /* Scan through the RTP payload types specified in a "m=" line: */
2387 while(!ast_strlen_zero(codecs)) {
2388 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2389 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2392 if (sip_debug_test_pvt(p))
2393 ast_verbose("Found video format %s\n", ast_getformatname(codec));
2394 ast_rtp_set_m_type(p->vrtp, codec);
2396 /* Skip over any whitespace */
2397 while(*codecs && (*codecs < 33)) codecs++;
2401 sin.sin_family = AF_INET;
2402 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2403 /* Setup audio port number */
2404 sin.sin_port = htons(portno);
2405 if (p->rtp && sin.sin_port)
2406 ast_rtp_set_peer(p->rtp, &sin);
2407 /* Setup video port number */
2408 sin.sin_port = htons(vportno);
2409 if (p->vrtp && sin.sin_port)
2410 ast_rtp_set_peer(p->vrtp, &sin);
2412 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2414 /* Next, scan through each "a=rtpmap:" line, noting each
2415 * specified RTP payload type (with corresponding MIME subtype):
2417 sdpLineNum_iterator_init(&iterator);
2418 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2419 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2420 if (!strcasecmp(a, "sendonly")) {
2424 if (!strcasecmp(a, "sendrecv")) {
2427 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2428 if (sip_debug_test_pvt(p))
2429 ast_verbose("Found description format %s\n", mimeSubtype);
2430 /* Note: should really look at the 'freq' and '#chans' params too */
2431 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2433 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2436 /* Now gather all of the codecs that were asked for: */
2437 ast_rtp_get_current_formats(p->rtp,
2438 &peercapability, &peernoncodeccapability);
2440 ast_rtp_get_current_formats(p->vrtp,
2441 &vpeercapability, &vpeernoncodeccapability);
2442 p->jointcapability = p->capability & (peercapability | vpeercapability);
2443 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
2445 if (sip_debug_test_pvt(p)) {
2446 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
2447 p->capability, peercapability, vpeercapability, p->jointcapability);
2448 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
2449 noncodeccapability, peernoncodeccapability,
2450 p->noncodeccapability);
2452 if (!p->jointcapability) {
2453 ast_log(LOG_WARNING, "No compatible codecs!\n");
2457 if (!(p->owner->nativeformats & p->jointcapability)) {
2458 ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->jointcapability, p->owner->nativeformats);
2459 p->owner->nativeformats = sip_codec_choose(p->jointcapability);
2460 ast_set_read_format(p->owner, p->owner->readformat);
2461 ast_set_write_format(p->owner, p->owner->writeformat);
2463 if (p->owner->bridge) {
2464 /* Turn on/off music on hold if we are holding/unholding */
2465 if (sin.sin_addr.s_addr && !sendonly) {
2466 ast_moh_stop(p->owner->bridge);
2468 ast_moh_start(p->owner->bridge, NULL);
2476 /*--- add_header: Add header to SIP message */
2477 static int add_header(struct sip_request *req, char *var, char *value)
2479 if (req->len >= sizeof(req->data) - 4) {
2480 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2484 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2487 req->header[req->headers] = req->data + req->len;
2488 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2489 req->len += strlen(req->header[req->headers]);
2490 if (req->headers < SIP_MAX_HEADERS)
2493 ast_log(LOG_WARNING, "Out of header space\n");
2499 /*--- add_blank_header: Add blank header to SIP message */
2500 static int add_blank_header(struct sip_request *req)
2502 if (req->len >= sizeof(req->data) - 4) {
2503 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2507 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2510 req->header[req->headers] = req->data + req->len;
2511 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2512 req->len += strlen(req->header[req->headers]);
2513 if (req->headers < SIP_MAX_HEADERS)
2516 ast_log(LOG_WARNING, "Out of header space\n");
2522 /*--- add_line: Add content (not header) to SIP message */
2523 static int add_line(struct sip_request *req, char *line)
2525 if (req->len >= sizeof(req->data) - 4) {
2526 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2530 /* Add extra empty return */
2531 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2532 req->len += strlen(req->data + req->len);
2534 req->line[req->lines] = req->data + req->len;
2535 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2536 req->len += strlen(req->line[req->lines]);
2537 if (req->lines < SIP_MAX_LINES)
2540 ast_log(LOG_WARNING, "Out of line space\n");
2546 /*--- copy_header: Copy one header field from one request to another */
2547 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2550 tmp = get_header(orig, field);
2551 if (!ast_strlen_zero(tmp)) {
2552 /* Add what we're responding to */
2553 return add_header(req, field, tmp);
2555 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2559 /*--- copy_all_header: Copy all headers from one request to another ---*/
2560 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2566 tmp = __get_header(orig, field, &start);
2567 if (!ast_strlen_zero(tmp)) {
2568 /* Add what we're responding to */
2569 add_header(req, field, tmp);
2574 return copied ? 0 : -1;
2577 /*--- copy_via_headers: Copy SIP VIA Headers from one request to another ---*/
2578 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2585 tmp = __get_header(orig, field, &start);
2586 if (!ast_strlen_zero(tmp)) {
2587 if (!copied && p->nat) {
2588 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2589 /* SLD: FIXME: Nice try, but the received= should not have a port */
2590 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2591 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
2593 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2594 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2597 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2598 add_header(req, field, new);
2600 /* Add what we're responding to */
2601 add_header(req, field, tmp);
2608 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2614 /*--- add_route: Add route header into request per learned route ---*/
2615 static void add_route(struct sip_request *req, struct sip_route *route)
2618 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2624 n = strlen(route->hop);
2625 if ((n+3)>rem) break;
2631 strcpy(p, route->hop); p += n;
2634 route = route->next;
2637 add_header(req, "Route", r);
2640 /*--- set_destination: Set destination from SIP URI ---*/
2641 static void set_destination(struct sip_pvt *p, char *uri)
2643 char *h, *maddr, hostname[256];
2646 struct ast_hostent ahp;
2648 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2649 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2651 if (sip_debug_test_pvt(p))
2652 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2654 /* Find and parse hostname */
2655 h = strchr(uri, '@');
2660 if (strncmp(h, "sip:", 4) == 0)
2662 else if (strncmp(h, "sips:", 5) == 0)
2665 hn = strcspn(h, ":;>");
2667 strncpy(hostname, h, hn); hostname[hn] = '\0';
2670 /* Is "port" present? if not default to 5060 */
2674 port = strtol(h, &h, 10);
2679 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2680 maddr = strstr(h, "maddr=");
2683 hn = strspn(maddr, "0123456789.");
2685 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2688 hp = ast_gethostbyname(hostname, &ahp);
2690 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2693 p->sa.sin_family = AF_INET;
2694 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2695 p->sa.sin_port = htons(port);
2696 if (sip_debug_test_pvt(p))
2697 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2700 /*--- init_resp: Initialize SIP response, based on SIP request ---*/
2701 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2703 /* Initialize a response */
2704 if (req->headers || req->len) {
2705 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2708 req->header[req->headers] = req->data + req->len;
2709 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2710 req->len += strlen(req->header[req->headers]);
2711 if (req->headers < SIP_MAX_HEADERS)
2714 ast_log(LOG_WARNING, "Out of header space\n");
2718 /*--- init_req: Initialize SIP request ---*/
2719 static int init_req(struct sip_request *req, char *resp, char *recip)
2721 /* Initialize a response */
2722 if (req->headers || req->len) {
2723 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2726 req->header[req->headers] = req->data + req->len;
2727 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2728 req->len += strlen(req->header[req->headers]);
2729 if (req->headers < SIP_MAX_HEADERS)
2732 ast_log(LOG_WARNING, "Out of header space\n");
2737 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2739 char newto[256] = "", *ot;
2740 memset(resp, 0, sizeof(*resp));
2741 init_resp(resp, msg, req);
2742 copy_via_headers(p, resp, req, "Via");
2743 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2744 copy_header(resp, req, "From");
2745 ot = get_header(req, "To");
2746 if (!strstr(ot, "tag=")) {
2747 /* Add the proper tag if we don't have it already. If they have specified
2748 their tag, use it. Otherwise, use our own tag */
2749 if (!ast_strlen_zero(p->theirtag) && p->outgoing)
2750 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2751 else if (p->tag && !p->outgoing)
2752 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2754 strncpy(newto, ot, sizeof(newto) - 1);
2757 add_header(resp, "To", ot);
2758 copy_header(resp, req, "Call-ID");
2759 copy_header(resp, req, "CSeq");
2760 add_header(resp, "User-Agent", "Asterisk PBX");
2761 add_header(resp, "Allow", ALLOWED_METHODS);
2763 /* For registration responses, we also need expiry and
2767 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2768 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2769 add_header(resp, "Expires", tmp);
2770 add_header(resp, "Contact", contact);
2772 add_header(resp, "Contact", p->our_contact);
2777 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno, int newbranch)
2779 struct sip_request *orig = &p->initreq;
2780 char stripped[80] ="";
2786 memset(req, 0, sizeof(struct sip_request));
2788 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2796 p->branch ^= rand();
2797 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2800 if (!ast_strlen_zero(p->uri)) {
2804 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2806 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2808 c = strchr(stripped, '<');
2820 init_req(req, msg, c);
2822 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2824 add_header(req, "Via", p->via);
2826 set_destination(p, p->route->hop);
2827 add_route(req, p->route->next);
2830 ot = get_header(orig, "To");
2831 of = get_header(orig, "From");
2833 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2834 as our original request, including tag (or presumably lack thereof) */
2835 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2836 /* Add the proper tag if we don't have it already. If they have specified
2837 their tag, use it. Otherwise, use our own tag */
2838 if (p->outgoing && !ast_strlen_zero(p->theirtag))
2839 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2840 else if (!p->outgoing)
2841 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2843 snprintf(newto, sizeof(newto), "%s", ot);
2848 add_header(req, "From", of);
2849 add_header(req, "To", ot);
2851 add_header(req, "From", ot);
2852 add_header(req, "To", of);
2854 add_header(req, "Contact", p->our_contact);
2855 copy_header(req, orig, "Call-ID");
2856 add_header(req, "CSeq", tmp);
2858 add_header(req, "User-Agent", "Asterisk PBX");
2862 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2864 struct sip_request resp;
2866 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2867 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2870 respprep(&resp, p, msg, req);
2871 add_header(&resp, "Content-Length", "0");
2872 add_blank_header(&resp);
2873 return send_response(p, &resp, reliable, seqno);
2876 /*--- transmit_response: Transmit response, no retransmits */
2877 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2879 return __transmit_response(p, msg, req, 0);
2882 /*--- transmit_response: Transmit response, Make sure you get a reply */
2883 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
2885 return __transmit_response(p, msg, req, fatal ? 2 : 1);
2888 /*--- append_date: Append date to SIP message ---*/
2889 static void append_date(struct sip_request *req)
2896 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2897 add_header(req, "Date", tmpdat);
2900 /*--- transmit_response_with_date: Append date and content length before transmitting response ---*/
2901 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2903 struct sip_request resp;
2904 respprep(&resp, p, msg, req);
2906 add_header(&resp, "Content-Length", "0");
2907 add_blank_header(&resp);
2908 return send_response(p, &resp, 0, 0);
2911 /*--- transmit_response_with_allow: Append Accept header, content length before transmitting response ---*/
2912 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2914 struct sip_request resp;
2915 respprep(&resp, p, msg, req);
2916 add_header(&resp, "Accept", "application/sdp");
2917 add_header(&resp, "Content-Length", "0");
2918 add_blank_header(&resp);
2919 return send_response(p, &resp, reliable, 0);
2922 /* transmit_response_with_auth: Respond with authorization request */
2923 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2925 struct sip_request resp;
2928 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2929 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2932 snprintf(tmp, sizeof(tmp), "Digest realm=\"%s\", nonce=\"%s\"", global_realm, randdata);
2933 respprep(&resp, p, msg, req);
2934 add_header(&resp, "Proxy-Authenticate", tmp);
2935 add_header(&resp, "Content-Length", "0");
2936 add_blank_header(&resp);
2937 return send_response(p, &resp, reliable, seqno);
2940 /*--- add_text: Add text body to SIP message ---*/
2941 static int add_text(struct sip_request *req, char *text)
2943 /* XXX Convert \n's to \r\n's XXX */
2944 int len = strlen(text);
2946 snprintf(clen, sizeof(clen), "%d", len);
2947 add_header(req, "Content-Type", "text/plain");
2948 add_header(req, "Content-Length", clen);
2949 add_line(req, text);
2953 /*--- add_digit: add DTMF INFO tone to sip message ---*/
2954 /* Always adds default duration 250 ms, regardless of what came in over the line */
2955 static int add_digit(struct sip_request *req, char digit)
2960 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2962 snprintf(clen, sizeof(clen), "%d", len);
2963 add_header(req, "Content-Type", "application/dtmf-relay");
2964 add_header(req, "Content-Length", clen);
2969 /*--- add_sdp: Add Session Description Protocol message ---*/
2970 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2974 int alreadysent = 0;
2976 struct sockaddr_in sin;
2977 struct sockaddr_in vsin;
2978 struct sip_codec_pref *cur;
2989 struct sockaddr_in dest;
2990 struct sockaddr_in vdest = { 0, };
2991 /* XXX We break with the "recommendation" and send our IP, in order that our
2992 peer doesn't have to ast_gethostbyname() us XXX */
2995 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2998 if (!p->sessionid) {
2999 p->sessionid = getpid();
3000 p->sessionversion = p->sessionid;
3002 p->sessionversion++;
3003 ast_rtp_get_us(p->rtp, &sin);
3005 ast_rtp_get_us(p->vrtp, &vsin);
3007 if (p->redirip.sin_addr.s_addr) {
3008 dest.sin_port = p->redirip.sin_port;
3009 dest.sin_addr = p->redirip.sin_addr;
3011 ast_rtp_get_peer(rtp, &dest);
3013 dest.sin_addr = p->ourip;
3014 dest.sin_port = sin.sin_port;
3017 /* Determine video destination */
3019 if (p->vredirip.sin_addr.s_addr) {
3020 vdest.sin_port = p->vredirip.sin_port;
3021 vdest.sin_addr = p->vredirip.sin_addr;
3023 ast_rtp_get_peer(vrtp, &vdest);
3025 vdest.sin_addr = p->ourip;
3026 vdest.sin_port = vsin.sin_port;
3029 if (sip_debug_test_pvt(p))
3030 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
3031 if (sip_debug_test_pvt(p) && p->vrtp)
3032 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
3033 snprintf(v, sizeof(v), "v=0\r\n");
3034 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
3035 snprintf(s, sizeof(s), "s=session\r\n");
3036 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
3037 snprintf(t, sizeof(t), "t=0 0\r\n");
3038 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
3039 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
3040 if (p->jointcapability & p->prefcodec) {
3041 if (sip_debug_test_pvt(p))
3042 ast_verbose("Answering/Requesting with root capability %d\n", p->prefcodec);
3043 codec = ast_rtp_lookup_code(p->rtp, 1, p->prefcodec);
3045 snprintf(costr, sizeof(costr), " %d", codec);
3046 if (p->prefcodec <= AST_FORMAT_MAX_AUDIO) {
3047 strncat(m, costr, sizeof(m) - strlen(m));
3048 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
3049 strncat(a, costr, sizeof(a));
3051 strncat(m2, costr, sizeof(m2) - strlen(m2));
3052 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
3053 strncat(a2, costr, sizeof(a2));
3056 alreadysent |= p->prefcodec;
3058 /* Start by sending our preferred codecs */
3061 if (p->jointcapability & cur->codec) {
3062 if (sip_debug_test_pvt(p))