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 struct sockaddr_in sa; /* Our peer */
149 struct in_addr ourip; /* Our IP */
150 struct ast_channel *owner; /* Who owns us */
151 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
152 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
153 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
154 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
155 struct sip_pvt *refer_call; /* Call we are referring */
156 char record_route[256];
157 char record_route_info[256];
158 char remote_party_id[256];
159 char context[AST_MAX_EXTENSION];
160 char language[MAX_LANGUAGE];
161 char theirtag[256]; /* Their tag */
165 char callerid[256]; /* Caller*ID */
167 char accountcode[256]; /* Account code */
168 int amaflags; /* AMA Flags */
169 struct sip_request initreq; /* Initial request */
171 int maxtime; /* Max time for first response */
172 int initid; /* Auto-congest ID if appropriate */
174 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
175 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
176 struct ast_rtp *rtp; /* RTP Session */
177 struct sip_pvt *next;
180 static struct sip_pkt {
182 struct sip_pvt *owner;
184 char data[SIP_MAX_PACKET];
185 struct sip_pkt *next;
189 /* Users who can access various contexts */
195 char accountcode[80];
201 struct sip_user *next;
207 char context[80]; /* JK02: peers need context too to allow parking etc */
210 char mailbox[AST_MAX_EXTENSION];
219 struct sockaddr_in addr;
223 struct sip_pvt *call; /* Call pointer */
224 int pokeexpire; /* When to expire poke */
225 int lastms; /* How long last response took (in ms), or -1 for no response */
226 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
227 struct timeval ps; /* Ping send time */
229 struct sockaddr_in defaddr;
233 struct sip_peer *next;
236 static struct ast_user_list {
237 struct sip_user *users;
238 pthread_mutex_t lock;
239 } userl = { NULL, AST_MUTEX_INITIALIZER };
241 static struct ast_peer_list {
242 struct sip_peer *peers;
243 pthread_mutex_t lock;
244 } peerl = { NULL, AST_MUTEX_INITIALIZER };
247 #define REG_STATE_UNREGISTERED 0
248 #define REG_STATE_REGSENT 1
249 #define REG_STATE_AUTHSENT 2
250 #define REG_STATE_REGISTERED 3
251 #define REG_STATE_REJECTED 4
252 #define REG_STATE_TIMEOUT 5
253 #define REG_STATE_NOAUTH 6
255 struct sip_registry {
256 pthread_mutex_t lock; /* Channel private lock */
257 struct sockaddr_in addr; /* Who we connect to for registration purposes */
259 char secret[80]; /* Password or key name in []'s */
260 char contact[80]; /* Contact extension */
262 int expire; /* Sched ID of expiration */
263 int timeout; /* sched id of sip_reg_timeout */
264 int refresh; /* How often to refresh */
265 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
267 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
268 char callid[80]; /* Global CallID for this registry */
269 struct sockaddr_in us; /* Who the server thinks we are */
270 struct sip_registry *next;
273 static int sip_do_register(struct sip_registry *r);
274 struct sip_registry *registrations;
276 static int sipsock = -1;
278 static struct sockaddr_in bindaddr;
280 static struct ast_frame *sip_read(struct ast_channel *ast);
281 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
282 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req);
283 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand);
284 static int transmit_request(struct sip_pvt *p, char *msg, int inc);
285 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
286 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
287 static int transmit_message_with_text(struct sip_pvt *p, char *text);
288 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
290 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
293 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
295 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));
300 static int send_response(struct sip_pvt *p, struct sip_request *req)
304 ast_verbose("Transmitting:\n%s\n to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
305 res = __sip_xmit(p, req->data, req->len);
311 static int send_request(struct sip_pvt *p, struct sip_request *req)
315 ast_verbose("XXX Need to handle Retransmitting XXX:\n%s 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);
320 static char *ditch_braces(char *tmp)
325 if ((n = strchr(tmp, '<')) ) {
327 while(*c && *c != '>') c++;
329 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
338 static int sip_sendtext(struct ast_channel *ast, char *text)
340 struct sip_pvt *p = ast->pvt->pvt;
342 ast_verbose("Sending text %s on %s\n", text, ast->name);
345 if (!text || !strlen(text))
348 ast_verbose("Really sending text %s on %s\n", text, ast->name);
349 transmit_message_with_text(p, text);
353 static int create_addr(struct sip_pvt *r, char *peer)
358 r->sa.sin_family = AF_INET;
359 ast_pthread_mutex_lock(&peerl.lock);
362 if (!strcasecmp(p->name, peer)) {
364 r->capability = p->capability;
365 strncpy(r->peername, p->username, sizeof(r->peername)-1);
366 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
367 strncpy(r->username, p->username, sizeof(r->username)-1);
368 r->insecure = p->insecure;
369 r->canreinvite = p->canreinvite;
370 r->maxtime = p->maxms;
371 strncpy(r->context, p->context,sizeof(r->context)-1);
372 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
373 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
374 if (p->addr.sin_addr.s_addr) {
375 r->sa.sin_addr = p->addr.sin_addr;
376 r->sa.sin_port = p->addr.sin_port;
378 r->sa.sin_addr = p->defaddr.sin_addr;
379 r->sa.sin_port = p->defaddr.sin_port;
386 ast_pthread_mutex_unlock(&peerl.lock);
388 hp = gethostbyname(peer);
390 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
391 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
394 ast_log(LOG_WARNING, "No such host: %s\n", peer);
403 static int auto_congest(void *nothing)
405 struct sip_pvt *p = nothing;
406 ast_pthread_mutex_lock(&p->lock);
409 if (!pthread_mutex_trylock(&p->owner->lock)) {
410 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
411 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
412 ast_pthread_mutex_unlock(&p->owner->lock);
415 ast_pthread_mutex_unlock(&p->lock);
419 static void sip_prefs_free(void)
421 struct sip_codec_pref *cur, *next;
431 static void sip_pref_remove(int format)
433 struct sip_codec_pref *cur, *prev;
436 if (cur->codec == format) {
438 prev->next = cur->next;
449 static int sip_pref_append(int format)
451 struct sip_codec_pref *cur, *tmp;
452 sip_pref_remove(format);
453 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
456 memset(tmp, 0, sizeof(struct sip_codec_pref));
468 static int sip_codec_choose(int formats)
470 struct sip_codec_pref *cur;
473 if (formats & cur->codec)
477 return ast_best_codec(formats);
480 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
484 char *vxml_url = NULL;
485 struct varshead *headp;
486 struct ast_var_t *current;
489 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
490 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
494 /* Check whether there is a VXML_URL variable */
495 headp=&ast->varshead;
496 AST_LIST_TRAVERSE(headp,current,entries) {
497 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
499 vxml_url = ast_var_value(current);
506 transmit_invite(p, "INVITE", 1, NULL, vxml_url);
508 /* Initialize auto-congest time */
509 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
514 static void __sip_destroy(struct sip_pvt *p, int lockowner)
516 struct sip_pvt *cur, *prev = NULL;
518 ast_rtp_destroy(p->rtp);
520 /* Unlink us from the owner if we have one */
523 ast_pthread_mutex_lock(&p->owner->lock);
524 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
525 p->owner->pvt->pvt = NULL;
527 ast_pthread_mutex_unlock(&p->owner->lock);
533 prev->next = cur->next;
542 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
545 ast_sched_del(sched, p->initid);
549 static void sip_destroy(struct sip_pvt *p)
551 ast_pthread_mutex_lock(&iflock);
553 ast_pthread_mutex_unlock(&iflock);
556 /* Interface lookup code courtesy Tilghman of DrunkCoder.com. Thanks! */
561 char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
566 struct sockaddr_in ifru_addr;
571 struct in_addr *lookup_iface(char *iface) {
574 static struct my_ifreq ifreq;
575 memset(&ifreq, 0, sizeof(ifreq));
576 strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
578 mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
579 res = ioctl(mysock,SIOCGIFADDR,&ifreq);
583 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
586 return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
589 static struct in_addr *myaddrfor(struct in_addr *them)
592 struct in_addr *temp = NULL;
593 unsigned int remote_ip;
595 remote_ip = them->s_addr;
597 PROC = fopen("/proc/net/route","r");
599 /* If /proc/net/route doesn't exist, fall back to the old method */
602 /* First line contains headers */
603 fgets(line,sizeof(line),PROC);
605 while (!feof(PROC)) {
607 unsigned int dest, gateway, mask;
611 fgets(line,sizeof(line),PROC);
614 for (i=0;i<sizeof(line);i++) {
617 fields[aoffset++] = line + i;
618 boffset = strchr(line + i,'\t');
619 if (boffset == NULL) {
628 sscanf(fields[0],"%s",iface);
629 sscanf(fields[1],"%x",&dest);
630 sscanf(fields[2],"%x",&gateway);
631 sscanf(fields[7],"%x",&mask);
633 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
635 if (((remote_ip & mask) ^ dest) == 0) {
637 ast_verbose("Interface is %s\n",iface);
638 temp = lookup_iface(iface);
640 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
646 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s. Using default\n", inet_ntoa(*them));
653 static int sip_hangup(struct ast_channel *ast)
655 struct sip_pvt *p = ast->pvt->pvt;
658 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
659 if (!ast->pvt->pvt) {
660 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
663 ast_pthread_mutex_lock(&p->lock);
664 /* Determine how to disconnect */
665 if (p->owner != ast) {
666 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
667 ast_pthread_mutex_unlock(&p->lock);
670 if (!ast || (ast->_state != AST_STATE_UP))
675 ast->pvt->pvt = NULL;
679 /* Invert sense of outgoing */
680 p->outgoing = 1 - p->outgoing;
682 /* Start the process if it's not already started */
683 if (!p->alreadygone && strlen(p->initreq.data)) {
685 transmit_request(p, "CANCEL", 0);
688 transmit_request(p, "BYE", p->outgoing);
692 /* Restore sense of outgoing */
693 p->outgoing = 1 - p->outgoing;
695 ast_pthread_mutex_unlock(&p->lock);
699 static int sip_answer(struct ast_channel *ast)
701 int res = 0,fmt,capability;
703 struct sip_pvt *p = ast->pvt->pvt;
704 struct sip_codec_pref *oldpref=NULL;
707 if (ast->_state != AST_STATE_UP) {
711 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
713 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
714 fmt=ast_getformatbyname(codec);
718 sip_pref_append(fmt);
719 capability=p->capability;
721 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
724 ast_setstate(ast, AST_STATE_UP);
726 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
727 res = transmit_response_with_sdp(p, "200 OK", &p->initreq);
731 p->capability=capability;
737 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
739 struct sip_pvt *p = ast->pvt->pvt;
741 if (frame->frametype != AST_FRAME_VOICE) {
742 if (frame->frametype == AST_FRAME_IMAGE)
745 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
749 if (!(frame->subclass & ast->nativeformats)) {
750 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
751 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
756 ast_pthread_mutex_lock(&p->lock);
758 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
759 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq);
762 res = ast_rtp_write(p->rtp, frame);
764 ast_pthread_mutex_unlock(&p->lock);
769 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
771 struct sip_pvt *p = newchan->pvt->pvt;
772 ast_pthread_mutex_lock(&p->lock);
773 if (p->owner != oldchan) {
774 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
775 ast_pthread_mutex_unlock(&p->lock);
779 ast_pthread_mutex_unlock(&p->lock);
783 static int sip_senddigit(struct ast_channel *ast, char digit)
785 struct sip_pvt *p = ast->pvt->pvt;
787 ast_rtp_senddigit(p->rtp, digit);
793 static int sip_indicate(struct ast_channel *ast, int condition)
795 struct sip_pvt *p = ast->pvt->pvt;
797 case AST_CONTROL_RINGING:
798 if (ast->_state == AST_STATE_RING) {
799 transmit_response(p, "180 Ringing", &p->initreq);
803 case AST_CONTROL_BUSY:
804 if (ast->_state != AST_STATE_UP) {
805 transmit_response(p, "600 Busy everywhere", &p->initreq);
807 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
811 case AST_CONTROL_CONGESTION:
812 if (ast->_state != AST_STATE_UP) {
813 transmit_response(p, "486 Busy here", &p->initreq);
815 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
822 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
830 static int sip_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
832 struct sip_pvt *p0, *p1;
834 struct ast_channel *who, *cs[3];
837 /* if need DTMF, cant native bridge */
838 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
840 ast_pthread_mutex_lock(&c0->lock);
841 ast_pthread_mutex_lock(&c1->lock);
844 ast_log(LOG_DEBUG, "Reinvite? %s: %s, %s: %s\n", c0->name, p0->canreinvite ? "yes" : "no", c1->name, p1->canreinvite ? "yes" : "no");
845 if (!p0->canreinvite || !p1->canreinvite) {
846 /* Not gonna support reinvite */
847 ast_pthread_mutex_unlock(&c0->lock);
848 ast_pthread_mutex_unlock(&c1->lock);
851 transmit_reinvite_with_sdp(p0, p1->rtp);
852 transmit_reinvite_with_sdp(p1, p0->rtp);
853 ast_pthread_mutex_unlock(&c0->lock);
854 ast_pthread_mutex_unlock(&c1->lock);
859 if ((c0->pvt->pvt != p0) ||
860 (c1->pvt->pvt != p1) ||
861 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
862 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
863 if (c0->pvt->pvt == p0)
864 transmit_reinvite_with_sdp(p0, NULL);
865 if (c1->pvt->pvt == p1)
866 transmit_reinvite_with_sdp(p1, NULL);
867 /* Tell it to try again later */
871 who = ast_waitfor_n(cs, 2, &to);
873 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
877 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
878 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
879 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
882 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
883 if (c0->pvt->pvt == p0 && !c0->_softhangup)
884 transmit_reinvite_with_sdp(p0, NULL);
885 if (c1->pvt->pvt == p1 && !c1->_softhangup)
886 transmit_reinvite_with_sdp(p1, NULL);
887 /* That's all we needed */
891 /* Swap priority not that it's a big deal at this point */
901 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
903 struct ast_channel *tmp;
905 tmp = ast_channel_alloc(1);
907 /* Select our native format based on codec preference until we receive
908 something from another device to the contrary. */
910 tmp->nativeformats = sip_codec_choose(i->capability);
912 tmp->nativeformats = sip_codec_choose(capability);
913 fmt = ast_best_codec(tmp->nativeformats);
915 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
917 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
919 tmp->fds[0] = ast_rtp_fd(i->rtp);
920 ast_setstate(tmp, state);
921 if (state == AST_STATE_RING)
923 tmp->writeformat = fmt;
924 tmp->pvt->rawwriteformat = fmt;
925 tmp->readformat = fmt;
926 tmp->pvt->rawreadformat = fmt;
928 tmp->pvt->send_text = sip_sendtext;
929 tmp->pvt->call = sip_call;
930 tmp->pvt->hangup = sip_hangup;
931 tmp->pvt->answer = sip_answer;
932 tmp->pvt->read = sip_read;
933 tmp->pvt->write = sip_write;
934 tmp->pvt->indicate = sip_indicate;
935 tmp->pvt->fixup = sip_fixup;
936 tmp->pvt->send_digit = sip_senddigit;
937 tmp->pvt->bridge = ast_rtp_bridge;
938 if (strlen(i->language))
939 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
941 ast_pthread_mutex_lock(&usecnt_lock);
943 ast_pthread_mutex_unlock(&usecnt_lock);
944 ast_update_use_count();
945 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
946 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
947 if (strlen(i->callerid))
948 tmp->callerid = strdup(i->callerid);
950 if (state != AST_STATE_DOWN) {
951 if (ast_pbx_start(tmp)) {
952 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
958 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
962 static struct cfalias {
966 { "Content-Type", "c" },
967 { "Content-Encoding", "e" },
971 { "Content-Length", "l" },
977 static char *get_sdp(struct sip_request *req, char *name)
980 int len = strlen(name);
982 for (x=0;x<req->lines;x++) {
983 if (!strncasecmp(req->line[x], name, len) &&
984 (req->line[x][len] == '=')) {
985 r = req->line[x] + len + 1;
986 while(*r && (*r < 33))
994 static char *__get_header(struct sip_request *req, char *name, int *start)
997 int len = strlen(name);
999 for (x=*start;x<req->headers;x++) {
1000 if (!strncasecmp(req->header[x], name, len) &&
1001 (req->header[x][len] == ':')) {
1002 r = req->header[x] + len + 1;
1003 while(*r && (*r < 33))
1010 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1011 if (!strcasecmp(aliases[x].fullname, name))
1012 return __get_header(req, aliases[x].shortname, start);
1014 /* Don't return NULL, so get_header is always a valid pointer */
1018 static char *get_header(struct sip_request *req, char *name)
1021 return __get_header(req, name, &start);
1024 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1026 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1027 struct ast_frame *f;
1028 f = ast_rtp_read(p->rtp);
1030 /* We already hold the channel lock */
1031 if (f->frametype == AST_FRAME_VOICE) {
1032 if (f->subclass != p->owner->nativeformats) {
1033 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1034 p->owner->nativeformats = f->subclass;
1035 ast_set_read_format(p->owner, p->owner->readformat);
1036 ast_set_write_format(p->owner, p->owner->writeformat);
1043 static struct ast_frame *sip_read(struct ast_channel *ast)
1045 struct ast_frame *fr;
1046 struct sip_pvt *p = ast->pvt->pvt;
1047 ast_pthread_mutex_lock(&p->lock);
1048 fr = sip_rtp_read(p);
1049 ast_pthread_mutex_unlock(&p->lock);
1053 static void build_callid(char *callid, int len, struct in_addr ourip)
1060 res = snprintf(callid, len, "%08x", val);
1064 /* It's not important that we really use our right IP here... */
1065 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1068 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin)
1072 p = malloc(sizeof(struct sip_pvt));
1075 /* Keep track of stuff */
1076 memset(p, 0, sizeof(struct sip_pvt));
1078 p->rtp = ast_rtp_new(NULL, NULL);
1081 /* Start with 101 instead of 1 */
1084 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1088 ast_rtp_settos(p->rtp, tos);
1089 ast_pthread_mutex_init(&p->lock);
1091 ast_rtp_set_data(p->rtp, p);
1092 ast_rtp_set_callback(p->rtp, rtpready);
1095 memcpy(&p->sa, sin, sizeof(p->sa));
1096 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1098 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1100 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1102 build_callid(p->callid, sizeof(p->callid), p->ourip);
1104 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1105 /* Assume reinvite OK */
1108 ast_pthread_mutex_lock(&iflock);
1111 ast_pthread_mutex_unlock(&iflock);
1113 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1117 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1121 callid = get_header(req, "Call-ID");
1122 if (!strlen(callid)) {
1123 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1126 ast_pthread_mutex_lock(&iflock);
1129 if (!strcmp(p->callid, callid)) {
1130 /* Found the call */
1132 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1133 (p->sa.sin_port != sin->sin_port))) {
1136 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1137 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1138 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1139 ast_pthread_mutex_unlock(&iflock);
1143 ast_pthread_mutex_unlock(&iflock);
1148 ast_pthread_mutex_unlock(&iflock);
1149 return sip_alloc(callid, sin);
1152 static int sip_register(char *value, int lineno)
1154 struct sip_registry *reg;
1155 char copy[256] = "";
1156 char *username, *hostname, *secret;
1164 strncpy(copy, value, sizeof(copy)-1);
1167 hostname = strrchr(stringp, '@');
1173 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1177 username = strsep(&stringp, ":");
1178 secret = strsep(&stringp, ":");
1180 hostname = strsep(&stringp, "/");
1181 contact = strsep(&stringp, "/");
1182 if (!contact || !strlen(contact))
1185 hostname = strsep(&stringp, ":");
1186 porta = strsep(&stringp, ":");
1188 if (porta && !atoi(porta)) {
1189 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1192 hp = gethostbyname(hostname);
1194 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1197 reg = malloc(sizeof(struct sip_registry));
1199 memset(reg, 0, sizeof(struct sip_registry));
1200 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1201 strncpy(reg->username, username, sizeof(reg->username)-1);
1203 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1205 reg->refresh = default_expirey;
1206 reg->addr.sin_family = AF_INET;
1207 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1208 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1209 reg->next = registrations;
1210 reg->callid_valid = 0;
1211 registrations = reg;
1213 ast_log(LOG_ERROR, "Out of memory\n");
1219 static void parse(struct sip_request *req)
1221 /* Divide fields by NULL's */
1226 /* First header starts immediately */
1230 /* We've got a new header */
1234 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1236 if (!strlen(req->header[f])) {
1237 /* Line by itself means we're now in content */
1241 if (f >= SIP_MAX_HEADERS - 1) {
1242 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1245 req->header[f] = c + 1;
1246 } else if (*c == '\r') {
1247 /* Ignore but eliminate \r's */
1252 /* Check for last header */
1253 if (strlen(req->header[f]))
1256 /* Now we process any mime content */
1261 /* We've got a new line */
1264 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1266 if (f >= SIP_MAX_LINES - 1) {
1267 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1270 req->line[f] = c + 1;
1271 } else if (*c == '\r') {
1272 /* Ignore and eliminate \r's */
1277 /* Check for last line */
1278 if (strlen(req->line[f]))
1282 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1284 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1287 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1295 struct sockaddr_in sin;
1299 /* Get codec and RTP info from SDP */
1300 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1301 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1304 m = get_sdp(req, "m");
1305 c = get_sdp(req, "c");
1306 if (!strlen(m) || !strlen(c)) {
1307 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1310 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1311 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1314 /* XXX This could block for a long time, and block the main thread! XXX */
1315 hp = gethostbyname(host);
1317 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1320 if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1321 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1324 sin.sin_family = AF_INET;
1325 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1326 sin.sin_port = htons(portno);
1328 ast_rtp_set_peer(p->rtp, &sin);
1330 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1334 while(strlen(codecs)) {
1335 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1336 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1340 printf("Codec: %d\n", codec);
1342 codec = rtp2ast(codec);
1344 peercapability |= codec;
1347 p->capability = capability & peercapability;
1349 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1350 capability, peercapability, p->capability);
1351 if (!p->capability) {
1352 ast_log(LOG_WARNING, "No compatible codecs!\n");
1356 if (!(p->owner->nativeformats & p->capability)) {
1357 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);
1358 p->owner->nativeformats = sip_codec_choose(p->capability);
1359 ast_set_read_format(p->owner, p->owner->readformat);
1360 ast_set_write_format(p->owner, p->owner->writeformat);
1362 if (p->owner->bridge) {
1363 /* Turn on/off music on hold if we are holding/unholding */
1364 if (sin.sin_addr.s_addr) {
1365 ast_moh_stop(p->owner->bridge);
1367 ast_moh_start(p->owner->bridge, NULL);
1375 static int add_header(struct sip_request *req, char *var, char *value)
1377 if (req->len >= sizeof(req->data) - 4) {
1378 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1382 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1385 req->header[req->headers] = req->data + req->len;
1386 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1387 req->len += strlen(req->header[req->headers]);
1388 if (req->headers < SIP_MAX_HEADERS)
1391 ast_log(LOG_WARNING, "Out of header space\n");
1397 static int add_blank_header(struct sip_request *req)
1399 if (req->len >= sizeof(req->data) - 4) {
1400 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1404 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1407 req->header[req->headers] = req->data + req->len;
1408 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1409 req->len += strlen(req->header[req->headers]);
1410 if (req->headers < SIP_MAX_HEADERS)
1413 ast_log(LOG_WARNING, "Out of header space\n");
1419 static int add_line(struct sip_request *req, char *line)
1421 if (req->len >= sizeof(req->data) - 4) {
1422 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1426 /* Add extra empty return */
1427 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1428 req->len += strlen(req->data + req->len);
1430 req->line[req->lines] = req->data + req->len;
1431 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1432 req->len += strlen(req->line[req->lines]);
1433 if (req->lines < SIP_MAX_LINES)
1436 ast_log(LOG_WARNING, "Out of line space\n");
1442 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1445 tmp = get_header(orig, field);
1447 /* Add what we're responding to */
1448 return add_header(req, field, tmp);
1450 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1454 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1460 tmp = __get_header(orig, field, &start);
1462 /* Add what we're responding to */
1463 add_header(req, field, tmp);
1469 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1475 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1477 /* Initialize a response */
1478 if (req->headers || req->len) {
1479 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1482 req->header[req->headers] = req->data + req->len;
1483 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1484 req->len += strlen(req->header[req->headers]);
1485 if (req->headers < SIP_MAX_HEADERS)
1488 ast_log(LOG_WARNING, "Out of header space\n");
1492 static int init_req(struct sip_request *req, char *resp, char *recip)
1494 /* Initialize a response */
1495 if (req->headers || req->len) {
1496 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1499 req->header[req->headers] = req->data + req->len;
1500 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1501 req->len += strlen(req->header[req->headers]);
1502 if (req->headers < SIP_MAX_HEADERS)
1505 ast_log(LOG_WARNING, "Out of header space\n");
1509 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1511 char newto[256] = "", *ot;
1512 memset(resp, 0, sizeof(*resp));
1513 init_resp(resp, msg, req);
1514 copy_all_header(resp, req, "Via");
1515 copy_header(resp, req, "From");
1516 ot = get_header(req, "To");
1517 if (!strstr(ot, "tag=")) {
1518 /* Add the proper tag if we don't have it already. If they have specified
1519 their tag, use it. Otherwise, use our own tag */
1520 if (strlen(p->theirtag))
1521 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1523 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1525 strncpy(newto, ot, sizeof(newto) - 1);
1528 add_header(resp, "To", ot);
1529 copy_header(resp, req, "Call-ID");
1530 copy_header(resp, req, "CSeq");
1531 add_header(resp, "User-Agent", "Asterisk PBX");
1533 /* For registration responses, we also need expirey and
1536 char contact2[256] = "", *c, contact[256];
1537 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1538 strncpy(contact2, get_header(req, "Contact"), sizeof(contact2)-1);
1539 c = ditch_braces(contact2);
1540 snprintf(contact, sizeof(contact), "<%s>", c);
1541 add_header(resp, "Expires", tmp);
1542 add_header(resp, "Contact", contact);
1544 char contact2[256] = "", *c, contact[256];
1545 /* XXX This isn't exactly right and it's implemented
1546 very stupidly *sigh* XXX */
1547 strncpy(contact2, get_header(req, "To"), sizeof(contact2)-1);
1548 c = ditch_braces(contact2);
1549 snprintf(contact, sizeof(contact), "<%s>", c);
1550 add_header(resp, "Contact", contact);
1555 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1557 struct sip_request *orig = &p->initreq;
1558 char stripped[80] ="";
1564 memset(req, 0, sizeof(struct sip_request));
1570 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1572 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1574 c = strchr(stripped, '<');
1583 init_req(req, msg, c);
1585 snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1587 add_header(req, "Via", p->via);
1589 ot = get_header(orig, "To");
1590 of = get_header(orig, "From");
1592 if (!strstr(ot, "tag=")) {
1593 /* Add the proper tag if we don't have it already. If they have specified
1594 their tag, use it. Otherwise, use our own tag */
1595 if (strlen(p->theirtag))
1596 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1598 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1603 add_header(req, "From", of);
1604 add_header(req, "To", ot);
1606 add_header(req, "From", ot);
1607 add_header(req, "To", of);
1609 copy_header(req, orig, "Call-ID");
1610 add_header(req, "CSeq", tmp);
1612 add_header(req, "User-Agent", "Asterisk PBX");
1616 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1618 struct sip_request resp;
1619 respprep(&resp, p, msg, req);
1620 add_header(&resp, "Content-Length", "0");
1621 add_blank_header(&resp);
1622 return send_response(p, &resp);
1625 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1627 struct sip_request resp;
1628 respprep(&resp, p, msg, req);
1629 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1630 add_header(&resp, "Accept", "application/sdp");
1631 add_header(&resp, "Content-Length", "0");
1632 add_blank_header(&resp);
1633 return send_response(p, &resp);
1636 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1638 struct sip_request resp;
1640 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1641 respprep(&resp, p, msg, req);
1642 add_header(&resp, "Proxy-Authenticate", tmp);
1643 add_header(&resp, "Content-Length", "0");
1644 add_blank_header(&resp);
1645 return send_response(p, &resp);
1648 static int add_text(struct sip_request *req, char *text)
1650 /* XXX Convert \n's to \r\n's XXX */
1651 int len = strlen(text);
1653 snprintf(clen, sizeof(clen), "%d", len);
1654 add_header(req, "Content-Type", "text/plain");
1655 add_header(req, "Content-Length", clen);
1656 add_line(req, text);
1660 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1664 int alreadysent = 0;
1666 struct sockaddr_in sin;
1667 struct sip_codec_pref *cur;
1676 struct sockaddr_in dest;
1677 /* XXX We break with the "recommendation" and send our IP, in order that our
1678 peer doesn't have to gethostbyname() us XXX */
1681 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1684 ast_rtp_get_us(p->rtp, &sin);
1686 ast_rtp_get_peer(rtp, &dest);
1688 dest.sin_addr = p->ourip;
1689 dest.sin_port = sin.sin_port;
1692 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
1693 snprintf(v, sizeof(v), "v=0\r\n");
1694 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1695 snprintf(s, sizeof(s), "s=session\r\n");
1696 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1697 snprintf(t, sizeof(t), "t=0 0\r\n");
1698 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1699 /* Start by sending our preferred codecs */
1702 if (p->capability & cur->codec) {
1704 ast_verbose("Answering with preferred capability %d\n", cur->codec);
1705 if ((codec = ast2rtp(cur->codec)) > -1) {
1706 snprintf(costr, sizeof(costr), " %d", codec);
1708 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(rtp2ast(codec)));
1712 alreadysent |= cur->codec;
1715 /* Now send anything else in no particular order */
1716 for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1717 if ((p->capability & x) && !(alreadysent & x)) {
1719 ast_verbose("Answering with capability %d\n", x);
1720 if ((codec = ast2rtp(x)) > -1) {
1721 snprintf(costr, sizeof(costr), " %d", codec);
1723 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(x));
1728 strcat(m, " 101\r\n");
1729 strcat(a, "a=rtpmap:101 telephone-event/8000\r\n");
1730 /* Indicate we support DTMF only... Not sure about 16, but MSN supports it so dang it, we will too... */
1731 strcat(a, "a=fmtp:101 0-16\r\n");
1732 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1733 snprintf(costr, sizeof(costr), "%d", len);
1734 add_header(resp, "Content-Type", "application/sdp");
1735 add_header(resp, "Content-Length", costr);
1746 static void copy_request(struct sip_request *dst,struct sip_request *src)
1750 offset = ((void *)dst) - ((void *)src);
1751 /* First copy stuff */
1752 memcpy(dst, src, sizeof(*dst));
1753 /* Now fix pointer arithmetic */
1754 for (x=0;x<src->headers;x++)
1755 dst->header[x] += offset;
1756 for (x=0;x<src->lines;x++)
1757 dst->line[x] += offset;
1760 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1762 struct sip_request resp;
1763 respprep(&resp, p, msg, req);
1764 add_sdp(&resp, p, NULL);
1765 return send_response(p, &resp);
1768 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1770 struct sip_request resp;
1771 reqprep(&resp, p, "INVITE", 1);
1772 add_sdp(&resp, p, rtp);
1773 return send_response(p, &resp);
1776 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1783 char *l = "asterisk", *n=NULL;
1784 if (p->owner && p->owner->callerid) {
1785 strcpy(cid, p->owner->callerid);
1786 ast_callerid_parse(cid, &n, &l);
1788 ast_shrink_phone_number(l);
1789 if (!l || !ast_isphonenumber(l))
1794 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1795 if (strlen(p->username)) {
1796 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1797 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1799 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1801 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1802 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1804 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1806 /* If there is a VXML URL append it to the SIP URL */
1809 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1813 snprintf(to, sizeof(to), "<%s>", invite );
1815 memset(req, 0, sizeof(struct sip_request));
1816 init_req(req, cmd, invite);
1817 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1819 add_header(req, "Via", p->via);
1820 add_header(req, "From", from);
1822 char contact2[256] ="", *c, contact[256];
1823 /* XXX This isn't exactly right and it's implemented
1824 very stupidly *sigh* XXX */
1825 strncpy(contact2, from, sizeof(contact2)-1);
1826 c = ditch_braces(contact2);
1827 snprintf(contact, sizeof(contact), "<%s>", c);
1828 add_header(req, "Contact", contact);
1830 add_header(req, "To", to);
1831 add_header(req, "Call-ID", p->callid);
1832 add_header(req, "CSeq", tmp);
1833 add_header(req, "User-Agent", "Asterisk PBX");
1836 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
1838 struct sip_request req;
1839 initreqprep(&req, p, cmd, vxml_url);
1841 add_header(&req, "Proxy-Authorization", auth);
1843 add_sdp(&req, p, NULL);
1845 add_header(&req, "Content-Length", "0");
1846 add_blank_header(&req);
1848 if (!p->initreq.headers) {
1849 /* Use this as the basis */
1850 copy_request(&p->initreq, &req);
1853 p->lastinvite = p->ocseq;
1854 return send_request(p, &req);
1857 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
1859 struct sip_request req;
1862 initreqprep(&req, p, "NOTIFY", NULL);
1863 add_header(&req, "Event", "message-summary");
1864 add_header(&req, "Content-Type", "text/plain");
1866 snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
1867 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
1868 add_header(&req, "Content-Length", clen);
1869 add_line(&req, tmp);
1871 if (!p->initreq.headers) {
1872 /* Use this as the basis */
1873 copy_request(&p->initreq, &req);
1877 p->lastinvite = p->ocseq;
1878 return send_request(p, &req);
1881 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
1883 static int sip_reregister(void *data)
1885 /* if we are here, we know that we need to reregister. */
1886 struct sip_registry *r=(struct sip_registry *)data;
1887 return sip_do_register(r);
1892 static int sip_do_register(struct sip_registry *r)
1895 ast_pthread_mutex_lock(&r->lock);
1896 res=transmit_register(r, "REGISTER", NULL);
1897 ast_pthread_mutex_unlock(&r->lock);
1901 static int sip_reg_timeout(void *data)
1903 /* if we are here, our registration timed out, so we'll just do it over */
1904 struct sip_registry *r=data;
1906 ast_pthread_mutex_lock(&r->lock);
1907 ast_log(LOG_NOTICE, "Registration timed out, trying again\n");
1908 r->regstate=REG_STATE_UNREGISTERED;
1909 /* cancel ourselves first!!! */
1910 /* ast_sched_del(sched,r->timeout); */
1911 res=transmit_register(r, "REGISTER", NULL);
1912 ast_pthread_mutex_unlock(&r->lock);
1916 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
1918 struct sip_request req;
1925 /* exit if we are already in process with this registrar ?*/
1926 if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
1927 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
1933 if (!r->callid_valid) {
1934 build_callid(r->callid, sizeof(r->callid), __ourip);
1937 p=sip_alloc( r->callid, &r->addr );
1941 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
1942 strncpy(p->peername, r->username, sizeof(p->peername)-1);
1943 strncpy(p->username, r->username, sizeof(p->username)-1);
1946 /* set up a timeout */
1947 if (auth==NULL && !r->timeout) {
1948 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
1949 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
1952 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1953 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1955 snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
1957 memset(&req, 0, sizeof(req));
1958 init_req(&req, cmd, addr);
1960 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1962 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1963 add_header(&req, "Via", via);
1964 add_header(&req, "From", from);
1965 add_header(&req, "To", to);
1968 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
1969 add_header(&req, "Contact", contact);
1971 add_header(&req, "Call-ID", p->callid);
1972 add_header(&req, "CSeq", tmp);
1973 add_header(&req, "User-Agent", "Asterisk PBX");
1975 add_header(&req, "Authorization", auth);
1977 snprintf(tmp, sizeof(tmp), "%d", default_expirey);
1978 add_header(&req, "Expires", tmp);
1979 add_header(&req, "Event", "registration");
1980 copy_request(&p->initreq, &req);
1981 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
1982 return send_request(p, &req);
1985 static int transmit_message_with_text(struct sip_pvt *p, char *text)
1987 struct sip_request req;
1988 reqprep(&req, p, "MESSAGE", 1);
1989 add_text(&req, text);
1990 return send_request(p, &req);
1993 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
1995 struct sip_request resp;
1996 reqprep(&resp, p, msg, inc);
1997 add_header(&resp, "Content-Length", "0");
1998 add_blank_header(&resp);
1999 return send_request(p, &resp);
2002 static int expire_register(void *data)
2004 struct sip_peer *p = data;
2005 memset(&p->addr, 0, sizeof(p->addr));
2010 static int sip_poke_peer(struct sip_peer *peer);
2012 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2014 char contact[80]= "";
2015 char *expires = get_header(req, "Expires");
2016 int expirey = atoi(expires);
2020 struct sockaddr_in oldsin;
2021 if (!strlen(expires)) {
2022 expires = strstr(get_header(req, "Contact"), "expires=");
2024 if (sscanf(expires + 8, "%d;", &expirey) != 1)
2027 /* Look for brackets */
2028 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2031 if ((n=strchr(c, '<'))) {
2034 /* Lose the part after the > */
2038 /* Make sure it's a SIP URL */
2039 if (strncasecmp(c, "sip:", 4)) {
2040 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contcact\n", c);
2057 pt = strchr(n, ':');
2063 port = DEFAULT_SIP_PORT;
2064 /* XXX This could block for a long time XXX */
2065 hp = gethostbyname(n);
2067 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2070 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2071 p->addr.sin_family = AF_INET;
2072 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2073 p->addr.sin_port = htons(port);
2075 strncpy(p->username, c, sizeof(p->username) - 1);
2077 strcpy(p->username, "");
2079 ast_sched_del(sched, p->expire);
2080 if ((expirey < 1) || (expirey > max_expirey))
2081 expirey = max_expirey;
2082 p->expire = ast_sched_add(sched, expirey * 1000, expire_register, p);
2083 pvt->expirey = expirey;
2084 if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2086 if (option_verbose > 2)
2087 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);
2092 static void md5_hash(char *output, char *input)
2094 struct MD5Context md5;
2095 unsigned char digest[16];
2099 MD5Update(&md5, input, strlen(input));
2100 MD5Final(digest, &md5);
2103 ptr += sprintf(ptr, "%2.2x", digest[x]);
2106 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
2109 /* Always OK if no secret */
2110 if (!strlen(secret))
2112 if (!strlen(randdata)) {
2113 snprintf(randdata, randlen, "%08x", rand());
2114 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
2117 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2118 an example in the spec of just what it is you're doing a hash on. */
2124 char resp_hash[256];
2130 /* Find their response among the mess that we'r sent for comparison */
2131 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2135 while (*c && (*c < 33)) c++;
2138 if (!strncasecmp(c, "response=", strlen("response="))) {
2139 c+= strlen("response=");
2142 if((c = strchr(c,'\"')))
2147 if((c = strchr(c,',')))
2151 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2155 if((c = strchr(c,'\"')))
2159 if((c = strchr(c,',')))
2168 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2169 if(strlen(resp_uri))
2170 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2172 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2173 md5_hash(a1_hash, a1);
2174 md5_hash(a2_hash, a2);
2175 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2176 md5_hash(resp_hash, resp);
2178 /* resp_hash now has the expected response, compare the two */
2180 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2184 /* Assume success ;-) */
2185 /* Eliminate random data */
2186 strcpy(randdata, "");
2191 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2194 struct sip_peer *peer;
2200 while(*t && (*t > 32) && (*t != ';'))
2204 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2205 c = ditch_braces(tmp);
2206 if (strncmp(c, "sip:", 4)) {
2207 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s\n", tmp, inet_ntoa(sin->sin_addr));
2211 c = strchr(name, '@');
2214 ast_pthread_mutex_lock(&peerl.lock);
2217 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2218 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2219 if (parse_contact(p, peer, req)) {
2220 ast_log(LOG_WARNING, "Failed to parse contact info\n");
2222 /* Say OK and ask subsystem to retransmit msg counter */
2223 transmit_response(p, "200 OK", req);
2224 peer->lastmsgssent = -1;
2232 ast_pthread_mutex_unlock(&peerl.lock);
2234 transmit_response(p, "401 Unauthorized", &p->initreq);
2238 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2240 char tmp[256] = "", *c, *a;
2241 struct sip_request *req;
2246 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2247 c = ditch_braces(tmp);
2248 if (strncmp(c, "sip:", 4)) {
2249 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2253 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2257 ast_verbose("Looking for %s in %s\n", c, p->context);
2258 if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2260 strncpy(p->exten, c, sizeof(p->exten) - 1);
2264 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2271 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2273 char tmp[256] = "", *c, *a;
2274 char tmp2[256] = "", *c2, *a2;
2277 char tmp5[256] = ""; /* CallID to replace */
2278 struct sip_request *req;
2284 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2285 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2286 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2287 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2289 c = ditch_braces(tmp);
2290 c2 = ditch_braces(tmp2);
2293 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2294 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2295 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
2300 if ((a = strchr(c, '?'))) {
2301 /* Search for arguemnts */
2304 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2305 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2306 if ((a = strchr(tmp5, '%'))) {
2307 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
2309 if ((a[1] == '4') && (a[2] == '0')) {
2311 memmove(a + 1, a+3, strlen(a + 3));
2314 if ((a = strchr(tmp5, '%')))
2319 if ((a = strchr(c, '@')))
2321 if ((a = strchr(c, ';')))
2325 if ((a2 = strchr(c2, '@')))
2328 if ((a2 = strchr(c2, ';')))
2333 ast_verbose("Looking for %s in %s\n", c, p->context);
2334 ast_verbose("Looking for %s in %s\n", c2, p->context);
2337 /* This is a supervised transfer */
2338 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2340 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2341 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2342 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2343 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2344 p->refer_call = NULL;
2345 ast_pthread_mutex_lock(&iflock);
2346 /* Search interfaces and find the match */
2349 if (!strcmp(p2->callid, tmp5)) {
2350 /* Go ahead and lock it before returning */
2351 ast_pthread_mutex_lock(&p2->lock);
2357 ast_pthread_mutex_unlock(&iflock);
2361 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2362 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2363 /* This is an unsupervised transfer */
2364 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2365 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2366 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2367 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2368 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2369 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2370 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2371 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2372 p->refer_call = NULL;
2374 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2382 static int check_via(struct sip_pvt *p, struct sip_request *req)
2388 memset(via, 0, sizeof(via));
2389 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2390 c = strchr(via, ';');
2393 c = strchr(via, ' ');
2397 while(*c && (*c < 33))
2399 if (strcmp(via, "SIP/2.0/UDP")) {
2400 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2403 pt = strchr(c, ':');
2408 hp = gethostbyname(c);
2410 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2413 memset(&p->sa, 0, sizeof(p->sa));
2414 p->sa.sin_family = AF_INET;
2415 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2416 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2418 ast_verbose("Sending to %s : %d\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2423 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2425 struct sip_user *user;
2426 char *of, from[256] = "", *c;
2431 while(*t && (*t > 32) && (*t != ';'))
2434 of = get_header(req, "From");
2435 strncpy(from, of, sizeof(from) - 1);
2436 of = ditch_braces(from);
2437 if (strncmp(of, "sip:", 4))
2441 /* Get just the username part */
2442 if ((c = strchr(of, '@')))
2444 if ((c = strchr(of, ':')))
2446 strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2449 ast_pthread_mutex_lock(&userl.lock);
2452 if (!strcasecmp(user->name, of)) {
2453 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2454 strncpy(p->context, user->context, sizeof(p->context) - 1);
2455 if (strlen(user->callerid) && strlen(p->callerid))
2456 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2457 strncpy(p->username, user->name, sizeof(p->username) - 1);
2458 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
2459 p->canreinvite = user->canreinvite;
2460 p->amaflags = user->amaflags;
2466 ast_pthread_mutex_unlock(&userl.lock);
2470 static int get_msg_text(char *buf, int len, struct sip_request *req)
2474 for (x=0;x<req->lines;x++) {
2475 strncat(buf, req->line[x], len - strlen(buf) - 5);
2481 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2485 if (get_msg_text(buf, sizeof(buf), req)) {
2486 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2491 ast_verbose("Message received: '%s'\n", buf);
2492 memset(&f, 0, sizeof(f));
2493 f.frametype = AST_FRAME_TEXT;
2497 f.datalen = strlen(buf);
2498 ast_queue_frame(p->owner, &f, 1);
2502 static int sip_show_users(int fd, int argc, char *argv[])
2504 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2505 struct sip_user *user;
2507 return RESULT_SHOWUSAGE;
2508 ast_pthread_mutex_lock(&userl.lock);
2509 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2510 for(user=userl.users;user;user=user->next) {
2511 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2513 user->ha ? "Yes" : "No");
2515 ast_pthread_mutex_unlock(&userl.lock);
2516 return RESULT_SUCCESS;
2520 static int sip_show_peers(int fd, int argc, char *argv[])
2522 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2523 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2524 struct sip_peer *peer;
2525 char name[256] = "";
2527 return RESULT_SHOWUSAGE;
2528 ast_pthread_mutex_lock(&peerl.lock);
2529 ast_cli(fd, FORMAT2, "Name/username", "Host", " ", "Mask", "Port", "Status");
2530 for (peer = peerl.peers;peer;peer = peer->next) {
2533 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2534 if (strlen(peer->username))
2535 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2537 strncpy(name, peer->name, sizeof(name) - 1);
2539 if (peer->lastms < 0)
2540 strcpy(status, "UNREACHABLE");
2541 else if (peer->lastms > peer->maxms)
2542 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2543 else if (peer->lastms)
2544 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2546 strcpy(status, "UNKNOWN");
2548 strcpy(status, "Unmonitored");
2549 ast_cli(fd, FORMAT, name,
2550 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2551 peer->dynamic ? "(D)" : " ",
2553 ntohs(peer->addr.sin_port), status);
2555 ast_pthread_mutex_unlock(&peerl.lock);
2556 return RESULT_SUCCESS;
2561 static char *regstate2str(int regstate)
2564 case REG_STATE_UNREGISTERED:
2565 return "Unregistered";
2566 case REG_STATE_REGSENT:
2567 return "Request Sent";
2568 case REG_STATE_AUTHSENT:
2569 return "Auth. Sent";
2570 case REG_STATE_REGISTERED:
2571 return "Registered";
2572 case REG_STATE_REJECTED:
2574 case REG_STATE_TIMEOUT:
2576 case REG_STATE_NOAUTH:
2577 return "No Authentication";
2583 static int sip_show_registry(int fd, int argc, char *argv[])
2585 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2586 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2587 struct sip_registry *reg;
2591 return RESULT_SHOWUSAGE;
2592 ast_pthread_mutex_lock(&peerl.lock);
2593 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2594 for (reg = registrations;reg;reg = reg->next) {
2595 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2596 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2597 ast_cli(fd, FORMAT, host,
2598 reg->username, state, reg->refresh, regstate2str(reg->regstate));
2600 ast_pthread_mutex_unlock(&peerl.lock);
2601 return RESULT_SUCCESS;
2606 static int sip_show_channels(int fd, int argc, char *argv[])
2608 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2609 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
2610 struct sip_pvt *cur;
2613 return RESULT_SHOWUSAGE;
2614 ast_pthread_mutex_lock(&iflock);
2616 ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2618 ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr),
2619 strlen(cur->username) ? cur->username : "(None)",
2621 cur->ocseq, cur->icseq,
2624 cur->owner ? cur->owner->nativeformats : 0);
2628 ast_pthread_mutex_unlock(&iflock);
2629 ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2630 return RESULT_SUCCESS;
2635 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2637 char buf[1024] = "";
2640 /* Try getting the "signal=" part */
2641 if ((c = get_sdp(req, "Signal"))) {
2642 strncpy(buf, c, sizeof(buf) - 1);
2643 } else if (get_msg_text(buf, sizeof(buf), req)) {
2644 /* Normal INFO method */
2645 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2652 ast_verbose("DTMF received: '%c'\n", buf[0]);
2653 memset(&f, 0, sizeof(f));
2654 f.frametype = AST_FRAME_DTMF;
2655 f.subclass = buf[0];
2659 ast_queue_frame(p->owner, &f, 1);
2664 static int sip_do_debug(int fd, int argc, char *argv[])
2667 return RESULT_SHOWUSAGE;
2669 ast_cli(fd, "SIP Debugging Enabled\n");
2670 return RESULT_SUCCESS;
2673 static int sip_no_debug(int fd, int argc, char *argv[])
2676 return RESULT_SHOWUSAGE;
2678 ast_cli(fd, "SIP Debugging Disabled\n");
2679 return RESULT_SUCCESS;
2682 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2684 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2686 memset(digest,0,sizeof(digest));
2687 reply_digest(p,req, "WWW-Authenticate", "REGISTER", (char *)&digest, sizeof(digest) );
2688 return transmit_register(p->registry,"REGISTER",(char *)&digest);
2691 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2693 memset(digest,0,sizeof(digest));
2694 reply_digest(p,req, "Proxy-Authenticate", "INVITE", (char *)&digest, sizeof(digest) );
2695 return transmit_invite(p,"INVITE",1,(char *)&digest, NULL);
2698 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2709 char resp_hash[256];
2713 strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2715 c+=strlen("Digest ");
2717 while (*c && (*c < 33)) c++;
2720 if (!strncasecmp(c,"realm=", strlen("realm="))) {
2721 c+=strlen("realm=");
2724 if ((c = strchr(c,'\"')))
2728 if ((c = strchr(c,',')))
2732 } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
2733 c+=strlen("nonce=");
2736 if ((c = strchr(c,'\"')))
2740 if ((c = strchr(c,',')))
2749 /* Okay. We've got the realm and nonce from the server. Now lets build the MD5 digest. */
2750 snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2752 snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
2753 snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
2754 md5_hash(a1_hash,a1);
2755 md5_hash(a2_hash,a2);
2756 snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
2757 md5_hash(resp_hash,resp);
2759 snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
2769 static char show_users_usage[] =
2770 "Usage: sip show users\n"
2771 " Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
2773 static char show_channels_usage[] =
2774 "Usage: sip show channels\n"
2775 " Lists all currently active SIP channels.\n";
2777 static char show_peers_usage[] =
2778 "Usage: sip show peers\n"
2779 " Lists all known SIP peers.\n";
2781 static char show_reg_usage[] =
2782 "Usage: sip show registry\n"
2783 " Lists all registration requests and status.\n";
2785 static char debug_usage[] =
2786 "Usage: sip debug\n"
2787 " Enables dumping of SIP packets for debugging purposes\n";
2789 static char no_debug_usage[] =
2790 "Usage: sip no debug\n"
2791 " Disables dumping of SIP packets for debugging purposes\n";
2793 static struct ast_cli_entry cli_show_users =
2794 { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
2795 static struct ast_cli_entry cli_show_channels =
2796 { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage };
2797 static struct ast_cli_entry cli_show_peers =
2798 { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
2799 static struct ast_cli_entry cli_show_registry =
2800 { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
2801 static struct ast_cli_entry cli_debug =
2802 { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
2803 static struct ast_cli_entry cli_no_debug =
2804 { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
2807 static int sip_poke_peer_s(void *data)
2809 struct sip_peer *peer = data;
2810 peer->pokeexpire = -1;
2811 sip_poke_peer(peer);
2815 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
2819 struct ast_rtp *rtp;
2820 struct ast_channel *owner;
2821 struct sip_peer *peer;
2824 c = get_header(req, "Cseq");
2825 msg = strchr(c, ' ');
2826 if (!msg) msg = ""; else msg++;
2828 ast_pthread_mutex_lock(&p->lock);
2829 /* Go ahead and lock the owner if it has one -- we may need it */
2830 if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
2831 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
2832 ast_pthread_mutex_unlock(&p->lock);
2833 /* Sleep infintismly short amount of time */
2839 /* We don't really care what the response is, just that it replied back.
2840 Well, as long as it's not a 100 response... since we might
2841 need to hang around for something more "difinitive" */
2844 gettimeofday(&tv, NULL);
2845 pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
2846 (tv.tv_usec - peer->ps.tv_usec) / 1000;
2849 if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
2850 if (pingtime <= peer->maxms)
2851 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
2852 } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
2853 if (pingtime > peer->maxms)
2854 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
2856 peer->lastms = pingtime;
2858 if (peer->pokeexpire > -1)
2859 ast_sched_del(sched, peer->pokeexpire);
2860 if (!strcasecmp(msg, "INVITE"))
2861 transmit_request(p, "ACK", 0);
2864 /* Try again eventually */
2865 if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
2866 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
2868 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
2870 } else if (p->outgoing) {
2871 if (p->initid > -1) {
2872 /* Don't auto congest anymore since we've gotten something useful back */
2873 ast_sched_del(sched, p->initid);
2876 /* Get their tag if we haven't already */
2877 if (!strlen(p->theirtag)) {
2878 to = get_header(req, "To");
2879 to = strstr(to, "tag=");
2882 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
2883 to = strchr(p->theirtag, ';');
2892 case 183: /* We don't really need this since we pass in-band audio anyway */
2894 if (strlen(get_header(req, "Content-Type")))
2895 process_sdp(p, req);
2899 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
2900 if (p->owner->_state != AST_STATE_UP)
2901 ast_setstate(p->owner, AST_STATE_RINGING);
2905 if (strlen(get_header(req, "Content-Type")))
2906 process_sdp(p, req);
2908 if (p->owner->_state != AST_STATE_UP) {
2909 ast_setstate(p->owner, AST_STATE_UP);
2910 ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
2913 if (!strcasecmp(msg, "INVITE"))
2914 transmit_request(p, "ACK", 0);
2915 else if (!strcasecmp(msg, "REGISTER"))
2919 struct sip_registry *r;
2920 transmit_request(p, "ACK", 0);
2922 r->regstate=REG_STATE_REGISTERED;
2923 ast_log(LOG_NOTICE, "Registration successful\n");
2924 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
2926 ast_sched_del(sched, r->timeout);
2928 /* set us up for re-registering */
2929 /* figure out how long we got registered for */
2930 if (r->expire != -1)
2931 ast_sched_del(sched, r->expire);
2932 expires=atoi(get_header(req, "expires"));
2933 if (!expires) expires=default_expirey;
2934 r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r);
2938 case 401: /* Not authorized on REGISTER */
2939 /* XXX: Do I need to ACK the 401?
2940 transmit_request(p, "ACK", 0);
2942 do_register_auth(p, req);
2946 transmit_request(p, "ACK", 0);
2948 do_proxy_auth(p, req);
2949 /* This is just a hack to kill the channel while testing */
2955 ast_rtp_destroy(rtp);
2958 ast_queue_hangup(p->owner,0);
2959 transmit_request(p,"ACK",0);
2965 if ((resp >= 400) && (resp < 700)) {
2966 if (option_verbose > 2)
2967 ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
2972 /* Immediately stop RTP */
2973 ast_rtp_destroy(rtp);
2975 /* XXX Locking issues?? XXX */
2977 case 486: /* Busy here */
2978 case 600: /* Busy everywhere */
2980 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
2982 case 480: /* Temporarily Unavailable */
2983 case 404: /* Not Found */
2984 case 410: /* Gone */
2985 case 500: /* Server error */
2986 case 501: /* Not Implemented */
2988 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
2993 ast_queue_hangup(p->owner, 0);
2996 transmit_request(p, "ACK", 0);
2997 __sip_destroy(p, 0);
3000 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));
3004 ast_verbose("Message is %s\n", msg);
3007 if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
3008 transmit_request(p, "ACK", 0);
3013 ast_pthread_mutex_unlock(&owner->lock);
3015 ast_pthread_mutex_unlock(&p->lock);
3018 static int determine_firstline_parts( struct sip_request *req ) {
3023 cmd= req->header[0];
3024 while(*cmd && (*cmd < 33)) {
3031 while(*e && (*e > 32)) {
3034 /* Get the command */
3040 while( *e && ( *e < 33 ) ) {
3047 if ( !strcasecmp(cmd, "SIP/2.0") ) {
3048 /* We have a response */
3050 len= strlen( req->rlPart2 );
3051 if( len < 2 ) { return -1; }
3053 while( *e && *e<33 ) {
3058 /* We have a request */
3061 if( !*e ) { return -1; }
3064 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3067 while( isspace( *(--e) ) ) {}
3077 static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
3079 if (!p1->owner || !p2->owner) {
3080 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
3083 if (p1->owner->bridge) {
3084 if (p2->owner->bridge)
3085 ast_moh_stop(p2->owner->bridge);
3086 ast_moh_stop(p1->owner->bridge);
3087 ast_moh_stop(p1->owner);
3088 ast_moh_stop(p2->owner);
3089 if (ast_channel_masquerade(p2->owner, p1->owner->bridge)) {
3090 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p2->owner->name, p1->owner->bridge->name);
3093 } else if (p2->owner->bridge) {
3094 ast_moh_stop(p2->owner->bridge);
3095 ast_moh_stop(p2->owner);
3096 ast_moh_stop(p1->owner);
3097 if (ast_channel_masquerade(p1->owner, p2->owner->bridge)) {
3098 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p1->owner->name, p2->owner->bridge->name);