2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Session Initiation Protocol
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
18 #include <asterisk/lock.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <asterisk/lock.h>
27 #include <asterisk/sched.h>
28 #include <asterisk/io.h>
29 #include <asterisk/rtp.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/md5.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <sys/socket.h>
38 #include <sys/ioctl.h>
45 #include <arpa/inet.h>
46 #include <sys/signal.h>
47 #include <netinet/ip.h>
49 /* #define VOCAL_DATA_HACK */
52 #define DEFAULT_DEFAULT_EXPIREY 120
53 #define DEFAULT_MAX_EXPIREY 3600
55 #define SIP_DTMF_RFC2833 (1 << 0)
56 #define SIP_DTMF_INBAND (1 << 1)
57 #define SIP_DTMF_INFO (1 << 2)
59 static int max_expirey = DEFAULT_MAX_EXPIREY;
60 static int default_expirey = DEFAULT_DEFAULT_EXPIREY;
62 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
64 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
65 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
66 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
68 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
69 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
71 static char *desc = "Session Initiation Protocol (SIP)";
72 static char *type = "sip";
73 static char *tdesc = "Session Initiation Protocol (SIP)";
74 static char *config = "sip.conf";
76 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
77 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
79 static char context[AST_MAX_EXTENSION] = "default";
81 static char language[MAX_LANGUAGE] = "";
83 static char callerid[AST_MAX_EXTENSION] = "asterisk";
85 static char fromdomain[AST_MAX_EXTENSION] = "";
88 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
90 /* Protect the interface list (of sip_pvt's) */
91 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
93 /* Protect the monitoring thread, so only one process can kill or start it, and not
94 when it's doing something critical. */
95 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
97 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
99 /* This is the thread for the monitor which checks for input on the channels
100 which are not currently in use. */
101 static pthread_t monitor_thread = 0;
103 static int restart_monitor(void);
105 /* Codecs that we support by default: */
106 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
107 static int noncodeccapability = AST_RTP_DTMF;
109 static char ourhost[256];
110 static struct in_addr __ourip;
113 static int sipdebug = 0;
117 static int globaldtmfmode = SIP_DTMF_RFC2833;
120 static int expirey = 900;
122 static struct sched_context *sched;
123 static struct io_context *io;
124 /* The private structures of the sip channels are linked for
125 selecting outgoing channels */
127 #define SIP_MAX_HEADERS 64
128 #define SIP_MAX_LINES 64
130 static struct sip_codec_pref {
132 struct sip_codec_pref *next;
136 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
137 char *rlPart2; /* The Request URI or Response Status */
139 int headers; /* SIP Headers */
140 char *header[SIP_MAX_HEADERS];
141 int lines; /* SDP Content */
142 char *line[SIP_MAX_LINES];
143 char data[SIP_MAX_PACKET];
149 struct sip_route *next;
153 static struct sip_pvt {
154 pthread_mutex_t lock; /* Channel private lock */
155 char callid[80]; /* Global CallID */
156 char randdata[80]; /* Random data */
157 unsigned int ocseq; /* Current outgoing seqno */
158 unsigned int icseq; /* Current incoming seqno */
159 int lastinvite; /* Last Cseq of invite */
160 int alreadygone; /* Whether or not we've already been destroyed by or peer */
161 int needdestroy; /* if we need to be destroyed */
162 int capability; /* Special capability */
163 int noncodeccapability;
164 int outgoing; /* Outgoing or incoming call? */
165 int insecure; /* Don't check source port/ip */
166 int expirey; /* How long we take to expire */
167 int branch; /* One random number */
168 int canreinvite; /* Do we support reinvite */
169 int progress; /* Have sent 183 message progress */
170 int tag; /* Another random number */
171 int nat; /* Whether to try to support NAT */
172 struct sockaddr_in sa; /* Our peer */
173 struct sockaddr_in recv; /* Received as */
174 struct in_addr ourip; /* Our IP */
175 struct ast_channel *owner; /* Who owns us */
176 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
177 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
178 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
179 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
180 struct sip_pvt *refer_call; /* Call we are referring */
181 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
182 char remote_party_id[256];
183 char context[AST_MAX_EXTENSION];
184 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
185 char language[MAX_LANGUAGE];
186 char theirtag[256]; /* Their tag */
190 char callerid[256]; /* Caller*ID */
192 char accountcode[256]; /* Account code */
193 char realm[256]; /* Authorization realm */
194 char nonce[256]; /* Authorization nonce */
195 int amaflags; /* AMA Flags */
196 struct sip_request initreq; /* Initial request */
198 int maxtime; /* Max time for first response */
199 int initid; /* Auto-congest ID if appropriate */
200 int autokillid; /* Auto-kill ID */
209 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
210 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
211 struct ast_rtp *rtp; /* RTP Session */
212 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
213 struct sip_pvt *next;
217 struct sip_pkt *next; /* Next packet */
218 int retrans; /* Retransmission number */
219 int seqno; /* Sequence number */
220 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
221 struct sip_pvt *owner; /* Owner call */
222 int retransid; /* Retransmission ID */
223 int packetlen; /* Length of packet */
228 /* Users who can access various contexts */
234 char accountcode[80];
242 struct sip_user *next;
248 char context[80]; /* JK02: peers need context too to allow parking etc */
252 char mailbox[AST_MAX_EXTENSION];
263 struct sockaddr_in addr;
267 struct sip_pvt *call; /* Call pointer */
268 int pokeexpire; /* When to expire poke */
269 int lastms; /* How long last response took (in ms), or -1 for no response */
270 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
271 struct timeval ps; /* Ping send time */
273 struct sockaddr_in defaddr;
277 struct sip_peer *next;
280 static struct ast_user_list {
281 struct sip_user *users;
282 pthread_mutex_t lock;
283 } userl = { NULL, AST_MUTEX_INITIALIZER };
285 static struct ast_peer_list {
286 struct sip_peer *peers;
287 pthread_mutex_t lock;
288 } peerl = { NULL, AST_MUTEX_INITIALIZER };
291 #define REG_STATE_UNREGISTERED 0
292 #define REG_STATE_REGSENT 1
293 #define REG_STATE_AUTHSENT 2
294 #define REG_STATE_REGISTERED 3
295 #define REG_STATE_REJECTED 4
296 #define REG_STATE_TIMEOUT 5
297 #define REG_STATE_NOAUTH 6
299 struct sip_registry {
300 pthread_mutex_t lock; /* Channel private lock */
301 struct sockaddr_in addr; /* Who we connect to for registration purposes */
303 char secret[80]; /* Password or key name in []'s */
304 char contact[80]; /* Contact extension */
306 int expire; /* Sched ID of expiration */
307 int timeout; /* sched id of sip_reg_timeout */
308 int refresh; /* How often to refresh */
309 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
311 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
312 char callid[80]; /* Global CallID for this registry */
313 struct sockaddr_in us; /* Who the server thinks we are */
314 struct sip_registry *next;
317 #define REINVITE_INVITE 1
318 #define REINVITE_UPDATE 2
320 static int sip_do_register(struct sip_registry *r);
321 struct sip_registry *registrations;
323 static int sipsock = -1;
324 static int globalnat = 0;
326 static struct sockaddr_in bindaddr;
328 static struct ast_frame *sip_read(struct ast_channel *ast);
329 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
330 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
331 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
332 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
333 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
334 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
335 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
336 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
337 static int transmit_message_with_text(struct sip_pvt *p, char *text);
338 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
339 char *getsipuri(char *header);
340 static void free_old_route(struct sip_route *route);
341 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
343 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
347 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
349 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
351 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));
356 static void sip_destroy(struct sip_pvt *p);
358 static int retrans_pkt(void *data)
360 struct sip_pkt *pkt=data;
362 ast_pthread_mutex_lock(&pkt->owner->lock);
363 if (!pkt->owner->needdestroy) {
364 if (pkt->retrans < MAX_RETRANS) {
368 ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
370 ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
372 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
375 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
377 if (pkt->owner->owner) {
378 /* XXX Potential deadlocK?? XXX */
379 ast_queue_hangup(pkt->owner->owner, 1);
381 /* If no owner, destroy now */
382 ast_pthread_mutex_unlock(&pkt->owner->lock);
383 sip_destroy(pkt->owner);
388 /* Don't bother retransmitting. It's about to be killed anyway */
390 if (pkt->owner->owner) {
391 /* XXX Potential deadlocK?? XXX */
392 ast_queue_hangup(pkt->owner->owner, 1);
394 /* If no owner, destroy now */
395 ast_pthread_mutex_unlock(&pkt->owner->lock);
396 sip_destroy(pkt->owner);
401 ast_pthread_mutex_unlock(&pkt->owner->lock);
405 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
408 pkt = malloc(sizeof(struct sip_pkt) + len);
411 memset(pkt, 0, sizeof(struct sip_pkt));
412 memcpy(pkt->data, data, len);
413 pkt->packetlen = len;
414 pkt->next = p->packets;
418 /* Schedule retransmission */
419 pkt->retransid = ast_sched_add(sched, 1000, retrans_pkt, pkt);
420 pkt->next = p->packets;
422 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
426 static int __sip_autodestruct(void *data)
428 struct sip_pvt *p = data;
430 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
432 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
433 ast_queue_hangup(p->owner, 0);
440 static int sip_scheddestroy(struct sip_pvt *p, int ms)
442 if (p->autokillid > -1)
443 ast_sched_del(sched, p->autokillid);
444 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
448 static int sip_cancel_destroy(struct sip_pvt *p)
450 if (p->autokillid > -1)
451 ast_sched_del(sched, p->autokillid);
456 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
458 struct sip_pkt *cur, *prev = NULL;
462 if ((cur->seqno == seqno) && (cur->resp == resp)) {
463 /* this is our baby */
465 prev->next = cur->next;
467 p->packets = cur->next;
468 if (cur->retransid > -1)
469 ast_sched_del(sched, cur->retransid);
477 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
481 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
486 ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
488 ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
491 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
493 res = __sip_xmit(p, req->data, req->len);
499 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
504 ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
506 ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
509 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
511 res = __sip_xmit(p, req->data, req->len);
515 static char *ditch_braces(char *tmp)
520 if ((n = strchr(tmp, '<')) ) {
522 while(*c && *c != '>') c++;
524 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
533 static int sip_sendtext(struct ast_channel *ast, char *text)
535 struct sip_pvt *p = ast->pvt->pvt;
537 ast_verbose("Sending text %s on %s\n", text, ast->name);
540 if (!text || !strlen(text))
543 ast_verbose("Really sending text %s on %s\n", text, ast->name);
544 transmit_message_with_text(p, text);
548 static int create_addr(struct sip_pvt *r, char *peer)
553 r->sa.sin_family = AF_INET;
554 ast_pthread_mutex_lock(&peerl.lock);
557 if (!strcasecmp(p->name, peer)) {
559 r->capability = p->capability;
562 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
563 ast_rtp_setnat(r->rtp, r->nat);
565 strncpy(r->peername, p->username, sizeof(r->peername)-1);
566 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
567 strncpy(r->username, p->username, sizeof(r->username)-1);
568 if (strlen(p->fromdomain))
569 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
570 r->insecure = p->insecure;
571 r->canreinvite = p->canreinvite;
572 r->maxtime = p->maxms;
574 r->dtmfmode = p->dtmfmode;
575 if (r->dtmfmode & SIP_DTMF_RFC2833)
576 r->noncodeccapability |= AST_RTP_DTMF;
578 r->noncodeccapability &= ~AST_RTP_DTMF;
580 strncpy(r->context, p->context,sizeof(r->context)-1);
581 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
582 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
583 if (p->addr.sin_addr.s_addr) {
584 r->sa.sin_addr = p->addr.sin_addr;
585 r->sa.sin_port = p->addr.sin_port;
587 r->sa.sin_addr = p->defaddr.sin_addr;
588 r->sa.sin_port = p->defaddr.sin_port;
590 memcpy(&r->recv, &r->sa, sizeof(r->recv));
596 ast_pthread_mutex_unlock(&peerl.lock);
598 hp = gethostbyname(peer);
600 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
601 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
602 memcpy(&r->recv, &r->sa, sizeof(r->recv));
605 ast_log(LOG_WARNING, "No such host: %s\n", peer);
614 static int auto_congest(void *nothing)
616 struct sip_pvt *p = nothing;
617 ast_pthread_mutex_lock(&p->lock);
620 if (!pthread_mutex_trylock(&p->owner->lock)) {
621 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
622 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
623 ast_pthread_mutex_unlock(&p->owner->lock);
626 ast_pthread_mutex_unlock(&p->lock);
630 static void sip_prefs_free(void)
632 struct sip_codec_pref *cur, *next;
642 static void sip_pref_remove(int format)
644 struct sip_codec_pref *cur, *prev=NULL;
647 if (cur->codec == format) {
649 prev->next = cur->next;
660 static int sip_pref_append(int format)
662 struct sip_codec_pref *cur, *tmp;
663 sip_pref_remove(format);
664 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
667 memset(tmp, 0, sizeof(struct sip_codec_pref));
679 static int sip_codec_choose(int formats)
681 struct sip_codec_pref *cur;
684 if (formats & cur->codec)
688 return ast_best_codec(formats);
691 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
695 char *vxml_url = NULL;
696 struct varshead *headp;
697 struct ast_var_t *current;
700 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
701 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
705 /* Check whether there is a VXML_URL variable */
706 headp=&ast->varshead;
707 AST_LIST_TRAVERSE(headp,current,entries) {
708 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
710 vxml_url = ast_var_value(current);
717 transmit_invite(p, "INVITE", 1, NULL, vxml_url);
719 /* Initialize auto-congest time */
720 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
725 static void __sip_destroy(struct sip_pvt *p, int lockowner)
727 struct sip_pvt *cur, *prev = NULL;
730 ast_extension_state_del(p->stateid, NULL);
732 ast_sched_del(sched, p->initid);
733 if (p->autokillid > -1)
734 ast_sched_del(sched, p->autokillid);
737 ast_rtp_destroy(p->rtp);
740 free_old_route(p->route);
743 /* Unlink us from the owner if we have one */
746 ast_pthread_mutex_lock(&p->owner->lock);
747 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
748 p->owner->pvt->pvt = NULL;
750 ast_pthread_mutex_unlock(&p->owner->lock);
756 prev->next = cur->next;
765 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
768 ast_sched_del(sched, p->initid);
769 while((cp = p->packets)) {
770 p->packets = p->packets->next;
771 if (cp->retransid > -1)
772 ast_sched_del(sched, cp->retransid);
778 static void sip_destroy(struct sip_pvt *p)
780 ast_pthread_mutex_lock(&iflock);
782 ast_pthread_mutex_unlock(&iflock);
785 /* Interface lookup code courtesy Tilghman of DrunkCoder.com. Thanks! */
788 char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
789 struct sockaddr_in ifru_addr;
792 struct in_addr *lookup_iface(char *iface) {
795 static struct my_ifreq ifreq;
796 memset(&ifreq, 0, sizeof(ifreq));
797 strncpy(ifreq.ifrn_name,iface,sizeof(ifreq.ifrn_name) - 1);
799 mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
800 res = ioctl(mysock,SIOCGIFADDR,&ifreq);
804 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
807 return( (struct in_addr *) &ifreq.ifru_addr.sin_addr );
810 static struct in_addr *myaddrfor(struct in_addr *them)
813 struct in_addr *temp = NULL;
814 unsigned int remote_ip;
816 remote_ip = them->s_addr;
818 PROC = fopen("/proc/net/route","r");
820 /* If /proc/net/route doesn't exist, fall back to the old method */
823 /* First line contains headers */
824 fgets(line,sizeof(line),PROC);
826 while (!feof(PROC)) {
828 unsigned int dest, gateway, mask;
832 fgets(line,sizeof(line),PROC);
835 for (i=0;i<sizeof(line);i++) {
838 fields[aoffset++] = line + i;
839 boffset = strchr(line + i,'\t');
840 if (boffset == NULL) {
849 sscanf(fields[0],"%s",iface);
850 sscanf(fields[1],"%x",&dest);
851 sscanf(fields[2],"%x",&gateway);
852 sscanf(fields[7],"%x",&mask);
854 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
856 if (((remote_ip & mask) ^ dest) == 0) {
858 ast_verbose("Interface is %s\n",iface);
859 temp = lookup_iface(iface);
861 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
867 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s. Using default\n", inet_ntoa(*them));
873 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
876 static int sip_hangup(struct ast_channel *ast)
878 struct sip_pvt *p = ast->pvt->pvt;
881 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
882 if (!ast->pvt->pvt) {
883 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
886 ast_pthread_mutex_lock(&p->lock);
887 /* Determine how to disconnect */
888 if (p->owner != ast) {
889 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
890 ast_pthread_mutex_unlock(&p->lock);
893 if (!ast || (ast->_state != AST_STATE_UP))
898 ast_dsp_free(p->vad);
901 ast->pvt->pvt = NULL;
904 /* Start the process if it's not already started */
905 if (!p->alreadygone && strlen(p->initreq.data)) {
908 transmit_request_with_auth(p, "CANCEL", 0, 1);
909 /* Actually don't destroy us yet, wait for the 487 on our original
910 INVITE, but do set an autodestruct just in case. */
912 sip_scheddestroy(p, 15000);
914 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
917 transmit_request_with_auth(p, "BYE", 1, 1);
920 ast_pthread_mutex_unlock(&p->lock);
924 static int sip_answer(struct ast_channel *ast)
928 struct sip_pvt *p = ast->pvt->pvt;
931 if (ast->_state != AST_STATE_UP) {
935 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
937 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
938 fmt=ast_getformatbyname(codec);
941 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
944 ast_setstate(ast, AST_STATE_UP);
946 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
947 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
952 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
954 struct sip_pvt *p = ast->pvt->pvt;
956 if (frame->frametype != AST_FRAME_VOICE) {
957 if (frame->frametype == AST_FRAME_IMAGE)
960 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
964 if (!(frame->subclass & ast->nativeformats)) {
965 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
966 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
971 ast_pthread_mutex_lock(&p->lock);
973 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
974 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
977 res = ast_rtp_write(p->rtp, frame);
979 ast_pthread_mutex_unlock(&p->lock);
984 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
986 struct sip_pvt *p = newchan->pvt->pvt;
987 ast_pthread_mutex_lock(&p->lock);
988 if (p->owner != oldchan) {
989 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
990 ast_pthread_mutex_unlock(&p->lock);
994 ast_pthread_mutex_unlock(&p->lock);
998 static int sip_senddigit(struct ast_channel *ast, char digit)
1000 struct sip_pvt *p = ast->pvt->pvt;
1001 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1002 transmit_info_with_digit(p, digit);
1004 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1005 ast_rtp_senddigit(p->rtp, digit);
1007 /* If in-band DTMF is desired, send that */
1008 if (p->dtmfmode & SIP_DTMF_INBAND)
1013 static int sip_indicate(struct ast_channel *ast, int condition)
1015 struct sip_pvt *p = ast->pvt->pvt;
1017 case AST_CONTROL_RINGING:
1018 if (ast->_state == AST_STATE_RING) {
1019 transmit_response(p, "180 Ringing", &p->initreq);
1023 case AST_CONTROL_BUSY:
1024 if (ast->_state != AST_STATE_UP) {
1025 transmit_response(p, "600 Busy everywhere", &p->initreq);
1027 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1031 case AST_CONTROL_CONGESTION:
1032 if (ast->_state != AST_STATE_UP) {
1033 transmit_response(p, "486 Busy here", &p->initreq);
1035 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1042 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1050 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1052 struct ast_channel *tmp;
1054 tmp = ast_channel_alloc(1);
1056 /* Select our native format based on codec preference until we receive
1057 something from another device to the contrary. */
1059 tmp->nativeformats = sip_codec_choose(i->capability);
1061 tmp->nativeformats = sip_codec_choose(capability);
1062 fmt = ast_best_codec(tmp->nativeformats);
1064 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1066 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
1068 if (i->dtmfmode & SIP_DTMF_INBAND) {
1069 i->vad = ast_dsp_new();
1070 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1072 tmp->fds[0] = ast_rtp_fd(i->rtp);
1073 ast_setstate(tmp, state);
1074 if (state == AST_STATE_RING)
1076 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1077 tmp->writeformat = fmt;
1078 tmp->pvt->rawwriteformat = fmt;
1079 tmp->readformat = fmt;
1080 tmp->pvt->rawreadformat = fmt;
1082 tmp->pvt->send_text = sip_sendtext;
1083 tmp->pvt->call = sip_call;
1084 tmp->pvt->hangup = sip_hangup;
1085 tmp->pvt->answer = sip_answer;
1086 tmp->pvt->read = sip_read;
1087 tmp->pvt->write = sip_write;
1088 tmp->pvt->indicate = sip_indicate;
1089 tmp->pvt->fixup = sip_fixup;
1090 tmp->pvt->send_digit = sip_senddigit;
1091 tmp->pvt->bridge = ast_rtp_bridge;
1092 if (strlen(i->language))
1093 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1095 ast_pthread_mutex_lock(&usecnt_lock);
1097 ast_pthread_mutex_unlock(&usecnt_lock);
1098 ast_update_use_count();
1099 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1100 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1101 if (strlen(i->callerid))
1102 tmp->callerid = strdup(i->callerid);
1104 if (state != AST_STATE_DOWN) {
1105 if (ast_pbx_start(tmp)) {
1106 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1112 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1116 static struct cfalias {
1120 { "Content-Type", "c" },
1121 { "Content-Encoding", "e" },
1125 { "Content-Length", "l" },
1131 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1132 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1133 char* r = line + nameLen + 1;
1134 while (*r && (*r < 33)) ++r;
1141 static char *get_sdp(struct sip_request *req, char *name) {
1143 int len = strlen(name);
1146 for (x=0; x<req->lines; x++) {
1147 r = get_sdp_by_line(req->line[x], name, len);
1148 if (r[0] != '\0') return r;
1153 static void sdpLineNum_iterator_init(int* iterator) {
1157 static char* get_sdp_iterate(int* iterator,
1158 struct sip_request *req, char *name) {
1159 int len = strlen(name);
1161 while (*iterator < req->lines) {
1162 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1163 if (r[0] != '\0') return r;
1168 static char *__get_header(struct sip_request *req, char *name, int *start)
1171 int len = strlen(name);
1173 for (x=*start;x<req->headers;x++) {
1174 if (!strncasecmp(req->header[x], name, len) &&
1175 (req->header[x][len] == ':')) {
1176 r = req->header[x] + len + 1;
1177 while(*r && (*r < 33))
1184 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1185 if (!strcasecmp(aliases[x].fullname, name))
1186 return __get_header(req, aliases[x].shortname, start);
1188 /* Don't return NULL, so get_header is always a valid pointer */
1192 static char *get_header(struct sip_request *req, char *name)
1195 return __get_header(req, name, &start);
1198 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1200 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1201 struct ast_frame *f;
1202 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1203 f = ast_rtp_read(p->rtp);
1204 /* Don't send RFC2833 if we're not supposed to */
1205 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1208 /* We already hold the channel lock */
1209 if (f->frametype == AST_FRAME_VOICE) {
1210 if (f->subclass != p->owner->nativeformats) {
1211 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1212 p->owner->nativeformats = f->subclass;
1213 ast_set_read_format(p->owner, p->owner->readformat);
1214 ast_set_write_format(p->owner, p->owner->writeformat);
1216 if (p->dtmfmode & SIP_DTMF_INBAND) {
1217 f = ast_dsp_process(p->owner,p->vad,f,0);
1224 static struct ast_frame *sip_read(struct ast_channel *ast)
1226 struct ast_frame *fr;
1227 struct sip_pvt *p = ast->pvt->pvt;
1228 ast_pthread_mutex_lock(&p->lock);
1229 fr = sip_rtp_read(p);
1230 ast_pthread_mutex_unlock(&p->lock);
1234 static void build_callid(char *callid, int len, struct in_addr ourip)
1241 res = snprintf(callid, len, "%08x", val);
1245 /* It's not important that we really use our right IP here... */
1246 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1249 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1253 p = malloc(sizeof(struct sip_pvt));
1256 /* Keep track of stuff */
1257 memset(p, 0, sizeof(struct sip_pvt));
1261 p->rtp = ast_rtp_new(NULL, NULL);
1265 /* Start with 101 instead of 1 */
1268 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1272 ast_rtp_settos(p->rtp, tos);
1273 if (useglobalnat && sin) {
1274 /* Setup NAT structure according to global settings if we have an address */
1276 memcpy(&p->recv, sin, sizeof(p->recv));
1277 ast_rtp_setnat(p->rtp, p->nat);
1279 ast_pthread_mutex_init(&p->lock);
1281 ast_rtp_set_data(p->rtp, p);
1282 ast_rtp_set_callback(p->rtp, rtpready);
1285 memcpy(&p->sa, sin, sizeof(p->sa));
1286 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1288 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1290 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1292 build_callid(p->callid, sizeof(p->callid), p->ourip);
1294 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1295 /* Assume reinvite OK and via INVITE */
1296 p->canreinvite = REINVITE_INVITE;
1297 p->dtmfmode = globaldtmfmode;
1298 if (p->dtmfmode & SIP_DTMF_RFC2833)
1299 p->noncodeccapability |= AST_RTP_DTMF;
1300 strncpy(p->context, context, sizeof(p->context) - 1);
1301 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1303 ast_pthread_mutex_lock(&iflock);
1306 ast_pthread_mutex_unlock(&iflock);
1308 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1312 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1316 callid = get_header(req, "Call-ID");
1317 if (!strlen(callid)) {
1318 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1321 ast_pthread_mutex_lock(&iflock);
1324 if (!strcmp(p->callid, callid)) {
1325 /* Found the call */
1327 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1328 (p->sa.sin_port != sin->sin_port))) {
1331 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1332 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1333 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1334 ast_pthread_mutex_unlock(&iflock);
1338 ast_pthread_mutex_lock(&p->lock);
1339 ast_pthread_mutex_unlock(&iflock);
1344 ast_pthread_mutex_unlock(&iflock);
1345 return sip_alloc(callid, sin, 1);
1348 static int sip_register(char *value, int lineno)
1350 struct sip_registry *reg;
1351 char copy[256] = "";
1352 char *username, *hostname, *secret;
1360 strncpy(copy, value, sizeof(copy)-1);
1363 hostname = strrchr(stringp, '@');
1369 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1373 username = strsep(&stringp, ":");
1374 secret = strsep(&stringp, ":");
1376 hostname = strsep(&stringp, "/");
1377 contact = strsep(&stringp, "/");
1378 if (!contact || !strlen(contact))
1381 hostname = strsep(&stringp, ":");
1382 porta = strsep(&stringp, ":");
1384 if (porta && !atoi(porta)) {
1385 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1388 hp = gethostbyname(hostname);
1390 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1393 reg = malloc(sizeof(struct sip_registry));
1395 memset(reg, 0, sizeof(struct sip_registry));
1396 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1397 strncpy(reg->username, username, sizeof(reg->username)-1);
1399 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1401 reg->refresh = default_expirey;
1402 reg->addr.sin_family = AF_INET;
1403 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1404 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1405 reg->next = registrations;
1406 reg->callid_valid = 0;
1407 registrations = reg;
1409 ast_log(LOG_ERROR, "Out of memory\n");
1415 static void parse(struct sip_request *req)
1417 /* Divide fields by NULL's */
1422 /* First header starts immediately */
1426 /* We've got a new header */
1430 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1432 if (!strlen(req->header[f])) {
1433 /* Line by itself means we're now in content */
1437 if (f >= SIP_MAX_HEADERS - 1) {
1438 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1441 req->header[f] = c + 1;
1442 } else if (*c == '\r') {
1443 /* Ignore but eliminate \r's */
1448 /* Check for last header */
1449 if (strlen(req->header[f]))
1452 /* Now we process any mime content */
1457 /* We've got a new line */
1460 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1462 if (f >= SIP_MAX_LINES - 1) {
1463 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1466 req->line[f] = c + 1;
1467 } else if (*c == '\r') {
1468 /* Ignore and eliminate \r's */
1473 /* Check for last line */
1474 if (strlen(req->line[f]))
1478 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1480 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1483 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1491 int peercapability, peernoncodeccapability;
1492 struct sockaddr_in sin;
1498 /* Get codec and RTP info from SDP */
1499 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1500 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1503 m = get_sdp(req, "m");
1504 c = get_sdp(req, "c");
1505 if (!strlen(m) || !strlen(c)) {
1506 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1509 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1510 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1513 /* XXX This could block for a long time, and block the main thread! XXX */
1514 hp = gethostbyname(host);
1516 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1519 if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1520 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1523 sin.sin_family = AF_INET;
1524 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1525 sin.sin_port = htons(portno);
1527 ast_rtp_set_peer(p->rtp, &sin);
1529 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1531 // Scan through the RTP payload types specified in a "m=" line:
1532 ast_rtp_pt_clear(p->rtp);
1534 while(strlen(codecs)) {
1535 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1536 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1539 ast_rtp_set_m_type(p->rtp, codec);
1541 /* Skip over any whitespace */
1542 while(*codecs && (*codecs < 33)) codecs++;
1545 // Next, scan through each "a=rtpmap:" line, noting each
1546 // specified RTP payload type (with corresponding MIME subtype):
1547 sdpLineNum_iterator_init(&iterator);
1548 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1549 char* mimeSubtype = strdup(a); // ensures we have enough space
1550 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1551 // Note: should really look at the 'freq' and '#chans' params too
1552 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1556 // Now gather all of the codecs that were asked for:
1557 ast_rtp_get_current_formats(p->rtp,
1558 &peercapability, &peernoncodeccapability);
1559 p->capability = capability & peercapability;
1560 p->noncodeccapability = noncodeccapability & peernoncodeccapability;
1562 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1563 capability, peercapability, p->capability);
1564 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1565 noncodeccapability, peernoncodeccapability,
1566 p->noncodeccapability);
1568 if (!p->capability) {
1569 ast_log(LOG_WARNING, "No compatible codecs!\n");
1573 if (!(p->owner->nativeformats & p->capability)) {
1574 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);
1575 p->owner->nativeformats = sip_codec_choose(p->capability);
1576 ast_set_read_format(p->owner, p->owner->readformat);
1577 ast_set_write_format(p->owner, p->owner->writeformat);
1579 if (p->owner->bridge) {
1580 /* Turn on/off music on hold if we are holding/unholding */
1581 if (sin.sin_addr.s_addr) {
1582 ast_moh_stop(p->owner->bridge);
1584 ast_moh_start(p->owner->bridge, NULL);
1592 static int add_header(struct sip_request *req, char *var, char *value)
1594 if (req->len >= sizeof(req->data) - 4) {
1595 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1599 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1602 req->header[req->headers] = req->data + req->len;
1603 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1604 req->len += strlen(req->header[req->headers]);
1605 if (req->headers < SIP_MAX_HEADERS)
1608 ast_log(LOG_WARNING, "Out of header space\n");
1614 static int add_blank_header(struct sip_request *req)
1616 if (req->len >= sizeof(req->data) - 4) {
1617 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1621 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1624 req->header[req->headers] = req->data + req->len;
1625 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1626 req->len += strlen(req->header[req->headers]);
1627 if (req->headers < SIP_MAX_HEADERS)
1630 ast_log(LOG_WARNING, "Out of header space\n");
1636 static int add_line(struct sip_request *req, char *line)
1638 if (req->len >= sizeof(req->data) - 4) {
1639 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1643 /* Add extra empty return */
1644 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1645 req->len += strlen(req->data + req->len);
1647 req->line[req->lines] = req->data + req->len;
1648 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1649 req->len += strlen(req->line[req->lines]);
1650 if (req->lines < SIP_MAX_LINES)
1653 ast_log(LOG_WARNING, "Out of line space\n");
1659 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1662 tmp = get_header(orig, field);
1664 /* Add what we're responding to */
1665 return add_header(req, field, tmp);
1667 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1671 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1677 tmp = __get_header(orig, field, &start);
1679 /* Add what we're responding to */
1680 add_header(req, field, tmp);
1685 return copied ? 0 : -1;
1688 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1695 tmp = __get_header(orig, field, &start);
1697 if (!copied && p->nat) {
1698 /* SLD: FIXME: Nice try, but the received= should not have a port */
1699 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1700 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1701 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1703 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1704 add_header(req, field, new);
1706 /* Add what we're responding to */
1707 add_header(req, field, tmp);
1714 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1720 /* Add Route: header into request per learned route */
1721 static void add_route(struct sip_request *req, struct sip_route *route)
1724 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1730 n = strlen(route->hop);
1731 if ((n+3)>rem) break;
1737 strcpy(p, route->hop); p += n;
1740 route = route->next;
1743 add_header(req, "Route", r);
1746 static void set_destination(struct sip_pvt *p, char *uri)
1748 char *h, *maddr, hostname[256];
1752 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1753 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1756 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1758 /* Find and parse hostname */
1759 h = strchr(uri, '@');
1764 if (strncmp(h, "sip:", 4) == 0)
1766 else if (strncmp(h, "sips:", 5) == 0)
1769 hn = strcspn(h, ":;>");
1771 strncpy(hostname, h, hn); hostname[hn] = '\0';
1774 /* Is "port" present? if not default to 5060 */
1778 port = strtol(h, &h, 10);
1783 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
1784 maddr = strstr(h, "maddr=");
1787 hn = strspn(maddr, "0123456789.");
1789 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
1792 hp = gethostbyname(hostname);
1794 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
1797 p->sa.sin_family = AF_INET;
1798 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1799 p->sa.sin_port = htons(port);
1801 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1804 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1806 /* Initialize a response */
1807 if (req->headers || req->len) {
1808 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1811 req->header[req->headers] = req->data + req->len;
1812 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1813 req->len += strlen(req->header[req->headers]);
1814 if (req->headers < SIP_MAX_HEADERS)
1817 ast_log(LOG_WARNING, "Out of header space\n");
1821 static int init_req(struct sip_request *req, char *resp, char *recip)
1823 /* Initialize a response */
1824 if (req->headers || req->len) {
1825 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1828 req->header[req->headers] = req->data + req->len;
1829 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1830 req->len += strlen(req->header[req->headers]);
1831 if (req->headers < SIP_MAX_HEADERS)
1834 ast_log(LOG_WARNING, "Out of header space\n");
1838 static void append_contact(struct sip_request *req, struct sip_pvt *p)
1840 /* Add contact header */
1841 char contact2[256] ="", *c, contact[256];
1844 from = get_header(req, "From");
1846 from = get_header(req, "To");
1847 strncpy(contact2, from, sizeof(contact2)-1);
1848 if (strlen(contact2)) {
1849 c = ditch_braces(contact2);
1850 snprintf(contact, sizeof(contact), "<%s>", c);
1851 add_header(req, "Contact", contact);
1855 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1857 char newto[256] = "", *ot;
1858 memset(resp, 0, sizeof(*resp));
1859 init_resp(resp, msg, req);
1860 copy_via_headers(p, resp, req, "Via");
1861 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1862 copy_header(resp, req, "From");
1863 ot = get_header(req, "To");
1864 if (!strstr(ot, "tag=")) {
1865 /* Add the proper tag if we don't have it already. If they have specified
1866 their tag, use it. Otherwise, use our own tag */
1867 if (strlen(p->theirtag))
1868 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1870 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1872 strncpy(newto, ot, sizeof(newto) - 1);
1875 add_header(resp, "To", ot);
1876 copy_header(resp, req, "Call-ID");
1877 copy_header(resp, req, "CSeq");
1878 add_header(resp, "User-Agent", "Asterisk PBX");
1880 /* For registration responses, we also need expirey and
1885 if ((c=getsipuri(ot))) {
1886 snprintf(contact, sizeof(contact), "<%s@%s:%d>;expires=%d", c, inet_ntoa(p->ourip), ourport, p->expirey);
1889 snprintf(contact, sizeof(contact), "<%s:%d>;expires=%d", inet_ntoa(p->ourip), ourport, p->expirey);
1891 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1892 add_header(resp, "Expires", tmp);
1893 add_header(resp, "Contact", contact);
1896 /* XXX This isn't exactly right and it's implemented
1897 very stupidly *sigh* XXX */
1899 if ((c=getsipuri(ot))) {
1900 snprintf(contact, sizeof(contact), "<%s@%s:%d>", c, inet_ntoa(p->ourip), ourport);
1903 snprintf(contact, sizeof(contact), "<%s:%d>", inet_ntoa(p->ourip), ourport);
1905 add_header(resp, "Contact", contact);
1910 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1912 struct sip_request *orig = &p->initreq;
1913 char stripped[80] ="";
1919 memset(req, 0, sizeof(struct sip_request));
1925 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1927 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1929 c = strchr(stripped, '<');
1938 init_req(req, msg, c);
1940 snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1942 add_header(req, "Via", p->via);
1944 set_destination(p, p->route->hop);
1945 add_route(req, p->route->next);
1948 ot = get_header(orig, "To");
1949 of = get_header(orig, "From");
1951 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
1952 as our original request, including tag (or presumably lack thereof) */
1953 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
1954 /* Add the proper tag if we don't have it already. If they have specified
1955 their tag, use it. Otherwise, use our own tag */
1956 if (p->outgoing && strlen(p->theirtag))
1957 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1958 else if (!p->outgoing)
1959 snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1961 snprintf(newto, sizeof(newto), "%s", ot);
1966 add_header(req, "From", of);
1967 add_header(req, "To", ot);
1969 add_header(req, "From", ot);
1970 add_header(req, "To", of);
1972 append_contact(req, p);
1973 copy_header(req, orig, "Call-ID");
1974 add_header(req, "CSeq", tmp);
1976 add_header(req, "User-Agent", "Asterisk PBX");
1980 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
1982 struct sip_request resp;
1984 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
1985 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
1988 respprep(&resp, p, msg, req);
1989 add_header(&resp, "Content-Length", "0");
1990 add_blank_header(&resp);
1991 return send_response(p, &resp, reliable, seqno);
1994 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1996 return __transmit_response(p, msg, req, 0);
1998 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2000 return __transmit_response(p, msg, req, 1);
2003 static void append_date(struct sip_request *req)
2010 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2011 add_header(req, "Date", tmpdat);
2014 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2016 struct sip_request resp;
2017 respprep(&resp, p, msg, req);
2019 add_header(&resp, "Content-Length", "0");
2020 add_blank_header(&resp);
2021 return send_response(p, &resp, 0, 0);
2024 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2026 struct sip_request resp;
2027 respprep(&resp, p, msg, req);
2028 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
2029 add_header(&resp, "Accept", "application/sdp");
2030 add_header(&resp, "Content-Length", "0");
2031 add_blank_header(&resp);
2032 return send_response(p, &resp, 0, 0);
2035 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2037 struct sip_request resp;
2040 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2041 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2044 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2045 respprep(&resp, p, msg, req);
2046 add_header(&resp, "Proxy-Authenticate", tmp);
2047 add_header(&resp, "Content-Length", "0");
2048 add_blank_header(&resp);
2049 return send_response(p, &resp, reliable, seqno);
2052 static int add_text(struct sip_request *req, char *text)
2054 /* XXX Convert \n's to \r\n's XXX */
2055 int len = strlen(text);
2057 snprintf(clen, sizeof(clen), "%d", len);
2058 add_header(req, "Content-Type", "text/plain");
2059 add_header(req, "Content-Length", clen);
2060 add_line(req, text);
2064 static int add_digit(struct sip_request *req, char digit)
2069 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2071 snprintf(clen, sizeof(clen), "%d", len);
2072 add_header(req, "Content-Type", "application/dtmf-relay");
2073 add_header(req, "Content-Length", clen);
2078 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
2082 int alreadysent = 0;
2084 struct sockaddr_in sin;
2085 struct sip_codec_pref *cur;
2094 struct sockaddr_in dest;
2095 /* XXX We break with the "recommendation" and send our IP, in order that our
2096 peer doesn't have to gethostbyname() us XXX */
2099 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2102 ast_rtp_get_us(p->rtp, &sin);
2104 ast_rtp_get_peer(rtp, &dest);
2106 dest.sin_addr = p->ourip;
2107 dest.sin_port = sin.sin_port;
2110 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2111 snprintf(v, sizeof(v), "v=0\r\n");
2112 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2113 snprintf(s, sizeof(s), "s=session\r\n");
2114 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2115 snprintf(t, sizeof(t), "t=0 0\r\n");
2116 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2117 /* Start by sending our preferred codecs */
2120 if (p->capability & cur->codec) {
2122 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2123 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2125 snprintf(costr, sizeof(costr), " %d", codec);
2127 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2131 alreadysent |= cur->codec;
2134 /* Now send any other common codecs, and non-codec formats: */
2135 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2136 if ((p->capability & x) && !(alreadysent & x)) {
2138 ast_verbose("Answering with capability %d\n", x);
2139 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2141 snprintf(costr, sizeof(costr), " %d", codec);
2143 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2148 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2149 if (p->noncodeccapability & x) {
2151 ast_verbose("Answering with non-codec capability %d\n", x);
2152 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2154 snprintf(costr, sizeof(costr), " %d", codec);
2156 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2158 if (x == AST_RTP_DTMF) {
2159 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2160 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2168 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2169 snprintf(costr, sizeof(costr), "%d", len);
2170 add_header(resp, "Content-Type", "application/sdp");
2171 add_header(resp, "Content-Length", costr);
2182 static void copy_request(struct sip_request *dst,struct sip_request *src)
2186 offset = ((void *)dst) - ((void *)src);
2187 /* First copy stuff */
2188 memcpy(dst, src, sizeof(*dst));
2189 /* Now fix pointer arithmetic */
2190 for (x=0;x<src->headers;x++)
2191 dst->header[x] += offset;
2192 for (x=0;x<src->lines;x++)
2193 dst->line[x] += offset;
2196 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2198 struct sip_request resp;
2200 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2201 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2204 respprep(&resp, p, msg, req);
2205 add_sdp(&resp, p, NULL);
2206 return send_response(p, &resp, retrans, seqno);
2209 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2211 struct sip_request resp;
2212 if (p->canreinvite == REINVITE_UPDATE)
2213 reqprep(&resp, p, "UPDATE", 1);
2215 reqprep(&resp, p, "INVITE", 1);
2216 add_sdp(&resp, p, rtp);
2217 return send_request(p, &resp, 1, p->ocseq);
2220 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2227 char *l = callerid, *n=NULL;
2228 if (p->owner && p->owner->callerid) {
2229 strcpy(cid, p->owner->callerid);
2230 ast_callerid_parse(cid, &n, &l);
2232 ast_shrink_phone_number(l);
2233 if (!l || !ast_isphonenumber(l))
2238 if (ourport != 5060)
2239 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), ourport, p->tag);
2241 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2243 if (strlen(p->username)) {
2244 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2245 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2247 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2249 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2250 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2252 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
2254 /* If there is a VXML URL append it to the SIP URL */
2257 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2261 snprintf(to, sizeof(to), "<%s>", invite );
2263 memset(req, 0, sizeof(struct sip_request));
2264 init_req(req, cmd, invite);
2265 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2267 add_header(req, "Via", p->via);
2268 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2269 * OTOH, then we won't have anything in p->route anyway */
2270 add_header(req, "From", from);
2272 char contact2[256] ="", *c, contact[256];
2273 /* XXX This isn't exactly right and it's implemented
2274 very stupidly *sigh* XXX */
2275 strncpy(contact2, from, sizeof(contact2)-1);
2276 c = ditch_braces(contact2);
2277 snprintf(contact, sizeof(contact), "<%s>", c);
2278 add_header(req, "Contact", contact);
2280 add_header(req, "To", to);
2281 add_header(req, "Call-ID", p->callid);
2282 add_header(req, "CSeq", tmp);
2283 add_header(req, "User-Agent", "Asterisk PBX");
2286 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2288 struct sip_request req;
2289 initreqprep(&req, p, cmd, vxml_url);
2291 add_header(&req, "Proxy-Authorization", auth);
2293 add_sdp(&req, p, NULL);
2295 add_header(&req, "Content-Length", "0");
2296 add_blank_header(&req);
2298 if (!p->initreq.headers) {
2299 /* Use this as the basis */
2300 copy_request(&p->initreq, &req);
2303 p->lastinvite = p->ocseq;
2304 return send_request(p, &req, 1, p->ocseq);
2307 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2310 char from[256], to[256];
2313 struct sip_request req;
2316 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2318 c = ditch_braces(from);
2319 if (strncmp(c, "sip:", 4)) {
2320 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2323 if ((a = strchr(c, ';'))) {
2328 reqprep(&req, p, "NOTIFY", 1);
2330 if (p->subscribed == 1) {
2331 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2333 c = ditch_braces(to);
2334 if (strncmp(c, "sip:", 4)) {
2335 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2338 if ((a = strchr(c, ';'))) {
2343 add_header(&req, "Content-Type", "application/xpidf+xml");
2345 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2347 else if (state==AST_EXTENSION_INUSE)
2353 sprintf(t, "<?xml version=\"1.0\"?>\n");
2354 t = tmp + strlen(tmp);
2355 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2356 t = tmp + strlen(tmp);
2357 sprintf(t, "<presence>\n");
2358 t = tmp + strlen(tmp);
2359 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2360 t = tmp + strlen(tmp);
2361 sprintf(t, "<atom id=\"%s\">\n", p->exten);
2362 t = tmp + strlen(tmp);
2363 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2364 t = tmp + strlen(tmp);
2365 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2366 t = tmp + strlen(tmp);
2367 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2368 t = tmp + strlen(tmp);
2369 sprintf(t, "</address>\n</atom>\n</presence>\n");
2371 add_header(&req, "Event", "dialog");
2372 add_header(&req, "Content-Type", "application/dialog-info+xml");
2375 sprintf(t, "<?xml version=\"1.0\"?>\n");
2376 t = tmp + strlen(tmp);
2377 sprintf(t, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mfrom);
2378 t = tmp + strlen(tmp);
2379 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2380 t = tmp + strlen(tmp);
2381 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2382 t = tmp + strlen(tmp);
2383 sprintf(t, "</dialog>\n</dialog-info>\n");
2386 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2387 add_header(&req, "Content-Length", clen);
2388 add_line(&req, tmp);
2390 return send_request(p, &req, 1, p->ocseq);
2393 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2395 struct sip_request req;
2399 initreqprep(&req, p, "NOTIFY", NULL);
2400 add_header(&req, "Event", "message-summary");
2401 add_header(&req, "Content-Type", "application/simple-message-summary");
2403 snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", newmsgs ? "yes" : "no");
2404 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2405 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2406 add_header(&req, "Content-Length", clen);
2407 add_line(&req, tmp);
2408 add_line(&req, tmp2);
2410 if (!p->initreq.headers) {
2411 /* Use this as the basis */
2412 copy_request(&p->initreq, &req);
2416 return send_request(p, &req, 1, p->ocseq);
2419 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2421 static int sip_reregister(void *data)
2423 /* if we are here, we know that we need to reregister. */
2424 struct sip_registry *r=(struct sip_registry *)data;
2425 return sip_do_register(r);
2430 static int sip_do_register(struct sip_registry *r)
2433 ast_pthread_mutex_lock(&r->lock);
2434 res=transmit_register(r, "REGISTER", NULL);
2435 ast_pthread_mutex_unlock(&r->lock);
2439 static int sip_reg_timeout(void *data)
2441 /* if we are here, our registration timed out, so we'll just do it over */
2442 struct sip_registry *r=data;
2444 ast_pthread_mutex_lock(&r->lock);
2445 ast_log(LOG_NOTICE, "Registration timed out, trying again\n");
2446 r->regstate=REG_STATE_UNREGISTERED;
2447 /* cancel ourselves first!!! */
2448 /* ast_sched_del(sched,r->timeout); */
2449 res=transmit_register(r, "REGISTER", NULL);
2450 ast_pthread_mutex_unlock(&r->lock);
2454 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2456 struct sip_request req;
2463 /* exit if we are already in process with this registrar ?*/
2464 if ( r == NULL || (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2465 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2471 if (!r->callid_valid) {
2472 build_callid(r->callid, sizeof(r->callid), __ourip);
2475 p=sip_alloc( r->callid, &r->addr, 0);
2479 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2480 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2481 strncpy(p->username, r->username, sizeof(p->username)-1);
2484 /* set up a timeout */
2485 if (auth==NULL && !r->timeout) {
2486 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2487 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2490 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2491 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2493 snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2495 memset(&req, 0, sizeof(req));
2496 init_req(&req, cmd, addr);
2498 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2500 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2501 add_header(&req, "Via", via);
2502 add_header(&req, "From", from);
2503 add_header(&req, "To", to);
2506 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2507 add_header(&req, "Contact", contact);
2509 add_header(&req, "Call-ID", p->callid);
2510 add_header(&req, "CSeq", tmp);
2511 add_header(&req, "User-Agent", "Asterisk PBX");
2513 add_header(&req, "Authorization", auth);
2515 snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2516 add_header(&req, "Expires", tmp);
2517 add_header(&req, "Event", "registration");
2518 add_header(&req, "Content-length", "0");
2519 add_blank_header(&req);
2520 copy_request(&p->initreq, &req);
2521 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2522 return send_request(p, &req, 1, p->ocseq);
2525 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2527 struct sip_request req;
2528 reqprep(&req, p, "MESSAGE", 1);
2529 add_text(&req, text);
2530 return send_request(p, &req, 1, p->ocseq);
2533 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2535 struct sip_request req;
2536 reqprep(&req, p, "INFO", 1);
2537 add_digit(&req, digit);
2538 return send_request(p, &req, 1, p->ocseq);
2541 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable)
2543 struct sip_request resp;
2544 reqprep(&resp, p, msg, inc);
2545 add_header(&resp, "Content-Length", "0");
2546 add_blank_header(&resp);
2547 return send_request(p, &resp, reliable, p->ocseq);
2550 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable)
2552 struct sip_request resp;
2553 reqprep(&resp, p, msg, inc);
2557 memset(digest,0,sizeof(digest));
2558 build_reply_digest(p, msg, digest, sizeof(digest));
2559 add_header(&resp, "Proxy-Authorization", digest);
2562 add_header(&resp, "Content-Length", "0");
2563 add_blank_header(&resp);
2564 return send_request(p, &resp, reliable, p->ocseq);
2567 static int expire_register(void *data)
2569 struct sip_peer *p = data;
2570 memset(&p->addr, 0, sizeof(p->addr));
2572 ast_device_state_changed("SIP/%s", p->name);
2576 static int sip_poke_peer(struct sip_peer *peer);
2578 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2580 char contact[80]= "";
2581 char *expires = get_header(req, "Expires");
2582 int expirey = atoi(expires);
2586 struct sockaddr_in oldsin;
2587 if (!strlen(expires)) {
2588 expires = strstr(get_header(req, "Contact"), "expires=");
2590 if (sscanf(expires + 8, "%d;", &expirey) != 1)
2593 /* Look for brackets */
2594 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2597 if ((n=strchr(c, '<'))) {
2600 /* Lose the part after the > */
2604 if (!strcasecmp(c, "*") || !expirey) {
2605 /* This means remove all registrations and return OK */
2606 memset(&p->addr, 0, sizeof(p->addr));
2608 ast_sched_del(sched, p->expire);
2610 if (option_verbose > 2)
2611 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
2614 /* Make sure it's a SIP URL */
2615 if (strncasecmp(c, "sip:", 4)) {
2616 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2632 pt = strchr(n, ':');
2638 port = DEFAULT_SIP_PORT;
2639 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2641 /* XXX This could block for a long time XXX */
2642 hp = gethostbyname(n);
2644 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2647 p->addr.sin_family = AF_INET;
2648 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2649 p->addr.sin_port = htons(port);
2651 /* Don't trust the contact field. Just use what they came to us
2653 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2656 strncpy(p->username, c, sizeof(p->username) - 1);
2658 strcpy(p->username, "");
2660 ast_sched_del(sched, p->expire);
2661 if ((expirey < 1) || (expirey > max_expirey))
2662 expirey = max_expirey;
2663 p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2664 pvt->expirey = expirey;
2665 if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2667 if (option_verbose > 2)
2668 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);
2673 static void free_old_route(struct sip_route *route)
2675 struct sip_route *next;
2683 static void list_route(struct sip_route *route)
2686 ast_verbose("list_route: no route\n");
2690 ast_verbose("list_route: hop: <%s>\n", route->hop);
2691 route = route->next;
2695 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
2697 struct sip_route *thishop, *head, *tail;
2700 char *rr, *contact, *c;
2703 free_old_route(p->route);
2706 /* We build up head, then assign it to p->route when we're done */
2707 head = NULL; tail = head;
2708 /* 1st we pass through all the hops in any Record-Route headers */
2710 /* Each Record-Route header */
2711 rr = __get_header(req, "Record-Route", &start);
2712 if (*rr == '\0') break;
2714 /* Each route entry */
2716 rr = strchr(rr, '<');
2717 if (!rr) break; /* No more hops */
2719 len = strcspn(rr, ">");
2720 /* Make a struct route */
2721 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2723 strncpy(thishop->hop, rr, len);
2724 thishop->hop[len] = '\0';
2725 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
2728 /* Link in at head so they end up in reverse order */
2729 thishop->next = head;
2731 /* If this was the first then it'll be the tail */
2732 if (!tail) tail = thishop;
2734 thishop->next = NULL;
2735 /* Link in at the end */
2737 tail->next = thishop;
2746 /* 2nd append the Contact: if there is one */
2747 /* Can be multiple Contact headers, comma separated values - we just take the first */
2748 contact = get_header(req, "Contact");
2749 if (strlen(contact)) {
2750 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
2751 /* Look for <: delimited address */
2752 c = strchr(contact, '<');
2756 len = strcspn(c, ">");
2758 /* No <> - just take the lot */
2759 c = contact; len = strlen(contact);
2761 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2763 strncpy(thishop->hop, c, len);
2764 thishop->hop[len] = '\0';
2765 thishop->next = NULL;
2766 /* Goes at the end */
2768 tail->next = thishop;
2773 /* Store as new route */
2776 /* For debugging dump what we ended up with */
2778 list_route(p->route);
2781 static void md5_hash(char *output, char *input)
2783 struct MD5Context md5;
2784 unsigned char digest[16];
2788 MD5Update(&md5, input, strlen(input));
2789 MD5Final(digest, &md5);
2792 ptr += sprintf(ptr, "%2.2x", digest[x]);
2795 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri, int reliable)
2798 /* Always OK if no secret */
2799 if (!strlen(secret))
2801 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2802 snprintf(randdata, randlen, "%08x", rand());
2803 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2804 /* Schedule auto destroy in 15 seconds */
2805 sip_scheddestroy(p, 15000);
2808 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2809 an example in the spec of just what it is you're doing a hash on. */
2815 char resp_hash[256];
2821 /* Find their response among the mess that we'r sent for comparison */
2822 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2826 while (*c && (*c < 33)) c++;
2829 if (!strncasecmp(c, "response=", strlen("response="))) {
2830 c+= strlen("response=");
2833 if((c = strchr(c,'\"')))
2838 if((c = strchr(c,',')))
2842 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2846 if((c = strchr(c,'\"')))
2850 if((c = strchr(c,',')))
2859 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2860 if(strlen(resp_uri))
2861 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2863 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2864 md5_hash(a1_hash, a1);
2865 md5_hash(a2_hash, a2);
2866 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2867 md5_hash(resp_hash, resp);
2869 /* resp_hash now has the expected response, compare the two */
2871 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2875 /* Assume success ;-) */
2876 /* Eliminate random data */
2877 strcpy(randdata, "");
2882 static int cb_extensionstate(char *context, char* exten, int state, void *data)
2884 struct sip_pvt *p = data;
2886 sip_scheddestroy(p, 15000);
2891 transmit_state_notify(p, state, 1);
2894 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
2898 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2901 struct sip_peer *peer;
2907 while(*t && (*t > 32) && (*t != ';'))
2911 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2912 c = ditch_braces(tmp);
2913 if (!strncmp(c, "sip:", 4)) {
2917 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2919 c = strchr(name, '@');
2922 ast_pthread_mutex_lock(&peerl.lock);
2925 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2927 transmit_response(p, "100 Trying", req);
2928 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
2929 sip_cancel_destroy(p);
2930 if (parse_contact(p, peer, req)) {
2931 ast_log(LOG_WARNING, "Failed to parse contact info\n");
2933 /* Say OK and ask subsystem to retransmit msg counter */
2934 transmit_response_with_date(p, "200 OK", req);
2935 peer->lastmsgssent = -1;
2943 ast_pthread_mutex_unlock(&peerl.lock);
2945 ast_device_state_changed("SIP/%s", peer->name);
2948 transmit_response(p, "401 Unauthorized", &p->initreq);
2952 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2954 char tmp[256] = "", *c, *a;
2955 struct sip_request *req;
2960 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2961 c = ditch_braces(tmp);
2962 if (strncmp(c, "sip:", 4)) {
2963 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2967 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2971 ast_verbose("Looking for %s in %s\n", c, p->context);
2972 if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2974 strncpy(p->exten, c, sizeof(p->exten) - 1);
2978 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2985 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2987 char tmp[256] = "", *c, *a;
2988 char tmp2[256] = "", *c2, *a2;
2991 char tmp5[256] = ""; /* CallID to replace */
2992 struct sip_request *req;
2998 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2999 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
3000 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
3001 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
3003 c = ditch_braces(tmp);
3004 c2 = ditch_braces(tmp2);
3007 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
3008 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3009 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
3014 if ((a = strchr(c, '?'))) {
3015 /* Search for arguemnts */
3018 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
3019 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
3020 if ((a = strchr(tmp5, '%'))) {
3021 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
3023 if ((a[1] == '4') && (a[2] == '0')) {
3025 memmove(a + 1, a+3, strlen(a + 3));
3028 if ((a = strchr(tmp5, '%')))
3033 if ((a = strchr(c, '@')))
3035 if ((a = strchr(c, ';')))
3039 if ((a2 = strchr(c2, '@')))
3042 if ((a2 = strchr(c2, ';')))
3047 ast_verbose("Looking for %s in %s\n", c, p->context);
3048 ast_verbose("Looking for %s in %s\n", c2, p->context);
3051 /* This is a supervised transfer */
3052 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
3054 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
3055 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
3056 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
3057 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
3058 p->refer_call = NULL;
3059 ast_pthread_mutex_lock(&iflock);
3060 /* Search interfaces and find the match */
3063 if (!strcmp(p2->callid, tmp5)) {
3064 /* Go ahead and lock it before returning */
3065 ast_pthread_mutex_lock(&p2->lock);
3071 ast_pthread_mutex_unlock(&iflock);
3075 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
3076 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3077 /* This is an unsupervised transfer */
3078 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
3079 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
3080 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
3081 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
3082 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
3083 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
3084 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
3085 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
3086 p->refer_call = NULL;
3088 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
3096 static int check_via(struct sip_pvt *p, struct sip_request *req)
3102 memset(via, 0, sizeof(via));
3103 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
3104 c = strchr(via, ';');
3107 c = strchr(via, ' ');
3111 while(*c && (*c < 33))
3113 if (strcmp(via, "SIP/2.0/UDP")) {
3114 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
3117 pt = strchr(c, ':');
3122 hp = gethostbyname(c);
3124 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
3127 memset(&p->sa, 0, sizeof(p->sa));
3128 p->sa.sin_family = AF_INET;
3129 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
3130 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
3133 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3135 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3141 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri, int reliable)
3143 struct sip_user *user;
3144 struct sip_peer *peer;
3145 char *of, from[256] = "", *c;
3150 while(*t && (*t > 32) && (*t != ';'))
3153 of = get_header(req, "From");
3154 strncpy(from, of, sizeof(from) - 1);
3155 of = ditch_braces(from);
3156 if (strncmp(of, "sip:", 4)) {
3157 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3160 /* Get just the username part */
3161 if ((c = strchr(of, '@')))
3163 if ((c = strchr(of, ':')))
3165 strncpy(p->callerid, of, sizeof(p->callerid) - 1);
3168 ast_pthread_mutex_lock(&userl.lock);
3171 if (!strcasecmp(user->name, of)) {
3174 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
3175 ast_rtp_setnat(p->rtp, p->nat);
3177 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri, reliable))) {
3178 sip_cancel_destroy(p);
3179 strncpy(p->context, user->context, sizeof(p->context) - 1);
3180 if (strlen(user->callerid) && strlen(p->callerid))
3181 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
3182 strncpy(p->username, user->name, sizeof(p->username) - 1);
3183 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
3184 p->canreinvite = user->canreinvite;
3185 p->amaflags = user->amaflags;
3186 if (user->dtmfmode) {
3187 p->dtmfmode = user->dtmfmode;
3188 if (p->dtmfmode & SIP_DTMF_RFC2833)
3189 p->noncodeccapability |= AST_RTP_DTMF;
3191 p->noncodeccapability &= ~AST_RTP_DTMF;
3198 ast_pthread_mutex_unlock(&userl.lock);
3200 /* If we didn't find a user match, check for peers */
3201 ast_pthread_mutex_lock(&peerl.lock);
3204 if (!memcmp(&peer->addr, &p->recv, sizeof(peer->addr))) {
3208 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
3209 ast_rtp_setnat(p->rtp, p->nat);
3211 p->canreinvite = peer->canreinvite;
3212 strncpy(p->username, peer->name, sizeof(p->username) - 1);
3213 if (peer->dtmfmode) {
3214 p->dtmfmode = peer->dtmfmode;
3215 if (p->dtmfmode & SIP_DTMF_RFC2833)
3216 p->noncodeccapability |= AST_RTP_DTMF;
3218 p->noncodeccapability &= ~AST_RTP_DTMF;
3224 ast_pthread_mutex_unlock(&peerl.lock);
3229 static int get_msg_text(char *buf, int len, struct sip_request *req)
3233 for (x=0;x<req->lines;x++) {
3234 strncat(buf, req->line[x], len - strlen(buf) - 5);
3240 static void receive_message(struct sip_pvt *p, struct sip_request *req)
3244 if (get_msg_text(buf, sizeof(buf), req)) {
3245 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
3250 ast_verbose("Message received: '%s'\n", buf);
3251 memset(&f, 0, sizeof(f));
3252 f.frametype = AST_FRAME_TEXT;
3256 f.datalen = strlen(buf);
3257 ast_queue_frame(p->owner, &f, 0);
3261 static int sip_show_users(int fd, int argc, char *argv[])
3263 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
3264 struct sip_user *user;
3266 return RESULT_SHOWUSAGE;
3267 ast_pthread_mutex_lock(&userl.lock);
3268 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
3269 for(user=userl.users;user;user=user->next) {
3270 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
3272 user->ha ? "Yes" : "No");
3274 ast_pthread_mutex_unlock(&userl.lock);
3275 return RESULT_SUCCESS;
3279 static int sip_show_peers(int fd, int argc, char *argv[])
3281 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
3282 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
3283 struct sip_peer *peer;
3284 char name[256] = "";
3286 return RESULT_SHOWUSAGE;
3287 ast_pthread_mutex_lock(&peerl.lock);
3288 ast_cli(fd, FORMAT2, "Name/username", "Host", " ", "Mask", "Port", "Status");
3289 for (peer = peerl.peers;peer;peer = peer->next) {
3292 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
3293 if (strlen(peer->username))
3294 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
3296 strncpy(name, peer->name, sizeof(name) - 1);
3298 if (peer->lastms < 0)
3299 strcpy(status, "UNREACHABLE");
3300 else if (peer->lastms > peer->maxms)
3301 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
3302 else if (peer->lastms)
3303 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
3305 strcpy(status, "UNKNOWN");
3307 strcpy(status, "Unmonitored");
3308 ast_cli(fd, FORMAT, name,
3309 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
3310 peer->dynamic ? "(D)" : " ",
3312 ntohs(peer->addr.sin_port), status);
3314 ast_pthread_mutex_unlock(&peerl.lock);
3315 return RESULT_SUCCESS;
3320 static char *regstate2str(int regstate)
3323 case REG_STATE_UNREGISTERED:
3324 return "Unregistered";
3325 case REG_STATE_REGSENT:
3326 return "Request Sent";
3327 case REG_STATE_AUTHSENT:
3328 return "Auth. Sent";
3329 case REG_STATE_REGISTERED:
3330 return "Registered";
3331 case REG_STATE_REJECTED:
3333 case REG_STATE_TIMEOUT:
3335 case REG_STATE_NOAUTH:
3336 return "No Authentication";
3342 static int sip_show_registry(int fd, int argc, char *argv[])
3344 #define FORMAT2 "%-20.20s %-10.10s %8.8s %-20.20s\n"
3345 #define FORMAT "%-20.20s %-10.10s %8d %-20.20s\n"
3346 struct sip_registry *reg;
3349 return RESULT_SHOWUSAGE;
3350 ast_pthread_mutex_lock(&peerl.lock);
3351 ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
3352 for (reg = registrations;reg;reg = reg->next) {
3353 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
3354 ast_cli(fd, FORMAT, host,
3355 reg->username, reg->refresh, regstate2str(reg->regstate));
3357 ast_pthread_mutex_unlock(&peerl.lock);
3358 return RESULT_SUCCESS;
3363 static int sip_show_channels(int fd, int argc, char *argv[])
3365 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
3366 #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
3367 struct sip_pvt *cur;
3370 return RESULT_SHOWUSAGE;
3371 ast_pthread_mutex_lock(&iflock);
3373 ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
3375 if (!cur->subscribed) {
3376 ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr),
3377 strlen(cur->username) ? cur->username : "(None)",
3379 cur->ocseq, cur->icseq,
3382 cur->owner ? cur->owner->nativeformats : 0);
3387 ast_pthread_mutex_unlock(&iflock);
3388 ast_cli(fd, "%d active SIP channel(s)\n", numchans);
3389 return RESULT_SUCCESS;
3394 static char *complete_sipch(char *line, char *word, int pos, int state)
3397 struct sip_pvt *cur;
3399 ast_pthread_mutex_lock(&iflock);
3402 if (!strncasecmp(word, cur->callid, strlen(word))) {
3403 if (++which > state) {
3404 c = strdup(cur->callid);
3410 ast_pthread_mutex_unlock(&iflock);
3414 static int sip_show_channel(int fd, int argc, char *argv[])
3416 struct sip_pvt *cur;
3419 return RESULT_SHOWUSAGE;
3420 ast_pthread_mutex_lock(&iflock);
3423 if (!strcasecmp(cur->callid, argv[3])) {
3424 ast_cli(fd, "Call-ID: %s\n", cur->callid);
3425 ast_cli(fd, "Codec Capability: %d\n", cur->capability);
3426 ast_cli(fd, "Non-Codec Capability: %d\n", cur->noncodeccapability);
3427 ast_cli(fd, "Theoretical Address: %s:%d\n", inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
3428 ast_cli(fd, "Received Address: %s:%d\n", inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
3429 ast_cli(fd, "NAT Support: %s\n", cur->nat ? "Yes" : "No");
3430 ast_cli(fd, "Our Tag: %08d\n", cur->tag);
3431 ast_cli(fd, "Their Tag: %s\n", cur->theirtag);
3433 if (cur->dtmfmode & SIP_DTMF_RFC2833)
3434 strcat(tmp, "rfc2833 ");
3435 if (cur->dtmfmode & SIP_DTMF_INFO)
3436 strcat(tmp, "info ");
3437 if (cur->dtmfmode & SIP_DTMF_INBAND)
3438 strcat(tmp, "inband ");
3439 ast_cli(fd, "DTMF Mode: %s\n", tmp);
3444 ast_pthread_mutex_unlock(&iflock);
3446 ast_cli(fd, "No such SIP Call ID '%s'\n", argv[3]);
3447 return RESULT_SUCCESS;
3450 static void receive_info(struct sip_pvt *p, struct sip_request *req)
3452 char buf[1024] = "";
3455 /* Try getting the "signal=" part */
3456 if ((c = get_sdp(req, "Signal"))) {
3457 strncpy(buf, c, sizeof(buf) - 1);
3458 } else if (get_msg_text(buf, sizeof(buf), req)) {
3459 /* Normal INFO method */
3460 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
3467 ast_verbose("DTMF received: '%c'\n", buf[0]);
3468 memset(&f, 0, sizeof(f));
3469 f.frametype = AST_FRAME_DTMF;
3470 f.subclass = buf[0];
3474 ast_queue_frame(p->owner, &f, 0);
3479 static int sip_do_debug(int fd, int argc, char *argv[])
3482 return RESULT_SHOWUSAGE;
3484 ast_cli(fd, "SIP Debugging Enabled\n");
3485 return RESULT_SUCCESS;
3488 static int sip_no_debug(int fd, int argc, char *argv[])
3491 return RESULT_SHOWUSAGE;
3493 ast_cli(fd, "SIP Debugging Disabled\n");
3494 return RESULT_SUCCESS;
3497 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
3499 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
3501 memset(digest,0,sizeof(digest));
3502 reply_digest(p,req, "WWW-Authenticate", "REGISTER", digest, sizeof(digest) );
3503 return transmit_register(p->registry,"REGISTER",digest);
3506 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
3508 memset(digest,0,sizeof(digest));
3509 reply_digest(p,req, "Proxy-Authenticate", "INVITE", digest, sizeof(digest) );
3510 return transmit_invite(p,"INVITE",1,digest, NULL);
3513 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
3521 strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
3523 c+=strlen("Digest ");
3525 while (*c && (*c < 33)) c++;
3528 if (!strncasecmp(c,"realm=", strlen("realm="))) {
3529 c+=strlen("realm=");
3532 if ((c = strchr(c,'\"')))
3536 if ((c = strchr(c,',')))
3539 } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
3540 c+=strlen("nonce=");
3543 if ((c = strchr(c,'\"')))
3547 if ((c = strchr(c,',')))
3556 /* copy realm and nonce for later authorization of CANCELs and BYEs */
3557 strncpy(p->realm, realm, sizeof(p->realm)-1);
3558 strncpy(p->nonce, nonce, sizeof(p->nonce)-1);
3560 build_reply_digest(p, orig_header, digest, digest_len);
3564 static int build_reply_digest(struct sip_pvt *p, char* orig_header, char* digest, int digest_len)