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";
86 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
88 /* Protect the interface list (of sip_pvt's) */
89 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
91 /* Protect the monitoring thread, so only one process can kill or start it, and not
92 when it's doing something critical. */
93 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
95 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
97 /* This is the thread for the monitor which checks for input on the channels
98 which are not currently in use. */
99 static pthread_t monitor_thread = 0;
101 static int restart_monitor(void);
103 /* Codecs that we support by default: */
104 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
105 static int noncodeccapability = AST_RTP_DTMF;
107 static char ourhost[256];
108 static struct in_addr __ourip;
111 static int sipdebug = 0;
115 static int globaldtmfmode = SIP_DTMF_RFC2833;
118 static int expirey = 900;
120 static struct sched_context *sched;
121 static struct io_context *io;
122 /* The private structures of the sip channels are linked for
123 selecting outgoing channels */
125 #define SIP_MAX_HEADERS 64
126 #define SIP_MAX_LINES 64
128 static struct sip_codec_pref {
130 struct sip_codec_pref *next;
134 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
135 char *rlPart2; /* The Request URI or Response Status */
137 int headers; /* SIP Headers */
138 char *header[SIP_MAX_HEADERS];
139 int lines; /* SDP Content */
140 char *line[SIP_MAX_LINES];
141 char data[SIP_MAX_PACKET];
146 static struct sip_pvt {
147 pthread_mutex_t lock; /* Channel private lock */
148 char callid[80]; /* Global CallID */
149 char randdata[80]; /* Random data */
150 unsigned int ocseq; /* Current outgoing seqno */
151 unsigned int icseq; /* Current incoming seqno */
152 int lastinvite; /* Last Cseq of invite */
153 int alreadygone; /* Whether or not we've already been destroyed by or peer */
154 int needdestroy; /* if we need to be destroyed */
155 int capability; /* Special capability */
156 int noncodeccapability;
157 int outgoing; /* Outgoing or incoming call? */
158 int insecure; /* Don't check source port/ip */
159 int expirey; /* How long we take to expire */
160 int branch; /* One random number */
161 int canreinvite; /* Do we support reinvite */
162 int progress; /* Have sent 183 message progress */
163 int tag; /* Another random number */
164 int nat; /* Whether to try to support NAT */
165 struct sockaddr_in sa; /* Our peer */
166 struct sockaddr_in recv; /* Received as */
167 struct in_addr ourip; /* Our IP */
168 struct ast_channel *owner; /* Who owns us */
169 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
170 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
171 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
172 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
173 struct sip_pvt *refer_call; /* Call we are referring */
174 char record_route[256];
175 char record_route_info[256];
176 char remote_party_id[256];
177 char context[AST_MAX_EXTENSION];
178 char language[MAX_LANGUAGE];
179 char theirtag[256]; /* Their tag */
183 char callerid[256]; /* Caller*ID */
185 char accountcode[256]; /* Account code */
186 int amaflags; /* AMA Flags */
187 struct sip_request initreq; /* Initial request */
189 int maxtime; /* Max time for first response */
190 int initid; /* Auto-congest ID if appropriate */
191 int autokillid; /* Auto-kill ID */
196 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
197 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
198 struct ast_rtp *rtp; /* RTP Session */
199 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
200 struct sip_pvt *next;
204 struct sip_pkt *next; /* Next packet */
205 int retrans; /* Retransmission number */
206 int seqno; /* Sequence number */
207 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
208 struct sip_pvt *owner; /* Owner call */
209 int retransid; /* Retransmission ID */
210 int packetlen; /* Length of packet */
215 /* Users who can access various contexts */
221 char accountcode[80];
229 struct sip_user *next;
235 char context[80]; /* JK02: peers need context too to allow parking etc */
238 char mailbox[AST_MAX_EXTENSION];
249 struct sockaddr_in addr;
253 struct sip_pvt *call; /* Call pointer */
254 int pokeexpire; /* When to expire poke */
255 int lastms; /* How long last response took (in ms), or -1 for no response */
256 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
257 struct timeval ps; /* Ping send time */
259 struct sockaddr_in defaddr;
263 struct sip_peer *next;
266 static struct ast_user_list {
267 struct sip_user *users;
268 pthread_mutex_t lock;
269 } userl = { NULL, AST_MUTEX_INITIALIZER };
271 static struct ast_peer_list {
272 struct sip_peer *peers;
273 pthread_mutex_t lock;
274 } peerl = { NULL, AST_MUTEX_INITIALIZER };
277 #define REG_STATE_UNREGISTERED 0
278 #define REG_STATE_REGSENT 1
279 #define REG_STATE_AUTHSENT 2
280 #define REG_STATE_REGISTERED 3
281 #define REG_STATE_REJECTED 4
282 #define REG_STATE_TIMEOUT 5
283 #define REG_STATE_NOAUTH 6
285 struct sip_registry {
286 pthread_mutex_t lock; /* Channel private lock */
287 struct sockaddr_in addr; /* Who we connect to for registration purposes */
289 char secret[80]; /* Password or key name in []'s */
290 char contact[80]; /* Contact extension */
292 int expire; /* Sched ID of expiration */
293 int timeout; /* sched id of sip_reg_timeout */
294 int refresh; /* How often to refresh */
295 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
297 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
298 char callid[80]; /* Global CallID for this registry */
299 struct sockaddr_in us; /* Who the server thinks we are */
300 struct sip_registry *next;
303 #define REINVITE_INVITE 1
304 #define REINVITE_UPDATE 2
306 static int sip_do_register(struct sip_registry *r);
307 struct sip_registry *registrations;
309 static int sipsock = -1;
310 static int globalnat = 0;
312 static struct sockaddr_in bindaddr;
314 static struct ast_frame *sip_read(struct ast_channel *ast);
315 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
316 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
317 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
318 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
319 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
320 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
321 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
322 static int transmit_message_with_text(struct sip_pvt *p, char *text);
323 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
324 char *getsipuri(char *header);
326 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
330 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
332 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
334 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));
339 static void sip_destroy(struct sip_pvt *p);
341 static int retrans_pkt(void *data)
343 struct sip_pkt *pkt=data;
345 ast_pthread_mutex_lock(&pkt->owner->lock);
346 if (pkt->retrans < MAX_RETRANS) {
350 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));
352 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));
354 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
357 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
359 if (pkt->owner->owner) {
360 /* XXX Potential deadlocK?? XXX */
361 ast_queue_hangup(pkt->owner->owner, 1);
363 /* If no owner, destroy now */
364 sip_destroy(pkt->owner);
367 ast_pthread_mutex_unlock(&pkt->owner->lock);
371 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
374 pkt = malloc(sizeof(struct sip_pkt) + len);
377 memset(pkt, 0, sizeof(struct sip_pkt));
378 memcpy(pkt->data, data, len);
379 pkt->packetlen = len;
380 pkt->next = p->packets;
384 /* Schedule retransmission */
385 pkt->retransid = ast_sched_add(sched, 1000, retrans_pkt, pkt);
386 pkt->next = p->packets;
388 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
392 static int __sip_autodestruct(void *data)
394 struct sip_pvt *p = data;
396 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
398 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
399 ast_queue_hangup(p->owner, 0);
406 static int sip_scheddestroy(struct sip_pvt *p, int ms)
408 if (p->autokillid > -1)
409 ast_sched_del(sched, p->autokillid);
410 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
414 static int sip_cancel_destroy(struct sip_pvt *p)
416 if (p->autokillid > -1)
417 ast_sched_del(sched, p->autokillid);
422 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
424 struct sip_pkt *cur, *prev = NULL;
428 if ((cur->seqno == seqno) && (cur->resp == resp)) {
429 /* this is our baby */
431 prev->next = cur->next;
433 p->packets = cur->next;
434 if (cur->retransid > -1)
435 ast_sched_del(sched, cur->retransid);
443 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
447 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
452 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));
454 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));
457 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
459 res = __sip_xmit(p, req->data, req->len);
465 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
470 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));
472 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));
475 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
477 res = __sip_xmit(p, req->data, req->len);
481 static char *ditch_braces(char *tmp)
486 if ((n = strchr(tmp, '<')) ) {
488 while(*c && *c != '>') c++;
490 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
499 static int sip_sendtext(struct ast_channel *ast, char *text)
501 struct sip_pvt *p = ast->pvt->pvt;
503 ast_verbose("Sending text %s on %s\n", text, ast->name);
506 if (!text || !strlen(text))
509 ast_verbose("Really sending text %s on %s\n", text, ast->name);
510 transmit_message_with_text(p, text);
514 static int create_addr(struct sip_pvt *r, char *peer)
519 r->sa.sin_family = AF_INET;
520 ast_pthread_mutex_lock(&peerl.lock);
523 if (!strcasecmp(p->name, peer)) {
525 r->capability = p->capability;
528 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
529 ast_rtp_setnat(r->rtp, r->nat);
531 strncpy(r->peername, p->username, sizeof(r->peername)-1);
532 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
533 strncpy(r->username, p->username, sizeof(r->username)-1);
534 r->insecure = p->insecure;
535 r->canreinvite = p->canreinvite;
536 r->maxtime = p->maxms;
538 r->dtmfmode = p->dtmfmode;
539 if (r->dtmfmode & SIP_DTMF_RFC2833)
540 r->noncodeccapability |= AST_RTP_DTMF;
542 r->noncodeccapability &= ~AST_RTP_DTMF;
544 strncpy(r->context, p->context,sizeof(r->context)-1);
545 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
546 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
547 if (p->addr.sin_addr.s_addr) {
548 r->sa.sin_addr = p->addr.sin_addr;
549 r->sa.sin_port = p->addr.sin_port;
551 r->sa.sin_addr = p->defaddr.sin_addr;
552 r->sa.sin_port = p->defaddr.sin_port;
554 memcpy(&r->recv, &r->sa, sizeof(r->recv));
560 ast_pthread_mutex_unlock(&peerl.lock);
562 hp = gethostbyname(peer);
564 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
565 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
566 memcpy(&r->recv, &r->sa, sizeof(r->recv));
569 ast_log(LOG_WARNING, "No such host: %s\n", peer);
578 static int auto_congest(void *nothing)
580 struct sip_pvt *p = nothing;
581 ast_pthread_mutex_lock(&p->lock);
584 if (!pthread_mutex_trylock(&p->owner->lock)) {
585 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
586 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
587 ast_pthread_mutex_unlock(&p->owner->lock);
590 ast_pthread_mutex_unlock(&p->lock);
594 static void sip_prefs_free(void)
596 struct sip_codec_pref *cur, *next;
606 static void sip_pref_remove(int format)
608 struct sip_codec_pref *cur, *prev=NULL;
611 if (cur->codec == format) {
613 prev->next = cur->next;
624 static int sip_pref_append(int format)
626 struct sip_codec_pref *cur, *tmp;
627 sip_pref_remove(format);
628 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
631 memset(tmp, 0, sizeof(struct sip_codec_pref));
643 static int sip_codec_choose(int formats)
645 struct sip_codec_pref *cur;
648 if (formats & cur->codec)
652 return ast_best_codec(formats);
655 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
659 char *vxml_url = NULL;
660 struct varshead *headp;
661 struct ast_var_t *current;
664 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
665 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
669 /* Check whether there is a VXML_URL variable */
670 headp=&ast->varshead;
671 AST_LIST_TRAVERSE(headp,current,entries) {
672 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
674 vxml_url = ast_var_value(current);
681 transmit_invite(p, "INVITE", 1, NULL, vxml_url);
683 /* Initialize auto-congest time */
684 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
689 static void __sip_destroy(struct sip_pvt *p, int lockowner)
691 struct sip_pvt *cur, *prev = NULL;
694 ast_sched_del(sched, p->initid);
695 if (p->autokillid > -1)
696 ast_sched_del(sched, p->autokillid);
698 ast_rtp_destroy(p->rtp);
700 /* Unlink us from the owner if we have one */
703 ast_pthread_mutex_lock(&p->owner->lock);
704 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
705 p->owner->pvt->pvt = NULL;
707 ast_pthread_mutex_unlock(&p->owner->lock);
713 prev->next = cur->next;
722 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
725 ast_sched_del(sched, p->initid);
726 while((cp = p->packets)) {
727 p->packets = p->packets->next;
728 if (cp->retransid > -1)
729 ast_sched_del(sched, cp->retransid);
735 static void sip_destroy(struct sip_pvt *p)
737 ast_pthread_mutex_lock(&iflock);
739 ast_pthread_mutex_unlock(&iflock);
742 /* Interface lookup code courtesy Tilghman of DrunkCoder.com. Thanks! */
747 char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
752 struct sockaddr_in ifru_addr;
757 struct in_addr *lookup_iface(char *iface) {
760 static struct my_ifreq ifreq;
761 memset(&ifreq, 0, sizeof(ifreq));
762 strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
764 mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
765 res = ioctl(mysock,SIOCGIFADDR,&ifreq);
769 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
772 return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
775 static struct in_addr *myaddrfor(struct in_addr *them)
778 struct in_addr *temp = NULL;
779 unsigned int remote_ip;
781 remote_ip = them->s_addr;
783 PROC = fopen("/proc/net/route","r");
785 /* If /proc/net/route doesn't exist, fall back to the old method */
788 /* First line contains headers */
789 fgets(line,sizeof(line),PROC);
791 while (!feof(PROC)) {
793 unsigned int dest, gateway, mask;
797 fgets(line,sizeof(line),PROC);
800 for (i=0;i<sizeof(line);i++) {
803 fields[aoffset++] = line + i;
804 boffset = strchr(line + i,'\t');
805 if (boffset == NULL) {
814 sscanf(fields[0],"%s",iface);
815 sscanf(fields[1],"%x",&dest);
816 sscanf(fields[2],"%x",&gateway);
817 sscanf(fields[7],"%x",&mask);
819 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
821 if (((remote_ip & mask) ^ dest) == 0) {
823 ast_verbose("Interface is %s\n",iface);
824 temp = lookup_iface(iface);
826 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
832 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s. Using default\n", inet_ntoa(*them));
839 static int sip_hangup(struct ast_channel *ast)
841 struct sip_pvt *p = ast->pvt->pvt;
844 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
845 if (!ast->pvt->pvt) {
846 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
849 ast_pthread_mutex_lock(&p->lock);
850 /* Determine how to disconnect */
851 if (p->owner != ast) {
852 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
853 ast_pthread_mutex_unlock(&p->lock);
856 if (!ast || (ast->_state != AST_STATE_UP))
861 ast_dsp_free(p->vad);
864 ast->pvt->pvt = NULL;
867 /* Start the process if it's not already started */
868 if (!p->alreadygone && strlen(p->initreq.data)) {
870 transmit_request(p, "CANCEL", 0, 1);
873 transmit_request(p, "BYE", 1, 1);
876 ast_pthread_mutex_unlock(&p->lock);
880 static int sip_answer(struct ast_channel *ast)
884 struct sip_pvt *p = ast->pvt->pvt;
887 if (ast->_state != AST_STATE_UP) {
891 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
893 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
894 fmt=ast_getformatbyname(codec);
897 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
900 ast_setstate(ast, AST_STATE_UP);
902 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
903 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
908 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
910 struct sip_pvt *p = ast->pvt->pvt;
912 if (frame->frametype != AST_FRAME_VOICE) {
913 if (frame->frametype == AST_FRAME_IMAGE)
916 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
920 if (!(frame->subclass & ast->nativeformats)) {
921 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
922 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
927 ast_pthread_mutex_lock(&p->lock);
929 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
930 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
933 res = ast_rtp_write(p->rtp, frame);
935 ast_pthread_mutex_unlock(&p->lock);
940 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
942 struct sip_pvt *p = newchan->pvt->pvt;
943 ast_pthread_mutex_lock(&p->lock);
944 if (p->owner != oldchan) {
945 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
946 ast_pthread_mutex_unlock(&p->lock);
950 ast_pthread_mutex_unlock(&p->lock);
954 static int sip_senddigit(struct ast_channel *ast, char digit)
956 struct sip_pvt *p = ast->pvt->pvt;
957 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
958 transmit_info_with_digit(p, digit);
960 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
961 ast_rtp_senddigit(p->rtp, digit);
963 /* If in-band DTMF is desired, send that */
964 if (p->dtmfmode & SIP_DTMF_INBAND)
969 static int sip_indicate(struct ast_channel *ast, int condition)
971 struct sip_pvt *p = ast->pvt->pvt;
973 case AST_CONTROL_RINGING:
974 if (ast->_state == AST_STATE_RING) {
975 transmit_response(p, "180 Ringing", &p->initreq);
979 case AST_CONTROL_BUSY:
980 if (ast->_state != AST_STATE_UP) {
981 transmit_response(p, "600 Busy everywhere", &p->initreq);
983 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
987 case AST_CONTROL_CONGESTION:
988 if (ast->_state != AST_STATE_UP) {
989 transmit_response(p, "486 Busy here", &p->initreq);
991 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
998 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1006 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1008 struct ast_channel *tmp;
1010 tmp = ast_channel_alloc(1);
1012 /* Select our native format based on codec preference until we receive
1013 something from another device to the contrary. */
1015 tmp->nativeformats = sip_codec_choose(i->capability);
1017 tmp->nativeformats = sip_codec_choose(capability);
1018 fmt = ast_best_codec(tmp->nativeformats);
1020 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1022 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
1024 if (i->dtmfmode & SIP_DTMF_INBAND) {
1025 i->vad = ast_dsp_new();
1026 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1028 tmp->fds[0] = ast_rtp_fd(i->rtp);
1029 ast_setstate(tmp, state);
1030 if (state == AST_STATE_RING)
1032 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1033 tmp->writeformat = fmt;
1034 tmp->pvt->rawwriteformat = fmt;
1035 tmp->readformat = fmt;
1036 tmp->pvt->rawreadformat = fmt;
1038 tmp->pvt->send_text = sip_sendtext;
1039 tmp->pvt->call = sip_call;
1040 tmp->pvt->hangup = sip_hangup;
1041 tmp->pvt->answer = sip_answer;
1042 tmp->pvt->read = sip_read;
1043 tmp->pvt->write = sip_write;
1044 tmp->pvt->indicate = sip_indicate;
1045 tmp->pvt->fixup = sip_fixup;
1046 tmp->pvt->send_digit = sip_senddigit;
1047 tmp->pvt->bridge = ast_rtp_bridge;
1048 if (strlen(i->language))
1049 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1051 ast_pthread_mutex_lock(&usecnt_lock);
1053 ast_pthread_mutex_unlock(&usecnt_lock);
1054 ast_update_use_count();
1055 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1056 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1057 if (strlen(i->callerid))
1058 tmp->callerid = strdup(i->callerid);
1060 if (state != AST_STATE_DOWN) {
1061 if (ast_pbx_start(tmp)) {
1062 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1068 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1072 static struct cfalias {
1076 { "Content-Type", "c" },
1077 { "Content-Encoding", "e" },
1081 { "Content-Length", "l" },
1087 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1088 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1089 char* r = line + nameLen + 1;
1090 while (*r && (*r < 33)) ++r;
1097 static char *get_sdp(struct sip_request *req, char *name) {
1099 int len = strlen(name);
1102 for (x=0; x<req->lines; x++) {
1103 r = get_sdp_by_line(req->line[x], name, len);
1104 if (r[0] != '\0') return r;
1109 static void sdpLineNum_iterator_init(int* iterator) {
1113 static char* get_sdp_iterate(int* iterator,
1114 struct sip_request *req, char *name) {
1115 int len = strlen(name);
1117 while (*iterator < req->lines) {
1118 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1119 if (r[0] != '\0') return r;
1124 static char *__get_header(struct sip_request *req, char *name, int *start)
1127 int len = strlen(name);
1129 for (x=*start;x<req->headers;x++) {
1130 if (!strncasecmp(req->header[x], name, len) &&
1131 (req->header[x][len] == ':')) {
1132 r = req->header[x] + len + 1;
1133 while(*r && (*r < 33))
1140 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1141 if (!strcasecmp(aliases[x].fullname, name))
1142 return __get_header(req, aliases[x].shortname, start);
1144 /* Don't return NULL, so get_header is always a valid pointer */
1148 static char *get_header(struct sip_request *req, char *name)
1151 return __get_header(req, name, &start);
1154 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1156 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1157 struct ast_frame *f;
1158 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1159 f = ast_rtp_read(p->rtp);
1160 /* Don't send RFC2833 if we're not supposed to */
1161 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1164 /* We already hold the channel lock */
1165 if (f->frametype == AST_FRAME_VOICE) {
1166 if (f->subclass != p->owner->nativeformats) {
1167 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1168 p->owner->nativeformats = f->subclass;
1169 ast_set_read_format(p->owner, p->owner->readformat);
1170 ast_set_write_format(p->owner, p->owner->writeformat);
1172 if (p->dtmfmode & SIP_DTMF_INBAND) {
1173 f = ast_dsp_process(p->owner,p->vad,f,0);
1180 static struct ast_frame *sip_read(struct ast_channel *ast)
1182 struct ast_frame *fr;
1183 struct sip_pvt *p = ast->pvt->pvt;
1184 ast_pthread_mutex_lock(&p->lock);
1185 fr = sip_rtp_read(p);
1186 ast_pthread_mutex_unlock(&p->lock);
1190 static void build_callid(char *callid, int len, struct in_addr ourip)
1197 res = snprintf(callid, len, "%08x", val);
1201 /* It's not important that we really use our right IP here... */
1202 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1205 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1209 p = malloc(sizeof(struct sip_pvt));
1212 /* Keep track of stuff */
1213 memset(p, 0, sizeof(struct sip_pvt));
1216 p->rtp = ast_rtp_new(NULL, NULL);
1219 /* Start with 101 instead of 1 */
1222 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1226 ast_rtp_settos(p->rtp, tos);
1227 if (useglobalnat && sin) {
1228 /* Setup NAT structure according to global settings if we have an address */
1230 memcpy(&p->recv, sin, sizeof(p->recv));
1231 ast_rtp_setnat(p->rtp, p->nat);
1233 ast_pthread_mutex_init(&p->lock);
1235 ast_rtp_set_data(p->rtp, p);
1236 ast_rtp_set_callback(p->rtp, rtpready);
1239 memcpy(&p->sa, sin, sizeof(p->sa));
1240 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1242 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1244 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1246 build_callid(p->callid, sizeof(p->callid), p->ourip);
1248 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1249 /* Assume reinvite OK and via INVITE */
1250 p->canreinvite = REINVITE_INVITE;
1251 p->dtmfmode = globaldtmfmode;
1252 if (p->dtmfmode & SIP_DTMF_RFC2833)
1253 p->noncodeccapability |= AST_RTP_DTMF;
1255 ast_pthread_mutex_lock(&iflock);
1258 ast_pthread_mutex_unlock(&iflock);
1260 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1264 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1268 callid = get_header(req, "Call-ID");
1269 if (!strlen(callid)) {
1270 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1273 ast_pthread_mutex_lock(&iflock);
1276 if (!strcmp(p->callid, callid)) {
1277 /* Found the call */
1279 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1280 (p->sa.sin_port != sin->sin_port))) {
1283 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1284 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1285 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1286 ast_pthread_mutex_unlock(&iflock);
1290 ast_pthread_mutex_unlock(&iflock);
1295 ast_pthread_mutex_unlock(&iflock);
1296 return sip_alloc(callid, sin, 1);
1299 static int sip_register(char *value, int lineno)
1301 struct sip_registry *reg;
1302 char copy[256] = "";
1303 char *username, *hostname, *secret;
1311 strncpy(copy, value, sizeof(copy)-1);
1314 hostname = strrchr(stringp, '@');
1320 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1324 username = strsep(&stringp, ":");
1325 secret = strsep(&stringp, ":");
1327 hostname = strsep(&stringp, "/");
1328 contact = strsep(&stringp, "/");
1329 if (!contact || !strlen(contact))
1332 hostname = strsep(&stringp, ":");
1333 porta = strsep(&stringp, ":");
1335 if (porta && !atoi(porta)) {
1336 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1339 hp = gethostbyname(hostname);
1341 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1344 reg = malloc(sizeof(struct sip_registry));
1346 memset(reg, 0, sizeof(struct sip_registry));
1347 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1348 strncpy(reg->username, username, sizeof(reg->username)-1);
1350 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1352 reg->refresh = default_expirey;
1353 reg->addr.sin_family = AF_INET;
1354 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1355 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1356 reg->next = registrations;
1357 reg->callid_valid = 0;
1358 registrations = reg;
1360 ast_log(LOG_ERROR, "Out of memory\n");
1366 static void parse(struct sip_request *req)
1368 /* Divide fields by NULL's */
1373 /* First header starts immediately */
1377 /* We've got a new header */
1381 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1383 if (!strlen(req->header[f])) {
1384 /* Line by itself means we're now in content */
1388 if (f >= SIP_MAX_HEADERS - 1) {
1389 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1392 req->header[f] = c + 1;
1393 } else if (*c == '\r') {
1394 /* Ignore but eliminate \r's */
1399 /* Check for last header */
1400 if (strlen(req->header[f]))
1403 /* Now we process any mime content */
1408 /* We've got a new line */
1411 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1413 if (f >= SIP_MAX_LINES - 1) {
1414 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1417 req->line[f] = c + 1;
1418 } else if (*c == '\r') {
1419 /* Ignore and eliminate \r's */
1424 /* Check for last line */
1425 if (strlen(req->line[f]))
1429 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1431 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1434 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1442 int peercapability, peernoncodeccapability;
1443 struct sockaddr_in sin;
1449 /* Get codec and RTP info from SDP */
1450 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1451 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1454 m = get_sdp(req, "m");
1455 c = get_sdp(req, "c");
1456 if (!strlen(m) || !strlen(c)) {
1457 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1460 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1461 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1464 /* XXX This could block for a long time, and block the main thread! XXX */
1465 hp = gethostbyname(host);
1467 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1470 if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1471 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1474 sin.sin_family = AF_INET;
1475 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1476 sin.sin_port = htons(portno);
1478 ast_rtp_set_peer(p->rtp, &sin);
1480 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1482 // Scan through the RTP payload types specified in a "m=" line:
1483 ast_rtp_pt_clear(p->rtp);
1485 while(strlen(codecs)) {
1486 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1487 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1490 ast_rtp_set_m_type(p->rtp, codec);
1494 // Next, scan through each "a=rtpmap:" line, noting each
1495 // specified RTP payload type (with corresponding MIME subtype):
1496 sdpLineNum_iterator_init(&iterator);
1497 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1498 char* mimeSubtype = strdup(a); // ensures we have enough space
1499 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1500 // Note: should really look at the 'freq' and '#chans' params too
1501 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1505 // Now gather all of the codecs that were asked for:
1506 ast_rtp_get_current_formats(p->rtp,
1507 &peercapability, &peernoncodeccapability);
1508 p->capability = capability & peercapability;
1509 p->noncodeccapability = noncodeccapability & peernoncodeccapability;
1511 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1512 capability, peercapability, p->capability);
1513 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1514 noncodeccapability, peernoncodeccapability,
1515 p->noncodeccapability);
1517 if (!p->capability) {
1518 ast_log(LOG_WARNING, "No compatible codecs!\n");
1522 if (!(p->owner->nativeformats & p->capability)) {
1523 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);
1524 p->owner->nativeformats = sip_codec_choose(p->capability);
1525 ast_set_read_format(p->owner, p->owner->readformat);
1526 ast_set_write_format(p->owner, p->owner->writeformat);
1528 if (p->owner->bridge) {
1529 /* Turn on/off music on hold if we are holding/unholding */
1530 if (sin.sin_addr.s_addr) {
1531 ast_moh_stop(p->owner->bridge);
1533 ast_moh_start(p->owner->bridge, NULL);
1541 static int add_header(struct sip_request *req, char *var, char *value)
1543 if (req->len >= sizeof(req->data) - 4) {
1544 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1548 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1551 req->header[req->headers] = req->data + req->len;
1552 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1553 req->len += strlen(req->header[req->headers]);
1554 if (req->headers < SIP_MAX_HEADERS)
1557 ast_log(LOG_WARNING, "Out of header space\n");
1563 static int add_blank_header(struct sip_request *req)
1565 if (req->len >= sizeof(req->data) - 4) {
1566 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1570 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1573 req->header[req->headers] = req->data + req->len;
1574 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1575 req->len += strlen(req->header[req->headers]);
1576 if (req->headers < SIP_MAX_HEADERS)
1579 ast_log(LOG_WARNING, "Out of header space\n");
1585 static int add_line(struct sip_request *req, char *line)
1587 if (req->len >= sizeof(req->data) - 4) {
1588 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1592 /* Add extra empty return */
1593 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1594 req->len += strlen(req->data + req->len);
1596 req->line[req->lines] = req->data + req->len;
1597 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1598 req->len += strlen(req->line[req->lines]);
1599 if (req->lines < SIP_MAX_LINES)
1602 ast_log(LOG_WARNING, "Out of line space\n");
1608 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1611 tmp = get_header(orig, field);
1613 /* Add what we're responding to */
1614 return add_header(req, field, tmp);
1616 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1621 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1627 tmp = __get_header(orig, field, &start);
1629 /* Add what we're responding to */
1630 add_header(req, field, tmp);
1636 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1642 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1649 tmp = __get_header(orig, field, &start);
1651 if (!copied && p->nat) {
1652 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1653 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1655 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1656 add_header(req, field, new);
1658 /* Add what we're responding to */
1659 add_header(req, field, tmp);
1666 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1672 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1674 /* Initialize a response */
1675 if (req->headers || req->len) {
1676 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1679 req->header[req->headers] = req->data + req->len;
1680 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1681 req->len += strlen(req->header[req->headers]);
1682 if (req->headers < SIP_MAX_HEADERS)
1685 ast_log(LOG_WARNING, "Out of header space\n");
1689 static int init_req(struct sip_request *req, char *resp, char *recip)
1691 /* Initialize a response */
1692 if (req->headers || req->len) {
1693 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1696 req->header[req->headers] = req->data + req->len;
1697 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1698 req->len += strlen(req->header[req->headers]);
1699 if (req->headers < SIP_MAX_HEADERS)
1702 ast_log(LOG_WARNING, "Out of header space\n");
1706 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1708 char newto[256] = "", *ot;
1709 memset(resp, 0, sizeof(*resp));
1710 init_resp(resp, msg, req);
1711 copy_via_headers(p, resp, req, "Via");
1712 copy_header(resp, req, "From");
1713 ot = get_header(req, "To");
1714 if (strlen(get_header(req, "Record-Route")))
1715 copy_header(resp, req, "Record-Route");
1716 if (!strstr(ot, "tag=")) {
1717 /* Add the proper tag if we don't have it already. If they have specified
1718 their tag, use it. Otherwise, use our own tag */
1719 if (strlen(p->theirtag))
1720 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1722 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1724 strncpy(newto, ot, sizeof(newto) - 1);
1727 add_header(resp, "To", ot);
1728 copy_header(resp, req, "Call-ID");
1729 copy_header(resp, req, "CSeq");
1730 add_header(resp, "User-Agent", "Asterisk PBX");
1732 /* For registration responses, we also need expirey and
1737 if ((c=getsipuri(ot))) {
1738 snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1741 snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1743 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1744 add_header(resp, "Expires", tmp);
1745 add_header(resp, "Contact", contact);
1748 /* XXX This isn't exactly right and it's implemented
1749 very stupidly *sigh* XXX */
1751 if ((c=getsipuri(ot))) {
1752 snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1755 snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1757 add_header(resp, "Contact", contact);
1762 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1764 struct sip_request *orig = &p->initreq;
1765 char stripped[80] ="";
1771 memset(req, 0, sizeof(struct sip_request));
1777 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1779 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1781 c = strchr(stripped, '<');
1790 init_req(req, msg, c);
1792 snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1794 add_header(req, "Via", p->via);
1796 ot = get_header(orig, "To");
1797 of = get_header(orig, "From");
1799 if (!strstr(ot, "tag=")) {
1800 /* Add the proper tag if we don't have it already. If they have specified
1801 their tag, use it. Otherwise, use our own tag */
1802 if (strlen(p->theirtag))
1803 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1805 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1810 add_header(req, "From", of);
1811 add_header(req, "To", ot);
1813 add_header(req, "From", ot);
1814 add_header(req, "To", of);
1816 copy_header(req, orig, "Call-ID");
1817 add_header(req, "CSeq", tmp);
1819 add_header(req, "User-Agent", "Asterisk PBX");
1823 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1825 struct sip_request resp;
1826 respprep(&resp, p, msg, req);
1827 add_header(&resp, "Content-Length", "0");
1828 add_blank_header(&resp);
1829 return send_response(p, &resp, 0, 0);
1832 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1834 struct sip_request resp;
1835 respprep(&resp, p, msg, req);
1836 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1837 add_header(&resp, "Accept", "application/sdp");
1838 add_header(&resp, "Content-Length", "0");
1839 add_blank_header(&resp);
1840 return send_response(p, &resp, 0, 0);
1843 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
1845 struct sip_request resp;
1848 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
1849 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
1852 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1853 respprep(&resp, p, msg, req);
1854 add_header(&resp, "Proxy-Authenticate", tmp);
1855 add_header(&resp, "Content-Length", "0");
1856 add_blank_header(&resp);
1857 return send_response(p, &resp, reliable, seqno);
1860 static int add_text(struct sip_request *req, char *text)
1862 /* XXX Convert \n's to \r\n's XXX */
1863 int len = strlen(text);
1865 snprintf(clen, sizeof(clen), "%d", len);
1866 add_header(req, "Content-Type", "text/plain");
1867 add_header(req, "Content-Length", clen);
1868 add_line(req, text);
1872 static int add_digit(struct sip_request *req, char digit)
1877 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
1879 snprintf(clen, sizeof(clen), "%d", len);
1880 add_header(req, "Content-Type", "application/dtmf-relay");
1881 add_header(req, "Content-Length", clen);
1886 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1890 int alreadysent = 0;
1892 struct sockaddr_in sin;
1893 struct sip_codec_pref *cur;
1902 struct sockaddr_in dest;
1903 /* XXX We break with the "recommendation" and send our IP, in order that our
1904 peer doesn't have to gethostbyname() us XXX */
1907 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1910 ast_rtp_get_us(p->rtp, &sin);
1912 ast_rtp_get_peer(rtp, &dest);
1914 dest.sin_addr = p->ourip;
1915 dest.sin_port = sin.sin_port;
1918 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
1919 snprintf(v, sizeof(v), "v=0\r\n");
1920 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1921 snprintf(s, sizeof(s), "s=session\r\n");
1922 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1923 snprintf(t, sizeof(t), "t=0 0\r\n");
1924 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1925 /* Start by sending our preferred codecs */
1928 if (p->capability & cur->codec) {
1930 ast_verbose("Answering with preferred capability %d\n", cur->codec);
1931 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
1933 snprintf(costr, sizeof(costr), " %d", codec);
1935 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
1939 alreadysent |= cur->codec;
1942 /* Now send any other common codecs, and non-codec formats: */
1943 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1944 if ((p->capability & x) && !(alreadysent & x)) {
1946 ast_verbose("Answering with capability %d\n", x);
1947 codec = ast_rtp_lookup_code(p->rtp, 1, x);
1949 snprintf(costr, sizeof(costr), " %d", codec);
1951 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
1956 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
1957 if (p->noncodeccapability & x) {
1959 ast_verbose("Answering with non-codec capability %d\n", x);
1960 codec = ast_rtp_lookup_code(p->rtp, 0, x);
1962 snprintf(costr, sizeof(costr), " %d", codec);
1964 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
1966 if (x == AST_RTP_DTMF) {
1967 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
1968 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
1976 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1977 snprintf(costr, sizeof(costr), "%d", len);
1978 add_header(resp, "Content-Type", "application/sdp");
1979 add_header(resp, "Content-Length", costr);
1990 static void copy_request(struct sip_request *dst,struct sip_request *src)
1994 offset = ((void *)dst) - ((void *)src);
1995 /* First copy stuff */
1996 memcpy(dst, src, sizeof(*dst));
1997 /* Now fix pointer arithmetic */
1998 for (x=0;x<src->headers;x++)
1999 dst->header[x] += offset;
2000 for (x=0;x<src->lines;x++)
2001 dst->line[x] += offset;
2004 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2006 struct sip_request resp;
2008 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2009 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2012 respprep(&resp, p, msg, req);
2013 add_sdp(&resp, p, NULL);
2014 return send_response(p, &resp, retrans, seqno);
2017 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2019 struct sip_request resp;
2020 if (p->canreinvite == REINVITE_UPDATE)
2021 reqprep(&resp, p, "UPDATE", 1);
2023 reqprep(&resp, p, "INVITE", 1);
2024 add_sdp(&resp, p, rtp);
2025 return send_request(p, &resp, 1, p->ocseq);
2028 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2035 char *l = callerid, *n=NULL;
2036 if (p->owner && p->owner->callerid) {
2037 strcpy(cid, p->owner->callerid);
2038 ast_callerid_parse(cid, &n, &l);
2040 ast_shrink_phone_number(l);
2041 if (!l || !ast_isphonenumber(l))
2046 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
2047 if (strlen(p->username)) {
2048 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2049 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2051 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2053 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2054 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2056 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
2058 /* If there is a VXML URL append it to the SIP URL */
2061 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2065 snprintf(to, sizeof(to), "<%s>", invite );
2067 memset(req, 0, sizeof(struct sip_request));
2068 init_req(req, cmd, invite);
2069 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2071 add_header(req, "Via", p->via);
2072 add_header(req, "From", from);
2074 char contact2[256] ="", *c, contact[256];
2075 /* XXX This isn't exactly right and it's implemented
2076 very stupidly *sigh* XXX */
2077 strncpy(contact2, from, sizeof(contact2)-1);
2078 c = ditch_braces(contact2);
2079 snprintf(contact, sizeof(contact), "<%s>", c);
2080 add_header(req, "Contact", contact);
2082 add_header(req, "To", to);
2083 add_header(req, "Call-ID", p->callid);
2084 add_header(req, "CSeq", tmp);
2085 add_header(req, "User-Agent", "Asterisk PBX");
2088 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2090 struct sip_request req;
2091 initreqprep(&req, p, cmd, vxml_url);
2093 add_header(&req, "Proxy-Authorization", auth);
2095 add_sdp(&req, p, NULL);
2097 add_header(&req, "Content-Length", "0");
2098 add_blank_header(&req);
2100 if (!p->initreq.headers) {
2101 /* Use this as the basis */
2102 copy_request(&p->initreq, &req);
2105 p->lastinvite = p->ocseq;
2106 return send_request(p, &req, 1, p->ocseq);
2109 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2111 struct sip_request req;
2115 initreqprep(&req, p, "NOTIFY", NULL);
2116 add_header(&req, "Event", "message-summary");
2117 add_header(&req, "Content-Type", "application/simple-message-summary");
2119 snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", newmsgs ? "yes" : "no");
2120 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2121 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2122 add_header(&req, "Content-Length", clen);
2123 add_line(&req, tmp);
2124 add_line(&req, tmp2);
2126 if (!p->initreq.headers) {
2127 /* Use this as the basis */
2128 copy_request(&p->initreq, &req);
2132 p->lastinvite = p->ocseq;
2133 return send_request(p, &req, 1, p->ocseq);
2136 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2138 static int sip_reregister(void *data)
2140 /* if we are here, we know that we need to reregister. */
2141 struct sip_registry *r=(struct sip_registry *)data;
2142 return sip_do_register(r);
2147 static int sip_do_register(struct sip_registry *r)
2150 ast_pthread_mutex_lock(&r->lock);
2151 res=transmit_register(r, "REGISTER", NULL);
2152 ast_pthread_mutex_unlock(&r->lock);
2156 static int sip_reg_timeout(void *data)
2158 /* if we are here, our registration timed out, so we'll just do it over */
2159 struct sip_registry *r=data;
2161 ast_pthread_mutex_lock(&r->lock);
2162 ast_log(LOG_NOTICE, "Registration timed out, trying again\n");
2163 r->regstate=REG_STATE_UNREGISTERED;
2164 /* cancel ourselves first!!! */
2165 /* ast_sched_del(sched,r->timeout); */
2166 res=transmit_register(r, "REGISTER", NULL);
2167 ast_pthread_mutex_unlock(&r->lock);
2171 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2173 struct sip_request req;
2180 /* exit if we are already in process with this registrar ?*/
2181 if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2182 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2188 if (!r->callid_valid) {
2189 build_callid(r->callid, sizeof(r->callid), __ourip);
2192 p=sip_alloc( r->callid, &r->addr, 0);
2196 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2197 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2198 strncpy(p->username, r->username, sizeof(p->username)-1);
2201 /* set up a timeout */
2202 if (auth==NULL && !r->timeout) {
2203 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2204 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2207 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2208 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2210 snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2212 memset(&req, 0, sizeof(req));
2213 init_req(&req, cmd, addr);
2215 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2217 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2218 add_header(&req, "Via", via);
2219 add_header(&req, "From", from);
2220 add_header(&req, "To", to);
2223 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2224 add_header(&req, "Contact", contact);
2226 add_header(&req, "Call-ID", p->callid);
2227 add_header(&req, "CSeq", tmp);
2228 add_header(&req, "User-Agent", "Asterisk PBX");
2230 add_header(&req, "Authorization", auth);
2232 snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2233 add_header(&req, "Expires", tmp);
2234 add_header(&req, "Event", "registration");
2235 copy_request(&p->initreq, &req);
2236 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2237 return send_request(p, &req, 1, p->ocseq);
2240 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2242 struct sip_request req;
2243 reqprep(&req, p, "MESSAGE", 1);
2244 add_text(&req, text);
2245 return send_request(p, &req, 1, p->ocseq);
2248 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2250 struct sip_request req;
2251 reqprep(&req, p, "INFO", 1);
2252 add_digit(&req, digit);
2253 return send_request(p, &req, 1, p->ocseq);
2256 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable)
2258 struct sip_request resp;
2259 reqprep(&resp, p, msg, inc);
2260 add_header(&resp, "Content-Length", "0");
2261 add_blank_header(&resp);
2262 return send_request(p, &resp, reliable, p->ocseq);
2265 static int expire_register(void *data)
2267 struct sip_peer *p = data;
2268 memset(&p->addr, 0, sizeof(p->addr));
2273 static int sip_poke_peer(struct sip_peer *peer);
2275 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2277 char contact[80]= "";
2278 char *expires = get_header(req, "Expires");
2279 int expirey = atoi(expires);
2283 struct sockaddr_in oldsin;
2284 if (!strlen(expires)) {
2285 expires = strstr(get_header(req, "Contact"), "expires=");
2287 if (sscanf(expires + 8, "%d;", &expirey) != 1)
2290 /* Look for brackets */
2291 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2294 if ((n=strchr(c, '<'))) {
2297 /* Lose the part after the > */
2301 if (!strcasecmp(c, "*")) {
2302 /* This means remove all registrations and return OK */
2303 memset(&p->addr, 0, sizeof(p->addr));
2305 ast_sched_del(sched, p->expire);
2307 if (option_verbose > 2)
2308 ast_verbose(VERBOSE_PREFIX_3 "Unegistered SIP '%s'\n", p->username);
2311 /* Make sure it's a SIP URL */
2312 if (strncasecmp(c, "sip:", 4)) {
2313 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2329 pt = strchr(n, ':');
2335 port = DEFAULT_SIP_PORT;
2336 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2338 /* XXX This could block for a long time XXX */
2339 hp = gethostbyname(n);
2341 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2344 p->addr.sin_family = AF_INET;
2345 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2346 p->addr.sin_port = htons(port);
2348 /* Don't trust the contact field. Just use what they came to us
2350 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2353 strncpy(p->username, c, sizeof(p->username) - 1);
2355 strcpy(p->username, "");
2357 ast_sched_del(sched, p->expire);
2358 if ((expirey < 1) || (expirey > max_expirey))
2359 expirey = max_expirey;
2360 p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2361 pvt->expirey = expirey;
2362 if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2364 if (option_verbose > 2)
2365 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);
2370 static void md5_hash(char *output, char *input)
2372 struct MD5Context md5;
2373 unsigned char digest[16];
2377 MD5Update(&md5, input, strlen(input));
2378 MD5Final(digest, &md5);
2381 ptr += sprintf(ptr, "%2.2x", digest[x]);
2384 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)
2387 /* Always OK if no secret */
2388 if (!strlen(secret))
2390 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2391 snprintf(randdata, randlen, "%08x", rand());
2392 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2393 /* Schedule auto destroy in 15 seconds */
2394 sip_scheddestroy(p, 15000);
2397 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2398 an example in the spec of just what it is you're doing a hash on. */
2404 char resp_hash[256];
2410 /* Find their response among the mess that we'r sent for comparison */
2411 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2415 while (*c && (*c < 33)) c++;
2418 if (!strncasecmp(c, "response=", strlen("response="))) {
2419 c+= strlen("response=");
2422 if((c = strchr(c,'\"')))
2427 if((c = strchr(c,',')))
2431 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2435 if((c = strchr(c,'\"')))
2439 if((c = strchr(c,',')))
2448 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2449 if(strlen(resp_uri))
2450 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2452 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2453 md5_hash(a1_hash, a1);
2454 md5_hash(a2_hash, a2);
2455 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2456 md5_hash(resp_hash, resp);
2458 /* resp_hash now has the expected response, compare the two */
2460 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2464 /* Assume success ;-) */
2465 /* Eliminate random data */
2466 strcpy(randdata, "");
2471 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2474 struct sip_peer *peer;
2480 while(*t && (*t > 32) && (*t != ';'))
2484 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2485 c = ditch_braces(tmp);
2486 if (!strncmp(c, "sip:", 4)) {
2490 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2492 c = strchr(name, '@');
2495 ast_pthread_mutex_lock(&peerl.lock);
2498 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2500 transmit_response(p, "100 Trying", req);
2501 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
2502 sip_cancel_destroy(p);
2503 if (parse_contact(p, peer, req)) {
2504 ast_log(LOG_WARNING, "Failed to parse contact info\n");
2506 /* Say OK and ask subsystem to retransmit msg counter */
2507 transmit_response(p, "200 OK", req);
2508 peer->lastmsgssent = -1;
2516 ast_pthread_mutex_unlock(&peerl.lock);
2518 transmit_response(p, "401 Unauthorized", &p->initreq);
2522 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2524 char tmp[256] = "", *c, *a;
2525 struct sip_request *req;
2530 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2531 c = ditch_braces(tmp);
2532 if (strncmp(c, "sip:", 4)) {
2533 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2537 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2541 ast_verbose("Looking for %s in %s\n", c, p->context);
2542 if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2544 strncpy(p->exten, c, sizeof(p->exten) - 1);
2548 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2555 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2557 char tmp[256] = "", *c, *a;
2558 char tmp2[256] = "", *c2, *a2;
2561 char tmp5[256] = ""; /* CallID to replace */
2562 struct sip_request *req;
2568 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2569 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2570 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2571 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2573 c = ditch_braces(tmp);
2574 c2 = ditch_braces(tmp2);
2577 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2578 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2579 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
2584 if ((a = strchr(c, '?'))) {
2585 /* Search for arguemnts */
2588 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2589 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2590 if ((a = strchr(tmp5, '%'))) {
2591 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
2593 if ((a[1] == '4') && (a[2] == '0')) {
2595 memmove(a + 1, a+3, strlen(a + 3));
2598 if ((a = strchr(tmp5, '%')))
2603 if ((a = strchr(c, '@')))
2605 if ((a = strchr(c, ';')))
2609 if ((a2 = strchr(c2, '@')))
2612 if ((a2 = strchr(c2, ';')))
2617 ast_verbose("Looking for %s in %s\n", c, p->context);
2618 ast_verbose("Looking for %s in %s\n", c2, p->context);
2621 /* This is a supervised transfer */
2622 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2624 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2625 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2626 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2627 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2628 p->refer_call = NULL;
2629 ast_pthread_mutex_lock(&iflock);
2630 /* Search interfaces and find the match */
2633 if (!strcmp(p2->callid, tmp5)) {
2634 /* Go ahead and lock it before returning */
2635 ast_pthread_mutex_lock(&p2->lock);
2641 ast_pthread_mutex_unlock(&iflock);
2645 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2646 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2647 /* This is an unsupervised transfer */
2648 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2649 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2650 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2651 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2652 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2653 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2654 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2655 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2656 p->refer_call = NULL;
2658 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2666 static int check_via(struct sip_pvt *p, struct sip_request *req)
2672 memset(via, 0, sizeof(via));
2673 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2674 c = strchr(via, ';');
2677 c = strchr(via, ' ');
2681 while(*c && (*c < 33))
2683 if (strcmp(via, "SIP/2.0/UDP")) {
2684 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2687 pt = strchr(c, ':');
2692 hp = gethostbyname(c);
2694 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2697 memset(&p->sa, 0, sizeof(p->sa));
2698 p->sa.sin_family = AF_INET;
2699 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2700 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2703 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2705 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2711 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2713 struct sip_user *user;
2714 struct sip_peer *peer;
2715 char *of, from[256] = "", *c;
2720 while(*t && (*t > 32) && (*t != ';'))
2723 of = get_header(req, "From");
2724 strncpy(from, of, sizeof(from) - 1);
2725 of = ditch_braces(from);
2726 if (strncmp(of, "sip:", 4)) {
2727 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2730 /* Get just the username part */
2731 if ((c = strchr(of, '@')))
2733 if ((c = strchr(of, ':')))
2735 strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2738 ast_pthread_mutex_lock(&userl.lock);
2741 if (!strcasecmp(user->name, of)) {
2744 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2745 ast_rtp_setnat(p->rtp, p->nat);
2747 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri, 1))) {
2748 sip_cancel_destroy(p);
2749 strncpy(p->context, user->context, sizeof(p->context) - 1);
2750 if (strlen(user->callerid) && strlen(p->callerid))
2751 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2752 strncpy(p->username, user->name, sizeof(p->username) - 1);
2753 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
2754 p->canreinvite = user->canreinvite;
2755 p->amaflags = user->amaflags;
2756 if (user->dtmfmode) {
2757 p->dtmfmode = user->dtmfmode;
2758 if (p->dtmfmode & SIP_DTMF_RFC2833)
2759 p->noncodeccapability |= AST_RTP_DTMF;
2761 p->noncodeccapability &= ~AST_RTP_DTMF;
2768 ast_pthread_mutex_unlock(&userl.lock);
2770 /* If we didn't find a user match, check for peers */
2771 ast_pthread_mutex_lock(&peerl.lock);
2774 if (!memcmp(&peer->addr, &p->recv, sizeof(peer->addr))) {
2778 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2779 ast_rtp_setnat(p->rtp, p->nat);
2781 p->canreinvite = peer->canreinvite;
2782 strncpy(p->username, peer->name, sizeof(p->username) - 1);
2783 if (peer->dtmfmode) {
2784 p->dtmfmode = peer->dtmfmode;
2785 if (p->dtmfmode & SIP_DTMF_RFC2833)
2786 p->noncodeccapability |= AST_RTP_DTMF;
2788 p->noncodeccapability &= ~AST_RTP_DTMF;
2794 ast_pthread_mutex_unlock(&peerl.lock);
2799 static int get_msg_text(char *buf, int len, struct sip_request *req)
2803 for (x=0;x<req->lines;x++) {
2804 strncat(buf, req->line[x], len - strlen(buf) - 5);
2810 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2814 if (get_msg_text(buf, sizeof(buf), req)) {
2815 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2820 ast_verbose("Message received: '%s'\n", buf);
2821 memset(&f, 0, sizeof(f));
2822 f.frametype = AST_FRAME_TEXT;
2826 f.datalen = strlen(buf);
2827 ast_queue_frame(p->owner, &f, 1);
2831 static int sip_show_users(int fd, int argc, char *argv[])
2833 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2834 struct sip_user *user;
2836 return RESULT_SHOWUSAGE;
2837 ast_pthread_mutex_lock(&userl.lock);
2838 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2839 for(user=userl.users;user;user=user->next) {
2840 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2842 user->ha ? "Yes" : "No");
2844 ast_pthread_mutex_unlock(&userl.lock);
2845 return RESULT_SUCCESS;
2849 static int sip_show_peers(int fd, int argc, char *argv[])
2851 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2852 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2853 struct sip_peer *peer;
2854 char name[256] = "";
2856 return RESULT_SHOWUSAGE;
2857 ast_pthread_mutex_lock(&peerl.lock);
2858 ast_cli(fd, FORMAT2, "Name/username", "Host", " ", "Mask", "Port", "Status");
2859 for (peer = peerl.peers;peer;peer = peer->next) {
2862 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2863 if (strlen(peer->username))
2864 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2866 strncpy(name, peer->name, sizeof(name) - 1);
2868 if (peer->lastms < 0)
2869 strcpy(status, "UNREACHABLE");
2870 else if (peer->lastms > peer->maxms)
2871 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2872 else if (peer->lastms)
2873 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2875 strcpy(status, "UNKNOWN");
2877 strcpy(status, "Unmonitored");
2878 ast_cli(fd, FORMAT, name,
2879 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2880 peer->dynamic ? "(D)" : " ",
2882 ntohs(peer->addr.sin_port), status);
2884 ast_pthread_mutex_unlock(&peerl.lock);
2885 return RESULT_SUCCESS;
2890 static char *regstate2str(int regstate)
2893 case REG_STATE_UNREGISTERED:
2894 return "Unregistered";
2895 case REG_STATE_REGSENT:
2896 return "Request Sent";
2897 case REG_STATE_AUTHSENT:
2898 return "Auth. Sent";
2899 case REG_STATE_REGISTERED:
2900 return "Registered";
2901 case REG_STATE_REJECTED:
2903 case REG_STATE_TIMEOUT:
2905 case REG_STATE_NOAUTH:
2906 return "No Authentication";
2912 static int sip_show_registry(int fd, int argc, char *argv[])
2914 #define FORMAT2 "%-20.20s %-10.10s %8.8s %-20.20s\n"
2915 #define FORMAT "%-20.20s %-10.10s %8d %-20.20s\n"
2916 struct sip_registry *reg;
2919 return RESULT_SHOWUSAGE;
2920 ast_pthread_mutex_lock(&peerl.lock);
2921 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2922 for (reg = registrations;reg;reg = reg->next) {
2923 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2924 ast_cli(fd, FORMAT, host,
2925 reg->username, reg->refresh, regstate2str(reg->regstate));
2927 ast_pthread_mutex_unlock(&peerl.lock);
2928 return RESULT_SUCCESS;
2933 static int sip_show_channels(int fd, int argc, char *argv[])
2935 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2936 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
2937 struct sip_pvt *cur;
2940 return RESULT_SHOWUSAGE;
2941 ast_pthread_mutex_lock(&iflock);
2943 ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2945 ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr),
2946 strlen(cur->username) ? cur->username : "(None)",
2948 cur->ocseq, cur->icseq,
2951 cur->owner ? cur->owner->nativeformats : 0);
2955 ast_pthread_mutex_unlock(&iflock);
2956 ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2957 return RESULT_SUCCESS;
2962 static char *complete_sipch(char *line, char *word, int pos, int state)
2965 struct sip_pvt *cur;
2967 ast_pthread_mutex_lock(&iflock);
2970 if (!strncasecmp(word, cur->callid, strlen(word))) {
2971 if (++which > state) {
2972 c = strdup(cur->callid);
2978 ast_pthread_mutex_unlock(&iflock);
2982 static int sip_show_channel(int fd, int argc, char *argv[])
2984 struct sip_pvt *cur;
2987 return RESULT_SHOWUSAGE;
2988 ast_pthread_mutex_lock(&iflock);
2991 if (!strcasecmp(cur->callid, argv[3])) {
2992 ast_cli(fd, "Call-ID: %s\n", cur->callid);
2993 ast_cli(fd, "Codec Capability: %d\n", cur->capability);
2994 ast_cli(fd, "Non-Codec Capability: %d\n", cur->noncodeccapability);
2995 ast_cli(fd, "Theoretical Address: %s:%d\n", inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
2996 ast_cli(fd, "Received Address: %s:%d\n", inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
2997 ast_cli(fd, "NAT Support: %s\n", cur->nat ? "Yes" : "No");
2999 if (cur->dtmfmode & SIP_DTMF_RFC2833)
3000 strcat(tmp, "rfc2833 ");
3001 if (cur->dtmfmode & SIP_DTMF_INFO)
3002 strcat(tmp, "info ");
3003 if (cur->dtmfmode & SIP_DTMF_INBAND)
3004 strcat(tmp, "inband ");
3005 ast_cli(fd, "DTMF Mode: %s\n", tmp);
3010 ast_pthread_mutex_unlock(&iflock);
3012 ast_cli(fd, "No such SIP Call ID '%s'\n", argv[3]);
3013 return RESULT_SUCCESS;
3016 static void receive_info(struct sip_pvt *p, struct sip_request *req)
3018 char buf[1024] = "";
3021 /* Try getting the "signal=" part */
3022 if ((c = get_sdp(req, "Signal"))) {
3023 strncpy(buf, c, sizeof(buf) - 1);
3024 } else if (get_msg_text(buf, sizeof(buf), req)) {
3025 /* Normal INFO method */
3026 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
3033 ast_verbose("DTMF received: '%c'\n", buf[0]);
3034 memset(&f, 0, sizeof(f));
3035 f.frametype = AST_FRAME_DTMF;
3036 f.subclass = buf[0];
3040 ast_queue_frame(p->owner, &f, 1);
3045 static int sip_do_debug(int fd, int argc, char *argv[])
3048 return RESULT_SHOWUSAGE;
3050 ast_cli(fd, "SIP Debugging Enabled\n");
3051 return RESULT_SUCCESS;
3054 static int sip_no_debug(int fd, int argc, char *argv[])
3057 return RESULT_SHOWUSAGE;
3059 ast_cli(fd, "SIP Debugging Disabled\n");
3060 return RESULT_SUCCESS;
3063 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
3065 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
3067 memset(digest,0,sizeof(digest));
3068 reply_digest(p,req, "WWW-Authenticate", "REGISTER", digest, sizeof(digest) );
3069 return transmit_register(p->registry,"REGISTER",digest);
3072 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
3074 memset(digest,0,sizeof(digest));
3075 reply_digest(p,req, "Proxy-Authenticate", "INVITE", digest, sizeof(digest) );
3076 return transmit_invite(p,"INVITE",1,digest, NULL);
3079 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
3090 char resp_hash[256];
3094 strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
3096 c+=strlen("Digest ");
3098 while (*c && (*c < 33)) c++;
3101 if (!strncasecmp(c,"realm=", strlen("realm="))) {
3102 c+=strlen("realm=");
3105 if ((c = strchr(c,'\"')))
3109 if ((c = strchr(c,',')))
3113 } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
3114 c+=strlen("nonce=");
3117 if ((c = strchr(c,'\"')))
3121 if ((c = strchr(c,',')))
3130 /* Okay. We've got the realm and nonce from the server. Now lets build the MD5 digest. */
3131 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
3133 snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
3134 snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
3135 md5_hash(a1_hash,a1);
3136 md5_hash(a2_hash,a2);
3137 snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
3138 md5_hash(resp_hash,resp);
3140 snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
3150 static char show_users_usage[] =
3151 "Usage: sip show users\n"
3152 " Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
3154 static char show_channels_usage[] =
3155 "Usage: sip show channels\n"
3156 " Lists all currently active SIP channels.\n";
3158 static char show_channel_usage[] =
3159 "Usage: sip show channel <channel>\n"
3160 " Provides detailed status on a given SIP channel.\n";
3162 static char show_peers_usage[] =
3163 "Usage: sip show peers\n"
3164 " Lists all known SIP peers.\n";
3166 static char show_reg_usage[] =
3167 "Usage: sip show registry\n"
3168 " Lists all registration requests and status.\n";
3170 static char debug_usage[] =
3171 "Usage: sip debug\n"
3172 " Enables dumping of SIP packets for debugging purposes\n";
3174 static char no_debug_usage[] =
3175 "Usage: sip no debug\n"
3176 " Disables dumping of SIP packets for debugging purposes\n";
3178 static struct ast_cli_entry cli_show_users =
3179 { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
3180 static struct ast_cli_entry cli_show_channels =
3181 { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage};
3182 static struct ast_cli_entry cli_show_channel =
3183 { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch };
3184 static struct ast_cli_entry cli_show_peers =
3185 { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
3186 static struct ast_cli_entry cli_show_registry =
3187 { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
3188 static struct ast_cli_entry cli_debug =
3189 { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
3190 static struct ast_cli_entry cli_no_debug =
3191 { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
3194 static int sip_poke_peer_s(void *data)
3196 struct sip_peer *peer = data;
3197 peer->pokeexpire = -1;
3198 sip_poke_peer(peer);
3202 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
3206 strncpy(tmp, get_header(req, "Contact"), sizeof(tmp) - 1);
3208 e = strchr(tmp, '@');
3211 if (!strncasecmp(s, "sip:", 4))
3213 ast_log(LOG_DEBUG, "Found 302 Redirect to extension '%s'\n", s);
3215 strncpy(p->owner->call_forward, s, sizeof(p->owner->call_forward) - 1);
3218 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
3222 struct ast_channel *owner;
3223 struct sip_peer *peer;
3227 c = get_header(req, "Cseq");
3228 if (sscanf(c, "%d ", &seqno) != 1) {
3229 ast_log(LOG_WARNING, "Unable to determine sequence number\n");
3231 msg = strchr(c, ' ');
3232 if (!msg) msg = ""; else msg++;
3234 ast_pthread_mutex_lock(&p->lock);
3235 /* Go ahead and lock the owner if it has one -- we may need it */
3236 if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
3237 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
3238 ast_pthread_mutex_unlock(&p->lock);
3239 /* Sleep infintismly short amount of time */
3245 /* We don't really care what the response is, just that it replied back.
3246 Well, as long as it's not a 100 response... since we might
3247 need to hang around for something more "difinitive" */
3250 gettimeofday(&tv, NULL);
3251 pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
3252 (tv.tv_usec - peer->ps.tv_usec) / 1000;
3255 if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
3256 if (pingtime <= peer->maxms)
3257 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
3258 } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
3259 if (pingtime > peer->maxms)
3260 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
3262 peer->lastms = pingtime;
3264 if (peer->pokeexpire > -1)
3265 ast_sched_del(sched, peer->pokeexpire);
3266 if (!strcasecmp(msg, "INVITE"))
3267 transmit_request(p, "ACK", 0, 0);
3270 /* Try again eventually */
3271 if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
3272 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
3274 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
3276 } else if (p->outgoing) {
3277 /* Acknowledge sequence number */
3278 __sip_ack(p, seqno, 0);
3279 if (p->initid > -1) {
3280 /* Don't auto congest anymore since we've gotten something useful back */
3281 ast_sched_del(sched, p->initid);
3284 /* Get their tag if we haven't already */
3285 if (!strlen(p->theirtag)) {
3286 to = get_header(req, "To");
3287 to = strstr(to, "tag=");
3290 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
3291 to = strchr(p->theirtag, ';');
3300 case 183: /* We don't really need this since we pass in-band audio anyway */
3302 if (strlen(get_header(req, "Content-Type")))
3303 process_sdp(p, req);
3307 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
3308 if (p->owner->_state != AST_STATE_UP)
3309 ast_setstate(p->owner, AST_STATE_RINGING);
3313 if (!strcasecmp(msg, "NOTIFY")) {
3314 /* They got the notify, this is the end */
3316 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
3317 ast_queue_hangup(p->owner, 0);
3322 } else if (!strcasecmp(msg, "INVITE")) {
3323 if (strlen(get_header(req, "Content-Type")))
3324 process_sdp(p, req);
3326 if (p->owner->_state != AST_STATE_UP) {
3327 ast_setstate(p->owner, AST_STATE_UP);
3328 ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
3331 transmit_request(p, "ACK", 0, 0);
3332 } else if (!strcasecmp(msg, "REGISTER")) {
3335 struct sip_registry *r;
3337 r->regstate=REG_STATE_REGISTERED;
3338 ast_log(LOG_NOTICE, "Registration successful\n");
3339 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
3341 ast_sched_del(sched, r->timeout);
3343 /* set us up for re-registering */
3344 /* figure out how long we got registered for */
3345 if (r->expire != -1)
3346 ast_sched_del(sched, r->expire);
3347 expires=atoi(get_header(req, "expires"));
3348 if (!expires) expires=default_expirey;
3349 r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r);
3353 case 401: /* Not authorized on REGISTER */
3354 /* XXX: Do I need to ACK the 401?
3355 transmit_request(p, "ACK", 0);
3357 do_register_auth(p, req);
3361 transmit_request(p, "ACK", 0, 0);
3363 do_proxy_auth(p, req);
3364 /* This is just a hack to kill the channel while testing */
3370 ast_rtp_destroy(rtp);
3373 ast_queue_hangup(p->owner,0);
3374 transmit_request(p,"ACK",0);
3380 if ((resp >= 400) && (resp < 700)) {
3381 if (option_verbose > 2)
3382 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
3385 /* Immediately stop RTP */
3386 ast_rtp_stop(p->rtp);
3388 /* XXX Locking issues?? XXX */
3390 case 302: /* Moved temporarily */
3391 parse_moved_contact(p, req);
3393 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
3395 case 486: /* Busy here */
3396 case 600: /* Busy everywhere */
3398 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
3400 case 480: /* Temporarily Unavailable */
3401 case 404: /* Not Found */
3402 case 410: /* Gone */
3403 case 500: /* Server error */
3404 case 501: /* Not Implemented */
3406 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
3411 ast_queue_hangup(p->owner, 0);
3414 transmit_request(p, "ACK", 0, 0);
3417 ast_log(LOG_NOTICE, "Dunno anything about a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : inet_ntoa(p->sa.sin_addr));
3421 ast_verbose("Message is %s\n", msg);
3424 if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
3425 transmit_request(p, "ACK", 0, 0);
3430 ast_pthread_mutex_unlock(&owner->lock);
3432 ast_pthread_mutex_unlock(&p->lock);
3435 static int determine_firstline_parts( struct sip_request *req ) {
3440 cmd= req->header[0];
3441 while(*cmd && (*cmd < 33)) {
3448 while(*e && (*e > 32)) {
3451 /* Get the command */
3457 while( *e && ( *e < 33 ) ) {
3464 if ( !strcasecmp(cmd, "SIP/2.0") ) {
3465 /* We have a response */
3467 len= strlen( req->rlPart2 );
3468 if( len < 2 ) { return -1; }
3470 while( *e && *e<33 ) {
3475 /* We have a request */
3478 if( !*e ) { return -1; }
3481 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3484 while( isspace( *(--e) ) ) {}
3494 static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
3496 if (!p1->owner || !p2->owner) {
3497 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
3500 if (p1->owner->bridge) {
3501 if (p2->owner->bridge)
3502 ast_moh_stop(p2->owner->bridge);
3503 ast_moh_stop(p1->owner->bridge);
3504 ast_moh_stop(p1->owner);
3505 ast_moh_stop(p2->owner);
3506 if (ast_channel_masquerade(p2->owner, p1->owner->bridge)) {
3507 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p2->owner->name, p1->owner->bridge->name);
3510 } else if (p2->owner->bridge) {
3511 ast_moh_stop(p2->owner->bridge);
3512 ast_moh_stop(p2->owner);
3513 ast_moh_stop(p1->owner);
3514 if (ast_channel_masquerade(p1->owner, p2->owner->bridge)) {
3515 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p1->owner->name, p2->owner->bridge->name);
3519 ast_log(LOG_NOTICE, "Transfer attempted with no bridged calls to transfer\n");
3525 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
3527 struct sip_request resp;
3531 struct ast_channel *c=NULL;