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 <sys/socket.h>
38 #include <sys/ioctl.h>
45 #include <arpa/inet.h>
46 #include <sys/signal.h>
47 #include <netinet/ip.h>
49 /* #define VOCAL_DATA_HACK */
52 #define DEFAULT_DEFAULT_EXPIREY 120
53 #define DEFAULT_MAX_EXPIREY 3600
55 #define SIP_DTMF_RFC2833 (1 << 0)
56 #define SIP_DTMF_INBAND (1 << 1)
57 #define SIP_DTMF_INFO (1 << 2)
59 static int max_expirey = DEFAULT_MAX_EXPIREY;
60 static int default_expirey = DEFAULT_DEFAULT_EXPIREY;
62 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
64 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
65 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
66 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
68 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
69 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
71 static char *desc = "Session Initiation Protocol (SIP)";
72 static char *type = "sip";
73 static char *tdesc = "Session Initiation Protocol (SIP)";
74 static char *config = "sip.conf";
76 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
77 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
79 static char context[AST_MAX_EXTENSION] = "default";
81 static char language[MAX_LANGUAGE] = "";
83 static char callerid[AST_MAX_EXTENSION] = "asterisk";
85 static char fromdomain[AST_MAX_EXTENSION] = "";
88 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
90 /* Protect the interface list (of sip_pvt's) */
91 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
93 /* Protect the monitoring thread, so only one process can kill or start it, and not
94 when it's doing something critical. */
95 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
97 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
99 /* This is the thread for the monitor which checks for input on the channels
100 which are not currently in use. */
101 static pthread_t monitor_thread = 0;
103 static int restart_monitor(void);
105 /* Codecs that we support by default: */
106 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
107 static int noncodeccapability = AST_RTP_DTMF;
109 static char ourhost[256];
110 static struct in_addr __ourip;
113 static int sipdebug = 0;
117 static int globaldtmfmode = SIP_DTMF_RFC2833;
120 static int expirey = 900;
122 static struct sched_context *sched;
123 static struct io_context *io;
124 /* The private structures of the sip channels are linked for
125 selecting outgoing channels */
127 #define SIP_MAX_HEADERS 64
128 #define SIP_MAX_LINES 64
130 static struct sip_codec_pref {
132 struct sip_codec_pref *next;
136 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
137 char *rlPart2; /* The Request URI or Response Status */
139 int headers; /* SIP Headers */
140 char *header[SIP_MAX_HEADERS];
141 int lines; /* SDP Content */
142 char *line[SIP_MAX_LINES];
143 char data[SIP_MAX_PACKET];
149 struct sip_route *next;
153 static struct sip_pvt {
154 pthread_mutex_t lock; /* Channel private lock */
155 char callid[80]; /* Global CallID */
156 char randdata[80]; /* Random data */
157 unsigned int ocseq; /* Current outgoing seqno */
158 unsigned int icseq; /* Current incoming seqno */
159 int lastinvite; /* Last Cseq of invite */
160 int alreadygone; /* Whether or not we've already been destroyed by or peer */
161 int needdestroy; /* if we need to be destroyed */
162 int capability; /* Special capability */
163 int noncodeccapability;
164 int outgoing; /* Outgoing or incoming call? */
165 int insecure; /* Don't check source port/ip */
166 int expirey; /* How long we take to expire */
167 int branch; /* One random number */
168 int canreinvite; /* Do we support reinvite */
169 int progress; /* Have sent 183 message progress */
170 int tag; /* Another random number */
171 int nat; /* Whether to try to support NAT */
172 struct sockaddr_in sa; /* Our peer */
173 struct sockaddr_in recv; /* Received as */
174 struct in_addr ourip; /* Our IP */
175 struct ast_channel *owner; /* Who owns us */
176 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
177 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
178 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
179 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
180 struct sip_pvt *refer_call; /* Call we are referring */
181 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
182 char remote_party_id[256];
183 char context[AST_MAX_EXTENSION];
184 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
185 char language[MAX_LANGUAGE];
186 char theirtag[256]; /* Their tag */
190 char callerid[256]; /* Caller*ID */
192 char accountcode[256]; /* Account code */
193 char realm[256]; /* Authorization realm */
194 char nonce[256]; /* Authorization nonce */
195 int amaflags; /* AMA Flags */
196 int pendinginvite; /* Any pending invite */
197 int pendingbye; /* Need to send bye after we ack? */
198 struct sip_request initreq; /* Initial request */
200 int maxtime; /* Max time for first response */
201 int initid; /* Auto-congest ID if appropriate */
202 int autokillid; /* Auto-kill ID */
211 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
212 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
213 struct ast_rtp *rtp; /* RTP Session */
214 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
215 struct sip_pvt *next;
219 struct sip_pkt *next; /* Next packet */
220 int retrans; /* Retransmission number */
221 int seqno; /* Sequence number */
222 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
223 struct sip_pvt *owner; /* Owner call */
224 int retransid; /* Retransmission ID */
225 int packetlen; /* Length of packet */
230 /* Users who can access various contexts */
236 char accountcode[80];
244 struct sip_user *next;
250 char context[80]; /* JK02: peers need context too to allow parking etc */
254 char mailbox[AST_MAX_EXTENSION];
265 struct sockaddr_in addr;
269 struct sip_pvt *call; /* Call pointer */
270 int pokeexpire; /* When to expire poke */
271 int lastms; /* How long last response took (in ms), or -1 for no response */
272 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
273 struct timeval ps; /* Ping send time */
275 struct sockaddr_in defaddr;
279 struct sip_peer *next;
282 static struct ast_user_list {
283 struct sip_user *users;
284 pthread_mutex_t lock;
285 } userl = { NULL, AST_MUTEX_INITIALIZER };
287 static struct ast_peer_list {
288 struct sip_peer *peers;
289 pthread_mutex_t lock;
290 } peerl = { NULL, AST_MUTEX_INITIALIZER };
293 #define REG_STATE_UNREGISTERED 0
294 #define REG_STATE_REGSENT 1
295 #define REG_STATE_AUTHSENT 2
296 #define REG_STATE_REGISTERED 3
297 #define REG_STATE_REJECTED 4
298 #define REG_STATE_TIMEOUT 5
299 #define REG_STATE_NOAUTH 6
301 struct sip_registry {
302 pthread_mutex_t lock; /* Channel private lock */
303 struct sockaddr_in addr; /* Who we connect to for registration purposes */
305 char secret[80]; /* Password or key name in []'s */
306 char contact[80]; /* Contact extension */
308 int expire; /* Sched ID of expiration */
309 int timeout; /* sched id of sip_reg_timeout */
310 int refresh; /* How often to refresh */
311 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
313 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
314 char callid[80]; /* Global CallID for this registry */
315 struct sockaddr_in us; /* Who the server thinks we are */
316 struct sip_registry *next;
319 #define REINVITE_INVITE 1
320 #define REINVITE_UPDATE 2
322 static int sip_do_register(struct sip_registry *r);
323 struct sip_registry *registrations;
325 static int sipsock = -1;
326 static int globalnat = 0;
328 static struct sockaddr_in bindaddr;
330 static struct ast_frame *sip_read(struct ast_channel *ast);
331 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
332 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
333 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
334 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
335 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
336 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
337 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
338 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
339 static int transmit_message_with_text(struct sip_pvt *p, char *text);
340 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
341 char *getsipuri(char *header);
342 static void free_old_route(struct sip_route *route);
343 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
345 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
349 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
351 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
353 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));
358 static void sip_destroy(struct sip_pvt *p);
360 static int retrans_pkt(void *data)
362 struct sip_pkt *pkt=data;
364 ast_pthread_mutex_lock(&pkt->owner->lock);
365 if (!pkt->owner->needdestroy) {
366 if (pkt->retrans < MAX_RETRANS) {
370 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));
372 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));
374 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
377 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
379 if (pkt->owner->owner) {
380 /* XXX Potential deadlocK?? XXX */
381 ast_queue_hangup(pkt->owner->owner, 1);
383 /* If no owner, destroy now */
384 ast_pthread_mutex_unlock(&pkt->owner->lock);
385 sip_destroy(pkt->owner);
390 /* Don't bother retransmitting. It's about to be killed anyway */
392 if (pkt->owner->owner) {
393 /* XXX Potential deadlocK?? XXX */
394 ast_queue_hangup(pkt->owner->owner, 1);
396 /* If no owner, destroy now */
397 ast_pthread_mutex_unlock(&pkt->owner->lock);
398 sip_destroy(pkt->owner);
403 ast_pthread_mutex_unlock(&pkt->owner->lock);
407 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
410 pkt = malloc(sizeof(struct sip_pkt) + len);
413 memset(pkt, 0, sizeof(struct sip_pkt));
414 memcpy(pkt->data, data, len);
415 pkt->packetlen = len;
416 pkt->next = p->packets;
420 /* Schedule retransmission */
421 pkt->retransid = ast_sched_add(sched, 1000, retrans_pkt, pkt);
422 pkt->next = p->packets;
424 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
425 if (!strncasecmp(pkt->data, "INVITE", 6)) {
426 /* Note this is a pending invite */
427 p->pendinginvite = seqno;
432 static int __sip_autodestruct(void *data)
434 struct sip_pvt *p = data;
436 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
438 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
439 ast_queue_hangup(p->owner, 0);
446 static int sip_scheddestroy(struct sip_pvt *p, int ms)
448 if (p->autokillid > -1)
449 ast_sched_del(sched, p->autokillid);
450 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
454 static int sip_cancel_destroy(struct sip_pvt *p)
456 if (p->autokillid > -1)
457 ast_sched_del(sched, p->autokillid);
462 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
464 struct sip_pkt *cur, *prev = NULL;
469 if ((cur->seqno == seqno) && (cur->resp == resp)) {
470 if (!resp && (seqno == p->pendinginvite)) {
471 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
472 p->pendinginvite = 0;
475 /* this is our baby */
477 prev->next = cur->next;
479 p->packets = cur->next;
480 if (cur->retransid > -1)
481 ast_sched_del(sched, cur->retransid);
489 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
493 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
498 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));
500 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));
503 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
505 res = __sip_xmit(p, req->data, req->len);
511 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
516 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));
518 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));
521 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
523 res = __sip_xmit(p, req->data, req->len);
527 static char *ditch_braces(char *tmp)
532 if ((n = strchr(tmp, '<')) ) {
534 while(*c && *c != '>') c++;
536 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
545 static int sip_sendtext(struct ast_channel *ast, char *text)
547 struct sip_pvt *p = ast->pvt->pvt;
549 ast_verbose("Sending text %s on %s\n", text, ast->name);
552 if (!text || !strlen(text))
555 ast_verbose("Really sending text %s on %s\n", text, ast->name);
556 transmit_message_with_text(p, text);
560 static int create_addr(struct sip_pvt *r, char *peer)
565 r->sa.sin_family = AF_INET;
566 ast_pthread_mutex_lock(&peerl.lock);
569 if (!strcasecmp(p->name, peer)) {
571 r->capability = p->capability;
574 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
575 ast_rtp_setnat(r->rtp, r->nat);
577 strncpy(r->peername, p->username, sizeof(r->peername)-1);
578 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
579 strncpy(r->username, p->username, sizeof(r->username)-1);
580 if (strlen(p->fromdomain))
581 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
582 r->insecure = p->insecure;
583 r->canreinvite = p->canreinvite;
584 r->maxtime = p->maxms;
586 r->dtmfmode = p->dtmfmode;
587 if (r->dtmfmode & SIP_DTMF_RFC2833)
588 r->noncodeccapability |= AST_RTP_DTMF;
590 r->noncodeccapability &= ~AST_RTP_DTMF;
592 strncpy(r->context, p->context,sizeof(r->context)-1);
593 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
594 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
595 if (p->addr.sin_addr.s_addr) {
596 r->sa.sin_addr = p->addr.sin_addr;
597 r->sa.sin_port = p->addr.sin_port;
599 r->sa.sin_addr = p->defaddr.sin_addr;
600 r->sa.sin_port = p->defaddr.sin_port;
602 memcpy(&r->recv, &r->sa, sizeof(r->recv));
608 ast_pthread_mutex_unlock(&peerl.lock);
610 hp = gethostbyname(peer);
612 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
613 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
614 memcpy(&r->recv, &r->sa, sizeof(r->recv));
617 ast_log(LOG_WARNING, "No such host: %s\n", peer);
626 static int auto_congest(void *nothing)
628 struct sip_pvt *p = nothing;
629 ast_pthread_mutex_lock(&p->lock);
632 if (!pthread_mutex_trylock(&p->owner->lock)) {
633 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
634 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
635 ast_pthread_mutex_unlock(&p->owner->lock);
638 ast_pthread_mutex_unlock(&p->lock);
642 static void sip_prefs_free(void)
644 struct sip_codec_pref *cur, *next;
654 static void sip_pref_remove(int format)
656 struct sip_codec_pref *cur, *prev=NULL;
659 if (cur->codec == format) {
661 prev->next = cur->next;
672 static int sip_pref_append(int format)
674 struct sip_codec_pref *cur, *tmp;
675 sip_pref_remove(format);
676 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
679 memset(tmp, 0, sizeof(struct sip_codec_pref));
691 static int sip_codec_choose(int formats)
693 struct sip_codec_pref *cur;
696 if (formats & cur->codec)
700 return ast_best_codec(formats);
703 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
707 char *vxml_url = NULL;
708 struct varshead *headp;
709 struct ast_var_t *current;
712 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
713 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
717 /* Check whether there is a VXML_URL variable */
718 headp=&ast->varshead;
719 AST_LIST_TRAVERSE(headp,current,entries) {
720 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
722 vxml_url = ast_var_value(current);
729 transmit_invite(p, "INVITE", 1, NULL, vxml_url);
731 /* Initialize auto-congest time */
732 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
737 static void __sip_destroy(struct sip_pvt *p, int lockowner)
739 struct sip_pvt *cur, *prev = NULL;
742 ast_extension_state_del(p->stateid, NULL);
744 ast_sched_del(sched, p->initid);
745 if (p->autokillid > -1)
746 ast_sched_del(sched, p->autokillid);
749 ast_rtp_destroy(p->rtp);
752 free_old_route(p->route);
755 /* Unlink us from the owner if we have one */
758 ast_pthread_mutex_lock(&p->owner->lock);
759 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
760 p->owner->pvt->pvt = NULL;
762 ast_pthread_mutex_unlock(&p->owner->lock);
768 prev->next = cur->next;
777 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
780 ast_sched_del(sched, p->initid);
781 while((cp = p->packets)) {
782 p->packets = p->packets->next;
783 if (cp->retransid > -1)
784 ast_sched_del(sched, cp->retransid);
790 static void sip_destroy(struct sip_pvt *p)
792 ast_pthread_mutex_lock(&iflock);
794 ast_pthread_mutex_unlock(&iflock);
797 /* Interface lookup code courtesy Tilghman of DrunkCoder.com. Thanks! */
800 char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
801 struct sockaddr_in ifru_addr;
804 struct in_addr *lookup_iface(char *iface) {
807 static struct my_ifreq ifreq;
808 memset(&ifreq, 0, sizeof(ifreq));
809 strncpy(ifreq.ifrn_name,iface,sizeof(ifreq.ifrn_name) - 1);
811 mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
812 res = ioctl(mysock,SIOCGIFADDR,&ifreq);
816 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
819 return( (struct in_addr *) &ifreq.ifru_addr.sin_addr );
822 static struct in_addr *myaddrfor(struct in_addr *them)
825 struct in_addr *temp = NULL;
826 unsigned int remote_ip;
828 remote_ip = them->s_addr;
830 PROC = fopen("/proc/net/route","r");
832 /* If /proc/net/route doesn't exist, fall back to the old method */
835 /* First line contains headers */
836 fgets(line,sizeof(line),PROC);
838 while (!feof(PROC)) {
840 unsigned int dest, gateway, mask;
844 fgets(line,sizeof(line),PROC);
847 for (i=0;i<sizeof(line);i++) {
850 fields[aoffset++] = line + i;
851 boffset = strchr(line + i,'\t');
852 if (boffset == NULL) {
861 sscanf(fields[0],"%s",iface);
862 sscanf(fields[1],"%x",&dest);
863 sscanf(fields[2],"%x",&gateway);
864 sscanf(fields[7],"%x",&mask);
866 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
868 if (((remote_ip & mask) ^ dest) == 0) {
870 ast_verbose("Interface is %s\n",iface);
871 temp = lookup_iface(iface);
873 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
879 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s. Using default\n", inet_ntoa(*them));
885 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
888 static int sip_hangup(struct ast_channel *ast)
890 struct sip_pvt *p = ast->pvt->pvt;
893 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
894 if (!ast->pvt->pvt) {
895 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
898 ast_pthread_mutex_lock(&p->lock);
899 /* Determine how to disconnect */
900 if (p->owner != ast) {
901 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
902 ast_pthread_mutex_unlock(&p->lock);
905 if (!ast || (ast->_state != AST_STATE_UP))
910 ast_dsp_free(p->vad);
913 ast->pvt->pvt = NULL;
916 /* Start the process if it's not already started */
917 if (!p->alreadygone && strlen(p->initreq.data)) {
920 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
921 /* Actually don't destroy us yet, wait for the 487 on our original
922 INVITE, but do set an autodestruct just in case. */
924 sip_scheddestroy(p, 15000);
926 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
928 if (!p->pendinginvite) {
930 transmit_request_with_auth(p, "BYE", 0, 1);
932 /* Note we will need a BYE when this all settles out */
937 ast_pthread_mutex_unlock(&p->lock);
941 static int sip_answer(struct ast_channel *ast)
945 struct sip_pvt *p = ast->pvt->pvt;
948 if (ast->_state != AST_STATE_UP) {
952 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
954 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
955 fmt=ast_getformatbyname(codec);
958 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
961 ast_setstate(ast, AST_STATE_UP);
963 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
964 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
969 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
971 struct sip_pvt *p = ast->pvt->pvt;
973 if (frame->frametype != AST_FRAME_VOICE) {
974 if (frame->frametype == AST_FRAME_IMAGE)
977 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
981 if (!(frame->subclass & ast->nativeformats)) {
982 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
983 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
988 ast_pthread_mutex_lock(&p->lock);
990 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
991 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
994 res = ast_rtp_write(p->rtp, frame);
996 ast_pthread_mutex_unlock(&p->lock);
1001 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1003 struct sip_pvt *p = newchan->pvt->pvt;
1004 ast_pthread_mutex_lock(&p->lock);
1005 if (p->owner != oldchan) {
1006 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1007 ast_pthread_mutex_unlock(&p->lock);
1011 ast_pthread_mutex_unlock(&p->lock);
1015 static int sip_senddigit(struct ast_channel *ast, char digit)
1017 struct sip_pvt *p = ast->pvt->pvt;
1018 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1019 transmit_info_with_digit(p, digit);
1021 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1022 ast_rtp_senddigit(p->rtp, digit);
1024 /* If in-band DTMF is desired, send that */
1025 if (p->dtmfmode & SIP_DTMF_INBAND)
1030 static int sip_indicate(struct ast_channel *ast, int condition)
1032 struct sip_pvt *p = ast->pvt->pvt;
1034 case AST_CONTROL_RINGING:
1035 if (ast->_state == AST_STATE_RING) {
1036 transmit_response(p, "180 Ringing", &p->initreq);
1040 case AST_CONTROL_BUSY:
1041 if (ast->_state != AST_STATE_UP) {
1042 transmit_response(p, "600 Busy everywhere", &p->initreq);
1044 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1048 case AST_CONTROL_CONGESTION:
1049 if (ast->_state != AST_STATE_UP) {
1050 transmit_response(p, "486 Busy here", &p->initreq);
1052 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1059 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1067 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1069 struct ast_channel *tmp;
1071 tmp = ast_channel_alloc(1);
1073 /* Select our native format based on codec preference until we receive
1074 something from another device to the contrary. */
1076 tmp->nativeformats = sip_codec_choose(i->capability);
1078 tmp->nativeformats = sip_codec_choose(capability);
1079 fmt = ast_best_codec(tmp->nativeformats);
1081 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1083 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
1085 if (i->dtmfmode & SIP_DTMF_INBAND) {
1086 i->vad = ast_dsp_new();
1087 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1089 tmp->fds[0] = ast_rtp_fd(i->rtp);
1090 ast_setstate(tmp, state);
1091 if (state == AST_STATE_RING)
1093 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1094 tmp->writeformat = fmt;
1095 tmp->pvt->rawwriteformat = fmt;
1096 tmp->readformat = fmt;
1097 tmp->pvt->rawreadformat = fmt;
1099 tmp->pvt->send_text = sip_sendtext;
1100 tmp->pvt->call = sip_call;
1101 tmp->pvt->hangup = sip_hangup;
1102 tmp->pvt->answer = sip_answer;
1103 tmp->pvt->read = sip_read;
1104 tmp->pvt->write = sip_write;
1105 tmp->pvt->indicate = sip_indicate;
1106 tmp->pvt->fixup = sip_fixup;
1107 tmp->pvt->send_digit = sip_senddigit;
1108 tmp->pvt->bridge = ast_rtp_bridge;
1109 if (strlen(i->language))
1110 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1112 ast_pthread_mutex_lock(&usecnt_lock);
1114 ast_pthread_mutex_unlock(&usecnt_lock);
1115 ast_update_use_count();
1116 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1117 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1118 if (strlen(i->callerid))
1119 tmp->callerid = strdup(i->callerid);
1121 if (state != AST_STATE_DOWN) {
1122 if (ast_pbx_start(tmp)) {
1123 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1129 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1133 static struct cfalias {
1137 { "Content-Type", "c" },
1138 { "Content-Encoding", "e" },
1142 { "Content-Length", "l" },
1148 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1149 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1150 char* r = line + nameLen + 1;
1151 while (*r && (*r < 33)) ++r;
1158 static char *get_sdp(struct sip_request *req, char *name) {
1160 int len = strlen(name);
1163 for (x=0; x<req->lines; x++) {
1164 r = get_sdp_by_line(req->line[x], name, len);
1165 if (r[0] != '\0') return r;
1170 static void sdpLineNum_iterator_init(int* iterator) {
1174 static char* get_sdp_iterate(int* iterator,
1175 struct sip_request *req, char *name) {
1176 int len = strlen(name);
1178 while (*iterator < req->lines) {
1179 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1180 if (r[0] != '\0') return r;
1185 static char *__get_header(struct sip_request *req, char *name, int *start)
1188 int len = strlen(name);
1190 for (x=*start;x<req->headers;x++) {
1191 if (!strncasecmp(req->header[x], name, len) &&
1192 (req->header[x][len] == ':')) {
1193 r = req->header[x] + len + 1;
1194 while(*r && (*r < 33))
1201 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1202 if (!strcasecmp(aliases[x].fullname, name))
1203 return __get_header(req, aliases[x].shortname, start);
1205 /* Don't return NULL, so get_header is always a valid pointer */
1209 static char *get_header(struct sip_request *req, char *name)
1212 return __get_header(req, name, &start);
1215 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1217 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1218 struct ast_frame *f;
1219 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1220 f = ast_rtp_read(p->rtp);
1221 /* Don't send RFC2833 if we're not supposed to */
1222 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1225 /* We already hold the channel lock */
1226 if (f->frametype == AST_FRAME_VOICE) {
1227 if (f->subclass != p->owner->nativeformats) {
1228 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1229 p->owner->nativeformats = f->subclass;
1230 ast_set_read_format(p->owner, p->owner->readformat);
1231 ast_set_write_format(p->owner, p->owner->writeformat);
1233 if (p->dtmfmode & SIP_DTMF_INBAND) {
1234 f = ast_dsp_process(p->owner,p->vad,f,0);
1241 static struct ast_frame *sip_read(struct ast_channel *ast)
1243 struct ast_frame *fr;
1244 struct sip_pvt *p = ast->pvt->pvt;
1245 ast_pthread_mutex_lock(&p->lock);
1246 fr = sip_rtp_read(p);
1247 ast_pthread_mutex_unlock(&p->lock);
1251 static void build_callid(char *callid, int len, struct in_addr ourip)
1258 res = snprintf(callid, len, "%08x", val);
1262 /* It's not important that we really use our right IP here... */
1263 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1266 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1270 p = malloc(sizeof(struct sip_pvt));
1273 /* Keep track of stuff */
1274 memset(p, 0, sizeof(struct sip_pvt));
1278 p->rtp = ast_rtp_new(NULL, NULL);
1282 /* Start with 101 instead of 1 */
1285 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1289 ast_rtp_settos(p->rtp, tos);
1290 if (useglobalnat && sin) {
1291 /* Setup NAT structure according to global settings if we have an address */
1293 memcpy(&p->recv, sin, sizeof(p->recv));
1294 ast_rtp_setnat(p->rtp, p->nat);
1296 ast_pthread_mutex_init(&p->lock);
1298 ast_rtp_set_data(p->rtp, p);
1299 ast_rtp_set_callback(p->rtp, rtpready);
1302 memcpy(&p->sa, sin, sizeof(p->sa));
1303 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1305 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1307 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1309 build_callid(p->callid, sizeof(p->callid), p->ourip);
1311 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1312 /* Assume reinvite OK and via INVITE */
1313 p->canreinvite = REINVITE_INVITE;
1314 p->dtmfmode = globaldtmfmode;
1315 if (p->dtmfmode & SIP_DTMF_RFC2833)
1316 p->noncodeccapability |= AST_RTP_DTMF;
1317 strncpy(p->context, context, sizeof(p->context) - 1);
1318 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1320 ast_pthread_mutex_lock(&iflock);
1323 ast_pthread_mutex_unlock(&iflock);
1325 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1329 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1333 callid = get_header(req, "Call-ID");
1334 if (!strlen(callid)) {
1335 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1338 ast_pthread_mutex_lock(&iflock);
1341 if (!strcmp(p->callid, callid)) {
1342 /* Found the call */
1344 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1345 (p->sa.sin_port != sin->sin_port))) {
1348 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1349 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1350 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1351 ast_pthread_mutex_unlock(&iflock);
1355 ast_pthread_mutex_lock(&p->lock);
1356 ast_pthread_mutex_unlock(&iflock);
1361 ast_pthread_mutex_unlock(&iflock);
1362 return sip_alloc(callid, sin, 1);
1365 static int sip_register(char *value, int lineno)
1367 struct sip_registry *reg;
1368 char copy[256] = "";
1369 char *username, *hostname, *secret;
1377 strncpy(copy, value, sizeof(copy)-1);
1380 hostname = strrchr(stringp, '@');
1386 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1390 username = strsep(&stringp, ":");
1391 secret = strsep(&stringp, ":");
1393 hostname = strsep(&stringp, "/");
1394 contact = strsep(&stringp, "/");
1395 if (!contact || !strlen(contact))
1398 hostname = strsep(&stringp, ":");
1399 porta = strsep(&stringp, ":");
1401 if (porta && !atoi(porta)) {
1402 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1405 hp = gethostbyname(hostname);
1407 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1410 reg = malloc(sizeof(struct sip_registry));
1412 memset(reg, 0, sizeof(struct sip_registry));
1413 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1414 strncpy(reg->username, username, sizeof(reg->username)-1);
1416 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1418 reg->refresh = default_expirey;
1419 reg->addr.sin_family = AF_INET;
1420 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1421 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1422 reg->next = registrations;
1423 reg->callid_valid = 0;
1424 registrations = reg;
1426 ast_log(LOG_ERROR, "Out of memory\n");
1432 static void parse(struct sip_request *req)
1434 /* Divide fields by NULL's */
1439 /* First header starts immediately */
1443 /* We've got a new header */
1447 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1449 if (!strlen(req->header[f])) {
1450 /* Line by itself means we're now in content */
1454 if (f >= SIP_MAX_HEADERS - 1) {
1455 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1458 req->header[f] = c + 1;
1459 } else if (*c == '\r') {
1460 /* Ignore but eliminate \r's */
1465 /* Check for last header */
1466 if (strlen(req->header[f]))
1469 /* Now we process any mime content */
1474 /* We've got a new line */
1477 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1479 if (f >= SIP_MAX_LINES - 1) {
1480 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1483 req->line[f] = c + 1;
1484 } else if (*c == '\r') {
1485 /* Ignore and eliminate \r's */
1490 /* Check for last line */
1491 if (strlen(req->line[f]))
1495 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1497 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1500 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1508 int peercapability, peernoncodeccapability;
1509 struct sockaddr_in sin;
1515 /* Get codec and RTP info from SDP */
1516 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1517 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1520 m = get_sdp(req, "m");
1521 c = get_sdp(req, "c");
1522 if (!strlen(m) || !strlen(c)) {
1523 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1526 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1527 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1530 /* XXX This could block for a long time, and block the main thread! XXX */
1531 hp = gethostbyname(host);
1533 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1536 if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1537 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1540 sin.sin_family = AF_INET;
1541 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1542 sin.sin_port = htons(portno);
1544 ast_rtp_set_peer(p->rtp, &sin);
1546 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1548 // Scan through the RTP payload types specified in a "m=" line:
1549 ast_rtp_pt_clear(p->rtp);
1551 while(strlen(codecs)) {
1552 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1553 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1556 ast_rtp_set_m_type(p->rtp, codec);
1558 /* Skip over any whitespace */
1559 while(*codecs && (*codecs < 33)) codecs++;
1562 // Next, scan through each "a=rtpmap:" line, noting each
1563 // specified RTP payload type (with corresponding MIME subtype):
1564 sdpLineNum_iterator_init(&iterator);
1565 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1566 char* mimeSubtype = strdup(a); // ensures we have enough space
1567 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1568 // Note: should really look at the 'freq' and '#chans' params too
1569 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1573 // Now gather all of the codecs that were asked for:
1574 ast_rtp_get_current_formats(p->rtp,
1575 &peercapability, &peernoncodeccapability);
1576 p->capability = capability & peercapability;
1577 p->noncodeccapability = noncodeccapability & peernoncodeccapability;
1579 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1580 capability, peercapability, p->capability);
1581 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1582 noncodeccapability, peernoncodeccapability,
1583 p->noncodeccapability);
1585 if (!p->capability) {
1586 ast_log(LOG_WARNING, "No compatible codecs!\n");
1590 if (!(p->owner->nativeformats & p->capability)) {
1591 ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->capability, p->owner->nativeformats);
1592 p->owner->nativeformats = sip_codec_choose(p->capability);
1593 ast_set_read_format(p->owner, p->owner->readformat);
1594 ast_set_write_format(p->owner, p->owner->writeformat);
1596 if (p->owner->bridge) {
1597 /* Turn on/off music on hold if we are holding/unholding */
1598 if (sin.sin_addr.s_addr) {
1599 ast_moh_stop(p->owner->bridge);
1601 ast_moh_start(p->owner->bridge, NULL);
1609 static int add_header(struct sip_request *req, char *var, char *value)
1611 if (req->len >= sizeof(req->data) - 4) {
1612 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1616 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1619 req->header[req->headers] = req->data + req->len;
1620 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1621 req->len += strlen(req->header[req->headers]);
1622 if (req->headers < SIP_MAX_HEADERS)
1625 ast_log(LOG_WARNING, "Out of header space\n");
1631 static int add_blank_header(struct sip_request *req)
1633 if (req->len >= sizeof(req->data) - 4) {
1634 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1638 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1641 req->header[req->headers] = req->data + req->len;
1642 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1643 req->len += strlen(req->header[req->headers]);
1644 if (req->headers < SIP_MAX_HEADERS)
1647 ast_log(LOG_WARNING, "Out of header space\n");
1653 static int add_line(struct sip_request *req, char *line)
1655 if (req->len >= sizeof(req->data) - 4) {
1656 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1660 /* Add extra empty return */
1661 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1662 req->len += strlen(req->data + req->len);
1664 req->line[req->lines] = req->data + req->len;
1665 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1666 req->len += strlen(req->line[req->lines]);
1667 if (req->lines < SIP_MAX_LINES)
1670 ast_log(LOG_WARNING, "Out of line space\n");
1676 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1679 tmp = get_header(orig, field);
1681 /* Add what we're responding to */
1682 return add_header(req, field, tmp);
1684 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1688 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1694 tmp = __get_header(orig, field, &start);
1696 /* Add what we're responding to */
1697 add_header(req, field, tmp);
1702 return copied ? 0 : -1;
1705 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1712 tmp = __get_header(orig, field, &start);
1714 if (!copied && p->nat) {
1715 /* SLD: FIXME: Nice try, but the received= should not have a port */
1716 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1717 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1718 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1720 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1721 add_header(req, field, new);
1723 /* Add what we're responding to */
1724 add_header(req, field, tmp);
1731 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1737 /* Add Route: header into request per learned route */
1738 static void add_route(struct sip_request *req, struct sip_route *route)
1741 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1747 n = strlen(route->hop);
1748 if ((n+3)>rem) break;
1754 strcpy(p, route->hop); p += n;
1757 route = route->next;
1760 add_header(req, "Route", r);
1763 static void set_destination(struct sip_pvt *p, char *uri)
1765 char *h, *maddr, hostname[256];
1769 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1770 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1773 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1775 /* Find and parse hostname */
1776 h = strchr(uri, '@');
1781 if (strncmp(h, "sip:", 4) == 0)
1783 else if (strncmp(h, "sips:", 5) == 0)
1786 hn = strcspn(h, ":;>");
1788 strncpy(hostname, h, hn); hostname[hn] = '\0';
1791 /* Is "port" present? if not default to 5060 */
1795 port = strtol(h, &h, 10);
1800 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
1801 maddr = strstr(h, "maddr=");
1804 hn = strspn(maddr, "0123456789.");
1806 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
1809 hp = gethostbyname(hostname);
1811 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
1814 p->sa.sin_family = AF_INET;
1815 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1816 p->sa.sin_port = htons(port);
1818 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1821 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1823 /* Initialize a response */
1824 if (req->headers || req->len) {
1825 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1828 req->header[req->headers] = req->data + req->len;
1829 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1830 req->len += strlen(req->header[req->headers]);
1831 if (req->headers < SIP_MAX_HEADERS)
1834 ast_log(LOG_WARNING, "Out of header space\n");
1838 static int init_req(struct sip_request *req, char *resp, char *recip)
1840 /* Initialize a response */
1841 if (req->headers || req->len) {
1842 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1845 req->header[req->headers] = req->data + req->len;
1846 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1847 req->len += strlen(req->header[req->headers]);
1848 if (req->headers < SIP_MAX_HEADERS)
1851 ast_log(LOG_WARNING, "Out of header space\n");
1855 static void append_contact(struct sip_request *req, struct sip_pvt *p)
1857 /* Add contact header */
1858 char contact2[256] ="", *c, *c2, contact[256];
1861 from = get_header(req, "From");
1863 from = get_header(req, "To");
1864 strncpy(contact2, from, sizeof(contact2)-1);
1865 if (strlen(contact2)) {
1866 c = ditch_braces(contact2);
1867 c2 = strchr(c, ';');
1869 snprintf(contact, sizeof(contact), "<%s>", c);
1870 add_header(req, "Contact", contact);
1874 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1876 char newto[256] = "", *ot;
1877 memset(resp, 0, sizeof(*resp));
1878 init_resp(resp, msg, req);
1879 copy_via_headers(p, resp, req, "Via");
1880 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1881 copy_header(resp, req, "From");
1882 ot = get_header(req, "To");
1883 if (!strstr(ot, "tag=")) {
1884 /* Add the proper tag if we don't have it already. If they have specified
1885 their tag, use it. Otherwise, use our own tag */
1886 if (strlen(p->theirtag) && p->outgoing)
1887 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1888 else if (p->tag && !p->outgoing)
1889 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1891 strncpy(newto, ot, sizeof(newto) - 1);
1894 add_header(resp, "To", ot);
1895 copy_header(resp, req, "Call-ID");
1896 copy_header(resp, req, "CSeq");
1897 add_header(resp, "User-Agent", "Asterisk PBX");
1899 /* For registration responses, we also need expirey and
1904 if ((c=getsipuri(ot))) {
1905 snprintf(contact, sizeof(contact), "<%s@%s:%d>;expires=%d", c, inet_ntoa(p->ourip), ourport, p->expirey);
1908 snprintf(contact, sizeof(contact), "<%s:%d>;expires=%d", inet_ntoa(p->ourip), ourport, p->expirey);
1910 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1911 add_header(resp, "Expires", tmp);
1912 add_header(resp, "Contact", contact);
1915 /* XXX This isn't exactly right and it's implemented
1916 very stupidly *sigh* XXX */
1918 if ((c=getsipuri(ot))) {
1919 snprintf(contact, sizeof(contact), "<%s@%s:%d>", c, inet_ntoa(p->ourip), ourport);
1922 snprintf(contact, sizeof(contact), "<%s:%d>", inet_ntoa(p->ourip), ourport);
1924 add_header(resp, "Contact", contact);
1929 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
1931 struct sip_request *orig = &p->initreq;
1932 char stripped[80] ="";
1938 memset(req, 0, sizeof(struct sip_request));
1946 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1948 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1950 c = strchr(stripped, '<');
1962 init_req(req, msg, c);
1964 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
1966 add_header(req, "Via", p->via);
1968 set_destination(p, p->route->hop);
1969 add_route(req, p->route->next);
1972 ot = get_header(orig, "To");
1973 of = get_header(orig, "From");
1975 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
1976 as our original request, including tag (or presumably lack thereof) */
1977 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
1978 /* Add the proper tag if we don't have it already. If they have specified
1979 their tag, use it. Otherwise, use our own tag */
1980 if (p->outgoing && strlen(p->theirtag))
1981 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1982 else if (!p->outgoing)
1983 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1985 snprintf(newto, sizeof(newto), "%s", ot);
1990 add_header(req, "From", of);
1991 add_header(req, "To", ot);
1993 add_header(req, "From", ot);
1994 add_header(req, "To", of);
1996 append_contact(req, p);
1997 copy_header(req, orig, "Call-ID");
1998 add_header(req, "CSeq", tmp);
2000 add_header(req, "User-Agent", "Asterisk PBX");
2004 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2006 struct sip_request resp;
2008 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2009 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2012 respprep(&resp, p, msg, req);
2013 add_header(&resp, "Content-Length", "0");
2014 add_blank_header(&resp);
2015 return send_response(p, &resp, reliable, seqno);
2018 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2020 return __transmit_response(p, msg, req, 0);
2022 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2024 return __transmit_response(p, msg, req, 1);
2027 static void append_date(struct sip_request *req)
2034 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2035 add_header(req, "Date", tmpdat);
2038 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2040 struct sip_request resp;
2041 respprep(&resp, p, msg, req);
2043 add_header(&resp, "Content-Length", "0");
2044 add_blank_header(&resp);
2045 return send_response(p, &resp, 0, 0);
2048 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2050 struct sip_request resp;
2051 respprep(&resp, p, msg, req);
2052 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
2053 add_header(&resp, "Accept", "application/sdp");
2054 add_header(&resp, "Content-Length", "0");
2055 add_blank_header(&resp);
2056 return send_response(p, &resp, 0, 0);
2059 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2061 struct sip_request resp;
2064 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2065 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2068 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2069 respprep(&resp, p, msg, req);
2070 add_header(&resp, "Proxy-Authenticate", tmp);
2071 add_header(&resp, "Content-Length", "0");
2072 add_blank_header(&resp);
2073 return send_response(p, &resp, reliable, seqno);
2076 static int add_text(struct sip_request *req, char *text)
2078 /* XXX Convert \n's to \r\n's XXX */
2079 int len = strlen(text);
2081 snprintf(clen, sizeof(clen), "%d", len);
2082 add_header(req, "Content-Type", "text/plain");
2083 add_header(req, "Content-Length", clen);
2084 add_line(req, text);
2088 static int add_digit(struct sip_request *req, char digit)
2093 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2095 snprintf(clen, sizeof(clen), "%d", len);
2096 add_header(req, "Content-Type", "application/dtmf-relay");
2097 add_header(req, "Content-Length", clen);
2102 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
2106 int alreadysent = 0;
2108 struct sockaddr_in sin;
2109 struct sip_codec_pref *cur;
2118 struct sockaddr_in dest;
2119 /* XXX We break with the "recommendation" and send our IP, in order that our
2120 peer doesn't have to gethostbyname() us XXX */
2123 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2126 ast_rtp_get_us(p->rtp, &sin);
2128 ast_rtp_get_peer(rtp, &dest);
2130 dest.sin_addr = p->ourip;
2131 dest.sin_port = sin.sin_port;
2134 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2135 snprintf(v, sizeof(v), "v=0\r\n");
2136 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2137 snprintf(s, sizeof(s), "s=session\r\n");
2138 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2139 snprintf(t, sizeof(t), "t=0 0\r\n");
2140 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2141 /* Start by sending our preferred codecs */
2144 if (p->capability & cur->codec) {
2146 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2147 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2149 snprintf(costr, sizeof(costr), " %d", codec);
2151 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2155 alreadysent |= cur->codec;
2158 /* Now send any other common codecs, and non-codec formats: */
2159 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2160 if ((p->capability & x) && !(alreadysent & x)) {
2162 ast_verbose("Answering with capability %d\n", x);
2163 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2165 snprintf(costr, sizeof(costr), " %d", codec);
2167 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2172 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2173 if (p->noncodeccapability & x) {
2175 ast_verbose("Answering with non-codec capability %d\n", x);
2176 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2178 snprintf(costr, sizeof(costr), " %d", codec);
2180 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2182 if (x == AST_RTP_DTMF) {
2183 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2184 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2192 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2193 snprintf(costr, sizeof(costr), "%d", len);
2194 add_header(resp, "Content-Type", "application/sdp");
2195 add_header(resp, "Content-Length", costr);
2206 static void copy_request(struct sip_request *dst,struct sip_request *src)
2210 offset = ((void *)dst) - ((void *)src);
2211 /* First copy stuff */
2212 memcpy(dst, src, sizeof(*dst));
2213 /* Now fix pointer arithmetic */
2214 for (x=0;x<src->headers;x++)
2215 dst->header[x] += offset;
2216 for (x=0;x<src->lines;x++)
2217 dst->line[x] += offset;
2220 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2222 struct sip_request resp;
2224 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2225 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2228 respprep(&resp, p, msg, req);
2229 add_sdp(&resp, p, NULL);
2230 return send_response(p, &resp, retrans, seqno);
2233 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2235 struct sip_request req;
2236 if (p->canreinvite == REINVITE_UPDATE)
2237 reqprep(&req, p, "UPDATE", 0);
2239 reqprep(&req, p, "INVITE", 0);
2240 add_sdp(&req, p, rtp);
2241 /* Use this as the basis */
2242 copy_request(&p->initreq, &req);
2244 p->lastinvite = p->ocseq;
2246 return send_request(p, &req, 1, p->ocseq);
2249 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2256 char *l = callerid, *n=NULL;
2257 if (p->owner && p->owner->callerid) {
2258 strcpy(cid, p->owner->callerid);
2259 ast_callerid_parse(cid, &n, &l);
2261 ast_shrink_phone_number(l);
2262 if (!l || !ast_isphonenumber(l))
2267 if (ourport != 5060)
2268 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), ourport, p->tag);
2270 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2272 if (strlen(p->username)) {
2273 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2274 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2276 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2278 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2279 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2281 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
2283 /* If there is a VXML URL append it to the SIP URL */
2286 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2290 snprintf(to, sizeof(to), "<%s>", invite );
2292 memset(req, 0, sizeof(struct sip_request));
2293 init_req(req, cmd, invite);
2294 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2296 add_header(req, "Via", p->via);
2297 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2298 * OTOH, then we won't have anything in p->route anyway */
2299 add_header(req, "From", from);
2301 char contact2[256] ="", *c, contact[256];
2302 /* XXX This isn't exactly right and it's implemented
2303 very stupidly *sigh* XXX */
2304 strncpy(contact2, from, sizeof(contact2)-1);
2305 c = ditch_braces(contact2);
2306 snprintf(contact, sizeof(contact), "<%s>", c);
2307 add_header(req, "Contact", contact);
2309 add_header(req, "To", to);
2310 add_header(req, "Call-ID", p->callid);
2311 add_header(req, "CSeq", tmp);
2312 add_header(req, "User-Agent", "Asterisk PBX");
2315 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2317 struct sip_request req;
2318 initreqprep(&req, p, cmd, vxml_url);
2320 add_header(&req, "Proxy-Authorization", auth);
2322 add_sdp(&req, p, NULL);
2324 add_header(&req, "Content-Length", "0");
2325 add_blank_header(&req);
2327 if (!p->initreq.headers) {
2328 /* Use this as the basis */
2329 copy_request(&p->initreq, &req);
2332 p->lastinvite = p->ocseq;
2333 return send_request(p, &req, 1, p->ocseq);
2336 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2339 char from[256], to[256];
2342 struct sip_request req;
2345 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2347 c = ditch_braces(from);
2348 if (strncmp(c, "sip:", 4)) {
2349 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2352 if ((a = strchr(c, ';'))) {
2357 reqprep(&req, p, "NOTIFY", 0);
2359 if (p->subscribed == 1) {
2360 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2362 c = ditch_braces(to);
2363 if (strncmp(c, "sip:", 4)) {
2364 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2367 if ((a = strchr(c, ';'))) {
2372 add_header(&req, "Content-Type", "application/xpidf+xml");
2374 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2376 else if (state==AST_EXTENSION_INUSE)
2382 sprintf(t, "<?xml version=\"1.0\"?>\n");
2383 t = tmp + strlen(tmp);
2384 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2385 t = tmp + strlen(tmp);
2386 sprintf(t, "<presence>\n");
2387 t = tmp + strlen(tmp);
2388 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2389 t = tmp + strlen(tmp);
2390 sprintf(t, "<atom id=\"%s\">\n", p->exten);
2391 t = tmp + strlen(tmp);
2392 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2393 t = tmp + strlen(tmp);
2394 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2395 t = tmp + strlen(tmp);
2396 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2397 t = tmp + strlen(tmp);
2398 sprintf(t, "</address>\n</atom>\n</presence>\n");
2400 add_header(&req, "Event", "dialog");
2401 add_header(&req, "Content-Type", "application/dialog-info+xml");
2404 sprintf(t, "<?xml version=\"1.0\"?>\n");
2405 t = tmp + strlen(tmp);
2406 sprintf(t, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mfrom);
2407 t = tmp + strlen(tmp);
2408 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2409 t = tmp + strlen(tmp);
2410 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2411 t = tmp + strlen(tmp);
2412 sprintf(t, "</dialog>\n</dialog-info>\n");
2415 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2416 add_header(&req, "Content-Length", clen);
2417 add_line(&req, tmp);
2419 return send_request(p, &req, 1, p->ocseq);
2422 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2424 struct sip_request req;
2428 initreqprep(&req, p, "NOTIFY", NULL);
2429 add_header(&req, "Event", "message-summary");
2430 add_header(&req, "Content-Type", "application/simple-message-summary");
2432 snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", newmsgs ? "yes" : "no");
2433 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2434 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2435 add_header(&req, "Content-Length", clen);
2436 add_line(&req, tmp);
2437 add_line(&req, tmp2);
2439 if (!p->initreq.headers) {
2440 /* Use this as the basis */
2441 copy_request(&p->initreq, &req);
2445 return send_request(p, &req, 1, p->ocseq);
2448 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2450 static int sip_reregister(void *data)
2452 /* if we are here, we know that we need to reregister. */
2453 struct sip_registry *r=(struct sip_registry *)data;
2454 return sip_do_register(r);
2459 static int sip_do_register(struct sip_registry *r)
2462 ast_pthread_mutex_lock(&r->lock);
2463 res=transmit_register(r, "REGISTER", NULL);
2464 ast_pthread_mutex_unlock(&r->lock);
2468 static int sip_reg_timeout(void *data)
2470 /* if we are here, our registration timed out, so we'll just do it over */
2471 struct sip_registry *r=data;
2473 ast_pthread_mutex_lock(&r->lock);
2474 ast_log(LOG_NOTICE, "Registration timed out, trying again\n");
2475 r->regstate=REG_STATE_UNREGISTERED;
2476 /* cancel ourselves first!!! */
2477 /* ast_sched_del(sched,r->timeout); */
2478 res=transmit_register(r, "REGISTER", NULL);
2479 ast_pthread_mutex_unlock(&r->lock);
2483 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2485 struct sip_request req;
2492 /* exit if we are already in process with this registrar ?*/
2493 if ( r == NULL || (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2494 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2500 if (!r->callid_valid) {
2501 build_callid(r->callid, sizeof(r->callid), __ourip);
2504 p=sip_alloc( r->callid, &r->addr, 0);
2508 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2509 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2510 strncpy(p->username, r->username, sizeof(p->username)-1);
2513 /* set up a timeout */
2514 if (auth==NULL && !r->timeout) {
2515 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2516 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2519 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2520 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=as%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2522 snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2524 memset(&req, 0, sizeof(req));
2525 init_req(&req, cmd, addr);
2527 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2529 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2530 add_header(&req, "Via", via);
2531 add_header(&req, "From", from);
2532 add_header(&req, "To", to);
2535 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2536 add_header(&req, "Contact", contact);
2538 add_header(&req, "Call-ID", p->callid);
2539 add_header(&req, "CSeq", tmp);
2540 add_header(&req, "User-Agent", "Asterisk PBX");
2542 add_header(&req, "Authorization", auth);
2544 snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2545 add_header(&req, "Expires", tmp);
2546 add_header(&req, "Event", "registration");
2547 add_header(&req, "Content-length", "0");
2548 add_blank_header(&req);
2549 copy_request(&p->initreq, &req);
2550 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2551 return send_request(p, &req, 1, p->ocseq);
2554 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2556 struct sip_request req;
2557 reqprep(&req, p, "MESSAGE", 0);
2558 add_text(&req, text);
2559 return send_request(p, &req, 1, p->ocseq);
2562 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2564 struct sip_request req;
2565 reqprep(&req, p, "INFO", 0);
2566 add_digit(&req, digit);
2567 return send_request(p, &req, 1, p->ocseq);
2570 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
2572 struct sip_request resp;
2573 reqprep(&resp, p, msg, seqno);
2574 add_header(&resp, "Content-Length", "0");
2575 add_blank_header(&resp);
2576 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2579 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
2581 struct sip_request resp;
2582 reqprep(&resp, p, msg, seqno);
2586 memset(digest,0,sizeof(digest));
2587 build_reply_digest(p, msg, digest, sizeof(digest));
2588 add_header(&resp, "Proxy-Authorization", digest);
2591 add_header(&resp, "Content-Length", "0");
2592 add_blank_header(&resp);
2593 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2596 static int expire_register(void *data)
2598 struct sip_peer *p = data;
2599 memset(&p->addr, 0, sizeof(p->addr));
2601 ast_device_state_changed("SIP/%s", p->name);
2605 static int sip_poke_peer(struct sip_peer *peer);
2607 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2609 char contact[80]= "";
2610 char *expires = get_header(req, "Expires");
2611 int expirey = atoi(expires);
2615 struct sockaddr_in oldsin;
2616 if (!strlen(expires)) {
2617 expires = strstr(get_header(req, "Contact"), "expires=");
2619 if (sscanf(expires + 8, "%d;", &expirey) != 1)
2622 /* Look for brackets */
2623 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2626 if ((n=strchr(c, '<'))) {
2629 /* Lose the part after the > */
2633 if (!strcasecmp(c, "*") || !expirey) {
2634 /* This means remove all registrations and return OK */
2635 memset(&p->addr, 0, sizeof(p->addr));
2637 ast_sched_del(sched, p->expire);
2639 if (option_verbose > 2)
2640 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
2643 /* Make sure it's a SIP URL */
2644 if (strncasecmp(c, "sip:", 4)) {
2645 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2661 pt = strchr(n, ':');
2667 port = DEFAULT_SIP_PORT;
2668 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2670 /* XXX This could block for a long time XXX */
2671 hp = gethostbyname(n);
2673 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2676 p->addr.sin_family = AF_INET;
2677 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2678 p->addr.sin_port = htons(port);
2680 /* Don't trust the contact field. Just use what they came to us
2682 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2685 strncpy(p->username, c, sizeof(p->username) - 1);
2687 strcpy(p->username, "");
2689 ast_sched_del(sched, p->expire);
2690 if ((expirey < 1) || (expirey > max_expirey))
2691 expirey = max_expirey;
2692 p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2693 pvt->expirey = expirey;
2694 if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2696 if (option_verbose > 2)
2697 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->username, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expirey);
2702 static void free_old_route(struct sip_route *route)
2704 struct sip_route *next;
2712 static void list_route(struct sip_route *route)
2715 ast_verbose("list_route: no route\n");
2719 ast_verbose("list_route: hop: <%s>\n", route->hop);
2720 route = route->next;
2724 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
2726 struct sip_route *thishop, *head, *tail;
2729 char *rr, *contact, *c;
2732 free_old_route(p->route);
2735 /* We build up head, then assign it to p->route when we're done */
2736 head = NULL; tail = head;
2737 /* 1st we pass through all the hops in any Record-Route headers */
2739 /* Each Record-Route header */
2740 rr = __get_header(req, "Record-Route", &start);
2741 if (*rr == '\0') break;
2743 /* Each route entry */
2745 rr = strchr(rr, '<');
2746 if (!rr) break; /* No more hops */
2748 len = strcspn(rr, ">");
2749 /* Make a struct route */
2750 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2752 strncpy(thishop->hop, rr, len);
2753 thishop->hop[len] = '\0';
2754 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
2757 /* Link in at head so they end up in reverse order */
2758 thishop->next = head;
2760 /* If this was the first then it'll be the tail */
2761 if (!tail) tail = thishop;
2763 thishop->next = NULL;
2764 /* Link in at the end */
2766 tail->next = thishop;
2775 /* 2nd append the Contact: if there is one */
2776 /* Can be multiple Contact headers, comma separated values - we just take the first */
2777 contact = get_header(req, "Contact");
2778 if (strlen(contact)) {
2779 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
2780 /* Look for <: delimited address */
2781 c = strchr(contact, '<');
2785 len = strcspn(c, ">");
2787 /* No <> - just take the lot */
2788 c = contact; len = strlen(contact);
2790 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2792 strncpy(thishop->hop, c, len);
2793 thishop->hop[len] = '\0';
2794 thishop->next = NULL;
2795 /* Goes at the end */
2797 tail->next = thishop;
2802 /* Store as new route */
2805 /* For debugging dump what we ended up with */
2807 list_route(p->route);
2810 static void md5_hash(char *output, char *input)
2812 struct MD5Context md5;
2813 unsigned char digest[16];
2817 MD5Update(&md5, input, strlen(input));
2818 MD5Final(digest, &md5);
2821 ptr += sprintf(ptr, "%2.2x", digest[x]);
2824 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri, int reliable)
2827 /* Always OK if no secret */
2828 if (!strlen(secret))
2830 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2831 snprintf(randdata, randlen, "%08x", rand());
2832 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2833 /* Schedule auto destroy in 15 seconds */
2834 sip_scheddestroy(p, 15000);
2837 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2838 an example in the spec of just what it is you're doing a hash on. */
2844 char resp_hash[256];
2850 /* Find their response among the mess that we'r sent for comparison */
2851 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2855 while (*c && (*c < 33)) c++;
2858 if (!strncasecmp(c, "response=", strlen("response="))) {
2859 c+= strlen("response=");
2862 if((c = strchr(c,'\"')))
2867 if((c = strchr(c,',')))
2871 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2875 if((c = strchr(c,'\"')))
2879 if((c = strchr(c,',')))
2888 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2889 if(strlen(resp_uri))
2890 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2892 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2893 md5_hash(a1_hash, a1);
2894 md5_hash(a2_hash, a2);
2895 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2896 md5_hash(resp_hash, resp);
2898 /* resp_hash now has the expected response, compare the two */
2900 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2904 /* Assume success ;-) */
2905 /* Eliminate random data */
2906 strcpy(randdata, "");
2911 static int cb_extensionstate(char *context, char* exten, int state, void *data)
2913 struct sip_pvt *p = data;
2915 sip_scheddestroy(p, 15000);
2920 transmit_state_notify(p, state, 1);
2923 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
2927 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2930 struct sip_peer *peer;
2936 while(*t && (*t > 32) && (*t != ';'))
2940 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2941 c = ditch_braces(tmp);
2942 if (!strncmp(c, "sip:", 4)) {
2946 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2948 c = strchr(name, '@');
2951 ast_pthread_mutex_lock(&peerl.lock);
2954 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2956 transmit_response(p, "100 Trying", req);
2957 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
2958 sip_cancel_destroy(p);
2959 if (parse_contact(p, peer, req)) {
2960 ast_log(LOG_WARNING, "Failed to parse contact info\n");
2962 /* Say OK and ask subsystem to retransmit msg counter */
2963 transmit_response_with_date(p, "200 OK", req);
2964 peer->lastmsgssent = -1;
2972 ast_pthread_mutex_unlock(&peerl.lock);
2974 ast_device_state_changed("SIP/%s", peer->name);
2977 transmit_response(p, "401 Unauthorized", &p->initreq);
2981 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2983 char tmp[256] = "", *c, *a;
2984 struct sip_request *req;
2989 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2990 c = ditch_braces(tmp);
2991 if (strncmp(c, "sip:", 4)) {
2992 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2996 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3000 ast_verbose("Looking for %s in %s\n", c, p->context);
3001 if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3003 strncpy(p->exten, c, sizeof(p->exten) - 1);
3007 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
3014 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
3016 char tmp[256] = "", *c, *a;
3017 char tmp2[256] = "", *c2, *a2;
3020 char tmp5[256] = ""; /* CallID to replace */
3021 struct sip_request *req;
3027 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
3028 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
3029 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
3030 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
3032 c = ditch_braces(tmp);
3033 c2 = ditch_braces(tmp2);
3036 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
3037 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3038 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
3043 if ((a = strchr(c, '?'))) {
3044 /* Search for arguemnts */
3047 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
3048 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
3049 if ((a = strchr(tmp5, '%'))) {
3050 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
3052 if ((a[1] == '4') && (a[2] == '0')) {
3054 memmove(a + 1, a+3, strlen(a + 3));
3057 if ((a = strchr(tmp5, '%')))
3062 if ((a = strchr(c, '@')))
3064 if ((a = strchr(c, ';')))
3068 if ((a2 = strchr(c2, '@')))
3071 if ((a2 = strchr(c2, ';')))
3076 ast_verbose("Looking for %s in %s\n", c, p->context);
3077 ast_verbose("Looking for %s in %s\n", c2, p->context);
3080 /* This is a supervised transfer */
3081 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
3083 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
3084 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
3085 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
3086 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
3087 p->refer_call = NULL;
3088 ast_pthread_mutex_lock(&iflock);
3089 /* Search interfaces and find the match */
3092 if (!strcmp(p2->callid, tmp5)) {
3093 /* Go ahead and lock it before returning */
3094 ast_pthread_mutex_lock(&p2->lock);
3100 ast_pthread_mutex_unlock(&iflock);
3104 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
3105 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3106 /* This is an unsupervised transfer */
3107 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
3108 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
3109 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
3110 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
3111 strncpy(p->refer_to, c, sizeof(p->refer_to