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 <sys/socket.h>
37 #include <sys/ioctl.h>
44 #include <arpa/inet.h>
45 #include <sys/signal.h>
46 #include <netinet/ip.h>
48 /* #define VOCAL_DATA_HACK */
51 #define DEFAULT_DEFAULT_EXPIREY 120
52 #define DEFAULT_MAX_EXPIREY 3600
54 static int max_expirey = DEFAULT_MAX_EXPIREY;
55 static int default_expirey = DEFAULT_DEFAULT_EXPIREY;
57 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
59 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
60 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
61 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
63 static char *desc = "Session Initiation Protocol (SIP)";
64 static char *type = "sip";
65 static char *tdesc = "Session Initiation Protocol (SIP)";
66 static char *config = "sip.conf";
68 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
69 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
71 static char context[AST_MAX_EXTENSION] = "default";
73 static char language[MAX_LANGUAGE] = "";
76 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
78 /* Protect the interface list (of sip_pvt's) */
79 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
81 /* Protect the monitoring thread, so only one process can kill or start it, and not
82 when it's doing something critical. */
83 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
85 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
87 /* This is the thread for the monitor which checks for input on the channels
88 which are not currently in use. */
89 static pthread_t monitor_thread = 0;
91 static int restart_monitor(void);
93 /* Just about everybody seems to support ulaw, so make it a nice default */
94 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
96 static char ourhost[256];
97 static struct in_addr __ourip;
100 static int sipdebug = 0;
105 static int expirey = 900;
107 static struct sched_context *sched;
108 static struct io_context *io;
109 /* The private structures of the sip channels are linked for
110 selecting outgoing channels */
112 #define SIP_MAX_HEADERS 64
113 #define SIP_MAX_LINES 64
115 static struct sip_codec_pref {
117 struct sip_codec_pref *next;
121 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
122 char *rlPart2; /* The Request URI or Response Status */
124 int headers; /* SIP Headers */
125 char *header[SIP_MAX_HEADERS];
126 int lines; /* SDP Content */
127 char *line[SIP_MAX_LINES];
128 char data[SIP_MAX_PACKET];
131 static struct sip_pvt {
132 pthread_mutex_t lock; /* Channel private lock */
133 char callid[80]; /* Global CallID */
134 char randdata[80]; /* Random data */
135 unsigned int ocseq; /* Current outgoing seqno */
136 unsigned int icseq; /* Current incoming seqno */
137 int lastinvite; /* Last Cseq of invite */
138 int alreadygone; /* Whether or not we've already been destroyed by or peer */
139 int needdestroy; /* if we need to be destroyed */
140 int capability; /* Special capability */
141 int outgoing; /* Outgoing or incoming call? */
142 int insecure; /* Don't check source port/ip */
143 int expirey; /* How long we take to expire */
144 int branch; /* One random number */
145 int canreinvite; /* Do we support reinvite */
146 int progress; /* Have sent 183 message progress */
147 int tag; /* Another random number */
148 int nat; /* Whether to try to support NAT */
149 struct sockaddr_in sa; /* Our peer */
150 struct sockaddr_in recv; /* Received as */
151 struct in_addr ourip; /* Our IP */
152 struct ast_channel *owner; /* Who owns us */
153 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
154 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
155 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
156 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
157 struct sip_pvt *refer_call; /* Call we are referring */
158 char record_route[256];
159 char record_route_info[256];
160 char remote_party_id[256];
161 char context[AST_MAX_EXTENSION];
162 char language[MAX_LANGUAGE];
163 char theirtag[256]; /* Their tag */
167 char callerid[256]; /* Caller*ID */
169 char accountcode[256]; /* Account code */
170 int amaflags; /* AMA Flags */
171 struct sip_request initreq; /* Initial request */
173 int maxtime; /* Max time for first response */
174 int initid; /* Auto-congest ID if appropriate */
176 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
177 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
178 struct ast_rtp *rtp; /* RTP Session */
179 struct sip_pvt *next;
182 static struct sip_pkt {
184 struct sip_pvt *owner;
186 char data[SIP_MAX_PACKET];
187 struct sip_pkt *next;
191 /* Users who can access various contexts */
197 char accountcode[80];
204 struct sip_user *next;
210 char context[80]; /* JK02: peers need context too to allow parking etc */
213 char mailbox[AST_MAX_EXTENSION];
223 struct sockaddr_in addr;
227 struct sip_pvt *call; /* Call pointer */
228 int pokeexpire; /* When to expire poke */
229 int lastms; /* How long last response took (in ms), or -1 for no response */
230 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
231 struct timeval ps; /* Ping send time */
233 struct sockaddr_in defaddr;
237 struct sip_peer *next;
240 static struct ast_user_list {
241 struct sip_user *users;
242 pthread_mutex_t lock;
243 } userl = { NULL, AST_MUTEX_INITIALIZER };
245 static struct ast_peer_list {
246 struct sip_peer *peers;
247 pthread_mutex_t lock;
248 } peerl = { NULL, AST_MUTEX_INITIALIZER };
251 #define REG_STATE_UNREGISTERED 0
252 #define REG_STATE_REGSENT 1
253 #define REG_STATE_AUTHSENT 2
254 #define REG_STATE_REGISTERED 3
255 #define REG_STATE_REJECTED 4
256 #define REG_STATE_TIMEOUT 5
257 #define REG_STATE_NOAUTH 6
259 struct sip_registry {
260 pthread_mutex_t lock; /* Channel private lock */
261 struct sockaddr_in addr; /* Who we connect to for registration purposes */
263 char secret[80]; /* Password or key name in []'s */
264 char contact[80]; /* Contact extension */
266 int expire; /* Sched ID of expiration */
267 int timeout; /* sched id of sip_reg_timeout */
268 int refresh; /* How often to refresh */
269 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
271 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
272 char callid[80]; /* Global CallID for this registry */
273 struct sockaddr_in us; /* Who the server thinks we are */
274 struct sip_registry *next;
277 static int sip_do_register(struct sip_registry *r);
278 struct sip_registry *registrations;
280 static int sipsock = -1;
282 static struct sockaddr_in bindaddr;
284 static struct ast_frame *sip_read(struct ast_channel *ast);
285 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
286 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req);
287 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand);
288 static int transmit_request(struct sip_pvt *p, char *msg, int inc);
289 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
290 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
291 static int transmit_message_with_text(struct sip_pvt *p, char *text);
292 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
294 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
298 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
300 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
302 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));
307 static int send_response(struct sip_pvt *p, struct sip_request *req)
312 ast_verbose("Transmitting (NAT):\n%s\n to %s:%d\n", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
314 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));
316 res = __sip_xmit(p, req->data, req->len);
322 static int send_request(struct sip_pvt *p, struct sip_request *req)
327 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));
329 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));
331 res = __sip_xmit(p, req->data, req->len);
335 static char *ditch_braces(char *tmp)
340 if ((n = strchr(tmp, '<')) ) {
342 while(*c && *c != '>') c++;
344 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
353 static int sip_sendtext(struct ast_channel *ast, char *text)
355 struct sip_pvt *p = ast->pvt->pvt;
357 ast_verbose("Sending text %s on %s\n", text, ast->name);
360 if (!text || !strlen(text))
363 ast_verbose("Really sending text %s on %s\n", text, ast->name);
364 transmit_message_with_text(p, text);
368 static int create_addr(struct sip_pvt *r, char *peer)
373 r->sa.sin_family = AF_INET;
374 ast_pthread_mutex_lock(&peerl.lock);
377 if (!strcasecmp(p->name, peer)) {
379 r->capability = p->capability;
380 strncpy(r->peername, p->username, sizeof(r->peername)-1);
381 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
382 strncpy(r->username, p->username, sizeof(r->username)-1);
383 r->insecure = p->insecure;
384 r->canreinvite = p->canreinvite;
385 r->maxtime = p->maxms;
386 strncpy(r->context, p->context,sizeof(r->context)-1);
387 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
388 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
389 if (p->addr.sin_addr.s_addr) {
390 r->sa.sin_addr = p->addr.sin_addr;
391 r->sa.sin_port = p->addr.sin_port;
393 r->sa.sin_addr = p->defaddr.sin_addr;
394 r->sa.sin_port = p->defaddr.sin_port;
396 memcpy(&r->recv, &r->sa, sizeof(r->recv));
402 ast_pthread_mutex_unlock(&peerl.lock);
404 hp = gethostbyname(peer);
406 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
407 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
408 memcpy(&r->recv, &r->sa, sizeof(r->recv));
411 ast_log(LOG_WARNING, "No such host: %s\n", peer);
420 static int auto_congest(void *nothing)
422 struct sip_pvt *p = nothing;
423 ast_pthread_mutex_lock(&p->lock);
426 if (!pthread_mutex_trylock(&p->owner->lock)) {
427 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
428 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
429 ast_pthread_mutex_unlock(&p->owner->lock);
432 ast_pthread_mutex_unlock(&p->lock);
436 static void sip_prefs_free(void)
438 struct sip_codec_pref *cur, *next;
448 static void sip_pref_remove(int format)
450 struct sip_codec_pref *cur, *prev;
453 if (cur->codec == format) {
455 prev->next = cur->next;
466 static int sip_pref_append(int format)
468 struct sip_codec_pref *cur, *tmp;
469 sip_pref_remove(format);
470 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
473 memset(tmp, 0, sizeof(struct sip_codec_pref));
485 static int sip_codec_choose(int formats)
487 struct sip_codec_pref *cur;
490 if (formats & cur->codec)
494 return ast_best_codec(formats);
497 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
501 char *vxml_url = NULL;
502 struct varshead *headp;
503 struct ast_var_t *current;
506 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
507 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
511 /* Check whether there is a VXML_URL variable */
512 headp=&ast->varshead;
513 AST_LIST_TRAVERSE(headp,current,entries) {
514 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
516 vxml_url = ast_var_value(current);
523 transmit_invite(p, "INVITE", 1, NULL, vxml_url);
525 /* Initialize auto-congest time */
526 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
531 static void __sip_destroy(struct sip_pvt *p, int lockowner)
533 struct sip_pvt *cur, *prev = NULL;
535 ast_rtp_destroy(p->rtp);
537 /* Unlink us from the owner if we have one */
540 ast_pthread_mutex_lock(&p->owner->lock);
541 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
542 p->owner->pvt->pvt = NULL;
544 ast_pthread_mutex_unlock(&p->owner->lock);
550 prev->next = cur->next;
559 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
562 ast_sched_del(sched, p->initid);
566 static void sip_destroy(struct sip_pvt *p)
568 ast_pthread_mutex_lock(&iflock);
570 ast_pthread_mutex_unlock(&iflock);
573 /* Interface lookup code courtesy Tilghman of DrunkCoder.com. Thanks! */
578 char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
583 struct sockaddr_in ifru_addr;
588 struct in_addr *lookup_iface(char *iface) {
591 static struct my_ifreq ifreq;
592 memset(&ifreq, 0, sizeof(ifreq));
593 strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
595 mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
596 res = ioctl(mysock,SIOCGIFADDR,&ifreq);
600 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
603 return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
606 static struct in_addr *myaddrfor(struct in_addr *them)
609 struct in_addr *temp = NULL;
610 unsigned int remote_ip;
612 remote_ip = them->s_addr;
614 PROC = fopen("/proc/net/route","r");
616 /* If /proc/net/route doesn't exist, fall back to the old method */
619 /* First line contains headers */
620 fgets(line,sizeof(line),PROC);
622 while (!feof(PROC)) {
624 unsigned int dest, gateway, mask;
628 fgets(line,sizeof(line),PROC);
631 for (i=0;i<sizeof(line);i++) {
634 fields[aoffset++] = line + i;
635 boffset = strchr(line + i,'\t');
636 if (boffset == NULL) {
645 sscanf(fields[0],"%s",iface);
646 sscanf(fields[1],"%x",&dest);
647 sscanf(fields[2],"%x",&gateway);
648 sscanf(fields[7],"%x",&mask);
650 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
652 if (((remote_ip & mask) ^ dest) == 0) {
654 ast_verbose("Interface is %s\n",iface);
655 temp = lookup_iface(iface);
657 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
663 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s. Using default\n", inet_ntoa(*them));
670 static int sip_hangup(struct ast_channel *ast)
672 struct sip_pvt *p = ast->pvt->pvt;
675 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
676 if (!ast->pvt->pvt) {
677 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
680 ast_pthread_mutex_lock(&p->lock);
681 /* Determine how to disconnect */
682 if (p->owner != ast) {
683 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
684 ast_pthread_mutex_unlock(&p->lock);
687 if (!ast || (ast->_state != AST_STATE_UP))
692 ast->pvt->pvt = NULL;
696 /* Invert sense of outgoing */
697 p->outgoing = 1 - p->outgoing;
699 /* Start the process if it's not already started */
700 if (!p->alreadygone && strlen(p->initreq.data)) {
702 transmit_request(p, "CANCEL", 0);
705 transmit_request(p, "BYE", p->outgoing);
709 /* Restore sense of outgoing */
710 p->outgoing = 1 - p->outgoing;
712 ast_pthread_mutex_unlock(&p->lock);
716 static int sip_answer(struct ast_channel *ast)
718 int res = 0,fmt,capability;
720 struct sip_pvt *p = ast->pvt->pvt;
721 struct sip_codec_pref *oldpref=NULL;
724 if (ast->_state != AST_STATE_UP) {
728 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
730 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
731 fmt=ast_getformatbyname(codec);
735 sip_pref_append(fmt);
736 capability=p->capability;
738 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
741 ast_setstate(ast, AST_STATE_UP);
743 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
744 res = transmit_response_with_sdp(p, "200 OK", &p->initreq);
748 p->capability=capability;
754 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
756 struct sip_pvt *p = ast->pvt->pvt;
758 if (frame->frametype != AST_FRAME_VOICE) {
759 if (frame->frametype == AST_FRAME_IMAGE)
762 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
766 if (!(frame->subclass & ast->nativeformats)) {
767 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
768 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
773 ast_pthread_mutex_lock(&p->lock);
775 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
776 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq);
779 res = ast_rtp_write(p->rtp, frame);
781 ast_pthread_mutex_unlock(&p->lock);
786 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
788 struct sip_pvt *p = newchan->pvt->pvt;
789 ast_pthread_mutex_lock(&p->lock);
790 if (p->owner != oldchan) {
791 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
792 ast_pthread_mutex_unlock(&p->lock);
796 ast_pthread_mutex_unlock(&p->lock);
800 static int sip_senddigit(struct ast_channel *ast, char digit)
802 struct sip_pvt *p = ast->pvt->pvt;
804 ast_rtp_senddigit(p->rtp, digit);
810 static int sip_indicate(struct ast_channel *ast, int condition)
812 struct sip_pvt *p = ast->pvt->pvt;
814 case AST_CONTROL_RINGING:
815 if (ast->_state == AST_STATE_RING) {
816 transmit_response(p, "180 Ringing", &p->initreq);
820 case AST_CONTROL_BUSY:
821 if (ast->_state != AST_STATE_UP) {
822 transmit_response(p, "600 Busy everywhere", &p->initreq);
824 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
828 case AST_CONTROL_CONGESTION:
829 if (ast->_state != AST_STATE_UP) {
830 transmit_response(p, "486 Busy here", &p->initreq);
832 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
839 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
847 static int sip_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
849 struct sip_pvt *p0, *p1;
851 struct ast_channel *who, *cs[3];
854 /* if need DTMF, cant native bridge */
855 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
857 ast_pthread_mutex_lock(&c0->lock);
858 ast_pthread_mutex_lock(&c1->lock);
861 ast_log(LOG_DEBUG, "Reinvite? %s: %s, %s: %s\n", c0->name, p0->canreinvite ? "yes" : "no", c1->name, p1->canreinvite ? "yes" : "no");
862 if (!p0->canreinvite || !p1->canreinvite) {
863 /* Not gonna support reinvite */
864 ast_pthread_mutex_unlock(&c0->lock);
865 ast_pthread_mutex_unlock(&c1->lock);
868 transmit_reinvite_with_sdp(p0, p1->rtp);
869 transmit_reinvite_with_sdp(p1, p0->rtp);
870 ast_pthread_mutex_unlock(&c0->lock);
871 ast_pthread_mutex_unlock(&c1->lock);
876 if ((c0->pvt->pvt != p0) ||
877 (c1->pvt->pvt != p1) ||
878 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
879 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
880 if (c0->pvt->pvt == p0)
881 transmit_reinvite_with_sdp(p0, NULL);
882 if (c1->pvt->pvt == p1)
883 transmit_reinvite_with_sdp(p1, NULL);
884 /* Tell it to try again later */
888 who = ast_waitfor_n(cs, 2, &to);
890 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
894 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
895 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
896 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
899 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
900 if (c0->pvt->pvt == p0 && !c0->_softhangup)
901 transmit_reinvite_with_sdp(p0, NULL);
902 if (c1->pvt->pvt == p1 && !c1->_softhangup)
903 transmit_reinvite_with_sdp(p1, NULL);
904 /* That's all we needed */
908 /* Swap priority not that it's a big deal at this point */
918 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
920 struct ast_channel *tmp;
922 tmp = ast_channel_alloc(1);
924 /* Select our native format based on codec preference until we receive
925 something from another device to the contrary. */
927 tmp->nativeformats = sip_codec_choose(i->capability);
929 tmp->nativeformats = sip_codec_choose(capability);
930 fmt = ast_best_codec(tmp->nativeformats);
932 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
934 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
936 tmp->fds[0] = ast_rtp_fd(i->rtp);
937 ast_setstate(tmp, state);
938 if (state == AST_STATE_RING)
940 tmp->writeformat = fmt;
941 tmp->pvt->rawwriteformat = fmt;
942 tmp->readformat = fmt;
943 tmp->pvt->rawreadformat = fmt;
945 tmp->pvt->send_text = sip_sendtext;
946 tmp->pvt->call = sip_call;
947 tmp->pvt->hangup = sip_hangup;
948 tmp->pvt->answer = sip_answer;
949 tmp->pvt->read = sip_read;
950 tmp->pvt->write = sip_write;
951 tmp->pvt->indicate = sip_indicate;
952 tmp->pvt->fixup = sip_fixup;
953 tmp->pvt->send_digit = sip_senddigit;
954 tmp->pvt->bridge = ast_rtp_bridge;
955 if (strlen(i->language))
956 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
958 ast_pthread_mutex_lock(&usecnt_lock);
960 ast_pthread_mutex_unlock(&usecnt_lock);
961 ast_update_use_count();
962 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
963 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
964 if (strlen(i->callerid))
965 tmp->callerid = strdup(i->callerid);
967 if (state != AST_STATE_DOWN) {
968 if (ast_pbx_start(tmp)) {
969 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
975 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
979 static struct cfalias {
983 { "Content-Type", "c" },
984 { "Content-Encoding", "e" },
988 { "Content-Length", "l" },
994 static char *get_sdp(struct sip_request *req, char *name)
997 int len = strlen(name);
999 for (x=0;x<req->lines;x++) {
1000 if (!strncasecmp(req->line[x], name, len) &&
1001 (req->line[x][len] == '=')) {
1002 r = req->line[x] + len + 1;
1003 while(*r && (*r < 33))
1011 static char *__get_header(struct sip_request *req, char *name, int *start)
1014 int len = strlen(name);
1016 for (x=*start;x<req->headers;x++) {
1017 if (!strncasecmp(req->header[x], name, len) &&
1018 (req->header[x][len] == ':')) {
1019 r = req->header[x] + len + 1;
1020 while(*r && (*r < 33))
1027 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1028 if (!strcasecmp(aliases[x].fullname, name))
1029 return __get_header(req, aliases[x].shortname, start);
1031 /* Don't return NULL, so get_header is always a valid pointer */
1035 static char *get_header(struct sip_request *req, char *name)
1038 return __get_header(req, name, &start);
1041 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1043 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1044 struct ast_frame *f;
1045 f = ast_rtp_read(p->rtp);
1047 /* We already hold the channel lock */
1048 if (f->frametype == AST_FRAME_VOICE) {
1049 if (f->subclass != p->owner->nativeformats) {
1050 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1051 p->owner->nativeformats = f->subclass;
1052 ast_set_read_format(p->owner, p->owner->readformat);
1053 ast_set_write_format(p->owner, p->owner->writeformat);
1060 static struct ast_frame *sip_read(struct ast_channel *ast)
1062 struct ast_frame *fr;
1063 struct sip_pvt *p = ast->pvt->pvt;
1064 ast_pthread_mutex_lock(&p->lock);
1065 fr = sip_rtp_read(p);
1066 ast_pthread_mutex_unlock(&p->lock);
1070 static void build_callid(char *callid, int len, struct in_addr ourip)
1077 res = snprintf(callid, len, "%08x", val);
1081 /* It's not important that we really use our right IP here... */
1082 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1085 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin)
1089 p = malloc(sizeof(struct sip_pvt));
1092 /* Keep track of stuff */
1093 memset(p, 0, sizeof(struct sip_pvt));
1095 p->rtp = ast_rtp_new(NULL, NULL);
1098 /* Start with 101 instead of 1 */
1101 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1105 ast_rtp_settos(p->rtp, tos);
1106 ast_pthread_mutex_init(&p->lock);
1108 ast_rtp_set_data(p->rtp, p);
1109 ast_rtp_set_callback(p->rtp, rtpready);
1112 memcpy(&p->sa, sin, sizeof(p->sa));
1113 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1115 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1117 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1119 build_callid(p->callid, sizeof(p->callid), p->ourip);
1121 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1122 /* Assume reinvite OK */
1125 ast_pthread_mutex_lock(&iflock);
1128 ast_pthread_mutex_unlock(&iflock);
1130 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1134 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1138 callid = get_header(req, "Call-ID");
1139 if (!strlen(callid)) {
1140 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1143 ast_pthread_mutex_lock(&iflock);
1146 if (!strcmp(p->callid, callid)) {
1147 /* Found the call */
1149 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1150 (p->sa.sin_port != sin->sin_port))) {
1153 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1154 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1155 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1156 ast_pthread_mutex_unlock(&iflock);
1160 ast_pthread_mutex_unlock(&iflock);
1165 ast_pthread_mutex_unlock(&iflock);
1166 return sip_alloc(callid, sin);
1169 static int sip_register(char *value, int lineno)
1171 struct sip_registry *reg;
1172 char copy[256] = "";
1173 char *username, *hostname, *secret;
1181 strncpy(copy, value, sizeof(copy)-1);
1184 hostname = strrchr(stringp, '@');
1190 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1194 username = strsep(&stringp, ":");
1195 secret = strsep(&stringp, ":");
1197 hostname = strsep(&stringp, "/");
1198 contact = strsep(&stringp, "/");
1199 if (!contact || !strlen(contact))
1202 hostname = strsep(&stringp, ":");
1203 porta = strsep(&stringp, ":");
1205 if (porta && !atoi(porta)) {
1206 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1209 hp = gethostbyname(hostname);
1211 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1214 reg = malloc(sizeof(struct sip_registry));
1216 memset(reg, 0, sizeof(struct sip_registry));
1217 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1218 strncpy(reg->username, username, sizeof(reg->username)-1);
1220 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1222 reg->refresh = default_expirey;
1223 reg->addr.sin_family = AF_INET;
1224 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1225 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1226 reg->next = registrations;
1227 reg->callid_valid = 0;
1228 registrations = reg;
1230 ast_log(LOG_ERROR, "Out of memory\n");
1236 static void parse(struct sip_request *req)
1238 /* Divide fields by NULL's */
1243 /* First header starts immediately */
1247 /* We've got a new header */
1251 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1253 if (!strlen(req->header[f])) {
1254 /* Line by itself means we're now in content */
1258 if (f >= SIP_MAX_HEADERS - 1) {
1259 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1262 req->header[f] = c + 1;
1263 } else if (*c == '\r') {
1264 /* Ignore but eliminate \r's */
1269 /* Check for last header */
1270 if (strlen(req->header[f]))
1273 /* Now we process any mime content */
1278 /* We've got a new line */
1281 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1283 if (f >= SIP_MAX_LINES - 1) {
1284 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1287 req->line[f] = c + 1;
1288 } else if (*c == '\r') {
1289 /* Ignore and eliminate \r's */
1294 /* Check for last line */
1295 if (strlen(req->line[f]))
1299 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1301 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1304 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1312 struct sockaddr_in sin;
1316 /* Get codec and RTP info from SDP */
1317 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1318 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1321 m = get_sdp(req, "m");
1322 c = get_sdp(req, "c");
1323 if (!strlen(m) || !strlen(c)) {
1324 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1327 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1328 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1331 /* XXX This could block for a long time, and block the main thread! XXX */
1332 hp = gethostbyname(host);
1334 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1337 if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1338 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1341 sin.sin_family = AF_INET;
1342 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1343 sin.sin_port = htons(portno);
1345 ast_rtp_set_peer(p->rtp, &sin);
1347 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1351 while(strlen(codecs)) {
1352 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1353 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1357 printf("Codec: %d\n", codec);
1359 codec = rtp2ast(codec);
1361 peercapability |= codec;
1364 p->capability = capability & peercapability;
1366 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1367 capability, peercapability, p->capability);
1368 if (!p->capability) {
1369 ast_log(LOG_WARNING, "No compatible codecs!\n");
1373 if (!(p->owner->nativeformats & p->capability)) {
1374 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);
1375 p->owner->nativeformats = sip_codec_choose(p->capability);
1376 ast_set_read_format(p->owner, p->owner->readformat);
1377 ast_set_write_format(p->owner, p->owner->writeformat);
1379 if (p->owner->bridge) {
1380 /* Turn on/off music on hold if we are holding/unholding */
1381 if (sin.sin_addr.s_addr) {
1382 ast_moh_stop(p->owner->bridge);
1384 ast_moh_start(p->owner->bridge, NULL);
1392 static int add_header(struct sip_request *req, char *var, char *value)
1394 if (req->len >= sizeof(req->data) - 4) {
1395 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1399 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1402 req->header[req->headers] = req->data + req->len;
1403 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1404 req->len += strlen(req->header[req->headers]);
1405 if (req->headers < SIP_MAX_HEADERS)
1408 ast_log(LOG_WARNING, "Out of header space\n");
1414 static int add_blank_header(struct sip_request *req)
1416 if (req->len >= sizeof(req->data) - 4) {
1417 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1421 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1424 req->header[req->headers] = req->data + req->len;
1425 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1426 req->len += strlen(req->header[req->headers]);
1427 if (req->headers < SIP_MAX_HEADERS)
1430 ast_log(LOG_WARNING, "Out of header space\n");
1436 static int add_line(struct sip_request *req, char *line)
1438 if (req->len >= sizeof(req->data) - 4) {
1439 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1443 /* Add extra empty return */
1444 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1445 req->len += strlen(req->data + req->len);
1447 req->line[req->lines] = req->data + req->len;
1448 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1449 req->len += strlen(req->line[req->lines]);
1450 if (req->lines < SIP_MAX_LINES)
1453 ast_log(LOG_WARNING, "Out of line space\n");
1459 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1462 tmp = get_header(orig, field);
1464 /* Add what we're responding to */
1465 return add_header(req, field, tmp);
1467 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1472 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1478 tmp = __get_header(orig, field, &start);
1480 /* Add what we're responding to */
1481 add_header(req, field, tmp);
1487 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1493 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1500 tmp = __get_header(orig, field, &start);
1503 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1504 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1506 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1507 add_header(req, field, new);
1509 /* Add what we're responding to */
1510 add_header(req, field, tmp);
1517 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1523 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1525 /* Initialize a response */
1526 if (req->headers || req->len) {
1527 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1530 req->header[req->headers] = req->data + req->len;
1531 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1532 req->len += strlen(req->header[req->headers]);
1533 if (req->headers < SIP_MAX_HEADERS)
1536 ast_log(LOG_WARNING, "Out of header space\n");
1540 static int init_req(struct sip_request *req, char *resp, char *recip)
1542 /* Initialize a response */
1543 if (req->headers || req->len) {
1544 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1547 req->header[req->headers] = req->data + req->len;
1548 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1549 req->len += strlen(req->header[req->headers]);
1550 if (req->headers < SIP_MAX_HEADERS)
1553 ast_log(LOG_WARNING, "Out of header space\n");
1557 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1559 char newto[256] = "", *ot;
1560 memset(resp, 0, sizeof(*resp));
1561 init_resp(resp, msg, req);
1562 copy_via_headers(p, resp, req, "Via");
1563 copy_header(resp, req, "From");
1564 ot = get_header(req, "To");
1565 if (!strstr(ot, "tag=")) {
1566 /* Add the proper tag if we don't have it already. If they have specified
1567 their tag, use it. Otherwise, use our own tag */
1568 if (strlen(p->theirtag))
1569 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1571 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1573 strncpy(newto, ot, sizeof(newto) - 1);
1576 add_header(resp, "To", ot);
1577 copy_header(resp, req, "Call-ID");
1578 copy_header(resp, req, "CSeq");
1579 add_header(resp, "User-Agent", "Asterisk PBX");
1581 /* For registration responses, we also need expirey and
1584 char contact2[256] = "", *c, contact[256];
1585 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1586 strncpy(contact2, get_header(req, "Contact"), sizeof(contact2)-1);
1587 c = ditch_braces(contact2);
1588 snprintf(contact, sizeof(contact), "<%s>", c);
1589 add_header(resp, "Expires", tmp);
1590 add_header(resp, "Contact", contact);
1592 char contact2[256] = "", *c, contact[256];
1593 /* XXX This isn't exactly right and it's implemented
1594 very stupidly *sigh* XXX */
1595 strncpy(contact2, get_header(req, "To"), sizeof(contact2)-1);
1596 c = ditch_braces(contact2);
1597 snprintf(contact, sizeof(contact), "<%s>", c);
1598 add_header(resp, "Contact", contact);
1603 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1605 struct sip_request *orig = &p->initreq;
1606 char stripped[80] ="";
1612 memset(req, 0, sizeof(struct sip_request));
1618 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1620 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1622 c = strchr(stripped, '<');
1631 init_req(req, msg, c);
1633 snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1635 add_header(req, "Via", p->via);
1637 ot = get_header(orig, "To");
1638 of = get_header(orig, "From");
1640 if (!strstr(ot, "tag=")) {
1641 /* Add the proper tag if we don't have it already. If they have specified
1642 their tag, use it. Otherwise, use our own tag */
1643 if (strlen(p->theirtag))
1644 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1646 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1651 add_header(req, "From", of);
1652 add_header(req, "To", ot);
1654 add_header(req, "From", ot);
1655 add_header(req, "To", of);
1657 copy_header(req, orig, "Call-ID");
1658 add_header(req, "CSeq", tmp);
1660 add_header(req, "User-Agent", "Asterisk PBX");
1664 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1666 struct sip_request resp;
1667 respprep(&resp, p, msg, req);
1668 add_header(&resp, "Content-Length", "0");
1669 add_blank_header(&resp);
1670 return send_response(p, &resp);
1673 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1675 struct sip_request resp;
1676 respprep(&resp, p, msg, req);
1677 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1678 add_header(&resp, "Accept", "application/sdp");
1679 add_header(&resp, "Content-Length", "0");
1680 add_blank_header(&resp);
1681 return send_response(p, &resp);
1684 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1686 struct sip_request resp;
1688 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1689 respprep(&resp, p, msg, req);
1690 add_header(&resp, "Proxy-Authenticate", tmp);
1691 add_header(&resp, "Content-Length", "0");
1692 add_blank_header(&resp);
1693 return send_response(p, &resp);
1696 static int add_text(struct sip_request *req, char *text)
1698 /* XXX Convert \n's to \r\n's XXX */
1699 int len = strlen(text);
1701 snprintf(clen, sizeof(clen), "%d", len);
1702 add_header(req, "Content-Type", "text/plain");
1703 add_header(req, "Content-Length", clen);
1704 add_line(req, text);
1708 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1712 int alreadysent = 0;
1714 struct sockaddr_in sin;
1715 struct sip_codec_pref *cur;
1724 struct sockaddr_in dest;
1725 /* XXX We break with the "recommendation" and send our IP, in order that our
1726 peer doesn't have to gethostbyname() us XXX */
1729 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1732 ast_rtp_get_us(p->rtp, &sin);
1734 ast_rtp_get_peer(rtp, &dest);
1736 dest.sin_addr = p->ourip;
1737 dest.sin_port = sin.sin_port;
1740 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
1741 snprintf(v, sizeof(v), "v=0\r\n");
1742 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1743 snprintf(s, sizeof(s), "s=session\r\n");
1744 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1745 snprintf(t, sizeof(t), "t=0 0\r\n");
1746 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1747 /* Start by sending our preferred codecs */
1750 if (p->capability & cur->codec) {
1752 ast_verbose("Answering with preferred capability %d\n", cur->codec);
1753 if ((codec = ast2rtp(cur->codec)) > -1) {
1754 snprintf(costr, sizeof(costr), " %d", codec);
1756 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(rtp2ast(codec)));
1760 alreadysent |= cur->codec;
1763 /* Now send anything else in no particular order */
1764 for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1765 if ((p->capability & x) && !(alreadysent & x)) {
1767 ast_verbose("Answering with capability %d\n", x);
1768 if ((codec = ast2rtp(x)) > -1) {
1769 snprintf(costr, sizeof(costr), " %d", codec);
1771 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(x));
1776 strcat(m, " 101\r\n");
1777 strcat(a, "a=rtpmap:101 telephone-event/8000\r\n");
1778 /* Indicate we support DTMF only... Not sure about 16, but MSN supports it so dang it, we will too... */
1779 strcat(a, "a=fmtp:101 0-16\r\n");
1780 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1781 snprintf(costr, sizeof(costr), "%d", len);
1782 add_header(resp, "Content-Type", "application/sdp");
1783 add_header(resp, "Content-Length", costr);
1794 static void copy_request(struct sip_request *dst,struct sip_request *src)
1798 offset = ((void *)dst) - ((void *)src);
1799 /* First copy stuff */
1800 memcpy(dst, src, sizeof(*dst));
1801 /* Now fix pointer arithmetic */
1802 for (x=0;x<src->headers;x++)
1803 dst->header[x] += offset;
1804 for (x=0;x<src->lines;x++)
1805 dst->line[x] += offset;
1808 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1810 struct sip_request resp;
1811 respprep(&resp, p, msg, req);
1812 add_sdp(&resp, p, NULL);
1813 return send_response(p, &resp);
1816 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1818 struct sip_request resp;
1819 reqprep(&resp, p, "INVITE", 1);
1820 add_sdp(&resp, p, rtp);
1821 return send_response(p, &resp);
1824 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1831 char *l = "asterisk", *n=NULL;
1832 if (p->owner && p->owner->callerid) {
1833 strcpy(cid, p->owner->callerid);
1834 ast_callerid_parse(cid, &n, &l);
1836 ast_shrink_phone_number(l);
1837 if (!l || !ast_isphonenumber(l))
1842 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1843 if (strlen(p->username)) {
1844 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1845 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1847 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1849 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1850 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1852 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1854 /* If there is a VXML URL append it to the SIP URL */
1857 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1861 snprintf(to, sizeof(to), "<%s>", invite );
1863 memset(req, 0, sizeof(struct sip_request));
1864 init_req(req, cmd, invite);
1865 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1867 add_header(req, "Via", p->via);
1868 add_header(req, "From", from);
1870 char contact2[256] ="", *c, contact[256];
1871 /* XXX This isn't exactly right and it's implemented
1872 very stupidly *sigh* XXX */
1873 strncpy(contact2, from, sizeof(contact2)-1);
1874 c = ditch_braces(contact2);
1875 snprintf(contact, sizeof(contact), "<%s>", c);
1876 add_header(req, "Contact", contact);
1878 add_header(req, "To", to);
1879 add_header(req, "Call-ID", p->callid);
1880 add_header(req, "CSeq", tmp);
1881 add_header(req, "User-Agent", "Asterisk PBX");
1884 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
1886 struct sip_request req;
1887 initreqprep(&req, p, cmd, vxml_url);
1889 add_header(&req, "Proxy-Authorization", auth);
1891 add_sdp(&req, p, NULL);
1893 add_header(&req, "Content-Length", "0");
1894 add_blank_header(&req);
1896 if (!p->initreq.headers) {
1897 /* Use this as the basis */
1898 copy_request(&p->initreq, &req);
1901 p->lastinvite = p->ocseq;
1902 return send_request(p, &req);
1905 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
1907 struct sip_request req;
1910 initreqprep(&req, p, "NOTIFY", NULL);
1911 add_header(&req, "Event", "message-summary");
1912 add_header(&req, "Content-Type", "text/plain");
1914 snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
1915 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
1916 add_header(&req, "Content-Length", clen);
1917 add_line(&req, tmp);
1919 if (!p->initreq.headers) {
1920 /* Use this as the basis */
1921 copy_request(&p->initreq, &req);
1925 p->lastinvite = p->ocseq;
1926 return send_request(p, &req);
1929 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
1931 static int sip_reregister(void *data)
1933 /* if we are here, we know that we need to reregister. */
1934 struct sip_registry *r=(struct sip_registry *)data;
1935 return sip_do_register(r);
1940 static int sip_do_register(struct sip_registry *r)
1943 ast_pthread_mutex_lock(&r->lock);
1944 res=transmit_register(r, "REGISTER", NULL);
1945 ast_pthread_mutex_unlock(&r->lock);
1949 static int sip_reg_timeout(void *data)
1951 /* if we are here, our registration timed out, so we'll just do it over */
1952 struct sip_registry *r=data;
1954 ast_pthread_mutex_lock(&r->lock);
1955 ast_log(LOG_NOTICE, "Registration timed out, trying again\n");
1956 r->regstate=REG_STATE_UNREGISTERED;
1957 /* cancel ourselves first!!! */
1958 /* ast_sched_del(sched,r->timeout); */
1959 res=transmit_register(r, "REGISTER", NULL);
1960 ast_pthread_mutex_unlock(&r->lock);
1964 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
1966 struct sip_request req;
1973 /* exit if we are already in process with this registrar ?*/
1974 if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
1975 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
1981 if (!r->callid_valid) {
1982 build_callid(r->callid, sizeof(r->callid), __ourip);
1985 p=sip_alloc( r->callid, &r->addr );
1989 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
1990 strncpy(p->peername, r->username, sizeof(p->peername)-1);
1991 strncpy(p->username, r->username, sizeof(p->username)-1);
1994 /* set up a timeout */
1995 if (auth==NULL && !r->timeout) {
1996 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
1997 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2000 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2001 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2003 snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2005 memset(&req, 0, sizeof(req));
2006 init_req(&req, cmd, addr);
2008 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2010 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2011 add_header(&req, "Via", via);
2012 add_header(&req, "From", from);
2013 add_header(&req, "To", to);
2016 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2017 add_header(&req, "Contact", contact);
2019 add_header(&req, "Call-ID", p->callid);
2020 add_header(&req, "CSeq", tmp);
2021 add_header(&req, "User-Agent", "Asterisk PBX");
2023 add_header(&req, "Authorization", auth);
2025 snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2026 add_header(&req, "Expires", tmp);
2027 add_header(&req, "Event", "registration");
2028 copy_request(&p->initreq, &req);
2029 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2030 return send_request(p, &req);
2033 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2035 struct sip_request req;
2036 reqprep(&req, p, "MESSAGE", 1);
2037 add_text(&req, text);
2038 return send_request(p, &req);
2041 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
2043 struct sip_request resp;
2044 reqprep(&resp, p, msg, inc);
2045 add_header(&resp, "Content-Length", "0");
2046 add_blank_header(&resp);
2047 return send_request(p, &resp);
2050 static int expire_register(void *data)
2052 struct sip_peer *p = data;
2053 memset(&p->addr, 0, sizeof(p->addr));
2058 static int sip_poke_peer(struct sip_peer *peer);
2060 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2062 char contact[80]= "";
2063 char *expires = get_header(req, "Expires");
2064 int expirey = atoi(expires);
2068 struct sockaddr_in oldsin;
2069 if (!strlen(expires)) {
2070 expires = strstr(get_header(req, "Contact"), "expires=");
2072 if (sscanf(expires + 8, "%d;", &expirey) != 1)
2075 /* Look for brackets */
2076 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2079 if ((n=strchr(c, '<'))) {
2082 /* Lose the part after the > */
2086 if (!strcasecmp(c, "*")) {
2087 /* This means remove all registrations and return OK */
2088 memset(&p->addr, 0, sizeof(p->addr));
2090 ast_sched_del(sched, p->expire);
2092 if (option_verbose > 2)
2093 ast_verbose(VERBOSE_PREFIX_3 "Unegistered SIP '%s'\n", p->username);
2096 /* Make sure it's a SIP URL */
2097 if (strncasecmp(c, "sip:", 4)) {
2098 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2114 pt = strchr(n, ':');
2120 port = DEFAULT_SIP_PORT;
2121 /* XXX This could block for a long time XXX */
2122 hp = gethostbyname(n);
2124 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2127 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2128 p->addr.sin_family = AF_INET;
2129 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2130 p->addr.sin_port = htons(port);
2132 strncpy(p->username, c, sizeof(p->username) - 1);
2134 strcpy(p->username, "");
2136 ast_sched_del(sched, p->expire);
2137 if ((expirey < 1) || (expirey > max_expirey))
2138 expirey = max_expirey;
2139 p->expire = ast_sched_add(sched, expirey * 1000, expire_register, p);
2140 pvt->expirey = expirey;
2141 if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2143 if (option_verbose > 2)
2144 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);
2149 static void md5_hash(char *output, char *input)
2151 struct MD5Context md5;
2152 unsigned char digest[16];
2156 MD5Update(&md5, input, strlen(input));
2157 MD5Final(digest, &md5);
2160 ptr += sprintf(ptr, "%2.2x", digest[x]);
2163 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
2166 /* Always OK if no secret */
2167 if (!strlen(secret))
2169 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2170 snprintf(randdata, randlen, "%08x", rand());
2171 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
2174 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2175 an example in the spec of just what it is you're doing a hash on. */
2181 char resp_hash[256];
2187 /* Find their response among the mess that we'r sent for comparison */
2188 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2192 while (*c && (*c < 33)) c++;
2195 if (!strncasecmp(c, "response=", strlen("response="))) {
2196 c+= strlen("response=");
2199 if((c = strchr(c,'\"')))
2204 if((c = strchr(c,',')))
2208 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2212 if((c = strchr(c,'\"')))
2216 if((c = strchr(c,',')))
2225 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2226 if(strlen(resp_uri))
2227 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2229 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2230 md5_hash(a1_hash, a1);
2231 md5_hash(a2_hash, a2);
2232 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2233 md5_hash(resp_hash, resp);
2235 /* resp_hash now has the expected response, compare the two */
2237 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2241 /* Assume success ;-) */
2242 /* Eliminate random data */
2243 strcpy(randdata, "");
2248 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2251 struct sip_peer *peer;
2257 while(*t && (*t > 32) && (*t != ';'))
2261 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2262 c = ditch_braces(tmp);
2263 if (!strncmp(c, "sip:", 4)) {
2267 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2269 c = strchr(name, '@');
2272 ast_pthread_mutex_lock(&peerl.lock);
2275 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2277 transmit_response(p, "100 Trying", req);
2278 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2279 if (parse_contact(p, peer, req)) {
2280 ast_log(LOG_WARNING, "Failed to parse contact info\n");
2282 /* Say OK and ask subsystem to retransmit msg counter */
2283 transmit_response(p, "200 OK", req);
2284 peer->lastmsgssent = -1;
2292 ast_pthread_mutex_unlock(&peerl.lock);
2294 transmit_response(p, "401 Unauthorized", &p->initreq);
2298 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2300 char tmp[256] = "", *c, *a;
2301 struct sip_request *req;
2306 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2307 c = ditch_braces(tmp);
2308 if (strncmp(c, "sip:", 4)) {
2309 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2313 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2317 ast_verbose("Looking for %s in %s\n", c, p->context);
2318 if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2320 strncpy(p->exten, c, sizeof(p->exten) - 1);
2324 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2331 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2333 char tmp[256] = "", *c, *a;
2334 char tmp2[256] = "", *c2, *a2;
2337 char tmp5[256] = ""; /* CallID to replace */
2338 struct sip_request *req;
2344 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2345 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2346 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2347 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2349 c = ditch_braces(tmp);
2350 c2 = ditch_braces(tmp2);
2353 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2354 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2355 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
2360 if ((a = strchr(c, '?'))) {
2361 /* Search for arguemnts */
2364 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2365 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2366 if ((a = strchr(tmp5, '%'))) {
2367 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
2369 if ((a[1] == '4') && (a[2] == '0')) {
2371 memmove(a + 1, a+3, strlen(a + 3));
2374 if ((a = strchr(tmp5, '%')))
2379 if ((a = strchr(c, '@')))
2381 if ((a = strchr(c, ';')))
2385 if ((a2 = strchr(c2, '@')))
2388 if ((a2 = strchr(c2, ';')))
2393 ast_verbose("Looking for %s in %s\n", c, p->context);
2394 ast_verbose("Looking for %s in %s\n", c2, p->context);
2397 /* This is a supervised transfer */
2398 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2400 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2401 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2402 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2403 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2404 p->refer_call = NULL;
2405 ast_pthread_mutex_lock(&iflock);
2406 /* Search interfaces and find the match */
2409 if (!strcmp(p2->callid, tmp5)) {
2410 /* Go ahead and lock it before returning */
2411 ast_pthread_mutex_lock(&p2->lock);
2417 ast_pthread_mutex_unlock(&iflock);
2421 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2422 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2423 /* This is an unsupervised transfer */
2424 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2425 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2426 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2427 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2428 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2429 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2430 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2431 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2432 p->refer_call = NULL;
2434 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2442 static int check_via(struct sip_pvt *p, struct sip_request *req)
2448 memset(via, 0, sizeof(via));
2449 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2450 c = strchr(via, ';');
2453 c = strchr(via, ' ');
2457 while(*c && (*c < 33))
2459 if (strcmp(via, "SIP/2.0/UDP")) {
2460 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2463 pt = strchr(c, ':');
2468 hp = gethostbyname(c);
2470 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2473 memset(&p->sa, 0, sizeof(p->sa));
2474 p->sa.sin_family = AF_INET;
2475 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2476 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2479 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2481 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2487 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2489 struct sip_user *user;
2490 char *of, from[256] = "", *c;
2495 while(*t && (*t > 32) && (*t != ';'))
2498 of = get_header(req, "From");
2499 strncpy(from, of, sizeof(from) - 1);
2500 of = ditch_braces(from);
2501 if (strncmp(of, "sip:", 4)) {
2502 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2505 /* Get just the username part */
2506 if ((c = strchr(of, '@')))
2508 if ((c = strchr(of, ':')))
2510 strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2513 ast_pthread_mutex_lock(&userl.lock);
2516 if (!strcasecmp(user->name, of)) {
2518 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2519 strncpy(p->context, user->context, sizeof(p->context) - 1);
2520 if (strlen(user->callerid) && strlen(p->callerid))
2521 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2522 strncpy(p->username, user->name, sizeof(p->username) - 1);
2523 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
2524 p->canreinvite = user->canreinvite;
2525 p->amaflags = user->amaflags;
2531 ast_pthread_mutex_unlock(&userl.lock);
2535 static int get_msg_text(char *buf, int len, struct sip_request *req)
2539 for (x=0;x<req->lines;x++) {
2540 strncat(buf, req->line[x], len - strlen(buf) - 5);
2546 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2550 if (get_msg_text(buf, sizeof(buf), req)) {
2551 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2556 ast_verbose("Message received: '%s'\n", buf);
2557 memset(&f, 0, sizeof(f));
2558 f.frametype = AST_FRAME_TEXT;
2562 f.datalen = strlen(buf);
2563 ast_queue_frame(p->owner, &f, 1);
2567 static int sip_show_users(int fd, int argc, char *argv[])
2569 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2570 struct sip_user *user;
2572 return RESULT_SHOWUSAGE;
2573 ast_pthread_mutex_lock(&userl.lock);
2574 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2575 for(user=userl.users;user;user=user->next) {
2576 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2578 user->ha ? "Yes" : "No");
2580 ast_pthread_mutex_unlock(&userl.lock);
2581 return RESULT_SUCCESS;
2585 static int sip_show_peers(int fd, int argc, char *argv[])
2587 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2588 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2589 struct sip_peer *peer;
2590 char name[256] = "";
2592 return RESULT_SHOWUSAGE;
2593 ast_pthread_mutex_lock(&peerl.lock);
2594 ast_cli(fd, FORMAT2, "Name/username", "Host", " ", "Mask", "Port", "Status");
2595 for (peer = peerl.peers;peer;peer = peer->next) {
2598 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2599 if (strlen(peer->username))
2600 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2602 strncpy(name, peer->name, sizeof(name) - 1);
2604 if (peer->lastms < 0)
2605 strcpy(status, "UNREACHABLE");
2606 else if (peer->lastms > peer->maxms)
2607 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2608 else if (peer->lastms)
2609 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2611 strcpy(status, "UNKNOWN");
2613 strcpy(status, "Unmonitored");
2614 ast_cli(fd, FORMAT, name,
2615 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2616 peer->dynamic ? "(D)" : " ",
2618 ntohs(peer->addr.sin_port), status);
2620 ast_pthread_mutex_unlock(&peerl.lock);
2621 return RESULT_SUCCESS;
2626 static char *regstate2str(int regstate)
2629 case REG_STATE_UNREGISTERED:
2630 return "Unregistered";
2631 case REG_STATE_REGSENT:
2632 return "Request Sent";
2633 case REG_STATE_AUTHSENT:
2634 return "Auth. Sent";
2635 case REG_STATE_REGISTERED:
2636 return "Registered";
2637 case REG_STATE_REJECTED:
2639 case REG_STATE_TIMEOUT:
2641 case REG_STATE_NOAUTH:
2642 return "No Authentication";
2648 static int sip_show_registry(int fd, int argc, char *argv[])
2650 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2651 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2652 struct sip_registry *reg;
2656 return RESULT_SHOWUSAGE;
2657 ast_pthread_mutex_lock(&peerl.lock);
2658 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2659 for (reg = registrations;reg;reg = reg->next) {
2660 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2661 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2662 ast_cli(fd, FORMAT, host,
2663 reg->username, state, reg->refresh, regstate2str(reg->regstate));
2665 ast_pthread_mutex_unlock(&peerl.lock);
2666 return RESULT_SUCCESS;
2671 static int sip_show_channels(int fd, int argc, char *argv[])
2673 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2674 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
2675 struct sip_pvt *cur;
2678 return RESULT_SHOWUSAGE;
2679 ast_pthread_mutex_lock(&iflock);
2681 ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2683 ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr),
2684 strlen(cur->username) ? cur->username : "(None)",
2686 cur->ocseq, cur->icseq,
2689 cur->owner ? cur->owner->nativeformats : 0);
2693 ast_pthread_mutex_unlock(&iflock);
2694 ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2695 return RESULT_SUCCESS;
2700 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2702 char buf[1024] = "";
2705 /* Try getting the "signal=" part */
2706 if ((c = get_sdp(req, "Signal"))) {
2707 strncpy(buf, c, sizeof(buf) - 1);
2708 } else if (get_msg_text(buf, sizeof(buf), req)) {
2709 /* Normal INFO method */
2710 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2717 ast_verbose("DTMF received: '%c'\n", buf[0]);
2718 memset(&f, 0, sizeof(f));
2719 f.frametype = AST_FRAME_DTMF;
2720 f.subclass = buf[0];
2724 ast_queue_frame(p->owner, &f, 1);
2729 static int sip_do_debug(int fd, int argc, char *argv[])
2732 return RESULT_SHOWUSAGE;
2734 ast_cli(fd, "SIP Debugging Enabled\n");
2735 return RESULT_SUCCESS;
2738 static int sip_no_debug(int fd, int argc, char *argv[])
2741 return RESULT_SHOWUSAGE;
2743 ast_cli(fd, "SIP Debugging Disabled\n");
2744 return RESULT_SUCCESS;
2747 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2749 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2751 memset(digest,0,sizeof(digest));
2752 reply_digest(p,req, "WWW-Authenticate", "REGISTER", (char *)&digest, sizeof(digest) );
2753 return transmit_register(p->registry,"REGISTER",(char *)&digest);
2756 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2758 memset(digest,0,sizeof(digest));
2759 reply_digest(p,req, "Proxy-Authenticate", "INVITE", (char *)&digest, sizeof(digest) );
2760 return transmit_invite(p,"INVITE",1,(char *)&digest, NULL);
2763 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2774 char resp_hash[256];
2778 strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2780 c+=strlen("Digest ");
2782 while (*c && (*c < 33)) c++;
2785 if (!strncasecmp(c,"realm=", strlen("realm="))) {
2786 c+=strlen("realm=");
2789 if ((c = strchr(c,'\"')))
2793 if ((c = strchr(c,',')))
2797 } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
2798 c+=strlen("nonce=");
2801 if ((c = strchr(c,'\"')))
2805 if ((c = strchr(c,',')))
2814 /* Okay. We've got the realm and nonce from the server. Now lets build the MD5 digest. */
2815 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2817 snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
2818 snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
2819 md5_hash(a1_hash,a1);
2820 md5_hash(a2_hash,a2);
2821 snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
2822 md5_hash(resp_hash,resp);
2824 snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
2834 static char show_users_usage[] =
2835 "Usage: sip show users\n"
2836 " Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
2838 static char show_channels_usage[] =
2839 "Usage: sip show channels\n"
2840 " Lists all currently active SIP channels.\n";
2842 static char show_peers_usage[] =
2843 "Usage: sip show peers\n"
2844 " Lists all known SIP peers.\n";
2846 static char show_reg_usage[] =
2847 "Usage: sip show registry\n"
2848 " Lists all registration requests and status.\n";
2850 static char debug_usage[] =
2851 "Usage: sip debug\n"
2852 " Enables dumping of SIP packets for debugging purposes\n";
2854 static char no_debug_usage[] =
2855 "Usage: sip no debug\n"
2856 " Disables dumping of SIP packets for debugging purposes\n";
2858 static struct ast_cli_entry cli_show_users =
2859 { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
2860 static struct ast_cli_entry cli_show_channels =
2861 { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage };
2862 static struct ast_cli_entry cli_show_peers =
2863 { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
2864 static struct ast_cli_entry cli_show_registry =
2865 { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
2866 static struct ast_cli_entry cli_debug =
2867 { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
2868 static struct ast_cli_entry cli_no_debug =
2869 { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
2872 static int sip_poke_peer_s(void *data)
2874 struct sip_peer *peer = data;
2875 peer->pokeexpire = -1;
2876 sip_poke_peer(peer);
2880 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
2884 struct ast_rtp *rtp;
2885 struct ast_channel *owner;
2886 struct sip_peer *peer;
2889 c = get_header(req, "Cseq");
2890 msg = strchr(c, ' ');
2891 if (!msg) msg = ""; else msg++;
2893 ast_pthread_mutex_lock(&p->lock);
2894 /* Go ahead and lock the owner if it has one -- we may need it */
2895 if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
2896 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
2897 ast_pthread_mutex_unlock(&p->lock);
2898 /* Sleep infintismly short amount of time */
2904 /* We don't really care what the response is, just that it replied back.
2905 Well, as long as it's not a 100 response... since we might
2906 need to hang around for something more "difinitive" */
2909 gettimeofday(&tv, NULL);
2910 pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
2911 (tv.tv_usec - peer->ps.tv_usec) / 1000;
2914 if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
2915 if (pingtime <= peer->maxms)
2916 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
2917 } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
2918 if (pingtime > peer->maxms)
2919 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
2921 peer->lastms = pingtime;
2923 if (peer->pokeexpire > -1)
2924 ast_sched_del(sched, peer->pokeexpire);
2925 if (!strcasecmp(msg, "INVITE"))
2926 transmit_request(p, "ACK", 0);
2929 /* Try again eventually */
2930 if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
2931 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
2933 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
2935 } else if (p->outgoing) {
2936 if (p->initid > -1) {
2937 /* Don't auto congest anymore since we've gotten something useful back */
2938 ast_sched_del(sched, p->initid);
2941 /* Get their tag if we haven't already */
2942 if (!strlen(p->theirtag)) {
2943 to = get_header(req, "To");
2944 to = strstr(to, "tag=");
2947 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
2948 to = strchr(p->theirtag, ';');
2957 case 183: /* We don't really need this since we pass in-band audio anyway */
2959 if (strlen(get_header(req, "Content-Type")))
2960 process_sdp(p, req);
2964 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
2965 if (p->owner->_state != AST_STATE_UP)
2966 ast_setstate(p->owner, AST_STATE_RINGING);
2970 if (strlen(get_header(req, "Content-Type")))
2971 process_sdp(p, req);
2973 if (p->owner->_state != AST_STATE_UP) {
2974 ast_setstate(p->owner, AST_STATE_UP);
2975 ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
2978 if (!strcasecmp(msg, "INVITE"))
2979 transmit_request(p, "ACK", 0);
2980 else if (!strcasecmp(msg, "REGISTER"))
2984 struct sip_registry *r;
2985 transmit_request(p, "ACK", 0);
2987 r->regstate=REG_STATE_REGISTERED;
2988 ast_log(LOG_NOTICE, "Registration successful\n");
2989 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
2991 ast_sched_del(sched, r->timeout);
2993 /* set us up for re-registering */
2994 /* figure out how long we got registered for */
2995 if (r->expire != -1)
2996 ast_sched_del(sched, r->expire);
2997 expires=atoi(get_header(req, "expires"));
2998 if (!expires) expires=default_expirey;
2999 r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r);
3003 case 401: /* Not authorized on REGISTER */
3004 /* XXX: Do I need to ACK the 401?
3005 transmit_request(p, "ACK", 0);
3007 do_register_auth(p, req);
3011 transmit_request(p, "ACK", 0);
3013 do_proxy_auth(p, req);
3014 /* This is just a hack to kill the channel while testing */
3020 ast_rtp_destroy(rtp);
3023 ast_queue_hangup(p->owner,0);
3024 transmit_request(p,"ACK",0);
3030 if ((resp >= 400) && (resp < 700)) {
3031 if (option_verbose > 2)
3032 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
3037 /* Immediately stop RTP */
3038 ast_rtp_destroy(rtp);
3040 /* XXX Locking issues?? XXX */
3042 case 486: /* Busy here */
3043 case 600: /* Busy everywhere */
3045 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
3047 case 480: /* Temporarily Unavailable */
3048 case 404: /* Not Found */
3049 case 410: /* Gone */
3050 case 500: /* Server error */
3051 case 501: /* Not Implemented */
3053 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
3058 ast_queue_hangup(p->owner, 0);
3061 transmit_request(p, "ACK", 0);
3062 __sip_destroy(p, 0);
3065 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));
3069 ast_verbose("Message is %s\n", msg);
3072 if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
3073 transmit_request(p, "ACK", 0);
3078 ast_pthread_mutex_unlock(&owner->lock);