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] = "";
81 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
83 /* Protect the interface list (of sip_pvt's) */
84 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
86 /* Protect the monitoring thread, so only one process can kill or start it, and not
87 when it's doing something critical. */
88 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
90 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
92 /* This is the thread for the monitor which checks for input on the channels
93 which are not currently in use. */
94 static pthread_t monitor_thread = 0;
96 static int restart_monitor(void);
98 /* Codecs that we support by default: */
99 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
100 static int nonCodecCapability = AST_RTP_DTMF;
102 static char ourhost[256];
103 static struct in_addr __ourip;
106 static int sipdebug = 0;
110 static int globaldtmfmode = SIP_DTMF_RFC2833;
113 static int expirey = 900;
115 static struct sched_context *sched;
116 static struct io_context *io;
117 /* The private structures of the sip channels are linked for
118 selecting outgoing channels */
120 #define SIP_MAX_HEADERS 64
121 #define SIP_MAX_LINES 64
123 static struct sip_codec_pref {
125 struct sip_codec_pref *next;
129 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
130 char *rlPart2; /* The Request URI or Response Status */
132 int headers; /* SIP Headers */
133 char *header[SIP_MAX_HEADERS];
134 int lines; /* SDP Content */
135 char *line[SIP_MAX_LINES];
136 char data[SIP_MAX_PACKET];
139 static struct sip_pvt {
140 pthread_mutex_t lock; /* Channel private lock */
141 char callid[80]; /* Global CallID */
142 char randdata[80]; /* Random data */
143 unsigned int ocseq; /* Current outgoing seqno */
144 unsigned int icseq; /* Current incoming seqno */
145 int lastinvite; /* Last Cseq of invite */
146 int alreadygone; /* Whether or not we've already been destroyed by or peer */
147 int needdestroy; /* if we need to be destroyed */
148 int capability; /* Special capability */
149 int nonCodecCapability;
150 int outgoing; /* Outgoing or incoming call? */
151 int insecure; /* Don't check source port/ip */
152 int expirey; /* How long we take to expire */
153 int branch; /* One random number */
154 int canreinvite; /* Do we support reinvite */
155 int progress; /* Have sent 183 message progress */
156 int tag; /* Another random number */
157 int nat; /* Whether to try to support NAT */
158 struct sockaddr_in sa; /* Our peer */
159 struct sockaddr_in recv; /* Received as */
160 struct in_addr ourip; /* Our IP */
161 struct ast_channel *owner; /* Who owns us */
162 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
163 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
164 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
165 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
166 struct sip_pvt *refer_call; /* Call we are referring */
167 char record_route[256];
168 char record_route_info[256];
169 char remote_party_id[256];
170 char context[AST_MAX_EXTENSION];
171 char language[MAX_LANGUAGE];
172 char theirtag[256]; /* Their tag */
176 char callerid[256]; /* Caller*ID */
178 char accountcode[256]; /* Account code */
179 int amaflags; /* AMA Flags */
180 struct sip_request initreq; /* Initial request */
182 int maxtime; /* Max time for first response */
183 int initid; /* Auto-congest ID if appropriate */
188 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
189 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
190 struct ast_rtp *rtp; /* RTP Session */
191 struct sip_pvt *next;
194 static struct sip_pkt {
196 struct sip_pvt *owner;
198 char data[SIP_MAX_PACKET];
199 struct sip_pkt *next;
203 /* Users who can access various contexts */
209 char accountcode[80];
217 struct sip_user *next;
223 char context[80]; /* JK02: peers need context too to allow parking etc */
226 char mailbox[AST_MAX_EXTENSION];
233 int nonCodecCapability;
238 struct sockaddr_in addr;
242 struct sip_pvt *call; /* Call pointer */
243 int pokeexpire; /* When to expire poke */
244 int lastms; /* How long last response took (in ms), or -1 for no response */
245 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
246 struct timeval ps; /* Ping send time */
248 struct sockaddr_in defaddr;
252 struct sip_peer *next;
255 static struct ast_user_list {
256 struct sip_user *users;
257 pthread_mutex_t lock;
258 } userl = { NULL, AST_MUTEX_INITIALIZER };
260 static struct ast_peer_list {
261 struct sip_peer *peers;
262 pthread_mutex_t lock;
263 } peerl = { NULL, AST_MUTEX_INITIALIZER };
266 #define REG_STATE_UNREGISTERED 0
267 #define REG_STATE_REGSENT 1
268 #define REG_STATE_AUTHSENT 2
269 #define REG_STATE_REGISTERED 3
270 #define REG_STATE_REJECTED 4
271 #define REG_STATE_TIMEOUT 5
272 #define REG_STATE_NOAUTH 6
274 struct sip_registry {
275 pthread_mutex_t lock; /* Channel private lock */
276 struct sockaddr_in addr; /* Who we connect to for registration purposes */
278 char secret[80]; /* Password or key name in []'s */
279 char contact[80]; /* Contact extension */
281 int expire; /* Sched ID of expiration */
282 int timeout; /* sched id of sip_reg_timeout */
283 int refresh; /* How often to refresh */
284 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
286 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
287 char callid[80]; /* Global CallID for this registry */
288 struct sockaddr_in us; /* Who the server thinks we are */
289 struct sip_registry *next;
292 static int sip_do_register(struct sip_registry *r);
293 struct sip_registry *registrations;
295 static int sipsock = -1;
296 static int globalnat = 0;
298 static struct sockaddr_in bindaddr;
300 static struct ast_frame *sip_read(struct ast_channel *ast);
301 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
302 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req);
303 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand);
304 static int transmit_request(struct sip_pvt *p, char *msg, int inc);
305 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
306 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
307 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
308 static int transmit_message_with_text(struct sip_pvt *p, char *text);
309 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
310 char *getsipuri(char *header);
312 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
316 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
318 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
320 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));
325 static int send_response(struct sip_pvt *p, struct sip_request *req)
330 ast_verbose("Transmitting (NAT):\n%s\n to %s:%d\n", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
332 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));
334 res = __sip_xmit(p, req->data, req->len);
340 static int send_request(struct sip_pvt *p, struct sip_request *req)
345 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));
347 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));
349 res = __sip_xmit(p, req->data, req->len);
353 static char *ditch_braces(char *tmp)
358 if ((n = strchr(tmp, '<')) ) {
360 while(*c && *c != '>') c++;
362 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
371 static int sip_sendtext(struct ast_channel *ast, char *text)
373 struct sip_pvt *p = ast->pvt->pvt;
375 ast_verbose("Sending text %s on %s\n", text, ast->name);
378 if (!text || !strlen(text))
381 ast_verbose("Really sending text %s on %s\n", text, ast->name);
382 transmit_message_with_text(p, text);
386 static int create_addr(struct sip_pvt *r, char *peer)
391 r->sa.sin_family = AF_INET;
392 ast_pthread_mutex_lock(&peerl.lock);
395 if (!strcasecmp(p->name, peer)) {
397 r->capability = p->capability;
398 r->nonCodecCapability = p->nonCodecCapability;
401 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
402 ast_rtp_setnat(r->rtp, r->nat);
404 strncpy(r->peername, p->username, sizeof(r->peername)-1);
405 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
406 strncpy(r->username, p->username, sizeof(r->username)-1);
407 r->insecure = p->insecure;
408 r->canreinvite = p->canreinvite;
409 r->maxtime = p->maxms;
411 r->dtmfmode = p->dtmfmode;
412 strncpy(r->context, p->context,sizeof(r->context)-1);
413 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
414 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
415 if (p->addr.sin_addr.s_addr) {
416 r->sa.sin_addr = p->addr.sin_addr;
417 r->sa.sin_port = p->addr.sin_port;
419 r->sa.sin_addr = p->defaddr.sin_addr;
420 r->sa.sin_port = p->defaddr.sin_port;
422 memcpy(&r->recv, &r->sa, sizeof(r->recv));
428 ast_pthread_mutex_unlock(&peerl.lock);
430 hp = gethostbyname(peer);
432 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
433 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
434 memcpy(&r->recv, &r->sa, sizeof(r->recv));
437 ast_log(LOG_WARNING, "No such host: %s\n", peer);
446 static int auto_congest(void *nothing)
448 struct sip_pvt *p = nothing;
449 ast_pthread_mutex_lock(&p->lock);
452 if (!pthread_mutex_trylock(&p->owner->lock)) {
453 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
454 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
455 ast_pthread_mutex_unlock(&p->owner->lock);
458 ast_pthread_mutex_unlock(&p->lock);
462 static void sip_prefs_free(void)
464 struct sip_codec_pref *cur, *next;
474 static void sip_pref_remove(int format)
476 struct sip_codec_pref *cur, *prev;
479 if (cur->codec == format) {
481 prev->next = cur->next;
492 static int sip_pref_append(int format)
494 struct sip_codec_pref *cur, *tmp;
495 sip_pref_remove(format);
496 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
499 memset(tmp, 0, sizeof(struct sip_codec_pref));
511 static int sip_codec_choose(int formats)
513 struct sip_codec_pref *cur;
516 if (formats & cur->codec)
520 return ast_best_codec(formats);
523 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
527 char *vxml_url = NULL;
528 struct varshead *headp;
529 struct ast_var_t *current;
532 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
533 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
537 /* Check whether there is a VXML_URL variable */
538 headp=&ast->varshead;
539 AST_LIST_TRAVERSE(headp,current,entries) {
540 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
542 vxml_url = ast_var_value(current);
549 transmit_invite(p, "INVITE", 1, NULL, vxml_url);
551 /* Initialize auto-congest time */
552 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
557 static void __sip_destroy(struct sip_pvt *p, int lockowner)
559 struct sip_pvt *cur, *prev = NULL;
561 ast_rtp_destroy(p->rtp);
563 /* Unlink us from the owner if we have one */
566 ast_pthread_mutex_lock(&p->owner->lock);
567 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
568 p->owner->pvt->pvt = NULL;
570 ast_pthread_mutex_unlock(&p->owner->lock);
576 prev->next = cur->next;
585 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
588 ast_sched_del(sched, p->initid);
592 static void sip_destroy(struct sip_pvt *p)
594 ast_pthread_mutex_lock(&iflock);
596 ast_pthread_mutex_unlock(&iflock);
599 /* Interface lookup code courtesy Tilghman of DrunkCoder.com. Thanks! */
604 char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
609 struct sockaddr_in ifru_addr;
614 struct in_addr *lookup_iface(char *iface) {
617 static struct my_ifreq ifreq;
618 memset(&ifreq, 0, sizeof(ifreq));
619 strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
621 mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
622 res = ioctl(mysock,SIOCGIFADDR,&ifreq);
626 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
629 return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
632 static struct in_addr *myaddrfor(struct in_addr *them)
635 struct in_addr *temp = NULL;
636 unsigned int remote_ip;
638 remote_ip = them->s_addr;
640 PROC = fopen("/proc/net/route","r");
642 /* If /proc/net/route doesn't exist, fall back to the old method */
645 /* First line contains headers */
646 fgets(line,sizeof(line),PROC);
648 while (!feof(PROC)) {
650 unsigned int dest, gateway, mask;
654 fgets(line,sizeof(line),PROC);
657 for (i=0;i<sizeof(line);i++) {
660 fields[aoffset++] = line + i;
661 boffset = strchr(line + i,'\t');
662 if (boffset == NULL) {
671 sscanf(fields[0],"%s",iface);
672 sscanf(fields[1],"%x",&dest);
673 sscanf(fields[2],"%x",&gateway);
674 sscanf(fields[7],"%x",&mask);
676 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
678 if (((remote_ip & mask) ^ dest) == 0) {
680 ast_verbose("Interface is %s\n",iface);
681 temp = lookup_iface(iface);
683 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
689 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s. Using default\n", inet_ntoa(*them));
696 static int sip_hangup(struct ast_channel *ast)
698 struct sip_pvt *p = ast->pvt->pvt;
701 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
702 if (!ast->pvt->pvt) {
703 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
706 ast_pthread_mutex_lock(&p->lock);
707 /* Determine how to disconnect */
708 if (p->owner != ast) {
709 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
710 ast_pthread_mutex_unlock(&p->lock);
713 if (!ast || (ast->_state != AST_STATE_UP))
718 ast_dsp_free(p->vad);
721 ast->pvt->pvt = NULL;
725 /* Invert sense of outgoing */
726 p->outgoing = 1 - p->outgoing;
728 /* Start the process if it's not already started */
729 if (!p->alreadygone && strlen(p->initreq.data)) {
731 transmit_request(p, "CANCEL", 0);
734 transmit_request(p, "BYE", 1);
738 /* Restore sense of outgoing */
739 p->outgoing = 1 - p->outgoing;
741 ast_pthread_mutex_unlock(&p->lock);
745 static int sip_answer(struct ast_channel *ast)
747 int res = 0,fmt,capability;
749 struct sip_pvt *p = ast->pvt->pvt;
750 struct sip_codec_pref *oldpref=NULL;
753 if (ast->_state != AST_STATE_UP) {
757 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
759 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
760 fmt=ast_getformatbyname(codec);
764 sip_pref_append(fmt);
765 capability=p->capability;
767 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
770 ast_setstate(ast, AST_STATE_UP);
772 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
773 res = transmit_response_with_sdp(p, "200 OK", &p->initreq);
777 p->capability=capability;
783 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
785 struct sip_pvt *p = ast->pvt->pvt;
787 if (frame->frametype != AST_FRAME_VOICE) {
788 if (frame->frametype == AST_FRAME_IMAGE)
791 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
795 if (!(frame->subclass & ast->nativeformats)) {
796 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
797 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
802 ast_pthread_mutex_lock(&p->lock);
804 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
805 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq);
808 res = ast_rtp_write(p->rtp, frame);
810 ast_pthread_mutex_unlock(&p->lock);
815 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
817 struct sip_pvt *p = newchan->pvt->pvt;
818 ast_pthread_mutex_lock(&p->lock);
819 if (p->owner != oldchan) {
820 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
821 ast_pthread_mutex_unlock(&p->lock);
825 ast_pthread_mutex_unlock(&p->lock);
829 static int sip_senddigit(struct ast_channel *ast, char digit)
831 struct sip_pvt *p = ast->pvt->pvt;
832 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
833 transmit_info_with_digit(p, digit);
835 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
836 ast_rtp_senddigit(p->rtp, digit);
838 /* If in-band DTMF is desired, send that */
839 if (p->dtmfmode & SIP_DTMF_INBAND)
844 static int sip_indicate(struct ast_channel *ast, int condition)
846 struct sip_pvt *p = ast->pvt->pvt;
848 case AST_CONTROL_RINGING:
849 if (ast->_state == AST_STATE_RING) {
850 transmit_response(p, "180 Ringing", &p->initreq);
854 case AST_CONTROL_BUSY:
855 if (ast->_state != AST_STATE_UP) {
856 transmit_response(p, "600 Busy everywhere", &p->initreq);
858 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
862 case AST_CONTROL_CONGESTION:
863 if (ast->_state != AST_STATE_UP) {
864 transmit_response(p, "486 Busy here", &p->initreq);
866 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
873 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
881 static int sip_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
883 struct sip_pvt *p0, *p1;
885 struct ast_channel *who, *cs[3];
888 /* if need DTMF, cant native bridge */
889 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
891 ast_pthread_mutex_lock(&c0->lock);
892 ast_pthread_mutex_lock(&c1->lock);
895 ast_log(LOG_DEBUG, "Reinvite? %s: %s, %s: %s\n", c0->name, p0->canreinvite ? "yes" : "no", c1->name, p1->canreinvite ? "yes" : "no");
896 if (!p0->canreinvite || !p1->canreinvite) {
897 /* Not gonna support reinvite */
898 ast_pthread_mutex_unlock(&c0->lock);
899 ast_pthread_mutex_unlock(&c1->lock);
902 transmit_reinvite_with_sdp(p0, p1->rtp);
903 transmit_reinvite_with_sdp(p1, p0->rtp);
904 ast_pthread_mutex_unlock(&c0->lock);
905 ast_pthread_mutex_unlock(&c1->lock);
910 if ((c0->pvt->pvt != p0) ||
911 (c1->pvt->pvt != p1) ||
912 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
913 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
914 if (c0->pvt->pvt == p0)
915 transmit_reinvite_with_sdp(p0, NULL);
916 if (c1->pvt->pvt == p1)
917 transmit_reinvite_with_sdp(p1, NULL);
918 /* Tell it to try again later */
922 who = ast_waitfor_n(cs, 2, &to);
924 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
928 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
929 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
930 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
933 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
934 if (c0->pvt->pvt == p0 && !c0->_softhangup)
935 transmit_reinvite_with_sdp(p0, NULL);
936 if (c1->pvt->pvt == p1 && !c1->_softhangup)
937 transmit_reinvite_with_sdp(p1, NULL);
938 /* That's all we needed */
942 /* Swap priority not that it's a big deal at this point */
952 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
954 struct ast_channel *tmp;
956 tmp = ast_channel_alloc(1);
958 /* Select our native format based on codec preference until we receive
959 something from another device to the contrary. */
961 tmp->nativeformats = sip_codec_choose(i->capability);
963 tmp->nativeformats = sip_codec_choose(capability);
964 fmt = ast_best_codec(tmp->nativeformats);
966 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
968 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
970 if (i->dtmfmode & SIP_DTMF_INBAND) {
971 i->vad = ast_dsp_new();
972 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
974 tmp->fds[0] = ast_rtp_fd(i->rtp);
975 ast_setstate(tmp, state);
976 if (state == AST_STATE_RING)
978 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
979 tmp->writeformat = fmt;
980 tmp->pvt->rawwriteformat = fmt;
981 tmp->readformat = fmt;
982 tmp->pvt->rawreadformat = fmt;
984 tmp->pvt->send_text = sip_sendtext;
985 tmp->pvt->call = sip_call;
986 tmp->pvt->hangup = sip_hangup;
987 tmp->pvt->answer = sip_answer;
988 tmp->pvt->read = sip_read;
989 tmp->pvt->write = sip_write;
990 tmp->pvt->indicate = sip_indicate;
991 tmp->pvt->fixup = sip_fixup;
992 tmp->pvt->send_digit = sip_senddigit;
993 tmp->pvt->bridge = ast_rtp_bridge;
994 if (strlen(i->language))
995 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
997 ast_pthread_mutex_lock(&usecnt_lock);
999 ast_pthread_mutex_unlock(&usecnt_lock);
1000 ast_update_use_count();
1001 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1002 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1003 if (strlen(i->callerid))
1004 tmp->callerid = strdup(i->callerid);
1006 if (state != AST_STATE_DOWN) {
1007 if (ast_pbx_start(tmp)) {
1008 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1014 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1018 static struct cfalias {
1022 { "Content-Type", "c" },
1023 { "Content-Encoding", "e" },
1027 { "Content-Length", "l" },
1033 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1034 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1035 char* r = line + nameLen + 1;
1036 while (*r && (*r < 33)) ++r;
1043 static char *get_sdp(struct sip_request *req, char *name) {
1045 int len = strlen(name);
1048 for (x=0; x<req->lines; x++) {
1049 r = get_sdp_by_line(req->line[x], name, len);
1050 if (r[0] != '\0') return r;
1055 static void sdpLineNum_iterator_init(int* iterator) {
1059 static char* get_sdp_iterate(int* iterator,
1060 struct sip_request *req, char *name) {
1061 int len = strlen(name);
1063 while (*iterator < req->lines) {
1064 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1065 if (r[0] != '\0') return r;
1070 static char *__get_header(struct sip_request *req, char *name, int *start)
1073 int len = strlen(name);
1075 for (x=*start;x<req->headers;x++) {
1076 if (!strncasecmp(req->header[x], name, len) &&
1077 (req->header[x][len] == ':')) {
1078 r = req->header[x] + len + 1;
1079 while(*r && (*r < 33))
1086 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1087 if (!strcasecmp(aliases[x].fullname, name))
1088 return __get_header(req, aliases[x].shortname, start);
1090 /* Don't return NULL, so get_header is always a valid pointer */
1094 static char *get_header(struct sip_request *req, char *name)
1097 return __get_header(req, name, &start);
1100 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1102 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1103 struct ast_frame *f;
1104 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1105 f = ast_rtp_read(p->rtp);
1106 /* Don't send RFC2833 if we're not supposed to */
1107 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1110 /* We already hold the channel lock */
1111 if (f->frametype == AST_FRAME_VOICE) {
1112 if (f->subclass != p->owner->nativeformats) {
1113 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1114 p->owner->nativeformats = f->subclass;
1115 ast_set_read_format(p->owner, p->owner->readformat);
1116 ast_set_write_format(p->owner, p->owner->writeformat);
1118 if (p->dtmfmode & SIP_DTMF_INBAND) {
1119 f = ast_dsp_process(p->owner,p->vad,f,0);
1126 static struct ast_frame *sip_read(struct ast_channel *ast)
1128 struct ast_frame *fr;
1129 struct sip_pvt *p = ast->pvt->pvt;
1130 ast_pthread_mutex_lock(&p->lock);
1131 fr = sip_rtp_read(p);
1132 ast_pthread_mutex_unlock(&p->lock);
1136 static void build_callid(char *callid, int len, struct in_addr ourip)
1143 res = snprintf(callid, len, "%08x", val);
1147 /* It's not important that we really use our right IP here... */
1148 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1151 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1155 p = malloc(sizeof(struct sip_pvt));
1158 /* Keep track of stuff */
1159 memset(p, 0, sizeof(struct sip_pvt));
1161 p->rtp = ast_rtp_new(NULL, NULL);
1164 /* Start with 101 instead of 1 */
1167 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1171 ast_rtp_settos(p->rtp, tos);
1172 if (useglobalnat && sin) {
1173 /* Setup NAT structure according to global settings if we have an address */
1175 memcpy(&p->recv, sin, sizeof(p->recv));
1176 ast_rtp_setnat(p->rtp, p->nat);
1178 ast_pthread_mutex_init(&p->lock);
1180 ast_rtp_set_data(p->rtp, p);
1181 ast_rtp_set_callback(p->rtp, rtpready);
1184 memcpy(&p->sa, sin, sizeof(p->sa));
1185 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1187 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1189 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1191 build_callid(p->callid, sizeof(p->callid), p->ourip);
1193 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1194 /* Assume reinvite OK */
1196 p->dtmfmode = globaldtmfmode;
1198 ast_pthread_mutex_lock(&iflock);
1201 ast_pthread_mutex_unlock(&iflock);
1203 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1207 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1211 callid = get_header(req, "Call-ID");
1212 if (!strlen(callid)) {
1213 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1216 ast_pthread_mutex_lock(&iflock);
1219 if (!strcmp(p->callid, callid)) {
1220 /* Found the call */
1222 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1223 (p->sa.sin_port != sin->sin_port))) {
1226 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1227 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1228 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1229 ast_pthread_mutex_unlock(&iflock);
1233 ast_pthread_mutex_unlock(&iflock);
1238 ast_pthread_mutex_unlock(&iflock);
1239 return sip_alloc(callid, sin, 1);
1242 static int sip_register(char *value, int lineno)
1244 struct sip_registry *reg;
1245 char copy[256] = "";
1246 char *username, *hostname, *secret;
1254 strncpy(copy, value, sizeof(copy)-1);
1257 hostname = strrchr(stringp, '@');
1263 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1267 username = strsep(&stringp, ":");
1268 secret = strsep(&stringp, ":");
1270 hostname = strsep(&stringp, "/");
1271 contact = strsep(&stringp, "/");
1272 if (!contact || !strlen(contact))
1275 hostname = strsep(&stringp, ":");
1276 porta = strsep(&stringp, ":");
1278 if (porta && !atoi(porta)) {
1279 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1282 hp = gethostbyname(hostname);
1284 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1287 reg = malloc(sizeof(struct sip_registry));
1289 memset(reg, 0, sizeof(struct sip_registry));
1290 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1291 strncpy(reg->username, username, sizeof(reg->username)-1);
1293 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1295 reg->refresh = default_expirey;
1296 reg->addr.sin_family = AF_INET;
1297 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1298 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1299 reg->next = registrations;
1300 reg->callid_valid = 0;
1301 registrations = reg;
1303 ast_log(LOG_ERROR, "Out of memory\n");
1309 static void parse(struct sip_request *req)
1311 /* Divide fields by NULL's */
1316 /* First header starts immediately */
1320 /* We've got a new header */
1324 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1326 if (!strlen(req->header[f])) {
1327 /* Line by itself means we're now in content */
1331 if (f >= SIP_MAX_HEADERS - 1) {
1332 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1335 req->header[f] = c + 1;
1336 } else if (*c == '\r') {
1337 /* Ignore but eliminate \r's */
1342 /* Check for last header */
1343 if (strlen(req->header[f]))
1346 /* Now we process any mime content */
1351 /* We've got a new line */
1354 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1356 if (f >= SIP_MAX_LINES - 1) {
1357 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1360 req->line[f] = c + 1;
1361 } else if (*c == '\r') {
1362 /* Ignore and eliminate \r's */
1367 /* Check for last line */
1368 if (strlen(req->line[f]))
1372 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1374 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1377 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1385 int peercapability, peerNonCodecCapability;
1386 struct sockaddr_in sin;
1392 /* Get codec and RTP info from SDP */
1393 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1394 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1397 m = get_sdp(req, "m");
1398 c = get_sdp(req, "c");
1399 if (!strlen(m) || !strlen(c)) {
1400 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1403 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1404 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1407 /* XXX This could block for a long time, and block the main thread! XXX */
1408 hp = gethostbyname(host);
1410 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1413 if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1414 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1417 sin.sin_family = AF_INET;
1418 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1419 sin.sin_port = htons(portno);
1421 ast_rtp_set_peer(p->rtp, &sin);
1423 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1425 // Scan through the RTP payload types specified in a "m=" line:
1426 ast_rtp_pt_clear(p->rtp);
1428 while(strlen(codecs)) {
1429 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1430 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1433 ast_rtp_set_m_type(p->rtp, codec);
1437 // Next, scan through each "a=rtpmap:" line, noting each
1438 // specified RTP payload type (with corresponding MIME subtype):
1439 sdpLineNum_iterator_init(&iterator);
1440 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1441 char* mimeSubtype = strdup(a); // ensures we have enough space
1442 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1443 // Note: should really look at the 'freq' and '#chans' params too
1444 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1448 // Now gather all of the codecs that were asked for:
1449 ast_rtp_get_current_formats(p->rtp,
1450 &peercapability, &peerNonCodecCapability);
1451 p->capability = capability & peercapability;
1452 p->nonCodecCapability = nonCodecCapability & peerNonCodecCapability;
1454 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1455 capability, peercapability, p->capability);
1456 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1457 nonCodecCapability, peerNonCodecCapability,
1458 p->nonCodecCapability);
1460 if (!p->capability) {
1461 ast_log(LOG_WARNING, "No compatible codecs!\n");
1465 if (!(p->owner->nativeformats & p->capability)) {
1466 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);
1467 p->owner->nativeformats = sip_codec_choose(p->capability);
1468 ast_set_read_format(p->owner, p->owner->readformat);
1469 ast_set_write_format(p->owner, p->owner->writeformat);
1471 if (p->owner->bridge) {
1472 /* Turn on/off music on hold if we are holding/unholding */
1473 if (sin.sin_addr.s_addr) {
1474 ast_moh_stop(p->owner->bridge);
1476 ast_moh_start(p->owner->bridge, NULL);
1484 static int add_header(struct sip_request *req, char *var, char *value)
1486 if (req->len >= sizeof(req->data) - 4) {
1487 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1491 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1494 req->header[req->headers] = req->data + req->len;
1495 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1496 req->len += strlen(req->header[req->headers]);
1497 if (req->headers < SIP_MAX_HEADERS)
1500 ast_log(LOG_WARNING, "Out of header space\n");
1506 static int add_blank_header(struct sip_request *req)
1508 if (req->len >= sizeof(req->data) - 4) {
1509 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1513 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1516 req->header[req->headers] = req->data + req->len;
1517 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1518 req->len += strlen(req->header[req->headers]);
1519 if (req->headers < SIP_MAX_HEADERS)
1522 ast_log(LOG_WARNING, "Out of header space\n");
1528 static int add_line(struct sip_request *req, char *line)
1530 if (req->len >= sizeof(req->data) - 4) {
1531 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1535 /* Add extra empty return */
1536 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1537 req->len += strlen(req->data + req->len);
1539 req->line[req->lines] = req->data + req->len;
1540 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1541 req->len += strlen(req->line[req->lines]);
1542 if (req->lines < SIP_MAX_LINES)
1545 ast_log(LOG_WARNING, "Out of line space\n");
1551 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1554 tmp = get_header(orig, field);
1556 /* Add what we're responding to */
1557 return add_header(req, field, tmp);
1559 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1564 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1570 tmp = __get_header(orig, field, &start);
1572 /* Add what we're responding to */
1573 add_header(req, field, tmp);
1579 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1585 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1592 tmp = __get_header(orig, field, &start);
1594 if (!copied && p->nat) {
1595 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1596 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1598 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1599 add_header(req, field, new);
1601 /* Add what we're responding to */
1602 add_header(req, field, tmp);
1609 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1615 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1617 /* Initialize a response */
1618 if (req->headers || req->len) {
1619 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1622 req->header[req->headers] = req->data + req->len;
1623 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1624 req->len += strlen(req->header[req->headers]);
1625 if (req->headers < SIP_MAX_HEADERS)
1628 ast_log(LOG_WARNING, "Out of header space\n");
1632 static int init_req(struct sip_request *req, char *resp, char *recip)
1634 /* Initialize a response */
1635 if (req->headers || req->len) {
1636 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1639 req->header[req->headers] = req->data + req->len;
1640 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1641 req->len += strlen(req->header[req->headers]);
1642 if (req->headers < SIP_MAX_HEADERS)
1645 ast_log(LOG_WARNING, "Out of header space\n");
1649 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1651 char newto[256] = "", *ot;
1652 memset(resp, 0, sizeof(*resp));
1653 init_resp(resp, msg, req);
1654 copy_via_headers(p, resp, req, "Via");
1655 copy_header(resp, req, "From");
1656 ot = get_header(req, "To");
1657 copy_header(resp, req, "Record-Route");
1658 if (!strstr(ot, "tag=")) {
1659 /* Add the proper tag if we don't have it already. If they have specified
1660 their tag, use it. Otherwise, use our own tag */
1661 if (strlen(p->theirtag))
1662 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1664 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1666 strncpy(newto, ot, sizeof(newto) - 1);
1669 add_header(resp, "To", ot);
1670 copy_header(resp, req, "Call-ID");
1671 copy_header(resp, req, "CSeq");
1672 add_header(resp, "User-Agent", "Asterisk PBX");
1674 /* For registration responses, we also need expirey and
1679 if ((c=getsipuri(ot))) {
1680 snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1683 snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1685 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1686 add_header(resp, "Expires", tmp);
1687 add_header(resp, "Contact", contact);
1690 /* XXX This isn't exactly right and it's implemented
1691 very stupidly *sigh* XXX */
1693 if ((c=getsipuri(ot))) {
1694 snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1697 snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1699 add_header(resp, "Contact", contact);
1704 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1706 struct sip_request *orig = &p->initreq;
1707 char stripped[80] ="";
1713 memset(req, 0, sizeof(struct sip_request));
1719 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1721 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1723 c = strchr(stripped, '<');
1732 init_req(req, msg, c);
1734 snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1736 add_header(req, "Via", p->via);
1738 ot = get_header(orig, "To");
1739 of = get_header(orig, "From");
1741 if (!strstr(ot, "tag=")) {
1742 /* Add the proper tag if we don't have it already. If they have specified
1743 their tag, use it. Otherwise, use our own tag */
1744 if (strlen(p->theirtag))
1745 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1747 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1752 add_header(req, "From", of);
1753 add_header(req, "To", ot);
1755 add_header(req, "From", ot);
1756 add_header(req, "To", of);
1758 copy_header(req, orig, "Call-ID");
1759 add_header(req, "CSeq", tmp);
1761 add_header(req, "User-Agent", "Asterisk PBX");
1765 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1767 struct sip_request resp;
1768 respprep(&resp, p, msg, req);
1769 add_header(&resp, "Content-Length", "0");
1770 add_blank_header(&resp);
1771 return send_response(p, &resp);
1774 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1776 struct sip_request resp;
1777 respprep(&resp, p, msg, req);
1778 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1779 add_header(&resp, "Accept", "application/sdp");
1780 add_header(&resp, "Content-Length", "0");
1781 add_blank_header(&resp);
1782 return send_response(p, &resp);
1785 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1787 struct sip_request resp;
1789 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1790 respprep(&resp, p, msg, req);
1791 add_header(&resp, "Proxy-Authenticate", tmp);
1792 add_header(&resp, "Content-Length", "0");
1793 add_blank_header(&resp);
1794 return send_response(p, &resp);
1797 static int add_text(struct sip_request *req, char *text)
1799 /* XXX Convert \n's to \r\n's XXX */
1800 int len = strlen(text);
1802 snprintf(clen, sizeof(clen), "%d", len);
1803 add_header(req, "Content-Type", "text/plain");
1804 add_header(req, "Content-Length", clen);
1805 add_line(req, text);
1809 static int add_digit(struct sip_request *req, char digit)
1814 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
1816 snprintf(clen, sizeof(clen), "%d", len);
1817 add_header(req, "Content-Type", "application/dtmf-relay");
1818 add_header(req, "Content-Length", clen);
1823 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1827 int alreadysent = 0;
1829 struct sockaddr_in sin;
1830 struct sip_codec_pref *cur;
1839 struct sockaddr_in dest;
1840 /* XXX We break with the "recommendation" and send our IP, in order that our
1841 peer doesn't have to gethostbyname() us XXX */
1844 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1847 ast_rtp_get_us(p->rtp, &sin);
1849 ast_rtp_get_peer(rtp, &dest);
1851 dest.sin_addr = p->ourip;
1852 dest.sin_port = sin.sin_port;
1855 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
1856 snprintf(v, sizeof(v), "v=0\r\n");
1857 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1858 snprintf(s, sizeof(s), "s=session\r\n");
1859 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1860 snprintf(t, sizeof(t), "t=0 0\r\n");
1861 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1862 /* Start by sending our preferred codecs */
1865 if (p->capability & cur->codec) {
1867 ast_verbose("Answering with preferred capability %d\n", cur->codec);
1868 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
1870 snprintf(costr, sizeof(costr), " %d", codec);
1872 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
1876 alreadysent |= cur->codec;
1879 /* Now send any other common codecs, and non-codec formats: */
1880 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1881 if ((p->capability & x) && !(alreadysent & x)) {
1883 ast_verbose("Answering with capability %d\n", x);
1884 codec = ast_rtp_lookup_code(p->rtp, 1, x);
1886 snprintf(costr, sizeof(costr), " %d", codec);
1888 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
1893 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
1894 if (p->nonCodecCapability & x) {
1896 ast_verbose("Answering with non-codec capability %d\n", x);
1897 codec = ast_rtp_lookup_code(p->rtp, 0, x);
1899 snprintf(costr, sizeof(costr), " %d", codec);
1901 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
1903 if (x == AST_RTP_DTMF) {
1904 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
1905 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
1913 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1914 snprintf(costr, sizeof(costr), "%d", len);
1915 add_header(resp, "Content-Type", "application/sdp");
1916 add_header(resp, "Content-Length", costr);
1927 static void copy_request(struct sip_request *dst,struct sip_request *src)
1931 offset = ((void *)dst) - ((void *)src);
1932 /* First copy stuff */
1933 memcpy(dst, src, sizeof(*dst));
1934 /* Now fix pointer arithmetic */
1935 for (x=0;x<src->headers;x++)
1936 dst->header[x] += offset;
1937 for (x=0;x<src->lines;x++)
1938 dst->line[x] += offset;
1941 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1943 struct sip_request resp;
1944 respprep(&resp, p, msg, req);
1945 add_sdp(&resp, p, NULL);
1946 return send_response(p, &resp);
1949 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1951 struct sip_request resp;
1952 reqprep(&resp, p, "INVITE", 1);
1953 add_sdp(&resp, p, rtp);
1954 return send_response(p, &resp);
1957 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1964 char *l = "asterisk", *n=NULL;
1965 if (p->owner && p->owner->callerid) {
1966 strcpy(cid, p->owner->callerid);
1967 ast_callerid_parse(cid, &n, &l);
1969 ast_shrink_phone_number(l);
1970 if (!l || !ast_isphonenumber(l))
1975 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1976 if (strlen(p->username)) {
1977 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1978 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1980 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1982 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1983 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1985 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1987 /* If there is a VXML URL append it to the SIP URL */
1990 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1994 snprintf(to, sizeof(to), "<%s>", invite );
1996 memset(req, 0, sizeof(struct sip_request));
1997 init_req(req, cmd, invite);
1998 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2000 add_header(req, "Via", p->via);
2001 add_header(req, "From", from);
2003 char contact2[256] ="", *c, contact[256];
2004 /* XXX This isn't exactly right and it's implemented
2005 very stupidly *sigh* XXX */
2006 strncpy(contact2, from, sizeof(contact2)-1);
2007 c = ditch_braces(contact2);
2008 snprintf(contact, sizeof(contact), "<%s>", c);
2009 add_header(req, "Contact", contact);
2011 add_header(req, "To", to);
2012 add_header(req, "Call-ID", p->callid);
2013 add_header(req, "CSeq", tmp);
2014 add_header(req, "User-Agent", "Asterisk PBX");
2017 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2019 struct sip_request req;
2020 initreqprep(&req, p, cmd, vxml_url);
2022 add_header(&req, "Proxy-Authorization", auth);
2024 add_sdp(&req, p, NULL);
2026 add_header(&req, "Content-Length", "0");
2027 add_blank_header(&req);
2029 if (!p->initreq.headers) {
2030 /* Use this as the basis */
2031 copy_request(&p->initreq, &req);
2034 p->lastinvite = p->ocseq;
2035 return send_request(p, &req);
2038 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
2040 struct sip_request req;
2043 initreqprep(&req, p, "NOTIFY", NULL);
2044 add_header(&req, "Event", "message-summary");
2045 add_header(&req, "Content-Type", "text/plain");
2047 snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
2048 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2049 add_header(&req, "Content-Length", clen);
2050 add_line(&req, tmp);
2052 if (!p->initreq.headers) {
2053 /* Use this as the basis */
2054 copy_request(&p->initreq, &req);
2058 p->lastinvite = p->ocseq;
2059 return send_request(p, &req);
2062 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2064 static int sip_reregister(void *data)
2066 /* if we are here, we know that we need to reregister. */
2067 struct sip_registry *r=(struct sip_registry *)data;
2068 return sip_do_register(r);
2073 static int sip_do_register(struct sip_registry *r)
2076 ast_pthread_mutex_lock(&r->lock);
2077 res=transmit_register(r, "REGISTER", NULL);
2078 ast_pthread_mutex_unlock(&r->lock);
2082 static int sip_reg_timeout(void *data)
2084 /* if we are here, our registration timed out, so we'll just do it over */
2085 struct sip_registry *r=data;
2087 ast_pthread_mutex_lock(&r->lock);
2088 ast_log(LOG_NOTICE, "Registration timed out, trying again\n");
2089 r->regstate=REG_STATE_UNREGISTERED;
2090 /* cancel ourselves first!!! */
2091 /* ast_sched_del(sched,r->timeout); */
2092 res=transmit_register(r, "REGISTER", NULL);
2093 ast_pthread_mutex_unlock(&r->lock);
2097 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2099 struct sip_request req;
2106 /* exit if we are already in process with this registrar ?*/
2107 if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2108 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2114 if (!r->callid_valid) {
2115 build_callid(r->callid, sizeof(r->callid), __ourip);
2118 p=sip_alloc( r->callid, &r->addr, 0);
2122 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2123 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2124 strncpy(p->username, r->username, sizeof(p->username)-1);
2127 /* set up a timeout */
2128 if (auth==NULL && !r->timeout) {
2129 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2130 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2133 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2134 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2136 snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2138 memset(&req, 0, sizeof(req));
2139 init_req(&req, cmd, addr);
2141 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2143 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2144 add_header(&req, "Via", via);
2145 add_header(&req, "From", from);
2146 add_header(&req, "To", to);
2149 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2150 add_header(&req, "Contact", contact);
2152 add_header(&req, "Call-ID", p->callid);
2153 add_header(&req, "CSeq", tmp);
2154 add_header(&req, "User-Agent", "Asterisk PBX");
2156 add_header(&req, "Authorization", auth);
2158 snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2159 add_header(&req, "Expires", tmp);
2160 add_header(&req, "Event", "registration");
2161 copy_request(&p->initreq, &req);
2162 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2163 return send_request(p, &req);
2166 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2168 struct sip_request req;
2169 reqprep(&req, p, "MESSAGE", 1);
2170 add_text(&req, text);
2171 return send_request(p, &req);
2174 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2176 struct sip_request req;
2177 reqprep(&req, p, "INFO", 1);
2178 add_digit(&req, digit);
2179 return send_request(p, &req);
2182 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
2184 struct sip_request resp;
2185 reqprep(&resp, p, msg, inc);
2186 add_header(&resp, "Content-Length", "0");
2187 add_blank_header(&resp);
2188 return send_request(p, &resp);
2191 static int expire_register(void *data)
2193 struct sip_peer *p = data;
2194 memset(&p->addr, 0, sizeof(p->addr));
2199 static int sip_poke_peer(struct sip_peer *peer);
2201 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2203 char contact[80]= "";
2204 char *expires = get_header(req, "Expires");
2205 int expirey = atoi(expires);
2209 struct sockaddr_in oldsin;
2210 if (!strlen(expires)) {
2211 expires = strstr(get_header(req, "Contact"), "expires=");
2213 if (sscanf(expires + 8, "%d;", &expirey) != 1)
2216 /* Look for brackets */
2217 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2220 if ((n=strchr(c, '<'))) {
2223 /* Lose the part after the > */
2227 if (!strcasecmp(c, "*")) {
2228 /* This means remove all registrations and return OK */
2229 memset(&p->addr, 0, sizeof(p->addr));
2231 ast_sched_del(sched, p->expire);
2233 if (option_verbose > 2)
2234 ast_verbose(VERBOSE_PREFIX_3 "Unegistered SIP '%s'\n", p->username);
2237 /* Make sure it's a SIP URL */
2238 if (strncasecmp(c, "sip:", 4)) {
2239 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2255 pt = strchr(n, ':');
2261 port = DEFAULT_SIP_PORT;
2262 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2264 /* XXX This could block for a long time XXX */
2265 hp = gethostbyname(n);
2267 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2270 p->addr.sin_family = AF_INET;
2271 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2272 p->addr.sin_port = htons(port);
2274 /* Don't trust the contact field. Just use what they came to us
2276 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2279 strncpy(p->username, c, sizeof(p->username) - 1);
2281 strcpy(p->username, "");
2283 ast_sched_del(sched, p->expire);
2284 if ((expirey < 1) || (expirey > max_expirey))
2285 expirey = max_expirey;
2286 p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2287 pvt->expirey = expirey;
2288 if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2290 if (option_verbose > 2)
2291 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);
2296 static void md5_hash(char *output, char *input)
2298 struct MD5Context md5;
2299 unsigned char digest[16];
2303 MD5Update(&md5, input, strlen(input));
2304 MD5Final(digest, &md5);
2307 ptr += sprintf(ptr, "%2.2x", digest[x]);
2310 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
2313 /* Always OK if no secret */
2314 if (!strlen(secret))
2316 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2317 snprintf(randdata, randlen, "%08x", rand());
2318 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
2321 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2322 an example in the spec of just what it is you're doing a hash on. */
2328 char resp_hash[256];
2334 /* Find their response among the mess that we'r sent for comparison */
2335 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2339 while (*c && (*c < 33)) c++;
2342 if (!strncasecmp(c, "response=", strlen("response="))) {
2343 c+= strlen("response=");
2346 if((c = strchr(c,'\"')))
2351 if((c = strchr(c,',')))
2355 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2359 if((c = strchr(c,'\"')))
2363 if((c = strchr(c,',')))
2372 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2373 if(strlen(resp_uri))
2374 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2376 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2377 md5_hash(a1_hash, a1);
2378 md5_hash(a2_hash, a2);
2379 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2380 md5_hash(resp_hash, resp);
2382 /* resp_hash now has the expected response, compare the two */
2384 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2388 /* Assume success ;-) */
2389 /* Eliminate random data */
2390 strcpy(randdata, "");
2395 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2398 struct sip_peer *peer;
2404 while(*t && (*t > 32) && (*t != ';'))
2408 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2409 c = ditch_braces(tmp);
2410 if (!strncmp(c, "sip:", 4)) {
2414 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2416 c = strchr(name, '@');
2419 ast_pthread_mutex_lock(&peerl.lock);
2422 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2424 transmit_response(p, "100 Trying", req);
2425 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2426 if (parse_contact(p, peer, req)) {
2427 ast_log(LOG_WARNING, "Failed to parse contact info\n");
2429 /* Say OK and ask subsystem to retransmit msg counter */
2430 transmit_response(p, "200 OK", req);
2431 peer->lastmsgssent = -1;
2439 ast_pthread_mutex_unlock(&peerl.lock);
2441 transmit_response(p, "401 Unauthorized", &p->initreq);
2445 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2447 char tmp[256] = "", *c, *a;
2448 struct sip_request *req;
2453 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2454 c = ditch_braces(tmp);
2455 if (strncmp(c, "sip:", 4)) {
2456 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2460 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2464 ast_verbose("Looking for %s in %s\n", c, p->context);
2465 if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2467 strncpy(p->exten, c, sizeof(p->exten) - 1);
2471 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2478 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2480 char tmp[256] = "", *c, *a;
2481 char tmp2[256] = "", *c2, *a2;
2484 char tmp5[256] = ""; /* CallID to replace */
2485 struct sip_request *req;
2491 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2492 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2493 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2494 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2496 c = ditch_braces(tmp);
2497 c2 = ditch_braces(tmp2);
2500 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2501 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2502 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
2507 if ((a = strchr(c, '?'))) {
2508 /* Search for arguemnts */
2511 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2512 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2513 if ((a = strchr(tmp5, '%'))) {
2514 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
2516 if ((a[1] == '4') && (a[2] == '0')) {
2518 memmove(a + 1, a+3, strlen(a + 3));
2521 if ((a = strchr(tmp5, '%')))
2526 if ((a = strchr(c, '@')))
2528 if ((a = strchr(c, ';')))
2532 if ((a2 = strchr(c2, '@')))
2535 if ((a2 = strchr(c2, ';')))
2540 ast_verbose("Looking for %s in %s\n", c, p->context);
2541 ast_verbose("Looking for %s in %s\n", c2, p->context);
2544 /* This is a supervised transfer */
2545 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2547 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2548 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2549 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2550 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2551 p->refer_call = NULL;
2552 ast_pthread_mutex_lock(&iflock);
2553 /* Search interfaces and find the match */
2556 if (!strcmp(p2->callid, tmp5)) {
2557 /* Go ahead and lock it before returning */
2558 ast_pthread_mutex_lock(&p2->lock);
2564 ast_pthread_mutex_unlock(&iflock);
2568 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2569 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2570 /* This is an unsupervised transfer */
2571 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2572 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2573 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2574 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2575 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2576 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2577 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2578 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2579 p->refer_call = NULL;
2581 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2589 static int check_via(struct sip_pvt *p, struct sip_request *req)
2595 memset(via, 0, sizeof(via));
2596 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2597 c = strchr(via, ';');
2600 c = strchr(via, ' ');
2604 while(*c && (*c < 33))
2606 if (strcmp(via, "SIP/2.0/UDP")) {
2607 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2610 pt = strchr(c, ':');
2615 hp = gethostbyname(c);
2617 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2620 memset(&p->sa, 0, sizeof(p->sa));
2621 p->sa.sin_family = AF_INET;
2622 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2623 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2626 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2628 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2634 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2636 struct sip_user *user;
2637 char *of, from[256] = "", *c;
2642 while(*t && (*t > 32) && (*t != ';'))
2645 of = get_header(req, "From");
2646 strncpy(from, of, sizeof(from) - 1);
2647 of = ditch_braces(from);
2648 if (strncmp(of, "sip:", 4)) {
2649 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2652 /* Get just the username part */
2653 if ((c = strchr(of, '@')))
2655 if ((c = strchr(of, ':')))
2657 strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2660 ast_pthread_mutex_lock(&userl.lock);
2663 if (!strcasecmp(user->name, of)) {
2666 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2667 ast_rtp_setnat(p->rtp, p->nat);
2669 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2670 strncpy(p->context, user->context, sizeof(p->context) - 1);
2671 if (strlen(user->callerid) && strlen(p->callerid))
2672 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2673 strncpy(p->username, user->name, sizeof(p->username) - 1);
2674 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
2675 p->canreinvite = user->canreinvite;
2676 p->amaflags = user->amaflags;
2678 p->dtmfmode = user->dtmfmode;
2684 ast_pthread_mutex_unlock(&userl.lock);
2688 static int get_msg_text(char *buf, int len, struct sip_request *req)
2692 for (x=0;x<req->lines;x++) {
2693 strncat(buf, req->line[x], len - strlen(buf) - 5);
2699 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2703 if (get_msg_text(buf, sizeof(buf), req)) {
2704 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2709 ast_verbose("Message received: '%s'\n", buf);
2710 memset(&f, 0, sizeof(f));
2711 f.frametype = AST_FRAME_TEXT;
2715 f.datalen = strlen(buf);
2716 ast_queue_frame(p->owner, &f, 1);
2720 static int sip_show_users(int fd, int argc, char *argv[])
2722 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2723 struct sip_user *user;
2725 return RESULT_SHOWUSAGE;
2726 ast_pthread_mutex_lock(&userl.lock);
2727 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2728 for(user=userl.users;user;user=user->next) {
2729 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2731 user->ha ? "Yes" : "No");
2733 ast_pthread_mutex_unlock(&userl.lock);
2734 return RESULT_SUCCESS;
2738 static int sip_show_peers(int fd, int argc, char *argv[])
2740 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2741 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2742 struct sip_peer *peer;
2743 char name[256] = "";
2745 return RESULT_SHOWUSAGE;
2746 ast_pthread_mutex_lock(&peerl.lock);
2747 ast_cli(fd, FORMAT2, "Name/username", "Host", " ", "Mask", "Port", "Status");
2748 for (peer = peerl.peers;peer;peer = peer->next) {
2751 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2752 if (strlen(peer->username))
2753 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2755 strncpy(name, peer->name, sizeof(name) - 1);
2757 if (peer->lastms < 0)
2758 strcpy(status, "UNREACHABLE");
2759 else if (peer->lastms > peer->maxms)
2760 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2761 else if (peer->lastms)
2762 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2764 strcpy(status, "UNKNOWN");
2766 strcpy(status, "Unmonitored");
2767 ast_cli(fd, FORMAT, name,
2768 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2769 peer->dynamic ? "(D)" : " ",
2771 ntohs(peer->addr.sin_port), status);
2773 ast_pthread_mutex_unlock(&peerl.lock);
2774 return RESULT_SUCCESS;
2779 static char *regstate2str(int regstate)
2782 case REG_STATE_UNREGISTERED:
2783 return "Unregistered";
2784 case REG_STATE_REGSENT:
2785 return "Request Sent";
2786 case REG_STATE_AUTHSENT:
2787 return "Auth. Sent";
2788 case REG_STATE_REGISTERED:
2789 return "Registered";
2790 case REG_STATE_REJECTED:
2792 case REG_STATE_TIMEOUT:
2794 case REG_STATE_NOAUTH:
2795 return "No Authentication";
2801 static int sip_show_registry(int fd, int argc, char *argv[])
2803 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2804 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2805 struct sip_registry *reg;
2809 return RESULT_SHOWUSAGE;
2810 ast_pthread_mutex_lock(&peerl.lock);
2811 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2812 for (reg = registrations;reg;reg = reg->next) {
2813 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2814 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2815 ast_cli(fd, FORMAT, host,
2816 reg->username, state, reg->refresh, regstate2str(reg->regstate));
2818 ast_pthread_mutex_unlock(&peerl.lock);
2819 return RESULT_SUCCESS;
2824 static int sip_show_channels(int fd, int argc, char *argv[])
2826 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2827 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
2828 struct sip_pvt *cur;
2831 return RESULT_SHOWUSAGE;
2832 ast_pthread_mutex_lock(&iflock);
2834 ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2836 ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr),
2837 strlen(cur->username) ? cur->username : "(None)",
2839 cur->ocseq, cur->icseq,
2842 cur->owner ? cur->owner->nativeformats : 0);
2846 ast_pthread_mutex_unlock(&iflock);
2847 ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2848 return RESULT_SUCCESS;
2853 static char *complete_sipch(char *line, char *word, int pos, int state)
2856 struct sip_pvt *cur;
2858 ast_pthread_mutex_lock(&iflock);
2861 if (!strncasecmp(word, cur->callid, strlen(word))) {
2862 if (++which > state) {
2863 c = strdup(cur->callid);
2869 ast_pthread_mutex_unlock(&iflock);
2873 static int sip_show_channel(int fd, int argc, char *argv[])
2875 struct sip_pvt *cur;
2878 return RESULT_SHOWUSAGE;
2879 ast_pthread_mutex_lock(&iflock);
2882 if (!strcasecmp(cur->callid, argv[3])) {
2883 ast_cli(fd, "Call-ID: %s\n", cur->callid);
2884 ast_cli(fd, "Theoretical Address: %s:%d\n", inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
2885 ast_cli(fd, "Received Address: %s:%d\n", inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
2886 ast_cli(fd, "NAT Support: %s\n", cur->nat ? "Yes" : "No");
2888 if (cur->dtmfmode & SIP_DTMF_RFC2833)
2889 strcat(tmp, "rfc2833 ");
2890 if (cur->dtmfmode & SIP_DTMF_INFO)
2891 strcat(tmp, "info ");
2892 if (cur->dtmfmode & SIP_DTMF_INBAND)
2893 strcat(tmp, "inband ");
2894 ast_cli(fd, "DTMF Mode: %s\n", tmp);
2899 ast_pthread_mutex_unlock(&iflock);
2901 ast_cli(fd, "No such SIP Call ID '%s'\n", argv[3]);
2902 return RESULT_SUCCESS;
2905 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2907 char buf[1024] = "";
2910 /* Try getting the "signal=" part */
2911 if ((c = get_sdp(req, "Signal"))) {
2912 strncpy(buf, c, sizeof(buf) - 1);
2913 } else if (get_msg_text(buf, sizeof(buf), req)) {
2914 /* Normal INFO method */
2915 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2922 ast_verbose("DTMF received: '%c'\n", buf[0]);
2923 memset(&f, 0, sizeof(f));
2924 f.frametype = AST_FRAME_DTMF;
2925 f.subclass = buf[0];
2929 ast_queue_frame(p->owner, &f, 1);
2934 static int sip_do_debug(int fd, int argc, char *argv[])
2937 return RESULT_SHOWUSAGE;
2939 ast_cli(fd, "SIP Debugging Enabled\n");
2940 return RESULT_SUCCESS;
2943 static int sip_no_debug(int fd, int argc, char *argv[])
2946 return RESULT_SHOWUSAGE;
2948 ast_cli(fd, "SIP Debugging Disabled\n");
2949 return RESULT_SUCCESS;
2952 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2954 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2956 memset(digest,0,sizeof(digest));
2957 reply_digest(p,req, "WWW-Authenticate", "REGISTER", digest, sizeof(digest) );
2958 return transmit_register(p->registry,"REGISTER",digest);
2961 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2963 memset(digest,0,sizeof(digest));
2964 reply_digest(p,req, "Proxy-Authenticate", "INVITE", digest, sizeof(digest) );
2965 return transmit_invite(p,"INVITE",1,digest, NULL);
2968 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2979 char resp_hash[256];
2983 strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2985 c+=strlen("Digest ");
2987 while (*c && (*c < 33)) c++;
2990 if (!strncasecmp(c,"realm=", strlen("realm="))) {
2991 c+=strlen("realm=");
2994 if ((c = strchr(c,'\"')))
2998 if ((c = strchr(c,',')))
3002 } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
3003 c+=strlen("nonce=");
3006 if ((c = strchr(c,'\"')))
3010 if ((c = strchr(c,',')))
3019 /* Okay. We've got the realm and nonce from the server. Now lets build the MD5 digest. */
3020 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
3022 snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
3023 snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
3024 md5_hash(a1_hash,a1);
3025 md5_hash(a2_hash,a2);
3026 snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
3027 md5_hash(resp_hash,resp);
3029 snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
3039 static char show_users_usage[] =
3040 "Usage: sip show users\n"
3041 " Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
3043 static char show_channels_usage[] =
3044 "Usage: sip show channels\n"
3045 " Lists all currently active SIP channels.\n";
3047 static char show_channel_usage[] =
3048 "Usage: sip show channel <channel>\n"
3049 " Provides detailed status on a given SIP channel.\n";
3051 static char show_peers_usage[] =
3052 "Usage: sip show peers\n"
3053 " Lists all known SIP peers.\n";
3055 static char show_reg_usage[] =
3056 "Usage: sip show registry\n"
3057 " Lists all registration requests and status.\n";
3059 static char debug_usage[] =
3060 "Usage: sip debug\n"
3061 " Enables dumping of SIP packets for debugging purposes\n";
3063 static char no_debug_usage[] =
3064 "Usage: sip no debug\n"
3065 " Disables dumping of SIP packets for debugging purposes\n";
3067 static struct ast_cli_entry cli_show_users =
3068 { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
3069 static struct ast_cli_entry cli_show_channels =
3070 { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage};
3071 static struct ast_cli_entry cli_show_channel =
3072 { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch };
3073 static struct ast_cli_entry cli_show_peers =
3074 { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
3075 static struct ast_cli_entry cli_show_registry =
3076 { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
3077 static struct ast_cli_entry cli_debug =
3078 { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
3079 static struct ast_cli_entry cli_no_debug =
3080 { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
3083 static int sip_poke_peer_s(void *data)
3085 struct sip_peer *peer = data;
3086 peer->pokeexpire = -1;
3087 sip_poke_peer(peer);
3091 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
3095 struct ast_rtp *rtp;
3096 struct ast_channel *owner;
3097 struct sip_peer *peer;
3100 c = get_header(req, "Cseq");
3101 msg = strchr(c, ' ');
3102 if (!msg) msg = ""; else msg++;
3104 ast_pthread_mutex_lock(&p->lock);
3105 /* Go ahead and lock the owner if it has one -- we may need it */
3106 if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
3107 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
3108 ast_pthread_mutex_unlock(&p->lock);
3109 /* Sleep infintismly short amount of time */
3115 /* We don't really care what the response is, just that it replied back.
3116 Well, as long as it's not a 100 response... since we might
3117 need to hang around for something more "difinitive" */
3120 gettimeofday(&tv, NULL);
3121 pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
3122 (tv.tv_usec - peer->ps.tv_usec) / 1000;