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 <asterisk/parking.h>
38 #include <asterisk/acl.h>
39 #include <sys/socket.h>
40 #include <sys/ioctl.h>
47 #include <arpa/inet.h>
48 #include <sys/signal.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
53 #define IPTOS_MINCOST 0x02
56 /* #define VOCAL_DATA_HACK */
59 #define DEFAULT_DEFAULT_EXPIRY 120
60 #define DEFAULT_MAX_EXPIRY 3600
61 #define EXPIRY_GUARD_SECS 15
63 #define SIP_DTMF_RFC2833 (1 << 0)
64 #define SIP_DTMF_INBAND (1 << 1)
65 #define SIP_DTMF_INFO (1 << 2)
67 static int max_expiry = DEFAULT_MAX_EXPIRY;
68 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
70 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
72 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
73 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
74 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
76 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
77 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
79 static char *desc = "Session Initiation Protocol (SIP)";
80 static char *type = "sip";
81 static char *tdesc = "Session Initiation Protocol (SIP)";
82 static char *config = "sip.conf";
84 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
85 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
87 static char context[AST_MAX_EXTENSION] = "default";
89 static char language[MAX_LANGUAGE] = "";
91 static char callerid[AST_MAX_EXTENSION] = "asterisk";
93 static char fromdomain[AST_MAX_EXTENSION] = "";
95 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
98 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
100 /* Protect the interface list (of sip_pvt's) */
101 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
103 /* Protect the monitoring thread, so only one process can kill or start it, and not
104 when it's doing something critical. */
105 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
107 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
109 /* This is the thread for the monitor which checks for input on the channels
110 which are not currently in use. */
111 static pthread_t monitor_thread = 0;
113 static int restart_monitor(void);
115 /* Codecs that we support by default: */
116 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
117 static int noncodeccapability = AST_RTP_DTMF;
119 static char ourhost[256];
120 static struct in_addr __ourip;
123 static int sipdebug = 0;
127 static int globaldtmfmode = SIP_DTMF_RFC2833;
130 static int expiry = 900;
132 static struct sched_context *sched;
133 static struct io_context *io;
134 /* The private structures of the sip channels are linked for
135 selecting outgoing channels */
137 #define SIP_MAX_HEADERS 64
138 #define SIP_MAX_LINES 64
140 static struct sip_codec_pref {
142 struct sip_codec_pref *next;
146 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
147 char *rlPart2; /* The Request URI or Response Status */
149 int headers; /* SIP Headers */
150 char *header[SIP_MAX_HEADERS];
151 int lines; /* SDP Content */
152 char *line[SIP_MAX_LINES];
153 char data[SIP_MAX_PACKET];
159 struct sip_route *next;
163 static struct sip_pvt {
164 pthread_mutex_t lock; /* Channel private lock */
165 char callid[80]; /* Global CallID */
166 char randdata[80]; /* Random data */
167 unsigned int ocseq; /* Current outgoing seqno */
168 unsigned int icseq; /* Current incoming seqno */
169 unsigned int callgroup;
170 unsigned int pickupgroup;
171 int lastinvite; /* Last Cseq of invite */
172 int alreadygone; /* Whether or not we've already been destroyed by or peer */
173 int needdestroy; /* if we need to be destroyed */
174 int capability; /* Special capability */
175 int noncodeccapability;
176 int outgoing; /* Outgoing or incoming call? */
177 int authtries; /* Times we've tried to authenticate */
178 int insecure; /* Don't check source port/ip */
179 int expiry; /* How long we take to expire */
180 int branch; /* One random number */
181 int canreinvite; /* Do we support reinvite */
182 int ringing; /* Have sent 180 ringing */
183 int progress; /* Have sent 183 message progress */
184 int tag; /* Another random number */
185 int nat; /* Whether to try to support NAT */
186 struct sockaddr_in sa; /* Our peer */
187 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
188 struct sockaddr_in recv; /* Received as */
189 struct in_addr ourip; /* Our IP */
190 struct ast_channel *owner; /* Who owns us */
191 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
192 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
193 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
194 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
195 struct sip_pvt *refer_call; /* Call we are referring */
196 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
197 char remote_party_id[256];
198 char context[AST_MAX_EXTENSION];
199 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
200 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
201 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
202 char language[MAX_LANGUAGE];
203 char rdnis[256]; /* Referring DNIS */
204 char theirtag[256]; /* Their tag */
207 char uri[81]; /* Original requested URI */
209 char callerid[256]; /* Caller*ID */
211 char accountcode[20]; /* Account code */
212 char our_contact[256]; /* Our contact header */
213 char realm[256]; /* Authorization realm */
214 char nonce[256]; /* Authorization nonce */
215 int amaflags; /* AMA Flags */
216 int pendinginvite; /* Any pending invite */
217 int pendingbye; /* Need to send bye after we ack? */
218 struct sip_request initreq; /* Initial request */
220 int maxtime; /* Max time for first response */
221 int initid; /* Auto-congest ID if appropriate */
222 int autokillid; /* Auto-kill ID */
231 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
232 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
233 struct ast_rtp *rtp; /* RTP Session */
234 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
235 struct sip_pvt *next;
239 struct sip_pkt *next; /* Next packet */
240 int retrans; /* Retransmission number */
241 int seqno; /* Sequence number */
242 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
243 struct sip_pvt *owner; /* Owner call */
244 int retransid; /* Retransmission ID */
245 int packetlen; /* Length of packet */
250 /* Users who can access various contexts */
256 char accountcode[20];
257 unsigned int callgroup;
258 unsigned int pickupgroup;
266 struct sip_user *next;
272 char context[80]; /* JK02: peers need context too to allow parking etc */
278 char mailbox[AST_MAX_EXTENSION];
288 unsigned int callgroup;
289 unsigned int pickupgroup;
291 struct sockaddr_in addr;
295 struct sip_pvt *call; /* Call pointer */
296 int pokeexpire; /* When to expire poke */
297 int lastms; /* How long last response took (in ms), or -1 for no response */
298 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
299 struct timeval ps; /* Ping send time */
301 struct sockaddr_in defaddr;
305 struct sip_peer *next;
308 static struct ast_user_list {
309 struct sip_user *users;
310 pthread_mutex_t lock;
311 } userl = { NULL, AST_MUTEX_INITIALIZER };
313 static struct ast_peer_list {
314 struct sip_peer *peers;
315 pthread_mutex_t lock;
316 } peerl = { NULL, AST_MUTEX_INITIALIZER };
319 #define REG_STATE_UNREGISTERED 0
320 #define REG_STATE_REGSENT 1
321 #define REG_STATE_AUTHSENT 2
322 #define REG_STATE_REGISTERED 3
323 #define REG_STATE_REJECTED 4
324 #define REG_STATE_TIMEOUT 5
325 #define REG_STATE_NOAUTH 6
327 struct sip_registry {
328 pthread_mutex_t lock; /* Channel private lock */
329 struct sockaddr_in addr; /* Who we connect to for registration purposes */
330 char username[80]; /* Who we are registering as */
331 char authuser[80]; /* Who we *authenticate* as */
333 char secret[80]; /* Password or key name in []'s */
334 char contact[80]; /* Contact extension */
336 int expire; /* Sched ID of expiration */
337 int timeout; /* sched id of sip_reg_timeout */
338 int refresh; /* How often to refresh */
339 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
341 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
342 char callid[80]; /* Global CallID for this registry */
343 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
344 struct sockaddr_in us; /* Who the server thinks we are */
345 struct sip_registry *next;
348 #define REINVITE_INVITE 1
349 #define REINVITE_UPDATE 2
351 static int sip_do_register(struct sip_registry *r);
352 static struct sip_registry *registrations;
354 static int sipsock = -1;
355 static int globalnat = 0;
356 static int globalcanreinvite = REINVITE_INVITE;
359 static struct sockaddr_in bindaddr;
361 static struct ast_frame *sip_read(struct ast_channel *ast);
362 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
363 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
364 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
365 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
366 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
367 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
368 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
369 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
370 static int transmit_message_with_text(struct sip_pvt *p, char *text);
371 static int transmit_refer(struct sip_pvt *p, char *dest);
372 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
373 static char *getsipuri(char *header);
374 static void free_old_route(struct sip_route *route);
375 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
377 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
381 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
383 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
385 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));
390 static void sip_destroy(struct sip_pvt *p);
392 static int retrans_pkt(void *data)
394 struct sip_pkt *pkt=data;
396 ast_pthread_mutex_lock(&pkt->owner->lock);
397 if (1 /* !p->owner->needdestroy */) {
398 if (pkt->retrans < MAX_RETRANS) {
402 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));
404 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));
406 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
409 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
411 if (pkt->owner->owner) {
412 /* XXX Potential deadlocK?? XXX */
413 ast_queue_hangup(pkt->owner->owner, 1);
415 /* If no owner, destroy now */
416 ast_pthread_mutex_unlock(&pkt->owner->lock);
417 sip_destroy(pkt->owner);
422 /* Don't bother retransmitting. It's about to be killed anyway */
424 if (pkt->owner->owner) {
425 /* XXX Potential deadlocK?? XXX */
426 ast_queue_hangup(pkt->owner->owner, 1);
428 /* If no owner, destroy now */
429 ast_pthread_mutex_unlock(&pkt->owner->lock);
430 sip_destroy(pkt->owner);
435 ast_pthread_mutex_unlock(&pkt->owner->lock);
439 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
442 pkt = malloc(sizeof(struct sip_pkt) + len);
445 memset(pkt, 0, sizeof(struct sip_pkt));
446 memcpy(pkt->data, data, len);
447 pkt->packetlen = len;
448 pkt->next = p->packets;
452 /* Schedule retransmission */
453 pkt->retransid = ast_sched_add(sched, 1000, retrans_pkt, pkt);
454 pkt->next = p->packets;
456 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
457 if (!strncasecmp(pkt->data, "INVITE", 6)) {
458 /* Note this is a pending invite */
459 p->pendinginvite = seqno;
464 static int __sip_autodestruct(void *data)
466 struct sip_pvt *p = data;
468 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
470 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
471 ast_queue_hangup(p->owner, 0);
478 static int sip_scheddestroy(struct sip_pvt *p, int ms)
480 if (p->autokillid > -1)
481 ast_sched_del(sched, p->autokillid);
482 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
486 static int sip_cancel_destroy(struct sip_pvt *p)
488 if (p->autokillid > -1)
489 ast_sched_del(sched, p->autokillid);
494 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
496 struct sip_pkt *cur, *prev = NULL;
501 if ((cur->seqno == seqno) && (cur->resp == resp)) {
502 if (!resp && (seqno == p->pendinginvite)) {
503 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
504 p->pendinginvite = 0;
507 /* this is our baby */
509 prev->next = cur->next;
511 p->packets = cur->next;
512 if (cur->retransid > -1)
513 ast_sched_del(sched, cur->retransid);
521 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
525 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
530 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));
532 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));
535 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
537 res = __sip_xmit(p, req->data, req->len);
543 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
548 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));
550 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));
553 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
555 res = __sip_xmit(p, req->data, req->len);
559 static char *ditch_braces(char *tmp)
564 if ((n = strchr(tmp, '<')) ) {
566 while(*c && *c != '>') c++;
568 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
577 static int sip_sendtext(struct ast_channel *ast, char *text)
579 struct sip_pvt *p = ast->pvt->pvt;
581 ast_verbose("Sending text %s on %s\n", text, ast->name);
584 if (!text || !strlen(text))
587 ast_verbose("Really sending text %s on %s\n", text, ast->name);
588 transmit_message_with_text(p, text);
592 static int create_addr(struct sip_pvt *r, char *peer)
599 r->sa.sin_family = AF_INET;
600 ast_pthread_mutex_lock(&peerl.lock);
603 if (!strcasecmp(p->name, peer)) {
605 r->capability = p->capability;
608 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
609 ast_rtp_setnat(r->rtp, r->nat);
611 strncpy(r->peername, p->username, sizeof(r->peername)-1);
612 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
613 strncpy(r->username, p->username, sizeof(r->username)-1);
614 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
615 if (!strlen(r->tohost)) {
616 if (p->addr.sin_addr.s_addr)
617 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
619 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
621 if (strlen(p->fromdomain))
622 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
623 if (strlen(p->fromuser))
624 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
625 r->insecure = p->insecure;
626 r->canreinvite = p->canreinvite;
627 r->maxtime = p->maxms;
628 r->callgroup = p->callgroup;
629 r->pickupgroup = p->pickupgroup;
631 r->dtmfmode = p->dtmfmode;
632 if (r->dtmfmode & SIP_DTMF_RFC2833)
633 r->noncodeccapability |= AST_RTP_DTMF;
635 r->noncodeccapability &= ~AST_RTP_DTMF;
637 strncpy(r->context, p->context,sizeof(r->context)-1);
638 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
639 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
640 if (p->addr.sin_addr.s_addr) {
641 r->sa.sin_addr = p->addr.sin_addr;
642 r->sa.sin_port = p->addr.sin_port;
644 r->sa.sin_addr = p->defaddr.sin_addr;
645 r->sa.sin_port = p->defaddr.sin_port;
647 memcpy(&r->recv, &r->sa, sizeof(r->recv));
653 ast_pthread_mutex_unlock(&peerl.lock);
655 if ((port=strchr(peer, ':'))) {
659 hp = gethostbyname(peer);
661 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
662 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
664 r->sa.sin_port = htons(atoi(port));
666 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
668 memcpy(&r->recv, &r->sa, sizeof(r->recv));
671 ast_log(LOG_WARNING, "No such host: %s\n", peer);
680 static int auto_congest(void *nothing)
682 struct sip_pvt *p = nothing;
683 ast_pthread_mutex_lock(&p->lock);
686 if (!pthread_mutex_trylock(&p->owner->lock)) {
687 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
688 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
689 ast_pthread_mutex_unlock(&p->owner->lock);
692 ast_pthread_mutex_unlock(&p->lock);
696 static void sip_prefs_free(void)
698 struct sip_codec_pref *cur, *next;
708 static void sip_pref_remove(int format)
710 struct sip_codec_pref *cur, *prev=NULL;
713 if (cur->codec == format) {
715 prev->next = cur->next;
726 static int sip_pref_append(int format)
728 struct sip_codec_pref *cur, *tmp;
729 sip_pref_remove(format);
730 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
733 memset(tmp, 0, sizeof(struct sip_codec_pref));
745 static int sip_codec_choose(int formats)
747 struct sip_codec_pref *cur;
750 if (formats & cur->codec)
754 return ast_best_codec(formats);
757 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
761 char *vxml_url = NULL;
762 struct varshead *headp;
763 struct ast_var_t *current;
766 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
767 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
771 /* Check whether there is a VXML_URL variable */
772 headp=&ast->varshead;
773 AST_LIST_TRAVERSE(headp,current,entries) {
774 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
776 vxml_url = ast_var_value(current);
783 transmit_invite(p, "INVITE", 1, NULL, vxml_url);
785 /* Initialize auto-congest time */
786 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
791 static void __sip_destroy(struct sip_pvt *p, int lockowner)
793 struct sip_pvt *cur, *prev = NULL;
796 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
798 ast_extension_state_del(p->stateid, NULL);
800 ast_sched_del(sched, p->initid);
801 if (p->autokillid > -1)
802 ast_sched_del(sched, p->autokillid);
805 ast_rtp_destroy(p->rtp);
808 free_old_route(p->route);
811 /* Unlink us from the owner if we have one */
814 ast_pthread_mutex_lock(&p->owner->lock);
815 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
816 p->owner->pvt->pvt = NULL;
818 ast_pthread_mutex_unlock(&p->owner->lock);
824 prev->next = cur->next;
833 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
836 ast_sched_del(sched, p->initid);
837 while((cp = p->packets)) {
838 p->packets = p->packets->next;
839 if (cp->retransid > -1)
840 ast_sched_del(sched, cp->retransid);
846 static void sip_destroy(struct sip_pvt *p)
848 ast_pthread_mutex_lock(&iflock);
850 ast_pthread_mutex_unlock(&iflock);
853 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
856 static int sip_hangup(struct ast_channel *ast)
858 struct sip_pvt *p = ast->pvt->pvt;
862 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
863 if (!ast->pvt->pvt) {
864 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
867 ast_pthread_mutex_lock(&p->lock);
868 /* Determine how to disconnect */
869 if (p->owner != ast) {
870 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
871 ast_pthread_mutex_unlock(&p->lock);
874 if (!ast || (ast->_state != AST_STATE_UP))
879 ast_dsp_free(p->vad);
882 ast->pvt->pvt = NULL;
885 /* Start the process if it's not already started */
886 if (!p->alreadygone && strlen(p->initreq.data)) {
889 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
890 /* Actually don't destroy us yet, wait for the 487 on our original
891 INVITE, but do set an autodestruct just in case. */
893 sip_scheddestroy(p, 15000);
895 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
897 if (!p->pendinginvite) {
899 transmit_request_with_auth(p, "BYE", 0, 1);
901 /* Note we will need a BYE when this all settles out
902 but we can't send one while we have "INVITE" outstanding. */
907 p->needdestroy = needdestroy;
908 ast_pthread_mutex_unlock(&p->lock);
912 static int sip_answer(struct ast_channel *ast)
916 struct sip_pvt *p = ast->pvt->pvt;
919 if (ast->_state != AST_STATE_UP) {
923 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
925 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
926 fmt=ast_getformatbyname(codec);
929 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
932 ast_setstate(ast, AST_STATE_UP);
934 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
935 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
940 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
942 struct sip_pvt *p = ast->pvt->pvt;
944 if (frame->frametype != AST_FRAME_VOICE) {
945 if (frame->frametype == AST_FRAME_IMAGE)
948 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
952 if (!(frame->subclass & ast->nativeformats)) {
953 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
954 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
959 ast_pthread_mutex_lock(&p->lock);
961 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
962 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
965 res = ast_rtp_write(p->rtp, frame);
967 ast_pthread_mutex_unlock(&p->lock);
972 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
974 struct sip_pvt *p = newchan->pvt->pvt;
975 ast_pthread_mutex_lock(&p->lock);
976 if (p->owner != oldchan) {
977 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
978 ast_pthread_mutex_unlock(&p->lock);
982 ast_pthread_mutex_unlock(&p->lock);
986 static int sip_senddigit(struct ast_channel *ast, char digit)
988 struct sip_pvt *p = ast->pvt->pvt;
989 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
990 transmit_info_with_digit(p, digit);
992 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
993 ast_rtp_senddigit(p->rtp, digit);
995 /* If in-band DTMF is desired, send that */
996 if (p->dtmfmode & SIP_DTMF_INBAND)
1001 static int sip_transfer(struct ast_channel *ast, char *dest)
1003 struct sip_pvt *p = ast->pvt->pvt;
1005 res = transmit_refer(p, dest);
1009 static int sip_indicate(struct ast_channel *ast, int condition)
1011 struct sip_pvt *p = ast->pvt->pvt;
1013 case AST_CONTROL_RINGING:
1014 if (ast->_state == AST_STATE_RING) {
1015 if (!p->progress && !p->ringing) {
1016 transmit_response(p, "180 Ringing", &p->initreq);
1020 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1024 case AST_CONTROL_BUSY:
1025 if (ast->_state != AST_STATE_UP) {
1026 transmit_response(p, "486 Busy Here", &p->initreq);
1028 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1032 case AST_CONTROL_CONGESTION:
1033 if (ast->_state != AST_STATE_UP) {
1034 transmit_response(p, "503 Service Unavailable", &p->initreq);
1036 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1040 case AST_CONTROL_PROGRESS:
1041 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1042 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1050 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1058 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1060 struct ast_channel *tmp;
1062 tmp = ast_channel_alloc(1);
1064 /* Select our native format based on codec preference until we receive
1065 something from another device to the contrary. */
1067 tmp->nativeformats = sip_codec_choose(i->capability);
1069 tmp->nativeformats = sip_codec_choose(capability);
1070 fmt = ast_best_codec(tmp->nativeformats);
1072 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1074 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
1076 if (i->dtmfmode & SIP_DTMF_INBAND) {
1077 i->vad = ast_dsp_new();
1078 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1080 tmp->fds[0] = ast_rtp_fd(i->rtp);
1081 ast_setstate(tmp, state);
1082 if (state == AST_STATE_RING)
1084 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1085 tmp->writeformat = fmt;
1086 tmp->pvt->rawwriteformat = fmt;
1087 tmp->readformat = fmt;
1088 tmp->pvt->rawreadformat = fmt;
1090 tmp->pvt->send_text = sip_sendtext;
1091 tmp->pvt->call = sip_call;
1092 tmp->pvt->hangup = sip_hangup;
1093 tmp->pvt->answer = sip_answer;
1094 tmp->pvt->read = sip_read;
1095 tmp->pvt->write = sip_write;
1096 tmp->pvt->indicate = sip_indicate;
1097 tmp->pvt->transfer = sip_transfer;
1098 tmp->pvt->fixup = sip_fixup;
1099 tmp->pvt->send_digit = sip_senddigit;
1100 tmp->pvt->bridge = ast_rtp_bridge;
1101 tmp->callgroup = i->callgroup;
1102 tmp->pickupgroup = i->pickupgroup;
1103 if (strlen(i->accountcode))
1104 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1106 tmp->amaflags = i->amaflags;
1107 if (strlen(i->language))
1108 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1110 ast_pthread_mutex_lock(&usecnt_lock);
1112 ast_pthread_mutex_unlock(&usecnt_lock);
1113 ast_update_use_count();
1114 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1115 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1116 if (strlen(i->callerid))
1117 tmp->callerid = strdup(i->callerid);
1118 if (strlen(i->rdnis))
1119 tmp->rdnis = strdup(i->rdnis);
1121 if (state != AST_STATE_DOWN) {
1122 if (ast_pbx_start(tmp)) {
1123 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1129 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1133 static struct cfalias {
1137 { "Content-Type", "c" },
1138 { "Content-Encoding", "e" },
1142 { "Content-Length", "l" },
1148 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1149 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1150 char* r = line + nameLen + 1;
1151 while (*r && (*r < 33)) ++r;
1158 static char *get_sdp(struct sip_request *req, char *name) {
1160 int len = strlen(name);
1163 for (x=0; x<req->lines; x++) {
1164 r = get_sdp_by_line(req->line[x], name, len);
1165 if (r[0] != '\0') return r;
1170 static void sdpLineNum_iterator_init(int* iterator) {
1174 static char* get_sdp_iterate(int* iterator,
1175 struct sip_request *req, char *name) {
1176 int len = strlen(name);
1178 while (*iterator < req->lines) {
1179 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1180 if (r[0] != '\0') return r;
1185 static char *__get_header(struct sip_request *req, char *name, int *start)
1188 int len = strlen(name);
1190 for (x=*start;x<req->headers;x++) {
1191 if (!strncasecmp(req->header[x], name, len) &&
1192 (req->header[x][len] == ':')) {
1193 r = req->header[x] + len + 1;
1194 while(*r && (*r < 33))
1201 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1202 if (!strcasecmp(aliases[x].fullname, name))
1203 return __get_header(req, aliases[x].shortname, start);
1205 /* Don't return NULL, so get_header is always a valid pointer */
1209 static char *get_header(struct sip_request *req, char *name)
1212 return __get_header(req, name, &start);
1215 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1217 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1218 struct ast_frame *f;
1219 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1220 f = ast_rtp_read(p->rtp);
1221 /* Don't send RFC2833 if we're not supposed to */
1222 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1225 /* We already hold the channel lock */
1226 if (f->frametype == AST_FRAME_VOICE) {
1227 if (f->subclass != p->owner->nativeformats) {
1228 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1229 p->owner->nativeformats = f->subclass;
1230 ast_set_read_format(p->owner, p->owner->readformat);
1231 ast_set_write_format(p->owner, p->owner->writeformat);
1233 if (p->dtmfmode & SIP_DTMF_INBAND) {
1234 f = ast_dsp_process(p->owner,p->vad,f,0);
1241 static struct ast_frame *sip_read(struct ast_channel *ast)
1243 struct ast_frame *fr;
1244 struct sip_pvt *p = ast->pvt->pvt;
1245 ast_pthread_mutex_lock(&p->lock);
1246 fr = sip_rtp_read(p);
1247 ast_pthread_mutex_unlock(&p->lock);
1251 static void build_callid(char *callid, int len, struct in_addr ourip)
1258 res = snprintf(callid, len, "%08x", val);
1262 /* It's not important that we really use our right IP here... */
1263 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1266 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1270 p = malloc(sizeof(struct sip_pvt));
1273 /* Keep track of stuff */
1274 memset(p, 0, sizeof(struct sip_pvt));
1278 p->rtp = ast_rtp_new(NULL, NULL);
1282 /* Start with 101 instead of 1 */
1285 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1289 ast_rtp_settos(p->rtp, tos);
1290 if (useglobalnat && sin) {
1291 /* Setup NAT structure according to global settings if we have an address */
1293 memcpy(&p->recv, sin, sizeof(p->recv));
1294 ast_rtp_setnat(p->rtp, p->nat);
1296 ast_pthread_mutex_init(&p->lock);
1298 ast_rtp_set_data(p->rtp, p);
1299 ast_rtp_set_callback(p->rtp, rtpready);
1302 memcpy(&p->sa, sin, sizeof(p->sa));
1303 if (ast_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1304 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1306 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1308 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1309 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1311 build_callid(p->callid, sizeof(p->callid), p->ourip);
1313 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1314 /* Assume reinvite OK and via INVITE */
1315 p->canreinvite = globalcanreinvite;
1316 p->dtmfmode = globaldtmfmode;
1317 if (p->dtmfmode & SIP_DTMF_RFC2833)
1318 p->noncodeccapability |= AST_RTP_DTMF;
1319 strncpy(p->context, context, sizeof(p->context) - 1);
1320 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1322 ast_pthread_mutex_lock(&iflock);
1325 ast_pthread_mutex_unlock(&iflock);
1327 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1331 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1335 callid = get_header(req, "Call-ID");
1336 if (!strlen(callid)) {
1337 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1340 ast_pthread_mutex_lock(&iflock);
1343 if (!strcmp(p->callid, callid)) {
1344 /* Found the call */
1346 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1347 (p->sa.sin_port != sin->sin_port))) {
1350 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1351 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1352 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1353 ast_pthread_mutex_unlock(&iflock);
1357 ast_pthread_mutex_lock(&p->lock);
1358 ast_pthread_mutex_unlock(&iflock);
1363 ast_pthread_mutex_unlock(&iflock);
1364 p = sip_alloc(callid, sin, 1);
1366 ast_pthread_mutex_lock(&p->lock);
1370 static int sip_register(char *value, int lineno)
1372 struct sip_registry *reg;
1373 char copy[256] = "";
1374 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1382 strncpy(copy, value, sizeof(copy)-1);
1385 hostname = strrchr(stringp, '@');
1390 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1391 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port] at line %d", lineno);
1395 username = strsep(&stringp, ":");
1397 secret = strsep(&stringp, ":");
1399 authuser = strsep(&stringp, ":");
1402 hostname = strsep(&stringp, "/");
1404 contact = strsep(&stringp, "/");
1405 if (!contact || !strlen(contact))
1408 hostname = strsep(&stringp, ":");
1409 porta = strsep(&stringp, ":");
1411 if (porta && !atoi(porta)) {
1412 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1415 hp = gethostbyname(hostname);
1417 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1420 reg = malloc(sizeof(struct sip_registry));
1422 memset(reg, 0, sizeof(struct sip_registry));
1423 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1425 strncpy(reg->username, username, sizeof(reg->username)-1);
1427 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1429 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1431 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1434 reg->refresh = default_expiry;
1435 reg->addr.sin_family = AF_INET;
1436 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1437 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1438 reg->next = registrations;
1439 reg->callid_valid = 0;
1441 registrations = reg;
1443 ast_log(LOG_ERROR, "Out of memory\n");
1449 static void parse(struct sip_request *req)
1451 /* Divide fields by NULL's */
1456 /* First header starts immediately */
1460 /* We've got a new header */
1464 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1466 if (!strlen(req->header[f])) {
1467 /* Line by itself means we're now in content */
1471 if (f >= SIP_MAX_HEADERS - 1) {
1472 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1475 req->header[f] = c + 1;
1476 } else if (*c == '\r') {
1477 /* Ignore but eliminate \r's */
1482 /* Check for last header */
1483 if (strlen(req->header[f]))
1486 /* Now we process any mime content */
1491 /* We've got a new line */
1494 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1496 if (f >= SIP_MAX_LINES - 1) {
1497 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1500 req->line[f] = c + 1;
1501 } else if (*c == '\r') {
1502 /* Ignore and eliminate \r's */
1507 /* Check for last line */
1508 if (strlen(req->line[f]))
1512 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1514 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1517 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1525 int peercapability, peernoncodeccapability;
1526 struct sockaddr_in sin;
1532 /* Get codec and RTP info from SDP */
1533 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1534 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1537 m = get_sdp(req, "m");
1538 c = get_sdp(req, "c");
1539 if (!strlen(m) || !strlen(c)) {
1540 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1543 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1544 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1547 /* XXX This could block for a long time, and block the main thread! XXX */
1548 hp = gethostbyname(host);
1550 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1553 if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1554 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1557 sin.sin_family = AF_INET;
1558 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1559 sin.sin_port = htons(portno);
1561 ast_rtp_set_peer(p->rtp, &sin);
1563 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1565 // Scan through the RTP payload types specified in a "m=" line:
1566 ast_rtp_pt_clear(p->rtp);
1568 while(strlen(codecs)) {
1569 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1570 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1573 ast_rtp_set_m_type(p->rtp, codec);
1575 /* Skip over any whitespace */
1576 while(*codecs && (*codecs < 33)) codecs++;
1579 // Next, scan through each "a=rtpmap:" line, noting each
1580 // specified RTP payload type (with corresponding MIME subtype):
1581 sdpLineNum_iterator_init(&iterator);
1582 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1583 char* mimeSubtype = strdup(a); // ensures we have enough space
1584 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1585 // Note: should really look at the 'freq' and '#chans' params too
1586 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1590 // Now gather all of the codecs that were asked for:
1591 ast_rtp_get_current_formats(p->rtp,
1592 &peercapability, &peernoncodeccapability);
1593 p->capability = capability & peercapability;
1594 p->noncodeccapability = noncodeccapability & peernoncodeccapability;
1596 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1597 capability, peercapability, p->capability);
1598 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1599 noncodeccapability, peernoncodeccapability,
1600 p->noncodeccapability);
1602 if (!p->capability) {
1603 ast_log(LOG_WARNING, "No compatible codecs!\n");
1607 if (!(p->owner->nativeformats & p->capability)) {
1608 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);
1609 p->owner->nativeformats = sip_codec_choose(p->capability);
1610 ast_set_read_format(p->owner, p->owner->readformat);
1611 ast_set_write_format(p->owner, p->owner->writeformat);
1613 if (p->owner->bridge) {
1614 /* Turn on/off music on hold if we are holding/unholding */
1615 if (sin.sin_addr.s_addr) {
1616 ast_moh_stop(p->owner->bridge);
1618 ast_moh_start(p->owner->bridge, NULL);
1626 static int add_header(struct sip_request *req, char *var, char *value)
1628 if (req->len >= sizeof(req->data) - 4) {
1629 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1633 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1636 req->header[req->headers] = req->data + req->len;
1637 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1638 req->len += strlen(req->header[req->headers]);
1639 if (req->headers < SIP_MAX_HEADERS)
1642 ast_log(LOG_WARNING, "Out of header space\n");
1648 static int add_blank_header(struct sip_request *req)
1650 if (req->len >= sizeof(req->data) - 4) {
1651 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1655 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1658 req->header[req->headers] = req->data + req->len;
1659 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1660 req->len += strlen(req->header[req->headers]);
1661 if (req->headers < SIP_MAX_HEADERS)
1664 ast_log(LOG_WARNING, "Out of header space\n");
1670 static int add_line(struct sip_request *req, char *line)
1672 if (req->len >= sizeof(req->data) - 4) {
1673 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1677 /* Add extra empty return */
1678 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1679 req->len += strlen(req->data + req->len);
1681 req->line[req->lines] = req->data + req->len;
1682 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1683 req->len += strlen(req->line[req->lines]);
1684 if (req->lines < SIP_MAX_LINES)
1687 ast_log(LOG_WARNING, "Out of line space\n");
1693 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1696 tmp = get_header(orig, field);
1698 /* Add what we're responding to */
1699 return add_header(req, field, tmp);
1701 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1705 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1711 tmp = __get_header(orig, field, &start);
1713 /* Add what we're responding to */
1714 add_header(req, field, tmp);
1719 return copied ? 0 : -1;
1722 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1729 tmp = __get_header(orig, field, &start);
1731 if (!copied && p->nat) {
1732 /* SLD: FIXME: Nice try, but the received= should not have a port */
1733 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1734 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1735 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1737 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1738 add_header(req, field, new);
1740 /* Add what we're responding to */
1741 add_header(req, field, tmp);
1748 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1754 /* Add Route: header into request per learned route */
1755 static void add_route(struct sip_request *req, struct sip_route *route)
1758 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1764 n = strlen(route->hop);
1765 if ((n+3)>rem) break;
1771 strcpy(p, route->hop); p += n;
1774 route = route->next;
1777 add_header(req, "Route", r);
1780 static void set_destination(struct sip_pvt *p, char *uri)
1782 char *h, *maddr, hostname[256];
1786 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1787 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1790 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1792 /* Find and parse hostname */
1793 h = strchr(uri, '@');
1798 if (strncmp(h, "sip:", 4) == 0)
1800 else if (strncmp(h, "sips:", 5) == 0)
1803 hn = strcspn(h, ":;>");
1805 strncpy(hostname, h, hn); hostname[hn] = '\0';
1808 /* Is "port" present? if not default to 5060 */
1812 port = strtol(h, &h, 10);
1817 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
1818 maddr = strstr(h, "maddr=");
1821 hn = strspn(maddr, "0123456789.");
1823 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
1826 hp = gethostbyname(hostname);
1828 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
1831 p->sa.sin_family = AF_INET;
1832 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1833 p->sa.sin_port = htons(port);
1835 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1838 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1840 /* Initialize a response */
1841 if (req->headers || req->len) {
1842 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1845 req->header[req->headers] = req->data + req->len;
1846 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1847 req->len += strlen(req->header[req->headers]);
1848 if (req->headers < SIP_MAX_HEADERS)
1851 ast_log(LOG_WARNING, "Out of header space\n");
1855 static int init_req(struct sip_request *req, char *resp, char *recip)
1857 /* Initialize a response */
1858 if (req->headers || req->len) {
1859 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1862 req->header[req->headers] = req->data + req->len;
1863 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1864 req->len += strlen(req->header[req->headers]);
1865 if (req->headers < SIP_MAX_HEADERS)
1868 ast_log(LOG_WARNING, "Out of header space\n");
1872 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1874 char newto[256] = "", *ot;
1875 memset(resp, 0, sizeof(*resp));
1876 init_resp(resp, msg, req);
1877 copy_via_headers(p, resp, req, "Via");
1878 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1879 copy_header(resp, req, "From");
1880 ot = get_header(req, "To");
1881 if (!strstr(ot, "tag=")) {
1882 /* Add the proper tag if we don't have it already. If they have specified
1883 their tag, use it. Otherwise, use our own tag */
1884 if (strlen(p->theirtag) && p->outgoing)
1885 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1886 else if (p->tag && !p->outgoing)
1887 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1889 strncpy(newto, ot, sizeof(newto) - 1);
1892 add_header(resp, "To", ot);
1893 copy_header(resp, req, "Call-ID");
1894 copy_header(resp, req, "CSeq");
1895 add_header(resp, "User-Agent", "Asterisk PBX");
1897 /* For registration responses, we also need expiry and
1901 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
1902 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
1903 add_header(resp, "Expires", tmp);
1904 add_header(resp, "Contact", contact);
1906 add_header(resp, "Contact", p->our_contact);
1911 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
1913 struct sip_request *orig = &p->initreq;
1914 char stripped[80] ="";
1920 memset(req, 0, sizeof(struct sip_request));
1928 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1930 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1932 c = strchr(stripped, '<');
1944 init_req(req, msg, c);
1946 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
1948 add_header(req, "Via", p->via);
1950 set_destination(p, p->route->hop);
1951 add_route(req, p->route->next);
1954 ot = get_header(orig, "To");
1955 of = get_header(orig, "From");
1957 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
1958 as our original request, including tag (or presumably lack thereof) */
1959 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
1960 /* Add the proper tag if we don't have it already. If they have specified
1961 their tag, use it. Otherwise, use our own tag */
1962 if (p->outgoing && strlen(p->theirtag))
1963 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1964 else if (!p->outgoing)
1965 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1967 snprintf(newto, sizeof(newto), "%s", ot);
1972 add_header(req, "From", of);
1973 add_header(req, "To", ot);
1975 add_header(req, "From", ot);
1976 add_header(req, "To", of);
1978 add_header(req, "Contact", p->our_contact);
1979 copy_header(req, orig, "Call-ID");
1980 add_header(req, "CSeq", tmp);
1982 add_header(req, "User-Agent", "Asterisk PBX");
1986 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
1988 struct sip_request resp;
1990 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
1991 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
1994 respprep(&resp, p, msg, req);
1995 add_header(&resp, "Content-Length", "0");
1996 add_blank_header(&resp);
1997 return send_response(p, &resp, reliable, seqno);
2000 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2002 return __transmit_response(p, msg, req, 0);
2004 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2006 return __transmit_response(p, msg, req, 1);
2009 static void append_date(struct sip_request *req)
2016 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2017 add_header(req, "Date", tmpdat);
2020 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2022 struct sip_request resp;
2023 respprep(&resp, p, msg, req);
2025 add_header(&resp, "Content-Length", "0");
2026 add_blank_header(&resp);
2027 return send_response(p, &resp, 0, 0);
2030 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2032 struct sip_request resp;
2033 respprep(&resp, p, msg, req);
2034 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
2035 add_header(&resp, "Accept", "application/sdp");
2036 add_header(&resp, "Content-Length", "0");
2037 add_blank_header(&resp);
2038 return send_response(p, &resp, 0, 0);
2041 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2043 struct sip_request resp;
2046 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2047 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2050 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2051 respprep(&resp, p, msg, req);
2052 add_header(&resp, "Proxy-Authenticate", tmp);
2053 add_header(&resp, "Content-Length", "0");
2054 add_blank_header(&resp);
2055 return send_response(p, &resp, reliable, seqno);
2058 static int add_text(struct sip_request *req, char *text)
2060 /* XXX Convert \n's to \r\n's XXX */
2061 int len = strlen(text);
2063 snprintf(clen, sizeof(clen), "%d", len);
2064 add_header(req, "Content-Type", "text/plain");
2065 add_header(req, "Content-Length", clen);
2066 add_line(req, text);
2070 static int add_digit(struct sip_request *req, char digit)
2075 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2077 snprintf(clen, sizeof(clen), "%d", len);
2078 add_header(req, "Content-Type", "application/dtmf-relay");
2079 add_header(req, "Content-Length", clen);
2084 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
2088 int alreadysent = 0;
2090 struct sockaddr_in sin;
2091 struct sip_codec_pref *cur;
2100 struct sockaddr_in dest;
2101 /* XXX We break with the "recommendation" and send our IP, in order that our
2102 peer doesn't have to gethostbyname() us XXX */
2105 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2108 ast_rtp_get_us(p->rtp, &sin);
2109 if (p->redirip.sin_addr.s_addr) {
2110 dest.sin_port = p->redirip.sin_port;
2111 dest.sin_addr = p->redirip.sin_addr;
2113 ast_rtp_get_peer(rtp, &dest);
2115 dest.sin_addr = p->ourip;
2116 dest.sin_port = sin.sin_port;
2119 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2120 snprintf(v, sizeof(v), "v=0\r\n");
2121 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2122 snprintf(s, sizeof(s), "s=session\r\n");
2123 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2124 snprintf(t, sizeof(t), "t=0 0\r\n");
2125 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2126 /* Start by sending our preferred codecs */
2129 if (p->capability & cur->codec) {
2131 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2132 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2134 snprintf(costr, sizeof(costr), " %d", codec);
2136 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2140 alreadysent |= cur->codec;
2143 /* Now send any other common codecs, and non-codec formats: */
2144 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2145 if ((p->capability & x) && !(alreadysent & x)) {
2147 ast_verbose("Answering with capability %d\n", x);
2148 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2150 snprintf(costr, sizeof(costr), " %d", codec);
2152 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2157 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2158 if (p->noncodeccapability & x) {
2160 ast_verbose("Answering with non-codec capability %d\n", x);
2161 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2163 snprintf(costr, sizeof(costr), " %d", codec);
2165 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2167 if (x == AST_RTP_DTMF) {
2168 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2169 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2177 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2178 snprintf(costr, sizeof(costr), "%d", len);
2179 add_header(resp, "Content-Type", "application/sdp");
2180 add_header(resp, "Content-Length", costr);
2191 static void copy_request(struct sip_request *dst,struct sip_request *src)
2195 offset = ((void *)dst) - ((void *)src);
2196 /* First copy stuff */
2197 memcpy(dst, src, sizeof(*dst));
2198 /* Now fix pointer arithmetic */
2199 for (x=0;x<src->headers;x++)
2200 dst->header[x] += offset;
2201 for (x=0;x<src->lines;x++)
2202 dst->line[x] += offset;
2205 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2207 struct sip_request resp;
2209 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2210 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2213 respprep(&resp, p, msg, req);
2214 add_sdp(&resp, p, NULL);
2215 return send_response(p, &resp, retrans, seqno);
2218 static int determine_firstline_parts( struct sip_request *req ) {
2223 cmd= req->header[0];
2224 while(*cmd && (*cmd < 33)) {
2231 while(*e && (*e > 32)) {
2234 /* Get the command */
2240 while( *e && ( *e < 33 ) ) {
2247 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2248 /* We have a response */
2250 len= strlen( req->rlPart2 );
2251 if( len < 2 ) { return -1; }
2253 while( *e && *e<33 ) {
2258 /* We have a request */
2261 if( !*e ) { return -1; }
2264 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2267 while( isspace( *(--e) ) ) {}
2277 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2279 struct sip_request req;
2280 if (p->canreinvite == REINVITE_UPDATE)
2281 reqprep(&req, p, "UPDATE", 0);
2283 reqprep(&req, p, "INVITE", 0);
2284 add_sdp(&req, p, rtp);
2285 /* Use this as the basis */
2286 copy_request(&p->initreq, &req);
2288 determine_firstline_parts(&p->initreq);
2289 p->lastinvite = p->ocseq;
2291 return send_request(p, &req, 1, p->ocseq);
2294 static void build_contact(struct sip_pvt *p)
2296 /* Construct Contact: header */
2297 if (ourport != 5060)
2298 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2300 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2303 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2310 char *l = callerid, *n=NULL;
2311 if (p->owner && p->owner->callerid) {
2312 strcpy(cid, p->owner->callerid);
2313 ast_callerid_parse(cid, &n, &l);
2315 ast_shrink_phone_number(l);
2316 if (!l || !ast_isphonenumber(l))
2319 if (!n || !strlen(n))
2321 /* Allow user to be overridden */
2322 if (strlen(p->fromuser))
2325 if ((ourport != 5060) && !strlen(p->fromdomain))
2326 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), ourport, p->tag);
2328 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2330 if (strlen(p->username)) {
2331 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2332 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2334 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2336 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2337 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2339 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2341 strncpy(p->uri, invite, sizeof(p->uri) - 1);
2342 /* If there is a VXML URL append it to the SIP URL */
2345 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2349 snprintf(to, sizeof(to), "<%s>", invite );
2351 memset(req, 0, sizeof(struct sip_request));
2352 init_req(req, cmd, invite);
2353 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2355 add_header(req, "Via", p->via);
2356 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2357 * OTOH, then we won't have anything in p->route anyway */
2358 add_header(req, "From", from);
2359 strncpy(p->exten, l, sizeof(p->exten) - 1);
2361 add_header(req, "To", to);
2362 add_header(req, "Contact", p->our_contact);
2363 add_header(req, "Call-ID", p->callid);
2364 add_header(req, "CSeq", tmp);
2365 add_header(req, "User-Agent", "Asterisk PBX");
2368 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2370 struct sip_request req;
2371 initreqprep(&req, p, cmd, vxml_url);
2373 add_header(&req, "Proxy-Authorization", auth);
2375 add_sdp(&req, p, NULL);
2377 add_header(&req, "Content-Length", "0");
2378 add_blank_header(&req);
2380 if (!p->initreq.headers) {
2381 /* Use this as the basis */
2382 copy_request(&p->initreq, &req);
2384 determine_firstline_parts(&p->initreq);
2386 p->lastinvite = p->ocseq;
2387 return send_request(p, &req, 1, p->ocseq);
2390 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2393 char from[256], to[256];
2396 struct sip_request req;
2399 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2401 c = ditch_braces(from);
2402 if (strncmp(c, "sip:", 4)) {
2403 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2406 if ((a = strchr(c, ';'))) {
2411 reqprep(&req, p, "NOTIFY", 0);
2413 if (p->subscribed == 1) {
2414 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2416 c = ditch_braces(to);
2417 if (strncmp(c, "sip:", 4)) {
2418 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2421 if ((a = strchr(c, ';'))) {
2426 add_header(&req, "Content-Type", "application/xpidf+xml");
2428 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2430 else if (state==AST_EXTENSION_INUSE)
2436 sprintf(t, "<?xml version=\"1.0\"?>\n");
2437 t = tmp + strlen(tmp);
2438 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2439 t = tmp + strlen(tmp);
2440 sprintf(t, "<presence>\n");
2441 t = tmp + strlen(tmp);
2442 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2443 t = tmp + strlen(tmp);
2444 sprintf(t, "<atom id=\"%s\">\n", p->exten);
2445 t = tmp + strlen(tmp);
2446 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2447 t = tmp + strlen(tmp);
2448 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2449 t = tmp + strlen(tmp);
2450 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2451 t = tmp + strlen(tmp);
2452 sprintf(t, "</address>\n</atom>\n</presence>\n");
2454 add_header(&req, "Event", "dialog");
2455 add_header(&req, "Content-Type", "application/dialog-info+xml");
2458 sprintf(t, "<?xml version=\"1.0\"?>\n");
2459 t = tmp + strlen(tmp);
2460 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);
2461 t = tmp + strlen(tmp);
2462 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2463 t = tmp + strlen(tmp);
2464 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2465 t = tmp + strlen(tmp);
2466 sprintf(t, "</dialog>\n</dialog-info>\n");
2469 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2470 add_header(&req, "Content-Length", clen);
2471 add_line(&req, tmp);
2473 return send_request(p, &req, 1, p->ocseq);
2476 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2478 struct sip_request req;
2482 initreqprep(&req, p, "NOTIFY", NULL);
2483 add_header(&req, "Event", "message-summary");
2484 add_header(&req, "Content-Type", notifymime);
2486 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2487 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2488 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2489 add_header(&req, "Content-Length", clen);
2490 add_line(&req, tmp);
2491 add_line(&req, tmp2);
2493 if (!p->initreq.headers) {
2494 /* Use this as the basis */
2495 copy_request(&p->initreq, &req);
2497 determine_firstline_parts(&p->initreq);
2500 return send_request(p, &req, 1, p->ocseq);
2503 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2505 static int sip_reregister(void *data)
2507 /* if we are here, we know that we need to reregister. */
2508 struct sip_registry *r=(struct sip_registry *)data;
2515 static int sip_do_register(struct sip_registry *r)
2518 ast_pthread_mutex_lock(&r->lock);
2519 res=transmit_register(r, "REGISTER", NULL);
2520 ast_pthread_mutex_unlock(&r->lock);
2524 static int sip_reg_timeout(void *data)
2526 /* if we are here, our registration timed out, so we'll just do it over */
2527 struct sip_registry *r=data;
2530 ast_pthread_mutex_lock(&r->lock);
2531 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
2533 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
2534 in the single SIP manager thread. */
2540 r->regstate=REG_STATE_UNREGISTERED;
2542 res=transmit_register(r, "REGISTER", NULL);
2543 ast_pthread_mutex_unlock(&r->lock);
2547 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2549 struct sip_request req;
2556 /* exit if we are already in process with this registrar ?*/
2557 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2558 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2564 ast_log(LOG_WARNING, "Already have a call??\n");
2569 if (!r->callid_valid) {
2570 build_callid(r->callid, sizeof(r->callid), __ourip);
2571 r->callid_valid = 1;
2573 p=sip_alloc( r->callid, &r->addr, 0);
2575 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2581 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2582 if (strlen(r->authuser))
2583 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2585 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2586 strncpy(p->username, r->username, sizeof(p->username)-1);
2587 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2591 /* set up a timeout */
2593 if (r->timeout > -1) {
2594 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2595 ast_sched_del(sched, r->timeout);
2597 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2598 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2601 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2602 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
2604 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2605 strncpy(p->uri, addr, sizeof(p->uri) - 1);
2607 memset(&req, 0, sizeof(req));
2608 init_req(&req, cmd, addr);
2610 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2611 p->ocseq = r->ocseq;
2613 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2614 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2615 add_header(&req, "Via", via);
2616 add_header(&req, "From", from);
2617 add_header(&req, "To", to);
2618 add_header(&req, "Call-ID", p->callid);
2619 add_header(&req, "CSeq", tmp);
2620 add_header(&req, "User-Agent", "Asterisk PBX");
2622 add_header(&req, "Authorization", auth);
2624 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2625 add_header(&req, "Expires", tmp);
2626 add_header(&req, "Contact", p->our_contact);
2627 add_header(&req, "Event", "registration");
2628 add_header(&req, "Content-length", "0");
2629 add_blank_header(&req);
2630 copy_request(&p->initreq, &req);
2632 determine_firstline_parts(&p->initreq);
2633 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2634 return send_request(p, &req, 1, p->ocseq);
2637 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2639 struct sip_request req;
2640 reqprep(&req, p, "MESSAGE", 0);
2641 add_text(&req, text);
2642 return send_request(p, &req, 1, p->ocseq);
2645 static int transmit_refer(struct sip_pvt *p, char *dest)
2647 struct sip_request req;
2652 of = get_header(&p->initreq, "To");
2654 of = get_header(&p->initreq, "From");
2655 strncpy(from, of, sizeof(from) - 1);
2656 of = ditch_braces(from);
2657 if (strncmp(of, "sip:", 4)) {
2658 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2661 /* Get just the username part */
2662 if ((c = strchr(of, '@'))) {
2667 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
2669 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
2672 reqprep(&req, p, "REFER", 0);
2673 add_header(&req, "Refer-To", referto);
2674 add_header(&req, "Referred-By", callerid);
2675 return send_request(p, &req, 1, p->ocseq);
2678 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2680 struct sip_request req;
2681 reqprep(&req, p, "INFO", 0);
2682 add_digit(&req, digit);
2683 return send_request(p, &req, 1, p->ocseq);
2686 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
2688 struct sip_request resp;
2689 reqprep(&resp, p, msg, seqno);
2690 add_header(&resp, "Content-Length", "0");
2691 add_blank_header(&resp);
2692 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2695 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
2697 struct sip_request resp;
2698 reqprep(&resp, p, msg, seqno);
2702 memset(digest,0,sizeof(digest));
2703 build_reply_digest(p, msg, digest, sizeof(digest));
2704 add_header(&resp, "Proxy-Authorization", digest);
2707 add_header(&resp, "Content-Length", "0");
2708 add_blank_header(&resp);
2709 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2712 static int expire_register(void *data)
2714 struct sip_peer *p = data;
2715 memset(&p->addr, 0, sizeof(p->addr));
2717 ast_device_state_changed("SIP/%s", p->name);
2721 static int sip_poke_peer(struct sip_peer *peer);
2723 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2725 char contact[80]= "";
2726 char *expires = get_header(req, "Expires");
2727 int expiry = atoi(expires);
2731 struct sockaddr_in oldsin;
2732 if (!strlen(expires)) {
2733 expires = strstr(get_header(req, "Contact"), "expires=");
2735 if (sscanf(expires + 8, "%d;", &expiry) != 1)
2736 expiry = default_expiry;
2738 /* Nothing has been specified */
2739 expiry = default_expiry;
2742 /* Look for brackets */
2743 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2746 if ((n=strchr(c, '<'))) {
2749 /* Lose the part after the > */
2753 if (!strcasecmp(c, "*") || !expiry) {
2754 /* This means remove all registrations and return OK */
2755 memset(&p->addr, 0, sizeof(p->addr));
2757 ast_sched_del(sched, p->expire);
2759 if (option_verbose > 2)
2760 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
2763 /* Make sure it's a SIP URL */
2764 if (strncasecmp(c, "sip:", 4)) {
2765 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2781 pt = strchr(n, ':');
2787 port = DEFAULT_SIP_PORT;
2788 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2790 /* XXX This could block for a long time XXX */
2791 hp = gethostbyname(n);
2793 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2796 p->addr.sin_family = AF_INET;
2797 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2798 p->addr.sin_port = htons(port);
2800 /* Don't trust the contact field. Just use what they came to us
2802 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2805 strncpy(p->username, c, sizeof(p->username) - 1);
2807 strcpy(p->username, "");
2809 ast_sched_del(sched, p->expire);
2810 if ((expiry < 1) || (expiry > max_expiry))
2811 expiry = max_expiry;
2812 p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
2813 pvt->expiry = expiry;
2814 if (inaddrcmp(&p->addr, &oldsin)) {
2816 if (option_verbose > 2)
2817 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), expiry);
2822 static void free_old_route(struct sip_route *route)
2824 struct sip_route *next;
2832 static void list_route(struct sip_route *route)
2835 ast_verbose("list_route: no route\n");
2839 ast_verbose("list_route: hop: <%s>\n", route->hop);
2840 route = route->next;
2844 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
2846 struct sip_route *thishop, *head, *tail;
2849 char *rr, *contact, *c;
2852 free_old_route(p->route);
2855 /* We build up head, then assign it to p->route when we're done */
2856 head = NULL; tail = head;
2857 /* 1st we pass through all the hops in any Record-Route headers */
2859 /* Each Record-Route header */
2860 rr = __get_header(req, "Record-Route", &start);
2861 if (*rr == '\0') break;
2863 /* Each route entry */
2865 rr = strchr(rr, '<');
2866 if (!rr) break; /* No more hops */
2868 len = strcspn(rr, ">");
2869 /* Make a struct route */
2870 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2872 strncpy(thishop->hop, rr, len);
2873 thishop->hop[len] = '\0';
2874 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
2877 /* Link in at head so they end up in reverse order */
2878 thishop->next = head;
2880 /* If this was the first then it'll be the tail */
2881 if (!tail) tail = thishop;
2883 thishop->next = NULL;
2884 /* Link in at the end */
2886 tail->next = thishop;
2895 /* 2nd append the Contact: if there is one */
2896 /* Can be multiple Contact headers, comma separated values - we just take the first */
2897 contact = get_header(req, "Contact");
2898 if (strlen(contact)) {
2899 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
2900 /* Look for <: delimited address */
2901 c = strchr(contact, '<');
2905 len = strcspn(c, ">");
2907 /* No <> - just take the lot */
2908 c = contact; len = strlen(contact);
2910 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2912 strncpy(thishop->hop, c, len);
2913 thishop->hop[len] = '\0';
2914 thishop->next = NULL;
2915 /* Goes at the end */
2917 tail->next = thishop;
2922 /* Store as new route */
2925 /* For debugging dump what we ended up with */
2927 list_route(p->route);
2930 static void md5_hash(char *output, char *input)
2932 struct MD5Context md5;
2933 unsigned char digest[16];
2937 MD5Update(&md5, input, strlen(input));
2938 MD5Final(digest, &md5);
2941 ptr += sprintf(ptr, "%2.2x", digest[x]);
2944 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)
2947 /* Always OK if no secret */
2948 if (!strlen(secret))
2950 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2951 snprintf(randdata, randlen, "%08x", rand());
2952 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2953 /* Schedule auto destroy in 15 seconds */
2954 sip_scheddestroy(p, 15000);
2957 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2958 an example in the spec of just what it is you're doing a hash on. */
2964 char resp_hash[256];
2970 /* Find their response among the mess that we'r sent for comparison */
2971 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2975 while (*c && (*c < 33)) c++;
2978 if (!strncasecmp(c, "response=", strlen("response="))) {
2979 c+= strlen("response=");
2982 if((c = strchr(c,'\"')))
2987 if((c = strchr(c,',')))
2991 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2995 if((c = strchr(c,'\"')))
2999 if((c = strchr(c,',')))
3008 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
3009 if(strlen(resp_uri))
3010 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
3012 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
3013 md5_hash(a1_hash, a1);
3014 md5_hash(a2_hash, a2);
3015 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
3016 md5_hash(resp_hash, resp);
3018 /* resp_hash now has the expected response, compare the two */
3020 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
3024 /* Assume success ;-) */
3025 /* Eliminate random data */
3026 strcpy(randdata, "");
3031 static int cb_extensionstate(char *context, char* exten, int state, void *data)
3033 struct sip_pvt *p = data;
3035 sip_scheddestroy(p, 15000);
3040 transmit_state_notify(p, state, 1);
3043 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
3047 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
3050 struct sip_peer *peer;
3056 while(*t && (*t > 32) && (*t != ';'))
3060 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
3061 c = ditch_braces(tmp);
3062 /* Ditch ;user=phone */
3063 name = strchr(c, ';');
3067 if (!strncmp(c, "sip:", 4)) {
3071 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
3073 c = strchr(name, '@');
3076 strncpy(p->exten, name, sizeof(p->exten) - 1);
3078 ast_pthread_mutex_lock(&peerl.lock);
3081 if (!strcasecmp(peer->name, name) && peer->dynamic) {
3083 transmit_response(p, "100 Trying", req);
3084 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
3085 sip_cancel_destroy(p);
3086 if (parse_contact(p, peer, req)) {
3087 ast_log(LOG_WARNING, "Failed to parse contact info\n");
3089 /* Say OK and ask subsystem to retransmit msg counter */
3090 transmit_response_with_date(p, "200 OK", req);
3091 peer->lastmsgssent = -1;
3099 ast_pthread_mutex_unlock(&peerl.lock);
3101 ast_device_state_changed("SIP/%s", peer->name);
3104 transmit_response(p, "401 Unauthorized", &p->initreq);
3108 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
3110 char tmp[256] = "", *c, *a;
3111 struct sip_request *req;
3116 strncpy(tmp, get_header(req, "Diversion"), sizeof(tmp) - 1);
3119 c = ditch_braces(tmp);
3120 if (strncmp(c, "sip:", 4)) {
3121 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
3125 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3129 ast_verbose("RDNIS is %s\n", c);
3130 strncpy(p->rdnis, c, sizeof(p->rdnis) - 1);
3134 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
3136 char tmp[256] = "", *c, *a;
3137 struct sip_request *req;
3143 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
3144 c = ditch_braces(tmp);
3145 if (strncmp(c, "sip:", 4)) {
3146 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3150 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3154 ast_verbose("Looking for %s in %s\n", c, p->context);
3155 if (ast_exists_extension(NULL, p->context, c, 1, NULL) ||
3156 !strcmp(c, ast_pickup_ext())) {
3158 strncpy(p->exten, c, sizeof(p->exten) - 1);
3162 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL) ||
3163 !strncmp(c, ast_pickup_ext(),strlen(c))) {
3170 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
3172 char tmp[256] = "", *c, *a;
3173 char tmp2[256] = "", *c2, *a2;
3176 char tmp5[256] = ""; /* CallID to replace */
3177 struct sip_request *req;
3183 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
3184 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
3185 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
3186 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
3188 c = ditch_braces(tmp);
3189 c2 = ditch_braces(tmp2);
3192 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
3193 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3194 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
3199 if ((a = strchr(c, '?'))) {
3200 /* Search for arguemnts */
3203 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
3204 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
3205 if ((a = strchr(tmp5, '%'))) {
3206 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
3208 if ((a[1] == '4') && (a[2] == '0')) {
3210 memmove(a + 1, a+3, strlen(a + 3));
3213 if ((a = strchr(tmp5, '%')))
3218 if ((a = strchr(c, '@')))
3220 if ((a = strchr(c, ';')))
3224 if ((a2 = strchr(c2, '@')))
3227 if ((a2 = strchr(c2, ';')))
3232 ast_verbose("Looking for %s in %s\n", c, p->context);
3233 ast_verbose("Looking for %s in %s\n", c2, p->context);
3236 /* This is a supervised transfer */
3237 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
3239 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
3240 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
3241 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
3242 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
3243 p->refer_call = NULL;
3244 ast_pthread_mutex_lock(&iflock);
3245 /* Search interfaces and find the match */
3248 if (!strcmp(p2->callid, tmp5)) {
3249 /* Go ahead and lock it before returning */
3250 ast_pthread_mutex_lock(&p2->lock);
3256 ast_pthread_mutex_unlock(&iflock);
3260 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
3261 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3262 /* This is an unsupervised transfer */
3263 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
3264 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
3265 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
3266 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
3267 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
3268 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
3269 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
3270 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
3271 p->refer_call = NULL;
3273 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
3281 static int check_via(struct sip_pvt *p, struct sip_request *req)
3287 memset(via, 0, sizeof(via));
3288 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
3289 c = strchr(via, ';');
3292 c = strchr(via, ' ');
3296 while(*c && (*c < 33))
3298 if (strcmp(via, "SIP/2.0/UDP")) {
3299 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
3302 pt = strchr(c, ':');
3307 hp = gethostbyname(c);
3309 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
3312 memset(&p->sa, 0, sizeof(p->sa));
3313 p->sa.sin_family = AF_INET;
3314 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
3315 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
3318 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3320 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3325 static char *get_calleridname(char *input,char *output)
3327 char *end = strchr(input,'<');
3328 char *tmp = strchr(input,'\"');
3329 if (!end || (end == input)) return NULL;
3330 /* move away from "<" */
3332 /* we found "name" */
3333 if (tmp && tmp < end) {
3334 end = strchr(tmp+1,'\"');
3335 if (!end) return NULL;
3336 strncpy(output,tmp+1,(int)(end-tmp-1));
3338 /* we didn't find "name" */
3339 /* clear the empty characters in the begining*/
3340 while(*input && (*input < 33))
3342 /* clear the empty characters in the end */
3343 while(*end && (*end < 33) && end > input)
3346 strncpy(output,input,(int)(end-input));
3352 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri, int reliable)
3354 struct sip_user *user;
3355 struct sip_peer *peer;
3356 char *of, from[256] = "", *c;
3359 char calleridname[50];
3362 while(*t && (*t > 32) && (*t != ';'))
3365 of = get_header(req, "From");
3366 strncpy(from, of, sizeof(from) - 1);
3367 memset(calleridname,0,sizeof(calleridname));
3368 get_calleridname(from,calleridname);
3369 of = ditch_braces(from);
3370 if (strncmp(of, "sip:", 4)) {
3371 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3374 /* Get just the username part */
3375 if ((c = strchr(of, '@')))
3377 if ((c = strchr(of, ':')))
3380 sprintf(p->callerid,"\"%s\" <%s>",calleridname,of);
3382 strncpy(p->callerid, of, sizeof(p->callerid) - 1);
3385 ast_pthread_mutex_lock(&userl.lock);
3388 if (!strcasecmp(user->name, of)) {
3391 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
3392 ast_rtp_setnat(p->rtp, p->nat);
3394 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri, reliable))) {
3395 sip_cancel_destroy(p);
3396 if (strlen(user->context))
3397 strncpy(p->context, user->context, sizeof(p->context) - 1);
3398 if (strlen(user->callerid) && strlen(p->callerid))
3399 strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
3400 strncpy(p->username, user->name, sizeof(p->username) - 1);
3401 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
3402 p->canreinvite = user->canreinvite;
3403 p->amaflags = user->amaflags;
3404 p->callgroup = user->callgroup;
3405 p->pickupgroup = user->pickupgroup;
3406 if (user->dtmfmode) {
3407 p->dtmfmode = user->dtmfmode;
3408 if (p->dtmfmode & SIP_DTMF_RFC2833)
3409 p->noncodeccapability |= AST_RTP_DTMF;
3411 p->noncodeccapability &= ~AST_RTP_DTMF;
3418 ast_pthread_mutex_unlock(&userl.lock);
3420 /* If we didn't find a user match, check for peers */
3421 ast_pthread_mutex_lock(&peerl.lock);
3424 if (!inaddrcmp(&peer->addr, &p->recv) ||
3425 (peer->insecure && (peer->addr.sin_addr.s_addr == p->recv.sin_addr.s_addr))) {
3429 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
3430 ast_rtp_setnat(p->rtp, p->nat);
3432 p->canreinvite = peer->canreinvite;
3433 strncpy(p->username, peer->name, sizeof(p->username) - 1);
3434 if (strlen(peer->context))
3435 strncpy(p->context, peer->context, sizeof(p->context) - 1);
3436 p->callgroup = peer->callgroup;
3437 p->pickupgroup = peer->pickupgroup;
3438 if (peer->dtmfmode) {
3439 p->dtmfmode = peer->dtmfmode;
3440 if (p->dtmfmode & SIP_DTMF_RFC2833)
3441 p->noncodeccapability |= AST_RTP_DTMF;
3443 p->noncodeccapability &= ~AST_RTP_DTMF;
3449 ast_pthread_mutex_unlock(&peerl.lock);
3454 static int get_msg_text(char *buf, int len, struct sip_request *req)
3458 for (x=0;x<req->lines;x++) {
3459 strncat(buf, req->line[x], len - strlen(buf) - 5);
3465 static void receive_message(struct sip_pvt *p, struct sip_request *req)
3469 if (get_msg_text(buf, sizeof(buf), req)) {
3470 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
3475 ast_verbose("Message received: '%s'\n", buf);
3476 memset(&f, 0, sizeof(f));
3477 f.frametype = AST_FRAME_TEXT;
3481 f.datalen = strlen(buf);
3482 ast_queue_frame(p->owner, &f, 0);
3486 static int sip_show_users(int fd, int argc, char *argv[])
3488 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
3489 struct sip_user *user;
3491 return RESULT_SHOWUSAGE;
3492 ast_pthread_mutex_lock(&userl.lock);
3493 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
3494 for(user=userl.users;user;user=user->next) {
3495 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
3497 user->ha ? "Yes" : "No");
3499 ast_pthread_mutex_unlock(&userl.lock);
3500 return RESULT_SUCCESS;
3504 static int sip_show_peers(int fd, int argc, char *argv[])
3506 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
3507 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
3508 struct sip_peer *peer;
3509 char name[256] = "";
3511 return RESULT_SHOWUSAGE;
3512 ast_pthread_mutex_lock(&peerl.lock);
3513 ast_cli(fd, FORMAT2, "Name/username", "Host", " ", "Mask", "Port", "Status");
3514 for (peer = peerl.peers;peer;peer = peer->next) {
3517 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
3518 if (strlen(peer->username))
3519 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
3521 strncpy(name, peer->name, sizeof(name) - 1);
3523 if (peer->lastms < 0)
3524 strcpy(status, "UNREACHABLE");
3525 else if (peer->lastms > peer->maxms)
3526 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
3527 else if (peer->lastms)
3528 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
3530 strcpy(status, "UNKNOWN");
3532 strcpy(status, "Unmonitored");
3533 ast_cli(fd, FORMAT, name,
3534 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
3535 peer->dynamic ? "(D)" : " ",
3537 ntohs(peer->addr.sin_port), status);
3539 ast_pthread_mutex_unlock(&peerl.lock);
3540 return RESULT_SUCCESS;
3545 static char *regstate2str(int regstate)
3548 case REG_STATE_UNREGISTERED:
3549 return "Unregistered";
3550 case REG_STATE_REGSENT:
3551 return "Request Sent";
3552 case REG_STATE_AUTHSENT:
3553 return "Auth. Sent";
3554 case REG_STATE_REGISTERED:
3555 return "Registered";
3556 case REG_STATE_REJECTED:
3558 case REG_STATE_TIMEOUT:
3560 case REG_STATE_NOAUTH:
3561 return "No Authentication";