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 static char *desc = "Session Initiation Protocol (SIP)";
69 static char *type = "sip";
70 static char *tdesc = "Session Initiation Protocol (SIP)";
71 static char *config = "sip.conf";
73 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
74 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
76 static char context[AST_MAX_EXTENSION] = "default";
78 static char language[MAX_LANGUAGE] = "";
80 static char callerid[AST_MAX_EXTENSION] = "asterisk";
83 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
85 /* Protect the interface list (of sip_pvt's) */
86 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
88 /* Protect the monitoring thread, so only one process can kill or start it, and not
89 when it's doing something critical. */
90 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
92 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
94 /* This is the thread for the monitor which checks for input on the channels
95 which are not currently in use. */
96 static pthread_t monitor_thread = 0;
98 static int restart_monitor(void);
100 /* Codecs that we support by default: */
101 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
102 static int nonCodecCapability = AST_RTP_DTMF;
104 static char ourhost[256];
105 static struct in_addr __ourip;
108 static int sipdebug = 0;
112 static int globaldtmfmode = SIP_DTMF_RFC2833;
115 static int expirey = 900;
117 static struct sched_context *sched;
118 static struct io_context *io;
119 /* The private structures of the sip channels are linked for
120 selecting outgoing channels */
122 #define SIP_MAX_HEADERS 64
123 #define SIP_MAX_LINES 64
125 static struct sip_codec_pref {
127 struct sip_codec_pref *next;
131 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
132 char *rlPart2; /* The Request URI or Response Status */
134 int headers; /* SIP Headers */
135 char *header[SIP_MAX_HEADERS];
136 int lines; /* SDP Content */
137 char *line[SIP_MAX_LINES];
138 char data[SIP_MAX_PACKET];
141 static struct sip_pvt {
142 pthread_mutex_t lock; /* Channel private lock */
143 char callid[80]; /* Global CallID */
144 char randdata[80]; /* Random data */
145 unsigned int ocseq; /* Current outgoing seqno */
146 unsigned int icseq; /* Current incoming seqno */
147 int lastinvite; /* Last Cseq of invite */
148 int alreadygone; /* Whether or not we've already been destroyed by or peer */
149 int needdestroy; /* if we need to be destroyed */
150 int capability; /* Special capability */
151 int nonCodecCapability;
152 int outgoing; /* Outgoing or incoming call? */
153 int insecure; /* Don't check source port/ip */
154 int expirey; /* How long we take to expire */
155 int branch; /* One random number */
156 int canreinvite; /* Do we support reinvite */
157 int progress; /* Have sent 183 message progress */
158 int tag; /* Another random number */
159 int nat; /* Whether to try to support NAT */
160 struct sockaddr_in sa; /* Our peer */
161 struct sockaddr_in recv; /* Received as */
162 struct in_addr ourip; /* Our IP */
163 struct ast_channel *owner; /* Who owns us */
164 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
165 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
166 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
167 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
168 struct sip_pvt *refer_call; /* Call we are referring */
169 char record_route[256];
170 char record_route_info[256];
171 char remote_party_id[256];
172 char context[AST_MAX_EXTENSION];
173 char language[MAX_LANGUAGE];
174 char theirtag[256]; /* Their tag */
178 char callerid[256]; /* Caller*ID */
180 char accountcode[256]; /* Account code */
181 int amaflags; /* AMA Flags */
182 struct sip_request initreq; /* Initial request */
184 int maxtime; /* Max time for first response */
185 int initid; /* Auto-congest ID if appropriate */
190 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
191 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
192 struct ast_rtp *rtp; /* RTP Session */
193 struct sip_pvt *next;
196 static struct sip_pkt {
198 struct sip_pvt *owner;
200 char data[SIP_MAX_PACKET];
201 struct sip_pkt *next;
205 /* Users who can access various contexts */
211 char accountcode[80];
219 struct sip_user *next;
225 char context[80]; /* JK02: peers need context too to allow parking etc */
228 char mailbox[AST_MAX_EXTENSION];
235 int nonCodecCapability;
240 struct sockaddr_in addr;
244 struct sip_pvt *call; /* Call pointer */
245 int pokeexpire; /* When to expire poke */
246 int lastms; /* How long last response took (in ms), or -1 for no response */
247 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
248 struct timeval ps; /* Ping send time */
250 struct sockaddr_in defaddr;
254 struct sip_peer *next;
257 static struct ast_user_list {
258 struct sip_user *users;
259 pthread_mutex_t lock;
260 } userl = { NULL, AST_MUTEX_INITIALIZER };
262 static struct ast_peer_list {
263 struct sip_peer *peers;
264 pthread_mutex_t lock;
265 } peerl = { NULL, AST_MUTEX_INITIALIZER };
268 #define REG_STATE_UNREGISTERED 0
269 #define REG_STATE_REGSENT 1
270 #define REG_STATE_AUTHSENT 2
271 #define REG_STATE_REGISTERED 3
272 #define REG_STATE_REJECTED 4
273 #define REG_STATE_TIMEOUT 5
274 #define REG_STATE_NOAUTH 6
276 struct sip_registry {
277 pthread_mutex_t lock; /* Channel private lock */
278 struct sockaddr_in addr; /* Who we connect to for registration purposes */
280 char secret[80]; /* Password or key name in []'s */
281 char contact[80]; /* Contact extension */
283 int expire; /* Sched ID of expiration */
284 int timeout; /* sched id of sip_reg_timeout */
285 int refresh; /* How often to refresh */
286 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
288 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
289 char callid[80]; /* Global CallID for this registry */
290 struct sockaddr_in us; /* Who the server thinks we are */
291 struct sip_registry *next;
294 static int sip_do_register(struct sip_registry *r);
295 struct sip_registry *registrations;
297 static int sipsock = -1;
298 static int globalnat = 0;
300 static struct sockaddr_in bindaddr;
302 static struct ast_frame *sip_read(struct ast_channel *ast);
303 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
304 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req);
305 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand);
306 static int transmit_request(struct sip_pvt *p, char *msg, int inc);
307 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
308 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
309 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
310 static int transmit_message_with_text(struct sip_pvt *p, char *text);
311 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
312 char *getsipuri(char *header);
314 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
318 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
320 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
322 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));
327 static int send_response(struct sip_pvt *p, struct sip_request *req)
332 ast_verbose("Transmitting (NAT):\n%s\n to %s:%d\n", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
334 ast_verbose("Transmitting (no NAT):\n%s\n to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
336 res = __sip_xmit(p, req->data, req->len);
342 static int send_request(struct sip_pvt *p, struct sip_request *req)
347 ast_verbose("XXX Need to handle Retransmitting XXX:\n%s (NAT) to %s:%d\n", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
349 ast_verbose("XXX Need to handle Retransmitting XXX:\n%s (no NAT) to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
351 res = __sip_xmit(p, req->data, req->len);
355 static char *ditch_braces(char *tmp)
360 if ((n = strchr(tmp, '<')) ) {
362 while(*c && *c != '>') c++;
364 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
373 static int sip_sendtext(struct ast_channel *ast, char *text)
375 struct sip_pvt *p = ast->pvt->pvt;
377 ast_verbose("Sending text %s on %s\n", text, ast->name);
380 if (!text || !strlen(text))
383 ast_verbose("Really sending text %s on %s\n", text, ast->name);
384 transmit_message_with_text(p, text);
388 static int create_addr(struct sip_pvt *r, char *peer)
393 r->sa.sin_family = AF_INET;
394 ast_pthread_mutex_lock(&peerl.lock);
397 if (!strcasecmp(p->name, peer)) {
399 r->capability = p->capability;
400 r->nonCodecCapability = p->nonCodecCapability;
403 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
404 ast_rtp_setnat(r->rtp, r->nat);
406 strncpy(r->peername, p->username, sizeof(r->peername)-1);
407 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
408 strncpy(r->username, p->username, sizeof(r->username)-1);
409 r->insecure = p->insecure;
410 r->canreinvite = p->canreinvite;
411 r->maxtime = p->maxms;
413 r->dtmfmode = p->dtmfmode;
414 if (r->dtmfmode & SIP_DTMF_RFC2833)
415 r->nonCodecCapability |= AST_RTP_DTMF;
417 r->nonCodecCapability &= ~AST_RTP_DTMF;
419 strncpy(r->context, p->context,sizeof(r->context)-1);
420 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
421 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
422 if (p->addr.sin_addr.s_addr) {
423 r->sa.sin_addr = p->addr.sin_addr;
424 r->sa.sin_port = p->addr.sin_port;
426 r->sa.sin_addr = p->defaddr.sin_addr;
427 r->sa.sin_port = p->defaddr.sin_port;
429 memcpy(&r->recv, &r->sa, sizeof(r->recv));
435 ast_pthread_mutex_unlock(&peerl.lock);
437 hp = gethostbyname(peer);
439 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
440 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
441 memcpy(&r->recv, &r->sa, sizeof(r->recv));
444 ast_log(LOG_WARNING, "No such host: %s\n", peer);
453 static int auto_congest(void *nothing)
455 struct sip_pvt *p = nothing;
456 ast_pthread_mutex_lock(&p->lock);
459 if (!pthread_mutex_trylock(&p->owner->lock)) {
460 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
461 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
462 ast_pthread_mutex_unlock(&p->owner->lock);
465 ast_pthread_mutex_unlock(&p->lock);
469 static void sip_prefs_free(void)
471 struct sip_codec_pref *cur, *next;
481 static void sip_pref_remove(int format)
483 struct sip_codec_pref *cur, *prev=NULL;
486 if (cur->codec == format) {
488 prev->next = cur->next;
499 static int sip_pref_append(int format)
501 struct sip_codec_pref *cur, *tmp;
502 sip_pref_remove(format);
503 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
506 memset(tmp, 0, sizeof(struct sip_codec_pref));
518 static int sip_codec_choose(int formats)
520 struct sip_codec_pref *cur;
523 if (formats & cur->codec)
527 return ast_best_codec(formats);
530 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
534 char *vxml_url = NULL;
535 struct varshead *headp;
536 struct ast_var_t *current;
539 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
540 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
544 /* Check whether there is a VXML_URL variable */
545 headp=&ast->varshead;
546 AST_LIST_TRAVERSE(headp,current,entries) {
547 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
549 vxml_url = ast_var_value(current);
556 transmit_invite(p, "INVITE", 1, NULL, vxml_url);
558 /* Initialize auto-congest time */
559 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
564 static void __sip_destroy(struct sip_pvt *p, int lockowner)
566 struct sip_pvt *cur, *prev = NULL;
568 ast_rtp_destroy(p->rtp);
570 /* Unlink us from the owner if we have one */
573 ast_pthread_mutex_lock(&p->owner->lock);
574 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
575 p->owner->pvt->pvt = NULL;
577 ast_pthread_mutex_unlock(&p->owner->lock);
583 prev->next = cur->next;
592 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
595 ast_sched_del(sched, p->initid);
599 static void sip_destroy(struct sip_pvt *p)
601 ast_pthread_mutex_lock(&iflock);
603 ast_pthread_mutex_unlock(&iflock);
606 /* Interface lookup code courtesy Tilghman of DrunkCoder.com. Thanks! */
611 char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
616 struct sockaddr_in ifru_addr;
621 struct in_addr *lookup_iface(char *iface) {
624 static struct my_ifreq ifreq;
625 memset(&ifreq, 0, sizeof(ifreq));
626 strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
628 mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
629 res = ioctl(mysock,SIOCGIFADDR,&ifreq);
633 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
636 return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
639 static struct in_addr *myaddrfor(struct in_addr *them)
642 struct in_addr *temp = NULL;
643 unsigned int remote_ip;
645 remote_ip = them->s_addr;
647 PROC = fopen("/proc/net/route","r");
649 /* If /proc/net/route doesn't exist, fall back to the old method */
652 /* First line contains headers */
653 fgets(line,sizeof(line),PROC);
655 while (!feof(PROC)) {
657 unsigned int dest, gateway, mask;
661 fgets(line,sizeof(line),PROC);
664 for (i=0;i<sizeof(line);i++) {
667 fields[aoffset++] = line + i;
668 boffset = strchr(line + i,'\t');
669 if (boffset == NULL) {
678 sscanf(fields[0],"%s",iface);
679 sscanf(fields[1],"%x",&dest);
680 sscanf(fields[2],"%x",&gateway);
681 sscanf(fields[7],"%x",&mask);
683 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
685 if (((remote_ip & mask) ^ dest) == 0) {
687 ast_verbose("Interface is %s\n",iface);
688 temp = lookup_iface(iface);
690 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
696 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s. Using default\n", inet_ntoa(*them));
703 static int sip_hangup(struct ast_channel *ast)
705 struct sip_pvt *p = ast->pvt->pvt;
708 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
709 if (!ast->pvt->pvt) {
710 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
713 ast_pthread_mutex_lock(&p->lock);
714 /* Determine how to disconnect */
715 if (p->owner != ast) {
716 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
717 ast_pthread_mutex_unlock(&p->lock);
720 if (!ast || (ast->_state != AST_STATE_UP))
725 ast_dsp_free(p->vad);
728 ast->pvt->pvt = NULL;
731 /* Start the process if it's not already started */
732 if (!p->alreadygone && strlen(p->initreq.data)) {
734 transmit_request(p, "CANCEL", 0);
737 transmit_request(p, "BYE", 1);
740 ast_pthread_mutex_unlock(&p->lock);
744 static int sip_answer(struct ast_channel *ast)
748 struct sip_pvt *p = ast->pvt->pvt;
751 if (ast->_state != AST_STATE_UP) {
755 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
757 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
758 fmt=ast_getformatbyname(codec);
761 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
764 ast_setstate(ast, AST_STATE_UP);
766 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
767 res = transmit_response_with_sdp(p, "200 OK", &p->initreq);
772 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
774 struct sip_pvt *p = ast->pvt->pvt;
776 if (frame->frametype != AST_FRAME_VOICE) {
777 if (frame->frametype == AST_FRAME_IMAGE)
780 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
784 if (!(frame->subclass & ast->nativeformats)) {
785 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
786 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
791 ast_pthread_mutex_lock(&p->lock);
793 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
794 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq);
797 res = ast_rtp_write(p->rtp, frame);
799 ast_pthread_mutex_unlock(&p->lock);
804 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
806 struct sip_pvt *p = newchan->pvt->pvt;
807 ast_pthread_mutex_lock(&p->lock);
808 if (p->owner != oldchan) {
809 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
810 ast_pthread_mutex_unlock(&p->lock);
814 ast_pthread_mutex_unlock(&p->lock);
818 static int sip_senddigit(struct ast_channel *ast, char digit)
820 struct sip_pvt *p = ast->pvt->pvt;
821 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
822 transmit_info_with_digit(p, digit);
824 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
825 ast_rtp_senddigit(p->rtp, digit);
827 /* If in-band DTMF is desired, send that */
828 if (p->dtmfmode & SIP_DTMF_INBAND)
833 static int sip_indicate(struct ast_channel *ast, int condition)
835 struct sip_pvt *p = ast->pvt->pvt;
837 case AST_CONTROL_RINGING:
838 if (ast->_state == AST_STATE_RING) {
839 transmit_response(p, "180 Ringing", &p->initreq);
843 case AST_CONTROL_BUSY:
844 if (ast->_state != AST_STATE_UP) {
845 transmit_response(p, "600 Busy everywhere", &p->initreq);
847 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
851 case AST_CONTROL_CONGESTION:
852 if (ast->_state != AST_STATE_UP) {
853 transmit_response(p, "486 Busy here", &p->initreq);
855 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
862 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
870 static int sip_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
872 struct sip_pvt *p0, *p1;
874 struct ast_channel *who, *cs[3];
877 /* if need DTMF, cant native bridge */
878 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
880 ast_pthread_mutex_lock(&c0->lock);
881 ast_pthread_mutex_lock(&c1->lock);
884 ast_log(LOG_DEBUG, "Reinvite? %s: %s, %s: %s\n", c0->name, p0->canreinvite ? "yes" : "no", c1->name, p1->canreinvite ? "yes" : "no");
885 if (!p0->canreinvite || !p1->canreinvite) {
886 /* Not gonna support reinvite */
887 ast_pthread_mutex_unlock(&c0->lock);
888 ast_pthread_mutex_unlock(&c1->lock);
891 transmit_reinvite_with_sdp(p0, p1->rtp);
892 transmit_reinvite_with_sdp(p1, p0->rtp);
893 ast_pthread_mutex_unlock(&c0->lock);
894 ast_pthread_mutex_unlock(&c1->lock);
899 if ((c0->pvt->pvt != p0) ||
900 (c1->pvt->pvt != p1) ||
901 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
902 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
903 if (c0->pvt->pvt == p0)
904 transmit_reinvite_with_sdp(p0, NULL);
905 if (c1->pvt->pvt == p1)
906 transmit_reinvite_with_sdp(p1, NULL);
907 /* Tell it to try again later */
911 who = ast_waitfor_n(cs, 2, &to);
913 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
917 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
918 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
919 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
922 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
923 if (c0->pvt->pvt == p0 && !c0->_softhangup)
924 transmit_reinvite_with_sdp(p0, NULL);
925 if (c1->pvt->pvt == p1 && !c1->_softhangup)
926 transmit_reinvite_with_sdp(p1, NULL);
927 /* That's all we needed */
931 /* Swap priority not that it's a big deal at this point */
941 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
943 struct ast_channel *tmp;
945 tmp = ast_channel_alloc(1);
947 /* Select our native format based on codec preference until we receive
948 something from another device to the contrary. */
950 tmp->nativeformats = sip_codec_choose(i->capability);
952 tmp->nativeformats = sip_codec_choose(capability);
953 fmt = ast_best_codec(tmp->nativeformats);
955 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
957 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
959 if (i->dtmfmode & SIP_DTMF_INBAND) {
960 i->vad = ast_dsp_new();
961 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
963 tmp->fds[0] = ast_rtp_fd(i->rtp);
964 ast_setstate(tmp, state);
965 if (state == AST_STATE_RING)
967 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
968 tmp->writeformat = fmt;
969 tmp->pvt->rawwriteformat = fmt;
970 tmp->readformat = fmt;
971 tmp->pvt->rawreadformat = fmt;
973 tmp->pvt->send_text = sip_sendtext;
974 tmp->pvt->call = sip_call;
975 tmp->pvt->hangup = sip_hangup;
976 tmp->pvt->answer = sip_answer;
977 tmp->pvt->read = sip_read;
978 tmp->pvt->write = sip_write;
979 tmp->pvt->indicate = sip_indicate;
980 tmp->pvt->fixup = sip_fixup;
981 tmp->pvt->send_digit = sip_senddigit;
982 tmp->pvt->bridge = ast_rtp_bridge;
983 if (strlen(i->language))
984 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
986 ast_pthread_mutex_lock(&usecnt_lock);
988 ast_pthread_mutex_unlock(&usecnt_lock);
989 ast_update_use_count();
990 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
991 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
992 if (strlen(i->callerid))
993 tmp->callerid = strdup(i->callerid);
995 if (state != AST_STATE_DOWN) {
996 if (ast_pbx_start(tmp)) {
997 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1003 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1007 static struct cfalias {
1011 { "Content-Type", "c" },
1012 { "Content-Encoding", "e" },
1016 { "Content-Length", "l" },
1022 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1023 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1024 char* r = line + nameLen + 1;
1025 while (*r && (*r < 33)) ++r;
1032 static char *get_sdp(struct sip_request *req, char *name) {
1034 int len = strlen(name);
1037 for (x=0; x<req->lines; x++) {
1038 r = get_sdp_by_line(req->line[x], name, len);
1039 if (r[0] != '\0') return r;
1044 static void sdpLineNum_iterator_init(int* iterator) {
1048 static char* get_sdp_iterate(int* iterator,
1049 struct sip_request *req, char *name) {
1050 int len = strlen(name);
1052 while (*iterator < req->lines) {
1053 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1054 if (r[0] != '\0') return r;
1059 static char *__get_header(struct sip_request *req, char *name, int *start)
1062 int len = strlen(name);
1064 for (x=*start;x<req->headers;x++) {
1065 if (!strncasecmp(req->header[x], name, len) &&
1066 (req->header[x][len] == ':')) {
1067 r = req->header[x] + len + 1;
1068 while(*r && (*r < 33))
1075 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1076 if (!strcasecmp(aliases[x].fullname, name))
1077 return __get_header(req, aliases[x].shortname, start);
1079 /* Don't return NULL, so get_header is always a valid pointer */
1083 static char *get_header(struct sip_request *req, char *name)
1086 return __get_header(req, name, &start);
1089 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1091 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1092 struct ast_frame *f;
1093 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1094 f = ast_rtp_read(p->rtp);
1095 /* Don't send RFC2833 if we're not supposed to */
1096 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1099 /* We already hold the channel lock */
1100 if (f->frametype == AST_FRAME_VOICE) {
1101 if (f->subclass != p->owner->nativeformats) {
1102 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1103 p->owner->nativeformats = f->subclass;
1104 ast_set_read_format(p->owner, p->owner->readformat);
1105 ast_set_write_format(p->owner, p->owner->writeformat);
1107 if (p->dtmfmode & SIP_DTMF_INBAND) {
1108 f = ast_dsp_process(p->owner,p->vad,f,0);
1115 static struct ast_frame *sip_read(struct ast_channel *ast)
1117 struct ast_frame *fr;
1118 struct sip_pvt *p = ast->pvt->pvt;
1119 ast_pthread_mutex_lock(&p->lock);
1120 fr = sip_rtp_read(p);
1121 ast_pthread_mutex_unlock(&p->lock);
1125 static void build_callid(char *callid, int len, struct in_addr ourip)
1132 res = snprintf(callid, len, "%08x", val);
1136 /* It's not important that we really use our right IP here... */
1137 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1140 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1144 p = malloc(sizeof(struct sip_pvt));
1147 /* Keep track of stuff */
1148 memset(p, 0, sizeof(struct sip_pvt));
1150 p->rtp = ast_rtp_new(NULL, NULL);
1153 /* Start with 101 instead of 1 */
1156 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1160 ast_rtp_settos(p->rtp, tos);
1161 if (useglobalnat && sin) {
1162 /* Setup NAT structure according to global settings if we have an address */
1164 memcpy(&p->recv, sin, sizeof(p->recv));
1165 ast_rtp_setnat(p->rtp, p->nat);
1167 ast_pthread_mutex_init(&p->lock);
1169 ast_rtp_set_data(p->rtp, p);
1170 ast_rtp_set_callback(p->rtp, rtpready);
1173 memcpy(&p->sa, sin, sizeof(p->sa));
1174 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1176 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1178 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1180 build_callid(p->callid, sizeof(p->callid), p->ourip);
1182 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1183 /* Assume reinvite OK */
1185 p->dtmfmode = globaldtmfmode;
1186 if (p->dtmfmode & SIP_DTMF_RFC2833)
1187 p->nonCodecCapability |= AST_RTP_DTMF;
1189 ast_pthread_mutex_lock(&iflock);
1192 ast_pthread_mutex_unlock(&iflock);
1194 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1198 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1202 callid = get_header(req, "Call-ID");
1203 if (!strlen(callid)) {
1204 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1207 ast_pthread_mutex_lock(&iflock);
1210 if (!strcmp(p->callid, callid)) {
1211 /* Found the call */
1213 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1214 (p->sa.sin_port != sin->sin_port))) {
1217 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1218 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1219 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1220 ast_pthread_mutex_unlock(&iflock);
1224 ast_pthread_mutex_unlock(&iflock);
1229 ast_pthread_mutex_unlock(&iflock);
1230 return sip_alloc(callid, sin, 1);
1233 static int sip_register(char *value, int lineno)
1235 struct sip_registry *reg;
1236 char copy[256] = "";
1237 char *username, *hostname, *secret;
1245 strncpy(copy, value, sizeof(copy)-1);
1248 hostname = strrchr(stringp, '@');
1254 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1258 username = strsep(&stringp, ":");
1259 secret = strsep(&stringp, ":");
1261 hostname = strsep(&stringp, "/");
1262 contact = strsep(&stringp, "/");
1263 if (!contact || !strlen(contact))
1266 hostname = strsep(&stringp, ":");
1267 porta = strsep(&stringp, ":");
1269 if (porta && !atoi(porta)) {
1270 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1273 hp = gethostbyname(hostname);
1275 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1278 reg = malloc(sizeof(struct sip_registry));
1280 memset(reg, 0, sizeof(struct sip_registry));
1281 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1282 strncpy(reg->username, username, sizeof(reg->username)-1);
1284 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1286 reg->refresh = default_expirey;
1287 reg->addr.sin_family = AF_INET;
1288 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1289 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1290 reg->next = registrations;
1291 reg->callid_valid = 0;
1292 registrations = reg;
1294 ast_log(LOG_ERROR, "Out of memory\n");
1300 static void parse(struct sip_request *req)
1302 /* Divide fields by NULL's */
1307 /* First header starts immediately */
1311 /* We've got a new header */
1315 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1317 if (!strlen(req->header[f])) {
1318 /* Line by itself means we're now in content */
1322 if (f >= SIP_MAX_HEADERS - 1) {
1323 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1326 req->header[f] = c + 1;
1327 } else if (*c == '\r') {
1328 /* Ignore but eliminate \r's */
1333 /* Check for last header */
1334 if (strlen(req->header[f]))
1337 /* Now we process any mime content */
1342 /* We've got a new line */
1345 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1347 if (f >= SIP_MAX_LINES - 1) {
1348 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1351 req->line[f] = c + 1;
1352 } else if (*c == '\r') {
1353 /* Ignore and eliminate \r's */
1358 /* Check for last line */
1359 if (strlen(req->line[f]))
1363 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1365 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1368 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1376 int peercapability, peerNonCodecCapability;
1377 struct sockaddr_in sin;
1383 /* Get codec and RTP info from SDP */
1384 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1385 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1388 m = get_sdp(req, "m");
1389 c = get_sdp(req, "c");
1390 if (!strlen(m) || !strlen(c)) {
1391 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1394 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1395 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1398 /* XXX This could block for a long time, and block the main thread! XXX */
1399 hp = gethostbyname(host);
1401 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1404 if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1405 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1408 sin.sin_family = AF_INET;
1409 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1410 sin.sin_port = htons(portno);
1412 ast_rtp_set_peer(p->rtp, &sin);
1414 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1416 // Scan through the RTP payload types specified in a "m=" line:
1417 ast_rtp_pt_clear(p->rtp);
1419 while(strlen(codecs)) {
1420 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1421 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1424 ast_rtp_set_m_type(p->rtp, codec);
1428 // Next, scan through each "a=rtpmap:" line, noting each
1429 // specified RTP payload type (with corresponding MIME subtype):
1430 sdpLineNum_iterator_init(&iterator);
1431 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1432 char* mimeSubtype = strdup(a); // ensures we have enough space
1433 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1434 // Note: should really look at the 'freq' and '#chans' params too
1435 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1439 // Now gather all of the codecs that were asked for:
1440 ast_rtp_get_current_formats(p->rtp,
1441 &peercapability, &peerNonCodecCapability);
1442 p->capability = capability & peercapability;
1443 p->nonCodecCapability = nonCodecCapability & peerNonCodecCapability;
1445 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1446 capability, peercapability, p->capability);
1447 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1448 nonCodecCapability, peerNonCodecCapability,
1449 p->nonCodecCapability);
1451 if (!p->capability) {
1452 ast_log(LOG_WARNING, "No compatible codecs!\n");
1456 if (!(p->owner->nativeformats & p->capability)) {
1457 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);
1458 p->owner->nativeformats = sip_codec_choose(p->capability);
1459 ast_set_read_format(p->owner, p->owner->readformat);
1460 ast_set_write_format(p->owner, p->owner->writeformat);
1462 if (p->owner->bridge) {
1463 /* Turn on/off music on hold if we are holding/unholding */
1464 if (sin.sin_addr.s_addr) {
1465 ast_moh_stop(p->owner->bridge);
1467 ast_moh_start(p->owner->bridge, NULL);
1475 static int add_header(struct sip_request *req, char *var, char *value)
1477 if (req->len >= sizeof(req->data) - 4) {
1478 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1482 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1485 req->header[req->headers] = req->data + req->len;
1486 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1487 req->len += strlen(req->header[req->headers]);
1488 if (req->headers < SIP_MAX_HEADERS)
1491 ast_log(LOG_WARNING, "Out of header space\n");
1497 static int add_blank_header(struct sip_request *req)
1499 if (req->len >= sizeof(req->data) - 4) {
1500 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1504 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1507 req->header[req->headers] = req->data + req->len;
1508 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1509 req->len += strlen(req->header[req->headers]);
1510 if (req->headers < SIP_MAX_HEADERS)
1513 ast_log(LOG_WARNING, "Out of header space\n");
1519 static int add_line(struct sip_request *req, char *line)
1521 if (req->len >= sizeof(req->data) - 4) {
1522 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1526 /* Add extra empty return */
1527 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1528 req->len += strlen(req->data + req->len);
1530 req->line[req->lines] = req->data + req->len;
1531 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1532 req->len += strlen(req->line[req->lines]);
1533 if (req->lines < SIP_MAX_LINES)
1536 ast_log(LOG_WARNING, "Out of line space\n");
1542 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1545 tmp = get_header(orig, field);
1547 /* Add what we're responding to */
1548 return add_header(req, field, tmp);
1550 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1555 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1561 tmp = __get_header(orig, field, &start);
1563 /* Add what we're responding to */
1564 add_header(req, field, tmp);
1570 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1576 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1583 tmp = __get_header(orig, field, &start);
1585 if (!copied && p->nat) {
1586 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1587 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1589 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1590 add_header(req, field, new);
1592 /* Add what we're responding to */
1593 add_header(req, field, tmp);
1600 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1606 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1608 /* Initialize a response */
1609 if (req->headers || req->len) {
1610 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1613 req->header[req->headers] = req->data + req->len;
1614 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1615 req->len += strlen(req->header[req->headers]);
1616 if (req->headers < SIP_MAX_HEADERS)
1619 ast_log(LOG_WARNING, "Out of header space\n");
1623 static int init_req(struct sip_request *req, char *resp, char *recip)
1625 /* Initialize a response */
1626 if (req->headers || req->len) {
1627 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1630 req->header[req->headers] = req->data + req->len;
1631 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1632 req->len += strlen(req->header[req->headers]);
1633 if (req->headers < SIP_MAX_HEADERS)
1636 ast_log(LOG_WARNING, "Out of header space\n");
1640 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1642 char newto[256] = "", *ot;
1643 memset(resp, 0, sizeof(*resp));
1644 init_resp(resp, msg, req);
1645 copy_via_headers(p, resp, req, "Via");
1646 copy_header(resp, req, "From");
1647 ot = get_header(req, "To");
1648 if (strlen(get_header(req, "Record-Route")))
1649 copy_header(resp, req, "Record-Route");
1650 if (!strstr(ot, "tag=")) {
1651 /* Add the proper tag if we don't have it already. If they have specified
1652 their tag, use it. Otherwise, use our own tag */
1653 if (strlen(p->theirtag))
1654 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1656 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1658 strncpy(newto, ot, sizeof(newto) - 1);
1661 add_header(resp, "To", ot);
1662 copy_header(resp, req, "Call-ID");
1663 copy_header(resp, req, "CSeq");
1664 add_header(resp, "User-Agent", "Asterisk PBX");
1666 /* For registration responses, we also need expirey and
1671 if ((c=getsipuri(ot))) {
1672 snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1675 snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1677 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1678 add_header(resp, "Expires", tmp);
1679 add_header(resp, "Contact", contact);
1682 /* XXX This isn't exactly right and it's implemented
1683 very stupidly *sigh* XXX */
1685 if ((c=getsipuri(ot))) {
1686 snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1689 snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1691 add_header(resp, "Contact", contact);
1696 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1698 struct sip_request *orig = &p->initreq;
1699 char stripped[80] ="";
1705 memset(req, 0, sizeof(struct sip_request));
1711 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1713 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1715 c = strchr(stripped, '<');
1724 init_req(req, msg, c);
1726 snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1728 add_header(req, "Via", p->via);
1730 ot = get_header(orig, "To");
1731 of = get_header(orig, "From");
1733 if (!strstr(ot, "tag=")) {
1734 /* Add the proper tag if we don't have it already. If they have specified
1735 their tag, use it. Otherwise, use our own tag */
1736 if (strlen(p->theirtag))
1737 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1739 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1744 add_header(req, "From", of);
1745 add_header(req, "To", ot);
1747 add_header(req, "From", ot);
1748 add_header(req, "To", of);
1750 copy_header(req, orig, "Call-ID");
1751 add_header(req, "CSeq", tmp);
1753 add_header(req, "User-Agent", "Asterisk PBX");
1757 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1759 struct sip_request resp;
1760 respprep(&resp, p, msg, req);
1761 add_header(&resp, "Content-Length", "0");
1762 add_blank_header(&resp);
1763 return send_response(p, &resp);
1766 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1768 struct sip_request resp;
1769 respprep(&resp, p, msg, req);
1770 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1771 add_header(&resp, "Accept", "application/sdp");
1772 add_header(&resp, "Content-Length", "0");
1773 add_blank_header(&resp);
1774 return send_response(p, &resp);
1777 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1779 struct sip_request resp;
1781 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1782 respprep(&resp, p, msg, req);
1783 add_header(&resp, "Proxy-Authenticate", tmp);
1784 add_header(&resp, "Content-Length", "0");
1785 add_blank_header(&resp);
1786 return send_response(p, &resp);
1789 static int add_text(struct sip_request *req, char *text)
1791 /* XXX Convert \n's to \r\n's XXX */
1792 int len = strlen(text);
1794 snprintf(clen, sizeof(clen), "%d", len);
1795 add_header(req, "Content-Type", "text/plain");
1796 add_header(req, "Content-Length", clen);
1797 add_line(req, text);
1801 static int add_digit(struct sip_request *req, char digit)
1806 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
1808 snprintf(clen, sizeof(clen), "%d", len);
1809 add_header(req, "Content-Type", "application/dtmf-relay");
1810 add_header(req, "Content-Length", clen);
1815 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1819 int alreadysent = 0;
1821 struct sockaddr_in sin;
1822 struct sip_codec_pref *cur;
1831 struct sockaddr_in dest;
1832 /* XXX We break with the "recommendation" and send our IP, in order that our
1833 peer doesn't have to gethostbyname() us XXX */
1836 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1839 ast_rtp_get_us(p->rtp, &sin);
1841 ast_rtp_get_peer(rtp, &dest);
1843 dest.sin_addr = p->ourip;
1844 dest.sin_port = sin.sin_port;
1847 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
1848 snprintf(v, sizeof(v), "v=0\r\n");
1849 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1850 snprintf(s, sizeof(s), "s=session\r\n");
1851 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1852 snprintf(t, sizeof(t), "t=0 0\r\n");
1853 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1854 /* Start by sending our preferred codecs */
1857 if (p->capability & cur->codec) {
1859 ast_verbose("Answering with preferred capability %d\n", cur->codec);
1860 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
1862 snprintf(costr, sizeof(costr), " %d", codec);
1864 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
1868 alreadysent |= cur->codec;
1871 /* Now send any other common codecs, and non-codec formats: */
1872 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1873 if ((p->capability & x) && !(alreadysent & x)) {
1875 ast_verbose("Answering with capability %d\n", x);
1876 codec = ast_rtp_lookup_code(p->rtp, 1, x);
1878 snprintf(costr, sizeof(costr), " %d", codec);
1880 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
1885 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
1886 if (p->nonCodecCapability & x) {
1888 ast_verbose("Answering with non-codec capability %d\n", x);
1889 codec = ast_rtp_lookup_code(p->rtp, 0, x);
1891 snprintf(costr, sizeof(costr), " %d", codec);
1893 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
1895 if (x == AST_RTP_DTMF) {
1896 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
1897 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
1905 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1906 snprintf(costr, sizeof(costr), "%d", len);
1907 add_header(resp, "Content-Type", "application/sdp");
1908 add_header(resp, "Content-Length", costr);
1919 static void copy_request(struct sip_request *dst,struct sip_request *src)
1923 offset = ((void *)dst) - ((void *)src);
1924 /* First copy stuff */
1925 memcpy(dst, src, sizeof(*dst));
1926 /* Now fix pointer arithmetic */
1927 for (x=0;x<src->headers;x++)
1928 dst->header[x] += offset;
1929 for (x=0;x<src->lines;x++)
1930 dst->line[x] += offset;
1933 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1935 struct sip_request resp;
1936 respprep(&resp, p, msg, req);
1937 add_sdp(&resp, p, NULL);
1938 return send_response(p, &resp);
1941 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1943 struct sip_request resp;
1944 reqprep(&resp, p, "INVITE", 1);
1945 add_sdp(&resp, p, rtp);
1946 return send_response(p, &resp);
1949 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1956 char *l = callerid, *n=NULL;
1957 if (p->owner && p->owner->callerid) {
1958 strcpy(cid, p->owner->callerid);
1959 ast_callerid_parse(cid, &n, &l);
1961 ast_shrink_phone_number(l);
1962 if (!l || !ast_isphonenumber(l))
1967 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1968 if (strlen(p->username)) {
1969 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1970 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1972 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1974 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1975 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1977 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1979 /* If there is a VXML URL append it to the SIP URL */
1982 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1986 snprintf(to, sizeof(to), "<%s>", invite );
1988 memset(req, 0, sizeof(struct sip_request));
1989 init_req(req, cmd, invite);
1990 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1992 add_header(req, "Via", p->via);
1993 add_header(req, "From", from);
1995 char contact2[256] ="", *c, contact[256];
1996 /* XXX This isn't exactly right and it's implemented
1997 very stupidly *sigh* XXX */
1998 strncpy(contact2, from, sizeof(contact2)-1);
1999 c = ditch_braces(contact2);
2000 snprintf(contact, sizeof(contact), "<%s>", c);
2001 add_header(req, "Contact", contact);
2003 add_header(req, "To", to);
2004 add_header(req, "Call-ID", p->callid);
2005 add_header(req, "CSeq", tmp);
2006 add_header(req, "User-Agent", "Asterisk PBX");
2009 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2011 struct sip_request req;
2012 initreqprep(&req, p, cmd, vxml_url);
2014 add_header(&req, "Proxy-Authorization", auth);
2016 add_sdp(&req, p, NULL);
2018 add_header(&req, "Content-Length", "0");
2019 add_blank_header(&req);
2021 if (!p->initreq.headers) {
2022 /* Use this as the basis */
2023 copy_request(&p->initreq, &req);
2026 p->lastinvite = p->ocseq;
2027 return send_request(p, &req);
2030 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
2032 struct sip_request req;
2035 initreqprep(&req, p, "NOTIFY", NULL);
2036 add_header(&req, "Event", "message-summary");
2037 add_header(&req, "Content-Type", "text/plain");
2039 snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
2040 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2041 add_header(&req, "Content-Length", clen);
2042 add_line(&req, tmp);
2044 if (!p->initreq.headers) {
2045 /* Use this as the basis */
2046 copy_request(&p->initreq, &req);
2050 p->lastinvite = p->ocseq;
2051 return send_request(p, &req);
2054 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2056 static int sip_reregister(void *data)
2058 /* if we are here, we know that we need to reregister. */
2059 struct sip_registry *r=(struct sip_registry *)data;
2060 return sip_do_register(r);
2065 static int sip_do_register(struct sip_registry *r)
2068 ast_pthread_mutex_lock(&r->lock);
2069 res=transmit_register(r, "REGISTER", NULL);
2070 ast_pthread_mutex_unlock(&r->lock);
2074 static int sip_reg_timeout(void *data)
2076 /* if we are here, our registration timed out, so we'll just do it over */
2077 struct sip_registry *r=data;
2079 ast_pthread_mutex_lock(&r->lock);
2080 ast_log(LOG_NOTICE, "Registration timed out, trying again\n");
2081 r->regstate=REG_STATE_UNREGISTERED;
2082 /* cancel ourselves first!!! */
2083 /* ast_sched_del(sched,r->timeout); */
2084 res=transmit_register(r, "REGISTER", NULL);
2085 ast_pthread_mutex_unlock(&r->lock);
2089 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2091 struct sip_request req;
2098 /* exit if we are already in process with this registrar ?*/
2099 if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2100 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2106 if (!r->callid_valid) {
2107 build_callid(r->callid, sizeof(r->callid), __ourip);
2110 p=sip_alloc( r->callid, &r->addr, 0);
2114 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2115 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2116 strncpy(p->username, r->username, sizeof(p->username)-1);
2119 /* set up a timeout */
2120 if (auth==NULL && !r->timeout) {
2121 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2122 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2125 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2126 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2128 snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2130 memset(&req, 0, sizeof(req));
2131 init_req(&req, cmd, addr);
2133 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2135 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2136 add_header(&req, "Via", via);
2137 add_header(&req, "From", from);
2138 add_header(&req, "To", to);
2141 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2142 add_header(&req, "Contact", contact);
2144 add_header(&req, "Call-ID", p->callid);
2145 add_header(&req, "CSeq", tmp);
2146 add_header(&req, "User-Agent", "Asterisk PBX");
2148 add_header(&req, "Authorization", auth);
2150 snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2151 add_header(&req, "Expires", tmp);
2152 add_header(&req, "Event", "registration");
2153 copy_request(&p->initreq, &req);
2154 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2155 return send_request(p, &req);
2158 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2160 struct sip_request req;
2161 reqprep(&req, p, "MESSAGE", 1);
2162 add_text(&req, text);
2163 return send_request(p, &req);
2166 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2168 struct sip_request req;
2169 reqprep(&req, p, "INFO", 1);
2170 add_digit(&req, digit);
2171 return send_request(p, &req);
2174 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
2176 struct sip_request resp;
2177 reqprep(&resp, p, msg, inc);
2178 add_header(&resp, "Content-Length", "0");
2179 add_blank_header(&resp);
2180 return send_request(p, &resp);
2183 static int expire_register(void *data)
2185 struct sip_peer *p = data;
2186 memset(&p->addr, 0, sizeof(p->addr));
2191 static int sip_poke_peer(struct sip_peer *peer);
2193 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2195 char contact[80]= "";
2196 char *expires = get_header(req, "Expires");
2197 int expirey = atoi(expires);
2201 struct sockaddr_in oldsin;
2202 if (!strlen(expires)) {
2203 expires = strstr(get_header(req, "Contact"), "expires=");
2205 if (sscanf(expires + 8, "%d;", &expirey) != 1)
2208 /* Look for brackets */
2209 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2212 if ((n=strchr(c, '<'))) {
2215 /* Lose the part after the > */
2219 if (!strcasecmp(c, "*")) {
2220 /* This means remove all registrations and return OK */
2221 memset(&p->addr, 0, sizeof(p->addr));
2223 ast_sched_del(sched, p->expire);
2225 if (option_verbose > 2)
2226 ast_verbose(VERBOSE_PREFIX_3 "Unegistered SIP '%s'\n", p->username);
2229 /* Make sure it's a SIP URL */
2230 if (strncasecmp(c, "sip:", 4)) {
2231 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2247 pt = strchr(n, ':');
2253 port = DEFAULT_SIP_PORT;
2254 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2256 /* XXX This could block for a long time XXX */
2257 hp = gethostbyname(n);
2259 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2262 p->addr.sin_family = AF_INET;
2263 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2264 p->addr.sin_port = htons(port);
2266 /* Don't trust the contact field. Just use what they came to us
2268 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2271 strncpy(p->username, c, sizeof(p->username) - 1);
2273 strcpy(p->username, "");
2275 ast_sched_del(sched, p->expire);
2276 if ((expirey < 1) || (expirey > max_expirey))
2277 expirey = max_expirey;
2278 p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2279 pvt->expirey = expirey;
2280 if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2282 if (option_verbose > 2)
2283 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);
2288 static void md5_hash(char *output, char *input)
2290 struct MD5Context md5;
2291 unsigned char digest[16];
2295 MD5Update(&md5, input, strlen(input));
2296 MD5Final(digest, &md5);
2299 ptr += sprintf(ptr, "%2.2x", digest[x]);
2302 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
2305 /* Always OK if no secret */
2306 if (!strlen(secret))
2308 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2309 snprintf(randdata, randlen, "%08x", rand());
2310 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
2313 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2314 an example in the spec of just what it is you're doing a hash on. */
2320 char resp_hash[256];
2326 /* Find their response among the mess that we'r sent for comparison */
2327 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2331 while (*c && (*c < 33)) c++;
2334 if (!strncasecmp(c, "response=", strlen("response="))) {
2335 c+= strlen("response=");
2338 if((c = strchr(c,'\"')))
2343 if((c = strchr(c,',')))
2347 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2351 if((c = strchr(c,'\"')))
2355 if((c = strchr(c,',')))
2364 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2365 if(strlen(resp_uri))
2366 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2368 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2369 md5_hash(a1_hash, a1);
2370 md5_hash(a2_hash, a2);
2371 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2372 md5_hash(resp_hash, resp);
2374 /* resp_hash now has the expected response, compare the two */
2376 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2380 /* Assume success ;-) */
2381 /* Eliminate random data */
2382 strcpy(randdata, "");
2387 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2390 struct sip_peer *peer;
2396 while(*t && (*t > 32) && (*t != ';'))
2400 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2401 c = ditch_braces(tmp);
2402 if (!strncmp(c, "sip:", 4)) {
2406 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2408 c = strchr(name, '@');
2411 ast_pthread_mutex_lock(&peerl.lock);
2414 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2416 transmit_response(p, "100 Trying", req);
2417 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2418 if (parse_contact(p, peer, req)) {
2419 ast_log(LOG_WARNING, "Failed to parse contact info\n");
2421 /* Say OK and ask subsystem to retransmit msg counter */
2422 transmit_response(p, "200 OK", req);
2423 peer->lastmsgssent = -1;
2431 ast_pthread_mutex_unlock(&peerl.lock);
2433 transmit_response(p, "401 Unauthorized", &p->initreq);
2437 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2439 char tmp[256] = "", *c, *a;
2440 struct sip_request *req;
2445 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2446 c = ditch_braces(tmp);
2447 if (strncmp(c, "sip:", 4)) {
2448 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2452 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2456 ast_verbose("Looking for %s in %s\n", c, p->context);
2457 if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2459 strncpy(p->exten, c, sizeof(p->exten) - 1);
2463 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2470 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2472 char tmp[256] = "", *c, *a;
2473 char tmp2[256] = "", *c2, *a2;
2476 char tmp5[256] = ""; /* CallID to replace */
2477 struct sip_request *req;
2483 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2484 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2485 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2486 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2488 c = ditch_braces(tmp);
2489 c2 = ditch_braces(tmp2);
2492 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2493 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2494 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
2499 if ((a = strchr(c, '?'))) {
2500 /* Search for arguemnts */
2503 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2504 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2505 if ((a = strchr(tmp5, '%'))) {
2506 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
2508 if ((a[1] == '4') && (a[2] == '0')) {
2510 memmove(a + 1, a+3, strlen(a + 3));
2513 if ((a = strchr(tmp5, '%')))
2518 if ((a = strchr(c, '@')))
2520 if ((a = strchr(c, ';')))
2524 if ((a2 = strchr(c2, '@')))
2527 if ((a2 = strchr(c2, ';')))
2532 ast_verbose("Looking for %s in %s\n", c, p->context);
2533 ast_verbose("Looking for %s in %s\n", c2, p->context);
2536 /* This is a supervised transfer */
2537 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2539 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2540 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2541 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2542 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2543 p->refer_call = NULL;
2544 ast_pthread_mutex_lock(&iflock);
2545 /* Search interfaces and find the match */
2548 if (!strcmp(p2->callid, tmp5)) {
2549 /* Go ahead and lock it before returning */
2550 ast_pthread_mutex_lock(&p2->lock);
2556 ast_pthread_mutex_unlock(&iflock);
2560 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2561 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2562 /* This is an unsupervised transfer */
2563 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2564 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2565 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2566 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2567 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2568 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2569 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2570 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2571 p->refer_call = NULL;
2573 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2581 static int check_via(struct sip_pvt *p, struct sip_request *req)
2587 memset(via, 0, sizeof(via));
2588 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2589 c = strchr(via, ';');
2592 c = strchr(via, ' ');
2596 while(*c && (*c < 33))
2598 if (strcmp(via, "SIP/2.0/UDP")) {
2599 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2602 pt = strchr(c, ':');
2607 hp = gethostbyname(c);
2609 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2612 memset(&p->sa, 0, sizeof(p->sa));
2613 p->sa.sin_family = AF_INET;
2614 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2615 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2618 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2620 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2626 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2628 struct sip_user *user;
2629 struct sip_peer *peer;
2630 char *of, from[256] = "", *c;
2635 while(*t && (*t > 32) && (*t != ';'))
2638 of = get_header(req, "From");
2639 strncpy(from, of, sizeof(from) - 1);
2640 of = ditch_braces(from);
2641 if (strncmp(of, "sip:", 4)) {
2642 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2645 /* Get just the username part */
2646 if ((c = strchr(of, '@')))
2648 if ((c = strchr(of, ':')))
2650 strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2653 ast_pthread_mutex_lock(&userl.lock);
2656 if (!strcasecmp(user->name, of)) {
2659 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2660 ast_rtp_setnat(p->rtp, p->nat);
2662 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2663 strncpy(p->context, user->context, sizeof(p->context) - 1);
2664 if (strlen(user->callerid) && strlen(p->callerid))
2665 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2666 strncpy(p->username, user->name, sizeof(p->username) - 1);
2667 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
2668 p->canreinvite = user->canreinvite;
2669 p->amaflags = user->amaflags;
2670 if (user->dtmfmode) {
2671 p->dtmfmode = user->dtmfmode;
2672 if (p->dtmfmode & SIP_DTMF_RFC2833)
2673 p->nonCodecCapability |= AST_RTP_DTMF;
2675 p->nonCodecCapability &= ~AST_RTP_DTMF;
2682 ast_pthread_mutex_unlock(&userl.lock);
2684 /* If we didn't find a user match, check for peers */
2685 ast_pthread_mutex_lock(&peerl.lock);
2688 if (!memcmp(&peer->addr, &p->recv, sizeof(peer->addr))) {
2692 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2693 ast_rtp_setnat(p->rtp, p->nat);
2695 p->canreinvite = peer->canreinvite;
2696 strncpy(p->username, peer->name, sizeof(p->username) - 1);
2697 if (peer->dtmfmode) {
2698 p->dtmfmode = peer->dtmfmode;
2699 if (p->dtmfmode & SIP_DTMF_RFC2833)
2700 p->nonCodecCapability |= AST_RTP_DTMF;
2702 p->nonCodecCapability &= ~AST_RTP_DTMF;
2708 ast_pthread_mutex_unlock(&peerl.lock);
2713 static int get_msg_text(char *buf, int len, struct sip_request *req)
2717 for (x=0;x<req->lines;x++) {
2718 strncat(buf, req->line[x], len - strlen(buf) - 5);
2724 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2728 if (get_msg_text(buf, sizeof(buf), req)) {
2729 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2734 ast_verbose("Message received: '%s'\n", buf);
2735 memset(&f, 0, sizeof(f));
2736 f.frametype = AST_FRAME_TEXT;
2740 f.datalen = strlen(buf);
2741 ast_queue_frame(p->owner, &f, 1);
2745 static int sip_show_users(int fd, int argc, char *argv[])
2747 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2748 struct sip_user *user;
2750 return RESULT_SHOWUSAGE;
2751 ast_pthread_mutex_lock(&userl.lock);
2752 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2753 for(user=userl.users;user;user=user->next) {
2754 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2756 user->ha ? "Yes" : "No");
2758 ast_pthread_mutex_unlock(&userl.lock);
2759 return RESULT_SUCCESS;
2763 static int sip_show_peers(int fd, int argc, char *argv[])
2765 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2766 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2767 struct sip_peer *peer;
2768 char name[256] = "";
2770 return RESULT_SHOWUSAGE;
2771 ast_pthread_mutex_lock(&peerl.lock);
2772 ast_cli(fd, FORMAT2, "Name/username", "Host", " ", "Mask", "Port", "Status");
2773 for (peer = peerl.peers;peer;peer = peer->next) {
2776 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2777 if (strlen(peer->username))
2778 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2780 strncpy(name, peer->name, sizeof(name) - 1);
2782 if (peer->lastms < 0)
2783 strcpy(status, "UNREACHABLE");
2784 else if (peer->lastms > peer->maxms)
2785 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2786 else if (peer->lastms)
2787 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2789 strcpy(status, "UNKNOWN");
2791 strcpy(status, "Unmonitored");
2792 ast_cli(fd, FORMAT, name,
2793 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2794 peer->dynamic ? "(D)" : " ",
2796 ntohs(peer->addr.sin_port), status);
2798 ast_pthread_mutex_unlock(&peerl.lock);
2799 return RESULT_SUCCESS;
2804 static char *regstate2str(int regstate)
2807 case REG_STATE_UNREGISTERED:
2808 return "Unregistered";
2809 case REG_STATE_REGSENT:
2810 return "Request Sent";
2811 case REG_STATE_AUTHSENT:
2812 return "Auth. Sent";
2813 case REG_STATE_REGISTERED:
2814 return "Registered";
2815 case REG_STATE_REJECTED:
2817 case REG_STATE_TIMEOUT:
2819 case REG_STATE_NOAUTH:
2820 return "No Authentication";
2826 static int sip_show_registry(int fd, int argc, char *argv[])
2828 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2829 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2830 struct sip_registry *reg;
2834 return RESULT_SHOWUSAGE;
2835 ast_pthread_mutex_lock(&peerl.lock);
2836 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2837 for (reg = registrations;reg;reg = reg->next) {
2838 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2839 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2840 ast_cli(fd, FORMAT, host,
2841 reg->username, state, reg->refresh, regstate2str(reg->regstate));
2843 ast_pthread_mutex_unlock(&peerl.lock);
2844 return RESULT_SUCCESS;
2849 static int sip_show_channels(int fd, int argc, char *argv[])
2851 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2852 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
2853 struct sip_pvt *cur;
2856 return RESULT_SHOWUSAGE;
2857 ast_pthread_mutex_lock(&iflock);
2859 ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2861 ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr),
2862 strlen(cur->username) ? cur->username : "(None)",
2864 cur->ocseq, cur->icseq,
2867 cur->owner ? cur->owner->nativeformats : 0);
2871 ast_pthread_mutex_unlock(&iflock);
2872 ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2873 return RESULT_SUCCESS;
2878 static char *complete_sipch(char *line, char *word, int pos, int state)
2881 struct sip_pvt *cur;
2883 ast_pthread_mutex_lock(&iflock);
2886 if (!strncasecmp(word, cur->callid, strlen(word))) {
2887 if (++which > state) {
2888 c = strdup(cur->callid);
2894 ast_pthread_mutex_unlock(&iflock);
2898 static int sip_show_channel(int fd, int argc, char *argv[])
2900 struct sip_pvt *cur;
2903 return RESULT_SHOWUSAGE;
2904 ast_pthread_mutex_lock(&iflock);
2907 if (!strcasecmp(cur->callid, argv[3])) {
2908 ast_cli(fd, "Call-ID: %s\n", cur->callid);
2909 ast_cli(fd, "Theoretical Address: %s:%d\n", inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
2910 ast_cli(fd, "Received Address: %s:%d\n", inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
2911 ast_cli(fd, "NAT Support: %s\n", cur->nat ? "Yes" : "No");
2913 if (cur->dtmfmode & SIP_DTMF_RFC2833)
2914 strcat(tmp, "rfc2833 ");
2915 if (cur->dtmfmode & SIP_DTMF_INFO)
2916 strcat(tmp, "info ");
2917 if (cur->dtmfmode & SIP_DTMF_INBAND)
2918 strcat(tmp, "inband ");
2919 ast_cli(fd, "DTMF Mode: %s\n", tmp);
2924 ast_pthread_mutex_unlock(&iflock);
2926 ast_cli(fd, "No such SIP Call ID '%s'\n", argv[3]);
2927 return RESULT_SUCCESS;
2930 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2932 char buf[1024] = "";
2935 /* Try getting the "signal=" part */
2936 if ((c = get_sdp(req, "Signal"))) {
2937 strncpy(buf, c, sizeof(buf) - 1);
2938 } else if (get_msg_text(buf, sizeof(buf), req)) {
2939 /* Normal INFO method */
2940 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2947 ast_verbose("DTMF received: '%c'\n", buf[0]);
2948 memset(&f, 0, sizeof(f));
2949 f.frametype = AST_FRAME_DTMF;
2950 f.subclass = buf[0];
2954 ast_queue_frame(p->owner, &f, 1);
2959 static int sip_do_debug(int fd, int argc, char *argv[])
2962 return RESULT_SHOWUSAGE;
2964 ast_cli(fd, "SIP Debugging Enabled\n");
2965 return RESULT_SUCCESS;
2968 static int sip_no_debug(int fd, int argc, char *argv[])
2971 return RESULT_SHOWUSAGE;
2973 ast_cli(fd, "SIP Debugging Disabled\n");
2974 return RESULT_SUCCESS;
2977 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2979 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2981 memset(digest,0,sizeof(digest));
2982 reply_digest(p,req, "WWW-Authenticate", "REGISTER", digest, sizeof(digest) );
2983 return transmit_register(p->registry,"REGISTER",digest);
2986 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2988 memset(digest,0,sizeof(digest));
2989 reply_digest(p,req, "Proxy-Authenticate", "INVITE", digest, sizeof(digest) );
2990 return transmit_invite(p,"INVITE",1,digest, NULL);
2993 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
3004 char resp_hash[256];
3008 strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
3010 c+=strlen("Digest ");
3012 while (*c && (*c < 33)) c++;
3015 if (!strncasecmp(c,"realm=", strlen("realm="))) {
3016 c+=strlen("realm=");
3019 if ((c = strchr(c,'\"')))
3023 if ((c = strchr(c,',')))
3027 } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
3028 c+=strlen("nonce=");
3031 if ((c = strchr(c,'\"')))
3035 if ((c = strchr(c,',')))
3044 /* Okay. We've got the realm and nonce from the server. Now lets build the MD5 digest. */
3045 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
3047 snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
3048 snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
3049 md5_hash(a1_hash,a1);
3050 md5_hash(a2_hash,a2);
3051 snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
3052 md5_hash(resp_hash,resp);
3054 snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
3064 static char show_users_usage[] =
3065 "Usage: sip show users\n"
3066 " Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
3068 static char show_channels_usage[] =
3069 "Usage: sip show channels\n"
3070 " Lists all currently active SIP channels.\n";
3072 static char show_channel_usage[] =
3073 "Usage: sip show channel <channel>\n"
3074 " Provides detailed status on a given SIP channel.\n";
3076 static char show_peers_usage[] =
3077 "Usage: sip show peers\n"
3078 " Lists all known SIP peers.\n";
3080 static char show_reg_usage[] =
3081 "Usage: sip show registry\n"
3082 " Lists all registration requests and status.\n";
3084 static char debug_usage[] =
3085 "Usage: sip debug\n"
3086 " Enables dumping of SIP packets for debugging purposes\n";
3088 static char no_debug_usage[] =
3089 "Usage: sip no debug\n"
3090 " Disables dumping of SIP packets for debugging purposes\n";
3092 static struct ast_cli_entry cli_show_users =
3093 { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
3094 static struct ast_cli_entry cli_show_channels =
3095 { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage};
3096 static struct ast_cli_entry cli_show_channel =
3097 { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch };
3098 static struct ast_cli_entry cli_show_peers =
3099 { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
3100 static struct ast_cli_entry cli_show_registry =
3101 { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
3102 static struct ast_cli_entry cli_debug =
3103 { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
3104 static struct ast_cli_entry cli_no_debug =
3105 { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
3108 static int sip_poke_peer_s(void *data)
3110 struct sip_peer *peer = data;
3111 peer->pokeexpire = -1;
3112 sip_poke_peer(peer);
3116 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
3120 struct ast_rtp *rtp;
3121 struct ast_channel *owner;
3122 struct sip_peer *peer;
3125 c = get_header(req, "Cseq");
3126 msg = strchr(c, ' ');
3127 if (!msg) msg = ""; else msg++;
3129 ast_pthread_mutex_lock(&p->lock);
3130 /* Go ahead and lock the owner if it has one -- we may need it */
3131 if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
3132 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
3133 ast_pthread_mutex_unlock(&p->lock);
3134 /* Sleep infintismly short amount of time */
3140 /* We don't really care what the response is, just that it replied back.
3141 Well, as long as it's not a 100 response... since we might
3142 need to hang around for something more "difinitive" */
3145 gettimeofday(&tv, NULL);
3146 pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
3147 (tv.tv_usec - peer->ps.tv_usec) / 1000;
3150 if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
3151 if (pingtime <= peer->maxms)
3152 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
3153 } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
3154 if (pingtime > peer->maxms)
3155 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
3157 peer->lastms = pingtime;
3159 if (peer->pokeexpire > -1)
3160 ast_sched_del(sched, peer->pokeexpire);
3161 if (!strcasecmp(msg, "INVITE"))
3162 transmit_request(p, "ACK", 0);
3165 /* Try again eventually */
3166 if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
3167 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
3169 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
3171 } else if (p->outgoing) {
3172 if (p->initid > -1) {
3173 /* Don't auto congest anymore since we've gotten something useful back */
3174 ast_sched_del(sched, p->initid);
3177 /* Get their tag if we haven't already */
3178 if (!strlen(p->theirtag)) {
3179 to = get_header(req, "To");
3180 to = strstr(to, "tag=");
3183 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
3184 to = strchr(p->theirtag, ';');
3193 case 183: /* We don't really need this since we pass in-band audio anyway */
3195 if (strlen(get_header(req, "Content-Type")))
3196 process_sdp(p, req);
3200 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
3201 if (p->owner->_state != AST_STATE_UP)
3202 ast_setstate(p->owner, AST_STATE_RINGING);
3206 if (strlen(get_header(req, "Content-Type")))
3207 process_sdp(p, req);
3209 if (p->owner->_state != AST_STATE_UP) {
3210 ast_setstate(p->owner, AST_STATE_UP);
3211 ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
3214 if (!strcasecmp(msg, "INVITE"))
3215 transmit_request(p, "ACK", 0);
3216 else if (!strcasecmp(msg, "REGISTER"))
3220 struct sip_registry *r;
3222 r->regstate=REG_STATE_REGISTERED;
3223 ast_log(LOG_NOTICE, "Registration successful\n");
3224 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
3226 ast_sched_del(sched, r->timeout);
3228 /* set us up for re-registering */
3229 /* figure out how long we got registered for */
3230 if (r->expire != -1)
3231 ast_sched_del(sched, r->expire);
3232 expires=atoi(get_header(req, "expires"));
3233 if (!expires) expires=default_expirey;
3234 r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r);
3238 case 401: /* Not authorized on REGISTER */
3239 /* XXX: Do I need to ACK the 401?
3240 transmit_request(p, "ACK", 0);
3242 do_register_auth(p, req);
3246 transmit_request(p, "ACK", 0);
3248 do_proxy_auth(p, req);
3249 /* This is just a hack to kill the channel while testing */
3255 ast_rtp_destroy(rtp);
3258 ast_queue_hangup(p->owner,0);
3259 transmit_request(p,"ACK",0);
3265 if ((resp >= 400) && (resp < 700)) {
3266 if (option_verbose > 2)
3267 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
3270 struct sockaddr_in sin = { AF_INET, };
3271 /* Immediately stop RTP by setting transmit to 0 */
3272 ast_rtp_setpeer(p->rtp, &sin);
3274 /* XXX Locking issues?? XXX */
3276 case 486: /* Busy here */
3277 case 600: /* Busy everywhere */
3279 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
3281 case 480: /* Temporarily Unavailable */
3282 case 404: /* Not Found */
3283 case 410: /* Gone */
3284 case 500: /* Server error */
3285 case 501: /* Not Implemented */
3287 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
3292 ast_queue_hangup(p->owner, 0);
3295 transmit_request(p, "ACK", 0);
3296 __sip_destroy(p, 0);
3299 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));
3303 ast_verbose("Message is %s\n", msg);
3306 if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
3307 transmit_request(p, "ACK", 0);
3312 ast_pthread_mutex_unlock(&owner->lock);
3314 ast_pthread_mutex_unlock(&p->lock);
3317 static int determine_firstline_parts( struct sip_request *req ) {
3322 cmd= req->header[0];
3323 while(*cmd && (*cmd < 33)) {
3330 while(*e && (*e > 32)) {
3333 /* Get the command */
3339 while( *e && ( *e < 33 ) ) {
3346 if ( !strcasecmp(cmd, "SIP/2.0") ) {
3347 /* We have a response */
3349 len= strlen( req->rlPart2 );
3350 if( len < 2 ) { return -1; }
3352 while( *e && *e<33 ) {
3357 /* We have a request */
3360 if( !*e ) { return -1; }
3363 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3366 while( isspace( *(--e) ) ) {}
3376 static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
3378 if (!p1->owner || !p2->owner) {
3379 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
3382 if (p1->owner->bridge) {
3383 if (p2->owner->bridge)
3384 ast_moh_stop(p2->owner->bridge);
3385 ast_moh_stop(p1->owner->bridge);
3386 ast_moh_stop(p1->owner);
3387 ast_moh_stop(p2->owner);
3388 if (ast_channel_masquerade(p2->owner, p1->owner->bridge)) {
3389 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p2->owner->name, p1->owner->bridge->name);
3392 } else if (p2->owner->bridge) {
3393 ast_moh_stop(p2->owner->bridge);
3394 ast_moh_stop(p2->owner);
3395 ast_moh_stop(p1->owner);
3396 if (ast_channel_masquerade(p1->owner, p2->owner->bridge)) {
3397 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p1->owner->name, p2->owner->bridge->name);
3401 ast_log(LOG_NOTICE, "Transfer attempted with no bridged calls to transfer\n");
3407 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
3409 struct sip_request resp;
3413 struct ast_channel *c=NULL;
3419 /* Clear out potential response */
3420 memset(&resp, 0, sizeof(resp));
3421 /* Get Method and Cseq */
3422 cseq = get_header(req, "Cseq");
3423 cmd = req->header[0];
3424 /* Must have Cseq */
3425 if (!strlen(cmd) || !strlen(cseq))
3427 if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
3428 ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
3431 /* Get the command */
3434 /* Determine the request URI for sip, sips or tel URIs */
3435 if( determine_firstline_parts( req ) < 0 ) {
3441 if (strcasecmp(cmd, "SIP/2.0")) {
3442 /* Request coming in */
3443 if (p->icseq && (p->icseq < seqno)) {
3444 ast_log(LOG_DEBUG, "Ignoring out of order packet %d (expecting %d)\n", seqno, p->icseq);
3446 } else if (p->icseq && (p->icseq != seqno)) {
3447 /* ignore means "don't do anything with it" but still have to
3448 respond appropriately */
3452 /* Response to our request -- Do some sanity checks */
3453 if (!p->initreq.headers) {
3454 ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about.\n");
3457 } else if (p->ocseq && (p->ocseq < seqno)) {
3458 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
3460 } else if (p->ocseq && (p->ocseq != seqno)) {
3461 /* ignore means "don't do anything with it" but still have to
3462 respond appropriately */
3467 if (strcmp(cmd, "SIP/2.0") && (seqno >= p->icseq))
3468 /* Next should follow monotonically increasing */
3469 p->icseq = seqno + 1;
3471 /* Initialize the context if it hasn't been already */
3472 if (!strcasecmp(cmd, "OPTIONS")) {
3473 if (!strlen(p->context))
3474 strncpy(p->context, context, sizeof(p->context) - 1);
3475 res = get_destination(p, req);
3477 transmit_response_with_allow(p, "404 Not Found", req);
3479 transmit_response_with_allow(p, "484 Address Incomplete", req);
3481 transmit_response_with_allow(p, "200 OK", req);
3482 } else if (!strcasecmp(cmd, "INVITE")) {
3483 if (p->outgoing && p->owner && (p->owner->_state != AST_STATE_UP)) {
3484 /* This is a call to ourself. Send ourselves an error code and stop
3485 processing immediately, as SIP really has no good mechanism for
3486 being able to call yourself */
3487 transmit_response(p, "482 Loop Detected", req);
3488 /* We do NOT destroy p here, so that our response will be accepted */
3491 /* Process the SDP portion */
3493 /* Use this as the basis */
3495 ast_verbose("Using latest request as basis request\n");
3496 /* This call is no longer outgoing if it ever was */
3498 copy_request(&p->initreq, req);
3500 if (strlen(get_header(req, "Content-Type"))) {
3501 if (process_sdp(p, req))
3504 p->capability = capability;
3505 ast_log(LOG_DEBUG, "Hm.... No sdp for the moemnt\n");
3507 } else if (sipdebug)
3508 ast_verbose("Ignoring this request\n");
3509 if (!p->lastinvite) {
3510 /* Handle authentication if this is our first invite */
3511 res = check_user(p, req, cmd, e);
3514 ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
3519 /* Initialize the context if it hasn't been already */
3520 if (!strlen(p->context))
3521 strncpy(p->context, context, sizeof(p->context) - 1);
3522 if ((res = get_destination(p, NULL))) {
3524 transmit_response(p, "404 Not Found", req);