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 <asterisk/srv.h>
40 #include <sys/socket.h>
41 #include <sys/ioctl.h>
48 #include <arpa/inet.h>
49 #include <sys/signal.h>
50 #include <netinet/in_systm.h>
51 #include <netinet/ip.h>
54 #define IPTOS_MINCOST 0x02
57 /* #define VOCAL_DATA_HACK */
60 #define DEFAULT_DEFAULT_EXPIRY 120
61 #define DEFAULT_MAX_EXPIRY 3600
62 #define EXPIRY_GUARD_SECS 15
64 #define SIP_DTMF_RFC2833 (1 << 0)
65 #define SIP_DTMF_INBAND (1 << 1)
66 #define SIP_DTMF_INFO (1 << 2)
68 static int max_expiry = DEFAULT_MAX_EXPIRY;
69 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
71 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
72 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
73 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
75 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
76 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
78 static char *desc = "Session Initiation Protocol (SIP)";
79 static char *type = "sip";
80 static char *tdesc = "Session Initiation Protocol (SIP)";
81 static char *config = "sip.conf";
83 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
84 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
86 static char context[AST_MAX_EXTENSION] = "default";
88 static char language[MAX_LANGUAGE] = "";
90 static char callerid[AST_MAX_EXTENSION] = "asterisk";
92 static char fromdomain[AST_MAX_EXTENSION] = "";
94 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
96 static int srvlookup = 0;
99 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
101 /* Protect the interface list (of sip_pvt's) */
102 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
104 /* Protect the monitoring thread, so only one process can kill or start it, and not
105 when it's doing something critical. */
106 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
108 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
110 /* This is the thread for the monitor which checks for input on the channels
111 which are not currently in use. */
112 static pthread_t monitor_thread = 0;
114 static int restart_monitor(void);
116 /* Codecs that we support by default: */
117 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
118 static int noncodeccapability = AST_RTP_DTMF;
120 static char ourhost[256];
121 static struct in_addr __ourip;
124 static int sipdebug = 0;
128 static int videosupport = 0;
130 static int globaldtmfmode = SIP_DTMF_RFC2833;
133 static int expiry = 900;
135 static struct sched_context *sched;
136 static struct io_context *io;
137 /* The private structures of the sip channels are linked for
138 selecting outgoing channels */
140 #define SIP_MAX_HEADERS 64
141 #define SIP_MAX_LINES 64
143 static struct sip_codec_pref {
145 struct sip_codec_pref *next;
149 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
150 char *rlPart2; /* The Request URI or Response Status */
152 int headers; /* SIP Headers */
153 char *header[SIP_MAX_HEADERS];
154 int lines; /* SDP Content */
155 char *line[SIP_MAX_LINES];
156 char data[SIP_MAX_PACKET];
162 struct sip_route *next;
166 static struct sip_pvt {
167 pthread_mutex_t lock; /* Channel private lock */
168 char callid[80]; /* Global CallID */
169 char randdata[80]; /* Random data */
170 unsigned int ocseq; /* Current outgoing seqno */
171 unsigned int icseq; /* Current incoming seqno */
172 unsigned int callgroup;
173 unsigned int pickupgroup;
174 int lastinvite; /* Last Cseq of invite */
175 int alreadygone; /* Whether or not we've already been destroyed by or peer */
176 int needdestroy; /* if we need to be destroyed */
177 int capability; /* Special capability */
178 int noncodeccapability;
179 int outgoing; /* Outgoing or incoming call? */
180 int authtries; /* Times we've tried to authenticate */
181 int insecure; /* Don't check source port/ip */
182 int expiry; /* How long we take to expire */
183 int branch; /* One random number */
184 int canreinvite; /* Do we support reinvite */
185 int ringing; /* Have sent 180 ringing */
186 int progress; /* Have sent 183 message progress */
187 int tag; /* Another random number */
188 int nat; /* Whether to try to support NAT */
189 struct sockaddr_in sa; /* Our peer */
190 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
191 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
192 struct sockaddr_in recv; /* Received as */
193 struct in_addr ourip; /* Our IP */
194 struct ast_channel *owner; /* Who owns us */
195 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
196 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
197 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
198 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
199 struct sip_pvt *refer_call; /* Call we are referring */
200 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
201 char remote_party_id[256];
203 char context[AST_MAX_EXTENSION];
204 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
205 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
206 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
207 char language[MAX_LANGUAGE];
208 char rdnis[256]; /* Referring DNIS */
209 char theirtag[256]; /* Their tag */
212 char uri[81]; /* Original requested URI */
214 char callerid[256]; /* Caller*ID */
216 char accountcode[20]; /* Account code */
217 char our_contact[256]; /* Our contact header */
218 char realm[256]; /* Authorization realm */
219 char nonce[256]; /* Authorization nonce */
220 int amaflags; /* AMA Flags */
221 int pendinginvite; /* Any pending invite */
222 int pendingbye; /* Need to send bye after we ack? */
223 struct sip_request initreq; /* Initial request */
225 int maxtime; /* Max time for first response */
226 int initid; /* Auto-congest ID if appropriate */
227 int autokillid; /* Auto-kill ID */
236 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
237 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
238 struct ast_rtp *rtp; /* RTP Session */
239 struct ast_rtp *vrtp; /* Video RTP session */
240 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
241 struct sip_pvt *next;
245 struct sip_pkt *next; /* Next packet */
246 int retrans; /* Retransmission number */
247 int seqno; /* Sequence number */
248 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
249 struct sip_pvt *owner; /* Owner call */
250 int retransid; /* Retransmission ID */
251 int packetlen; /* Length of packet */
256 /* Users who can access various contexts */
262 char accountcode[20];
263 unsigned int callgroup;
264 unsigned int pickupgroup;
272 struct sip_user *next;
278 char context[80]; /* JK02: peers need context too to allow parking etc */
284 char mailbox[AST_MAX_EXTENSION];
294 unsigned int callgroup;
295 unsigned int pickupgroup;
297 struct sockaddr_in addr;
301 struct sip_pvt *call; /* Call pointer */
302 int pokeexpire; /* When to expire poke */
303 int lastms; /* How long last response took (in ms), or -1 for no response */
304 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
305 struct timeval ps; /* Ping send time */
307 struct sockaddr_in defaddr;
311 struct sip_peer *next;
314 static struct ast_user_list {
315 struct sip_user *users;
316 pthread_mutex_t lock;
317 } userl = { NULL, AST_MUTEX_INITIALIZER };
319 static struct ast_peer_list {
320 struct sip_peer *peers;
321 pthread_mutex_t lock;
322 } peerl = { NULL, AST_MUTEX_INITIALIZER };
325 #define REG_STATE_UNREGISTERED 0
326 #define REG_STATE_REGSENT 1
327 #define REG_STATE_AUTHSENT 2
328 #define REG_STATE_REGISTERED 3
329 #define REG_STATE_REJECTED 4
330 #define REG_STATE_TIMEOUT 5
331 #define REG_STATE_NOAUTH 6
333 struct sip_registry {
334 pthread_mutex_t lock; /* Channel private lock */
335 struct sockaddr_in addr; /* Who we connect to for registration purposes */
336 char username[80]; /* Who we are registering as */
337 char authuser[80]; /* Who we *authenticate* as */
339 char secret[80]; /* Password or key name in []'s */
340 char contact[80]; /* Contact extension */
342 int expire; /* Sched ID of expiration */
343 int timeout; /* sched id of sip_reg_timeout */
344 int refresh; /* How often to refresh */
345 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
347 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
348 char callid[80]; /* Global CallID for this registry */
349 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
350 struct sockaddr_in us; /* Who the server thinks we are */
351 struct sip_registry *next;
354 #define REINVITE_INVITE 1
355 #define REINVITE_UPDATE 2
357 static int sip_do_register(struct sip_registry *r);
358 static struct sip_registry *registrations;
360 static int sipsock = -1;
361 static int globalnat = 0;
362 static int globalcanreinvite = REINVITE_INVITE;
365 static struct sockaddr_in bindaddr;
367 static struct ast_frame *sip_read(struct ast_channel *ast);
368 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
369 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
370 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
371 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
372 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
373 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url,char *distinctive_ring);
374 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
375 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
376 static int transmit_message_with_text(struct sip_pvt *p, char *text);
377 static int transmit_refer(struct sip_pvt *p, char *dest);
378 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
379 static char *getsipuri(char *header);
380 static void free_old_route(struct sip_route *route);
381 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
383 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
387 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
389 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
391 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));
396 static void sip_destroy(struct sip_pvt *p);
398 static int retrans_pkt(void *data)
400 struct sip_pkt *pkt=data;
402 ast_pthread_mutex_lock(&pkt->owner->lock);
403 if (1 /* !p->owner->needdestroy */) {
404 if (pkt->retrans < MAX_RETRANS) {
408 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));
410 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));
412 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
415 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
417 if (pkt->owner->owner) {
418 /* XXX Potential deadlocK?? XXX */
419 ast_queue_hangup(pkt->owner->owner, 1);
421 /* If no owner, destroy now */
422 ast_pthread_mutex_unlock(&pkt->owner->lock);
423 sip_destroy(pkt->owner);
428 /* Don't bother retransmitting. It's about to be killed anyway */
430 if (pkt->owner->owner) {
431 /* XXX Potential deadlocK?? XXX */
432 ast_queue_hangup(pkt->owner->owner, 1);
434 /* If no owner, destroy now */
435 ast_pthread_mutex_unlock(&pkt->owner->lock);
436 sip_destroy(pkt->owner);
441 ast_pthread_mutex_unlock(&pkt->owner->lock);
445 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
448 pkt = malloc(sizeof(struct sip_pkt) + len);
451 memset(pkt, 0, sizeof(struct sip_pkt));
452 memcpy(pkt->data, data, len);
453 pkt->packetlen = len;
454 pkt->next = p->packets;
458 /* Schedule retransmission */
459 pkt->retransid = ast_sched_add(sched, 1000, retrans_pkt, pkt);
460 pkt->next = p->packets;
462 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
463 if (!strncasecmp(pkt->data, "INVITE", 6)) {
464 /* Note this is a pending invite */
465 p->pendinginvite = seqno;
470 static int __sip_autodestruct(void *data)
472 struct sip_pvt *p = data;
474 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
476 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
477 ast_queue_hangup(p->owner, 0);
484 static int sip_scheddestroy(struct sip_pvt *p, int ms)
486 if (p->autokillid > -1)
487 ast_sched_del(sched, p->autokillid);
488 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
492 static int sip_cancel_destroy(struct sip_pvt *p)
494 if (p->autokillid > -1)
495 ast_sched_del(sched, p->autokillid);
500 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
502 struct sip_pkt *cur, *prev = NULL;
507 if ((cur->seqno == seqno) && (cur->resp == resp)) {
508 if (!resp && (seqno == p->pendinginvite)) {
509 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
510 p->pendinginvite = 0;
513 /* this is our baby */
515 prev->next = cur->next;
517 p->packets = cur->next;
518 if (cur->retransid > -1)
519 ast_sched_del(sched, cur->retransid);
527 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
531 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
536 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));
538 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));
541 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
543 res = __sip_xmit(p, req->data, req->len);
549 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
554 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));
556 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));
559 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
561 res = __sip_xmit(p, req->data, req->len);
565 static char *ditch_braces(char *tmp)
570 if ((n = strchr(tmp, '<')) ) {
572 while(*c && *c != '>') c++;
574 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
583 static int sip_sendtext(struct ast_channel *ast, char *text)
585 struct sip_pvt *p = ast->pvt->pvt;
587 ast_verbose("Sending text %s on %s\n", text, ast->name);
590 if (!text || !strlen(text))
593 ast_verbose("Really sending text %s on %s\n", text, ast->name);
594 transmit_message_with_text(p, text);
598 static int create_addr(struct sip_pvt *r, char *peer)
605 char host[256], *hostn;
607 r->sa.sin_family = AF_INET;
608 ast_pthread_mutex_lock(&peerl.lock);
611 if (!strcasecmp(p->name, peer)) {
613 r->capability = p->capability;
616 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
617 ast_rtp_setnat(r->rtp, r->nat);
620 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
621 ast_rtp_setnat(r->vrtp, r->nat);
623 strncpy(r->peername, p->username, sizeof(r->peername)-1);
624 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
625 strncpy(r->username, p->username, sizeof(r->username)-1);
626 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
627 if (!strlen(r->tohost)) {
628 if (p->addr.sin_addr.s_addr)
629 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
631 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
633 if (strlen(p->fromdomain))
634 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
635 if (strlen(p->fromuser))
636 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
637 r->insecure = p->insecure;
638 r->canreinvite = p->canreinvite;
639 r->maxtime = p->maxms;
640 r->callgroup = p->callgroup;
641 r->pickupgroup = p->pickupgroup;
643 r->dtmfmode = p->dtmfmode;
644 if (r->dtmfmode & SIP_DTMF_RFC2833)
645 r->noncodeccapability |= AST_RTP_DTMF;
647 r->noncodeccapability &= ~AST_RTP_DTMF;
649 strncpy(r->context, p->context,sizeof(r->context)-1);
650 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
651 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
652 if (p->addr.sin_addr.s_addr) {
653 r->sa.sin_addr = p->addr.sin_addr;
654 r->sa.sin_port = p->addr.sin_port;
656 r->sa.sin_addr = p->defaddr.sin_addr;
657 r->sa.sin_port = p->defaddr.sin_port;
659 memcpy(&r->recv, &r->sa, sizeof(r->recv));
665 ast_pthread_mutex_unlock(&peerl.lock);
667 if ((port=strchr(peer, ':'))) {
675 portno = DEFAULT_SIP_PORT;
680 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
681 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
687 hp = gethostbyname(hostn);
689 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
690 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
691 r->sa.sin_port = htons(portno);
692 memcpy(&r->recv, &r->sa, sizeof(r->recv));
695 ast_log(LOG_WARNING, "No such host: %s\n", peer);
704 static int auto_congest(void *nothing)
706 struct sip_pvt *p = nothing;
707 ast_pthread_mutex_lock(&p->lock);
710 if (!pthread_mutex_trylock(&p->owner->lock)) {
711 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
712 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
713 ast_pthread_mutex_unlock(&p->owner->lock);
716 ast_pthread_mutex_unlock(&p->lock);
720 static void sip_prefs_free(void)
722 struct sip_codec_pref *cur, *next;
732 static void sip_pref_remove(int format)
734 struct sip_codec_pref *cur, *prev=NULL;
737 if (cur->codec == format) {
739 prev->next = cur->next;
750 static int sip_pref_append(int format)
752 struct sip_codec_pref *cur, *tmp;
753 sip_pref_remove(format);
754 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
757 memset(tmp, 0, sizeof(struct sip_codec_pref));
769 static int sip_codec_choose(int formats)
771 struct sip_codec_pref *cur;
772 formats &= (AST_FORMAT_MAX_AUDIO - 1);
775 if (formats & cur->codec)
779 return ast_best_codec(formats);
782 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
786 char *vxml_url = NULL;
787 char *distinctive_ring = NULL;
788 struct varshead *headp;
789 struct ast_var_t *current;
792 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
793 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
796 /* Check whether there is vxml_url, distinctive ring variables */
798 headp=&ast->varshead;
799 AST_LIST_TRAVERSE(headp,current,entries) {
800 /* Check whether there is a VXML_URL variable */
801 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
803 vxml_url = ast_var_value(current);
806 /* Check whether there is a ALERT_INFO variable */
807 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
809 distinctive_ring = ast_var_value(current);
816 transmit_invite(p, "INVITE", 1, NULL, vxml_url,distinctive_ring);
818 /* Initialize auto-congest time */
819 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
824 static void __sip_destroy(struct sip_pvt *p, int lockowner)
826 struct sip_pvt *cur, *prev = NULL;
829 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
831 ast_extension_state_del(p->stateid, NULL);
833 ast_sched_del(sched, p->initid);
834 if (p->autokillid > -1)
835 ast_sched_del(sched, p->autokillid);
838 ast_rtp_destroy(p->rtp);
841 ast_rtp_destroy(p->vrtp);
844 free_old_route(p->route);
848 p->registry->call=NULL;
850 /* Unlink us from the owner if we have one */
853 ast_pthread_mutex_lock(&p->owner->lock);
854 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
855 p->owner->pvt->pvt = NULL;
857 ast_pthread_mutex_unlock(&p->owner->lock);
863 prev->next = cur->next;
872 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
875 ast_sched_del(sched, p->initid);
876 while((cp = p->packets)) {
877 p->packets = p->packets->next;
878 if (cp->retransid > -1)
879 ast_sched_del(sched, cp->retransid);
885 static void sip_destroy(struct sip_pvt *p)
887 ast_pthread_mutex_lock(&iflock);
889 ast_pthread_mutex_unlock(&iflock);
892 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
895 static int sip_hangup(struct ast_channel *ast)
897 struct sip_pvt *p = ast->pvt->pvt;
901 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
902 if (!ast->pvt->pvt) {
903 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
906 ast_pthread_mutex_lock(&p->lock);
907 /* Determine how to disconnect */
908 if (p->owner != ast) {
909 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
910 ast_pthread_mutex_unlock(&p->lock);
913 if (!ast || (ast->_state != AST_STATE_UP))
918 ast_dsp_free(p->vad);
921 ast->pvt->pvt = NULL;
924 /* Start the process if it's not already started */
925 if (!p->alreadygone && strlen(p->initreq.data)) {
928 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
929 /* Actually don't destroy us yet, wait for the 487 on our original
930 INVITE, but do set an autodestruct just in case. */
932 sip_scheddestroy(p, 15000);
934 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
936 if (!p->pendinginvite) {
938 transmit_request_with_auth(p, "BYE", 0, 1);
940 /* Note we will need a BYE when this all settles out
941 but we can't send one while we have "INVITE" outstanding. */
946 p->needdestroy = needdestroy;
947 ast_pthread_mutex_unlock(&p->lock);
951 static int sip_answer(struct ast_channel *ast)
955 struct sip_pvt *p = ast->pvt->pvt;
958 if (ast->_state != AST_STATE_UP) {
962 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
964 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
965 fmt=ast_getformatbyname(codec);
968 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
971 ast_setstate(ast, AST_STATE_UP);
973 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
974 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
979 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
981 struct sip_pvt *p = ast->pvt->pvt;
983 if (frame->frametype == AST_FRAME_VOICE) {
984 if (!(frame->subclass & ast->nativeformats)) {
985 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
986 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
990 ast_pthread_mutex_lock(&p->lock);
992 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
993 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
996 res = ast_rtp_write(p->rtp, frame);
998 ast_pthread_mutex_unlock(&p->lock);
1000 } else if (frame->frametype == AST_FRAME_VIDEO) {
1002 ast_pthread_mutex_lock(&p->lock);
1004 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1005 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1008 res = ast_rtp_write(p->vrtp, frame);
1010 ast_pthread_mutex_unlock(&p->lock);
1012 } else if (frame->frametype == AST_FRAME_IMAGE) {
1015 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1022 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1024 struct sip_pvt *p = newchan->pvt->pvt;
1025 ast_pthread_mutex_lock(&p->lock);
1026 if (p->owner != oldchan) {
1027 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1028 ast_pthread_mutex_unlock(&p->lock);
1032 ast_pthread_mutex_unlock(&p->lock);
1036 static int sip_senddigit(struct ast_channel *ast, char digit)
1038 struct sip_pvt *p = ast->pvt->pvt;
1039 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1040 transmit_info_with_digit(p, digit);
1042 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1043 ast_rtp_senddigit(p->rtp, digit);
1045 /* If in-band DTMF is desired, send that */
1046 if (p->dtmfmode & SIP_DTMF_INBAND)
1051 static int sip_transfer(struct ast_channel *ast, char *dest)
1053 struct sip_pvt *p = ast->pvt->pvt;
1055 res = transmit_refer(p, dest);
1059 static int sip_indicate(struct ast_channel *ast, int condition)
1061 struct sip_pvt *p = ast->pvt->pvt;
1063 case AST_CONTROL_RINGING:
1064 if (ast->_state == AST_STATE_RING) {
1065 if (!p->progress && !p->ringing) {
1066 transmit_response(p, "180 Ringing", &p->initreq);
1070 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1074 case AST_CONTROL_BUSY:
1075 if (ast->_state != AST_STATE_UP) {
1076 transmit_response(p, "486 Busy Here", &p->initreq);
1078 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1082 case AST_CONTROL_CONGESTION:
1083 if (ast->_state != AST_STATE_UP) {
1084 transmit_response(p, "503 Service Unavailable", &p->initreq);
1086 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1090 case AST_CONTROL_PROGRESS:
1091 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1092 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1100 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1108 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1110 struct ast_channel *tmp;
1112 tmp = ast_channel_alloc(1);
1114 /* Select our native format based on codec preference until we receive
1115 something from another device to the contrary. */
1117 tmp->nativeformats = sip_codec_choose(i->capability);
1119 tmp->nativeformats = sip_codec_choose(capability);
1120 fmt = ast_best_codec(tmp->nativeformats);
1122 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1124 if (strchr(i->from,':'))
1126 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->from,':')+1, (int)(i));
1130 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->from, (int)(i));
1133 if (i->dtmfmode & SIP_DTMF_INBAND) {
1134 i->vad = ast_dsp_new();
1135 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1137 tmp->fds[0] = ast_rtp_fd(i->rtp);
1138 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1140 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1141 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1143 ast_setstate(tmp, state);
1144 if (state == AST_STATE_RING)
1146 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1147 tmp->writeformat = fmt;
1148 tmp->pvt->rawwriteformat = fmt;
1149 tmp->readformat = fmt;
1150 tmp->pvt->rawreadformat = fmt;
1152 tmp->pvt->send_text = sip_sendtext;
1153 tmp->pvt->call = sip_call;
1154 tmp->pvt->hangup = sip_hangup;
1155 tmp->pvt->answer = sip_answer;
1156 tmp->pvt->read = sip_read;
1157 tmp->pvt->write = sip_write;
1158 tmp->pvt->write_video = sip_write;
1159 tmp->pvt->indicate = sip_indicate;
1160 tmp->pvt->transfer = sip_transfer;
1161 tmp->pvt->fixup = sip_fixup;
1162 tmp->pvt->send_digit = sip_senddigit;
1164 tmp->pvt->bridge = ast_rtp_bridge;
1166 tmp->callgroup = i->callgroup;
1167 tmp->pickupgroup = i->pickupgroup;
1168 if (strlen(i->accountcode))
1169 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1171 tmp->amaflags = i->amaflags;
1172 if (strlen(i->language))
1173 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1175 ast_pthread_mutex_lock(&usecnt_lock);
1177 ast_pthread_mutex_unlock(&usecnt_lock);
1178 ast_update_use_count();
1179 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1180 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1181 if (strlen(i->callerid))
1182 tmp->callerid = strdup(i->callerid);
1183 if (strlen(i->rdnis))
1184 tmp->rdnis = strdup(i->rdnis);
1186 if (state != AST_STATE_DOWN) {
1187 if (ast_pbx_start(tmp)) {
1188 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1194 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1198 static struct cfalias {
1202 { "Content-Type", "c" },
1203 { "Content-Encoding", "e" },
1207 { "Content-Length", "l" },
1213 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1214 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1215 char* r = line + nameLen + 1;
1216 while (*r && (*r < 33)) ++r;
1223 static char *get_sdp(struct sip_request *req, char *name) {
1225 int len = strlen(name);
1228 for (x=0; x<req->lines; x++) {
1229 r = get_sdp_by_line(req->line[x], name, len);
1230 if (r[0] != '\0') return r;
1235 static void sdpLineNum_iterator_init(int* iterator) {
1239 static char* get_sdp_iterate(int* iterator,
1240 struct sip_request *req, char *name) {
1241 int len = strlen(name);
1243 while (*iterator < req->lines) {
1244 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1245 if (r[0] != '\0') return r;
1250 static char *__get_header(struct sip_request *req, char *name, int *start)
1253 int len = strlen(name);
1255 for (x=*start;x<req->headers;x++) {
1256 if (!strncasecmp(req->header[x], name, len) &&
1257 (req->header[x][len] == ':')) {
1258 r = req->header[x] + len + 1;
1259 while(*r && (*r < 33))
1266 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1267 if (!strcasecmp(aliases[x].fullname, name))
1268 return __get_header(req, aliases[x].shortname, start);
1270 /* Don't return NULL, so get_header is always a valid pointer */
1274 static char *get_header(struct sip_request *req, char *name)
1277 return __get_header(req, name, &start);
1280 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1282 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1283 struct ast_frame *f;
1284 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1287 f = ast_rtp_read(p->rtp);
1290 f = ast_rtcp_read(p->rtp);
1293 f = ast_rtp_read(p->vrtp);
1296 f = ast_rtcp_read(p->vrtp);
1301 /* Don't send RFC2833 if we're not supposed to */
1302 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1305 /* We already hold the channel lock */
1306 if (f->frametype == AST_FRAME_VOICE) {
1307 if (f->subclass != p->owner->nativeformats) {
1308 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1309 p->owner->nativeformats = f->subclass;
1310 ast_set_read_format(p->owner, p->owner->readformat);
1311 ast_set_write_format(p->owner, p->owner->writeformat);
1313 if (p->dtmfmode & SIP_DTMF_INBAND) {
1314 f = ast_dsp_process(p->owner,p->vad,f,0);
1321 static struct ast_frame *sip_read(struct ast_channel *ast)
1323 struct ast_frame *fr;
1324 struct sip_pvt *p = ast->pvt->pvt;
1325 ast_pthread_mutex_lock(&p->lock);
1326 fr = sip_rtp_read(ast, p);
1327 ast_pthread_mutex_unlock(&p->lock);
1331 static void build_callid(char *callid, int len, struct in_addr ourip)
1338 res = snprintf(callid, len, "%08x", val);
1342 /* It's not important that we really use our right IP here... */
1343 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1346 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1350 p = malloc(sizeof(struct sip_pvt));
1353 /* Keep track of stuff */
1354 memset(p, 0, sizeof(struct sip_pvt));
1358 p->rtp = ast_rtp_new(sched, io, 1, 0);
1360 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1364 /* Start with 101 instead of 1 */
1367 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1371 ast_rtp_settos(p->rtp, tos);
1373 ast_rtp_settos(p->vrtp, tos);
1374 if (useglobalnat && sin) {
1375 /* Setup NAT structure according to global settings if we have an address */
1377 memcpy(&p->recv, sin, sizeof(p->recv));
1378 ast_rtp_setnat(p->rtp, p->nat);
1380 ast_rtp_setnat(p->vrtp, p->nat);
1382 ast_pthread_mutex_init(&p->lock);
1385 memcpy(&p->sa, sin, sizeof(p->sa));
1386 if (ast_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1387 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1389 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1391 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1392 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1394 build_callid(p->callid, sizeof(p->callid), p->ourip);
1396 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1397 /* Assume reinvite OK and via INVITE */
1398 p->canreinvite = globalcanreinvite;
1399 p->dtmfmode = globaldtmfmode;
1400 if (p->dtmfmode & SIP_DTMF_RFC2833)
1401 p->noncodeccapability |= AST_RTP_DTMF;
1402 strncpy(p->context, context, sizeof(p->context) - 1);
1403 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1405 ast_pthread_mutex_lock(&iflock);
1408 ast_pthread_mutex_unlock(&iflock);
1410 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1414 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1418 callid = get_header(req, "Call-ID");
1419 if (!strlen(callid)) {
1420 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1423 ast_pthread_mutex_lock(&iflock);
1426 if (!strcmp(p->callid, callid)) {
1427 /* Found the call */
1429 if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1430 (p->sa.sin_port != sin->sin_port))) {
1433 snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1434 snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1435 ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1436 ast_pthread_mutex_unlock(&iflock);
1440 ast_pthread_mutex_lock(&p->lock);
1441 ast_pthread_mutex_unlock(&iflock);
1446 ast_pthread_mutex_unlock(&iflock);
1447 p = sip_alloc(callid, sin, 1);
1449 ast_pthread_mutex_lock(&p->lock);
1453 static int sip_register(char *value, int lineno)
1455 struct sip_registry *reg;
1456 char copy[256] = "";
1457 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1465 strncpy(copy, value, sizeof(copy)-1);
1468 hostname = strrchr(stringp, '@');
1473 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1474 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port] at line %d", lineno);
1478 username = strsep(&stringp, ":");
1480 secret = strsep(&stringp, ":");
1482 authuser = strsep(&stringp, ":");
1485 hostname = strsep(&stringp, "/");
1487 contact = strsep(&stringp, "/");
1488 if (!contact || !strlen(contact))
1491 hostname = strsep(&stringp, ":");
1492 porta = strsep(&stringp, ":");
1494 if (porta && !atoi(porta)) {
1495 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1498 hp = gethostbyname(hostname);
1500 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1503 reg = malloc(sizeof(struct sip_registry));
1505 memset(reg, 0, sizeof(struct sip_registry));
1506 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1508 strncpy(reg->username, username, sizeof(reg->username)-1);
1510 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1512 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1514 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1517 reg->refresh = default_expiry;
1518 reg->addr.sin_family = AF_INET;
1519 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1520 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1521 reg->next = registrations;
1522 reg->callid_valid = 0;
1524 registrations = reg;
1526 ast_log(LOG_ERROR, "Out of memory\n");
1532 static void parse(struct sip_request *req)
1534 /* Divide fields by NULL's */
1539 /* First header starts immediately */
1543 /* We've got a new header */
1547 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1549 if (!strlen(req->header[f])) {
1550 /* Line by itself means we're now in content */
1554 if (f >= SIP_MAX_HEADERS - 1) {
1555 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1558 req->header[f] = c + 1;
1559 } else if (*c == '\r') {
1560 /* Ignore but eliminate \r's */
1565 /* Check for last header */
1566 if (strlen(req->header[f]))
1569 /* Now we process any mime content */
1574 /* We've got a new line */
1577 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1579 if (f >= SIP_MAX_LINES - 1) {
1580 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1583 req->line[f] = c + 1;
1584 } else if (*c == '\r') {
1585 /* Ignore and eliminate \r's */
1590 /* Check for last line */
1591 if (strlen(req->line[f]))
1595 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1597 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1600 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1609 int peercapability, peernoncodeccapability;
1610 int vpeercapability=0, vpeernoncodeccapability=0;
1611 struct sockaddr_in sin;
1618 /* Get codec and RTP info from SDP */
1619 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1620 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1623 m = get_sdp(req, "m");
1624 c = get_sdp(req, "c");
1625 if (!strlen(m) || !strlen(c)) {
1626 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1629 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1630 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1633 /* XXX This could block for a long time, and block the main thread! XXX */
1634 hp = gethostbyname(host);
1636 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1639 sdpLineNum_iterator_init(&iterator);
1640 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
1641 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
1643 // Scan through the RTP payload types specified in a "m=" line:
1644 ast_rtp_pt_clear(p->rtp);
1646 while(strlen(codecs)) {
1647 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1648 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1652 ast_verbose("Found audio format %d\n", codec);
1653 ast_rtp_set_m_type(p->rtp, codec);
1655 /* Skip over any whitespace */
1656 while(*codecs && (*codecs < 33)) codecs++;
1659 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
1661 // Scan through the RTP payload types specified in a "m=" line:
1662 ast_rtp_pt_clear(p->vrtp);
1664 while(strlen(codecs)) {
1665 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1666 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1670 ast_verbose("Found video format %d\n", codec);
1671 ast_rtp_set_m_type(p->vrtp, codec);
1673 /* Skip over any whitespace */
1674 while(*codecs && (*codecs < 33)) codecs++;
1678 sin.sin_family = AF_INET;
1679 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1680 /* Setup audio port number */
1681 sin.sin_port = htons(portno);
1682 if (p->rtp && sin.sin_port)
1683 ast_rtp_set_peer(p->rtp, &sin);
1684 /* Setup video port number */
1685 sin.sin_port = htons(vportno);
1686 if (p->vrtp && sin.sin_port)
1687 ast_rtp_set_peer(p->vrtp, &sin);
1689 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1691 // Next, scan through each "a=rtpmap:" line, noting each
1692 // specified RTP payload type (with corresponding MIME subtype):
1693 sdpLineNum_iterator_init(&iterator);
1694 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1695 char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
1696 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1698 ast_verbose("Found description format %s\n", mimeSubtype);
1699 // Note: should really look at the 'freq' and '#chans' params too
1700 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1702 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
1705 // Now gather all of the codecs that were asked for:
1706 ast_rtp_get_current_formats(p->rtp,
1707 &peercapability, &peernoncodeccapability);
1709 ast_rtp_get_current_formats(p->vrtp,
1710 &vpeercapability, &vpeernoncodeccapability);
1711 p->capability = capability & (peercapability | vpeercapability);
1712 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
1715 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
1716 capability, peercapability, vpeercapability, p->capability);
1717 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1718 noncodeccapability, peernoncodeccapability,
1719 p->noncodeccapability);
1721 if (!p->capability) {
1722 ast_log(LOG_WARNING, "No compatible codecs!\n");
1726 if (!(p->owner->nativeformats & p->capability)) {
1727 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);
1728 p->owner->nativeformats = sip_codec_choose(p->capability);
1729 ast_set_read_format(p->owner, p->owner->readformat);
1730 ast_set_write_format(p->owner, p->owner->writeformat);
1732 if (p->owner->bridge) {
1733 /* Turn on/off music on hold if we are holding/unholding */
1734 if (sin.sin_addr.s_addr) {
1735 ast_moh_stop(p->owner->bridge);
1737 ast_moh_start(p->owner->bridge, NULL);
1745 static int add_header(struct sip_request *req, char *var, char *value)
1747 if (req->len >= sizeof(req->data) - 4) {
1748 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1752 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1755 req->header[req->headers] = req->data + req->len;
1756 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1757 req->len += strlen(req->header[req->headers]);
1758 if (req->headers < SIP_MAX_HEADERS)
1761 ast_log(LOG_WARNING, "Out of header space\n");
1767 static int add_blank_header(struct sip_request *req)
1769 if (req->len >= sizeof(req->data) - 4) {
1770 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1774 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1777 req->header[req->headers] = req->data + req->len;
1778 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1779 req->len += strlen(req->header[req->headers]);
1780 if (req->headers < SIP_MAX_HEADERS)
1783 ast_log(LOG_WARNING, "Out of header space\n");
1789 static int add_line(struct sip_request *req, char *line)
1791 if (req->len >= sizeof(req->data) - 4) {
1792 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1796 /* Add extra empty return */
1797 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1798 req->len += strlen(req->data + req->len);
1800 req->line[req->lines] = req->data + req->len;
1801 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1802 req->len += strlen(req->line[req->lines]);
1803 if (req->lines < SIP_MAX_LINES)
1806 ast_log(LOG_WARNING, "Out of line space\n");
1812 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1815 tmp = get_header(orig, field);
1817 /* Add what we're responding to */
1818 return add_header(req, field, tmp);
1820 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1824 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1830 tmp = __get_header(orig, field, &start);
1832 /* Add what we're responding to */
1833 add_header(req, field, tmp);
1838 return copied ? 0 : -1;
1841 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1848 tmp = __get_header(orig, field, &start);
1850 if (!copied && p->nat) {
1851 /* SLD: FIXME: Nice try, but the received= should not have a port */
1852 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1853 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1854 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1856 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1857 add_header(req, field, new);
1859 /* Add what we're responding to */
1860 add_header(req, field, tmp);
1867 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1873 /* Add Route: header into request per learned route */
1874 static void add_route(struct sip_request *req, struct sip_route *route)
1877 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1883 n = strlen(route->hop);
1884 if ((n+3)>rem) break;
1890 strcpy(p, route->hop); p += n;
1893 route = route->next;
1896 add_header(req, "Route", r);
1899 static void set_destination(struct sip_pvt *p, char *uri)
1901 char *h, *maddr, hostname[256];
1905 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1906 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1909 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1911 /* Find and parse hostname */
1912 h = strchr(uri, '@');
1917 if (strncmp(h, "sip:", 4) == 0)
1919 else if (strncmp(h, "sips:", 5) == 0)
1922 hn = strcspn(h, ":;>");
1924 strncpy(hostname, h, hn); hostname[hn] = '\0';
1927 /* Is "port" present? if not default to 5060 */
1931 port = strtol(h, &h, 10);
1936 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
1937 maddr = strstr(h, "maddr=");
1940 hn = strspn(maddr, "0123456789.");
1942 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
1945 hp = gethostbyname(hostname);
1947 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
1950 p->sa.sin_family = AF_INET;
1951 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1952 p->sa.sin_port = htons(port);
1954 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1957 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1959 /* Initialize a response */
1960 if (req->headers || req->len) {
1961 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1964 req->header[req->headers] = req->data + req->len;
1965 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1966 req->len += strlen(req->header[req->headers]);
1967 if (req->headers < SIP_MAX_HEADERS)
1970 ast_log(LOG_WARNING, "Out of header space\n");
1974 static int init_req(struct sip_request *req, char *resp, char *recip)
1976 /* Initialize a response */
1977 if (req->headers || req->len) {
1978 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1981 req->header[req->headers] = req->data + req->len;
1982 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1983 req->len += strlen(req->header[req->headers]);
1984 if (req->headers < SIP_MAX_HEADERS)
1987 ast_log(LOG_WARNING, "Out of header space\n");
1991 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1993 char newto[256] = "", *ot;
1994 memset(resp, 0, sizeof(*resp));
1995 init_resp(resp, msg, req);
1996 copy_via_headers(p, resp, req, "Via");
1997 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1998 copy_header(resp, req, "From");
1999 ot = get_header(req, "To");
2000 if (!strstr(ot, "tag=")) {
2001 /* Add the proper tag if we don't have it already. If they have specified
2002 their tag, use it. Otherwise, use our own tag */
2003 if (strlen(p->theirtag) && p->outgoing)
2004 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2005 else if (p->tag && !p->outgoing)
2006 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2008 strncpy(newto, ot, sizeof(newto) - 1);
2011 add_header(resp, "To", ot);
2012 copy_header(resp, req, "Call-ID");
2013 copy_header(resp, req, "CSeq");
2014 add_header(resp, "User-Agent", "Asterisk PBX");
2016 /* For registration responses, we also need expiry and
2020 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2021 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2022 add_header(resp, "Expires", tmp);
2023 add_header(resp, "Contact", contact);
2025 add_header(resp, "Contact", p->our_contact);
2030 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2032 struct sip_request *orig = &p->initreq;
2033 char stripped[80] ="";
2039 memset(req, 0, sizeof(struct sip_request));
2047 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2049 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2051 c = strchr(stripped, '<');
2063 init_req(req, msg, c);
2065 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2067 add_header(req, "Via", p->via);
2069 set_destination(p, p->route->hop);
2070 add_route(req, p->route->next);
2073 ot = get_header(orig, "To");
2074 of = get_header(orig, "From");
2076 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2077 as our original request, including tag (or presumably lack thereof) */
2078 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2079 /* Add the proper tag if we don't have it already. If they have specified
2080 their tag, use it. Otherwise, use our own tag */
2081 if (p->outgoing && strlen(p->theirtag))
2082 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2083 else if (!p->outgoing)
2084 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2086 snprintf(newto, sizeof(newto), "%s", ot);
2091 add_header(req, "From", of);
2092 add_header(req, "To", ot);
2094 add_header(req, "From", ot);
2095 add_header(req, "To", of);
2097 add_header(req, "Contact", p->our_contact);
2098 copy_header(req, orig, "Call-ID");
2099 add_header(req, "CSeq", tmp);
2101 add_header(req, "User-Agent", "Asterisk PBX");
2105 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2107 struct sip_request resp;
2109 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2110 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2113 respprep(&resp, p, msg, req);
2114 add_header(&resp, "Content-Length", "0");
2115 add_blank_header(&resp);
2116 return send_response(p, &resp, reliable, seqno);
2119 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2121 return __transmit_response(p, msg, req, 0);
2123 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2125 return __transmit_response(p, msg, req, 1);
2128 static void append_date(struct sip_request *req)
2135 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2136 add_header(req, "Date", tmpdat);
2139 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2141 struct sip_request resp;
2142 respprep(&resp, p, msg, req);
2144 add_header(&resp, "Content-Length", "0");
2145 add_blank_header(&resp);
2146 return send_response(p, &resp, 0, 0);
2149 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2151 struct sip_request resp;
2152 respprep(&resp, p, msg, req);
2153 add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
2154 add_header(&resp, "Accept", "application/sdp");
2155 add_header(&resp, "Content-Length", "0");
2156 add_blank_header(&resp);
2157 return send_response(p, &resp, 0, 0);
2160 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2162 struct sip_request resp;
2165 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2166 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2169 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2170 respprep(&resp, p, msg, req);
2171 add_header(&resp, "Proxy-Authenticate", tmp);
2172 add_header(&resp, "Content-Length", "0");
2173 add_blank_header(&resp);
2174 return send_response(p, &resp, reliable, seqno);
2177 static int add_text(struct sip_request *req, char *text)
2179 /* XXX Convert \n's to \r\n's XXX */
2180 int len = strlen(text);
2182 snprintf(clen, sizeof(clen), "%d", len);
2183 add_header(req, "Content-Type", "text/plain");
2184 add_header(req, "Content-Length", clen);
2185 add_line(req, text);
2189 static int add_digit(struct sip_request *req, char digit)
2194 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2196 snprintf(clen, sizeof(clen), "%d", len);
2197 add_header(req, "Content-Type", "application/dtmf-relay");
2198 add_header(req, "Content-Length", clen);
2203 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2207 int alreadysent = 0;
2209 struct sockaddr_in sin;
2210 struct sockaddr_in vsin;
2211 struct sip_codec_pref *cur;
2222 struct sockaddr_in dest;
2223 struct sockaddr_in vdest;
2224 /* XXX We break with the "recommendation" and send our IP, in order that our
2225 peer doesn't have to gethostbyname() us XXX */
2228 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2231 ast_rtp_get_us(p->rtp, &sin);
2233 ast_rtp_get_us(p->vrtp, &vsin);
2235 if (p->redirip.sin_addr.s_addr) {
2236 dest.sin_port = p->redirip.sin_port;
2237 dest.sin_addr = p->redirip.sin_addr;
2239 ast_rtp_get_peer(rtp, &dest);
2241 dest.sin_addr = p->ourip;
2242 dest.sin_port = sin.sin_port;
2245 /* Determine video destination */
2247 if (p->vredirip.sin_addr.s_addr) {
2248 vdest.sin_port = p->vredirip.sin_port;
2249 vdest.sin_addr = p->vredirip.sin_addr;
2251 ast_rtp_get_peer(vrtp, &vdest);
2253 vdest.sin_addr = p->ourip;
2254 vdest.sin_port = vsin.sin_port;
2258 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2259 if (sipdebug && p->vrtp)
2260 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2261 snprintf(v, sizeof(v), "v=0\r\n");
2262 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2263 snprintf(s, sizeof(s), "s=session\r\n");
2264 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2265 snprintf(t, sizeof(t), "t=0 0\r\n");
2266 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2267 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2268 /* Start by sending our preferred codecs */
2271 if (p->capability & cur->codec) {
2273 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2274 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2276 snprintf(costr, sizeof(costr), " %d", codec);
2277 if (cur->codec < AST_FORMAT_MAX_AUDIO) {
2279 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2283 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2288 alreadysent |= cur->codec;
2291 /* Now send any other common codecs, and non-codec formats: */
2292 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2293 if ((p->capability & x) && !(alreadysent & x)) {
2295 ast_verbose("Answering with capability %d\n", x);
2296 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2298 snprintf(costr, sizeof(costr), " %d", codec);
2299 if (x < AST_FORMAT_MAX_AUDIO) {
2301 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2305 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2311 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2312 if (p->noncodeccapability & x) {
2314 ast_verbose("Answering with non-codec capability %d\n", x);
2315 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2317 snprintf(costr, sizeof(costr), " %d", codec);
2319 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2321 if (x == AST_RTP_DTMF) {
2322 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2323 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2332 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2334 len += strlen(m2) + strlen(a2);
2335 snprintf(costr, sizeof(costr), "%d", len);
2336 add_header(resp, "Content-Type", "application/sdp");
2337 add_header(resp, "Content-Length", costr);
2352 static void copy_request(struct sip_request *dst,struct sip_request *src)
2356 offset = ((void *)dst) - ((void *)src);
2357 /* First copy stuff */
2358 memcpy(dst, src, sizeof(*dst));
2359 /* Now fix pointer arithmetic */
2360 for (x=0;x<src->headers;x++)
2361 dst->header[x] += offset;
2362 for (x=0;x<src->lines;x++)
2363 dst->line[x] += offset;
2366 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2368 struct sip_request resp;
2370 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2371 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2374 respprep(&resp, p, msg, req);
2375 add_sdp(&resp, p, NULL, NULL);
2376 return send_response(p, &resp, retrans, seqno);
2379 static int determine_firstline_parts( struct sip_request *req ) {
2384 cmd= req->header[0];
2385 while(*cmd && (*cmd < 33)) {
2392 while(*e && (*e > 32)) {
2395 /* Get the command */
2401 while( *e && ( *e < 33 ) ) {
2408 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2409 /* We have a response */
2411 len= strlen( req->rlPart2 );
2412 if( len < 2 ) { return -1; }
2414 while( *e && *e<33 ) {
2419 /* We have a request */
2422 if( !*e ) { return -1; }
2425 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2428 while( isspace( *(--e) ) ) {}
2438 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2440 struct sip_request req;
2441 if (p->canreinvite == REINVITE_UPDATE)
2442 reqprep(&req, p, "UPDATE", 0);
2444 reqprep(&req, p, "INVITE", 0);
2445 add_sdp(&req, p, rtp, vrtp);
2446 /* Use this as the basis */
2447 copy_request(&p->initreq, &req);
2449 determine_firstline_parts(&p->initreq);
2450 p->lastinvite = p->ocseq;
2452 return send_request(p, &req, 1, p->ocseq);
2455 static void build_contact(struct sip_pvt *p)
2457 /* Construct Contact: header */
2458 if (ourport != 5060)
2459 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2461 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2464 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2471 char *l = callerid, *n=NULL;
2472 if (p->owner && p->owner->callerid) {
2473 strcpy(cid, p->owner->callerid);
2474 ast_callerid_parse(cid, &n, &l);
2476 ast_shrink_phone_number(l);
2477 if (!l || !ast_isphonenumber(l))
2480 if (!n || !strlen(n))
2482 /* Allow user to be overridden */
2483 if (strlen(p->fromuser))
2486 if ((ourport != 5060) && !strlen(p->fromdomain))
2487 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);
2489 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2491 if (strlen(p->username)) {
2492 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2493 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2495 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2497 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2498 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2500 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2502 strncpy(p->uri, invite, sizeof(p->uri) - 1);
2503 /* If there is a VXML URL append it to the SIP URL */
2506 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2510 snprintf(to, sizeof(to), "<%s>", invite );
2512 memset(req, 0, sizeof(struct sip_request));
2513 init_req(req, cmd, invite);
2514 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2516 add_header(req, "Via", p->via);
2517 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2518 * OTOH, then we won't have anything in p->route anyway */
2519 add_header(req, "From", from);
2520 strncpy(p->exten, l, sizeof(p->exten) - 1);
2522 add_header(req, "To", to);
2523 add_header(req, "Contact", p->our_contact);
2524 add_header(req, "Call-ID", p->callid);
2525 add_header(req, "CSeq", tmp);
2526 add_header(req, "User-Agent", "Asterisk PBX");
2529 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url, char *distinctive_ring)
2531 struct sip_request req;
2532 initreqprep(&req, p, cmd, vxml_url);
2534 add_header(&req, "Proxy-Authorization", auth);
2536 if (distinctive_ring)
2538 add_header(&req, "Alert-info",distinctive_ring);
2541 add_sdp(&req, p, NULL, NULL);
2543 add_header(&req, "Content-Length", "0");
2544 add_blank_header(&req);
2547 if (!p->initreq.headers) {
2548 /* Use this as the basis */
2549 copy_request(&p->initreq, &req);
2551 determine_firstline_parts(&p->initreq);
2553 p->lastinvite = p->ocseq;
2554 return send_request(p, &req, 1, p->ocseq);
2557 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2560 char from[256], to[256];
2563 struct sip_request req;
2566 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2568 c = ditch_braces(from);
2569 if (strncmp(c, "sip:", 4)) {
2570 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2573 if ((a = strchr(c, ';'))) {
2578 reqprep(&req, p, "NOTIFY", 0);
2580 if (p->subscribed == 1) {
2581 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2583 c = ditch_braces(to);
2584 if (strncmp(c, "sip:", 4)) {
2585 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2588 if ((a = strchr(c, ';'))) {
2593 add_header(&req, "Content-Type", "application/xpidf+xml");
2595 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2597 else if (state==AST_EXTENSION_INUSE)
2603 sprintf(t, "<?xml version=\"1.0\"?>\n");
2604 t = tmp + strlen(tmp);
2605 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2606 t = tmp + strlen(tmp);
2607 sprintf(t, "<presence>\n");
2608 t = tmp + strlen(tmp);
2609 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2610 t = tmp + strlen(tmp);
2611 sprintf(t, "<atom id=\"%s\">\n", p->exten);
2612 t = tmp + strlen(tmp);
2613 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2614 t = tmp + strlen(tmp);
2615 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2616 t = tmp + strlen(tmp);
2617 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2618 t = tmp + strlen(tmp);
2619 sprintf(t, "</address>\n</atom>\n</presence>\n");
2621 add_header(&req, "Event", "dialog");
2622 add_header(&req, "Content-Type", "application/dialog-info+xml");
2625 sprintf(t, "<?xml version=\"1.0\"?>\n");
2626 t = tmp + strlen(tmp);
2627 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);
2628 t = tmp + strlen(tmp);
2629 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2630 t = tmp + strlen(tmp);
2631 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2632 t = tmp + strlen(tmp);
2633 sprintf(t, "</dialog>\n</dialog-info>\n");
2636 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2637 add_header(&req, "Content-Length", clen);
2638 add_line(&req, tmp);
2640 return send_request(p, &req, 1, p->ocseq);
2643 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2645 struct sip_request req;
2649 initreqprep(&req, p, "NOTIFY", NULL);
2650 add_header(&req, "Event", "message-summary");
2651 add_header(&req, "Content-Type", notifymime);
2653 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2654 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2655 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2656 add_header(&req, "Content-Length", clen);
2657 add_line(&req, tmp);
2658 add_line(&req, tmp2);
2660 if (!p->initreq.headers) {
2661 /* Use this as the basis */
2662 copy_request(&p->initreq, &req);
2664 determine_firstline_parts(&p->initreq);
2667 return send_request(p, &req, 1, p->ocseq);
2670 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2672 static int sip_reregister(void *data)
2674 /* if we are here, we know that we need to reregister. */
2675 struct sip_registry *r=(struct sip_registry *)data;
2682 static int sip_do_register(struct sip_registry *r)
2685 ast_pthread_mutex_lock(&r->lock);
2686 res=transmit_register(r, "REGISTER", NULL);
2687 ast_pthread_mutex_unlock(&r->lock);
2691 static int sip_reg_timeout(void *data)
2693 /* if we are here, our registration timed out, so we'll just do it over */
2694 struct sip_registry *r=data;
2697 ast_pthread_mutex_lock(&r->lock);
2698 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
2700 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
2701 in the single SIP manager thread. */
2707 r->regstate=REG_STATE_UNREGISTERED;
2709 res=transmit_register(r, "REGISTER", NULL);
2710 ast_pthread_mutex_unlock(&r->lock);
2714 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2716 struct sip_request req;
2723 /* exit if we are already in process with this registrar ?*/
2724 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2725 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2731 ast_log(LOG_WARNING, "Already have a call??\n");
2736 if (!r->callid_valid) {
2737 build_callid(r->callid, sizeof(r->callid), __ourip);
2738 r->callid_valid = 1;
2740 p=sip_alloc( r->callid, &r->addr, 0);
2742 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2748 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2749 if (strlen(r->authuser))
2750 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2752 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2753 strncpy(p->username, r->username, sizeof(p->username)-1);
2754 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2758 /* set up a timeout */
2760 if (r->timeout > -1) {
2761 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2762 ast_sched_del(sched, r->timeout);
2764 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2765 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2768 if (strchr(r->username, '@')) {
2769 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
2770 snprintf(to, sizeof(to), "<sip:%s>", r->username);
2772 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2773 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
2776 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2777 strncpy(p->uri, addr, sizeof(p->uri) - 1);
2779 memset(&req, 0, sizeof(req));
2780 init_req(&req, cmd, addr);
2782 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2783 p->ocseq = r->ocseq;
2785 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2786 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2787 add_header(&req, "Via", via);
2788 add_header(&req, "From", from);
2789 add_header(&req, "To", to);
2790 add_header(&req, "Call-ID", p->callid);
2791 add_header(&req, "CSeq", tmp);
2792 add_header(&req, "User-Agent", "Asterisk PBX");
2794 add_header(&req, "Authorization", auth);
2796 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2797 add_header(&req, "Expires", tmp);
2798 add_header(&req, "Contact", p->our_contact);
2799 add_header(&req, "Event", "registration");
2800 add_header(&req, "Content-length", "0");
2801 add_blank_header(&req);
2802 copy_request(&p->initreq, &req);
2804 determine_firstline_parts(&p->initreq);
2805 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2806 return send_request(p, &req, 1, p->ocseq);
2809 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2811 struct sip_request req;
2812 reqprep(&req, p, "MESSAGE", 0);
2813 add_text(&req, text);
2814 return send_request(p, &req, 1, p->ocseq);
2817 static int transmit_refer(struct sip_pvt *p, char *dest)
2819 struct sip_request req;
2824 of = get_header(&p->initreq, "To");
2826 of = get_header(&p->initreq, "From");
2827 strncpy(from, of, sizeof(from) - 1);
2828 of = ditch_braces(from);
2829 strncpy(p->from,of,sizeof(p->from) - 1);
2830 if (strncmp(of, "sip:", 4)) {
2831 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2834 /* Get just the username part */
2835 if ((c = strchr(of, '@'))) {
2840 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
2842 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
2845 reqprep(&req, p, "REFER", 0);
2846 add_header(&req, "Refer-To", referto);
2847 add_header(&req, "Referred-By", callerid);
2848 return send_request(p, &req, 1, p->ocseq);
2851 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2853 struct sip_request req;
2854 reqprep(&req, p, "INFO", 0);
2855 add_digit(&req, digit);
2856 return send_request(p, &req, 1, p->ocseq);
2859 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
2861 struct sip_request resp;
2862 reqprep(&resp, p, msg, seqno);
2863 add_header(&resp, "Content-Length", "0");
2864 add_blank_header(&resp);
2865 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2868 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
2870 struct sip_request resp;
2871 reqprep(&resp, p, msg, seqno);
2875 memset(digest,0,sizeof(digest));
2876 build_reply_digest(p, msg, digest, sizeof(digest));
2877 add_header(&resp, "Proxy-Authorization", digest);
2880 add_header(&resp, "Content-Length", "0");
2881 add_blank_header(&resp);
2882 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2885 static int expire_register(void *data)
2887 struct sip_peer *p = data;
2888 memset(&p->addr, 0, sizeof(p->addr));
2890 ast_device_state_changed("SIP/%s", p->name);
2894 static int sip_poke_peer(struct sip_peer *peer);
2896 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2898 char contact[80]= "";
2899 char *expires = get_header(req, "Expires");
2900 int expiry = atoi(expires);
2904 struct sockaddr_in oldsin;
2905 if (!strlen(expires)) {
2906 expires = strstr(get_header(req, "Contact"), "expires=");
2908 if (sscanf(expires + 8, "%d;", &expiry) != 1)
2909 expiry = default_expiry;
2911 /* Nothing has been specified */
2912 expiry = default_expiry;
2915 /* Look for brackets */
2916 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2919 if ((n=strchr(c, '<'))) {
2922 /* Lose the part after the > */
2926 if (!strcasecmp(c, "*") || !expiry) {
2927 /* This means remove all registrations and return OK */
2928 memset(&p->addr, 0, sizeof(p->addr));
2930 ast_sched_del(sched, p->expire);
2932 if (option_verbose > 2)
2933 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
2936 /* Make sure it's a SIP URL */
2937 if (strncasecmp(c, "sip:", 4)) {
2938 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2954 pt = strchr(n, ':');
2960 port = DEFAULT_SIP_PORT;
2961 memcpy(&oldsin, &p->addr, sizeof(oldsin));
2963 /* XXX This could block for a long time XXX */
2964 hp = gethostbyname(n);
2966 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2969 p->addr.sin_family = AF_INET;
2970 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2971 p->addr.sin_port = htons(port);
2973 /* Don't trust the contact field. Just use what they came to us
2975 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2978 strncpy(p->username, c, sizeof(p->username) - 1);
2980 strcpy(p->username, "");
2982 ast_sched_del(sched, p->expire);
2983 if ((expiry < 1) || (expiry > max_expiry))
2984 expiry = max_expiry;
2985 p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
2986 pvt->expiry = expiry;
2987 if (inaddrcmp(&p->addr, &oldsin)) {
2989 if (option_verbose > 2)
2990 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);
2995 static void free_old_route(struct sip_route *route)
2997 struct sip_route *next;
3005 static void list_route(struct sip_route *route)
3008 ast_verbose("list_route: no route\n");
3012 ast_verbose("list_route: hop: <%s>\n", route->hop);
3013 route = route->next;
3017 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
3019 struct sip_route *thishop, *head, *tail;
3022 char *rr, *contact, *c;
3025 free_old_route(p->route);
3028 /* We build up head, then assign it to p->route when we're done */
3029 head = NULL; tail = head;
3030 /* 1st we pass through all the hops in any Record-Route headers */
3032 /* Each Record-Route header */
3033 rr = __get_header(req, "Record-Route", &start);
3034 if (*rr == '\0') break;
3036 /* Each route entry */
3038 rr = strchr(rr, '<');
3039 if (!rr) break; /* No more hops */
3041 len = strcspn(rr, ">");
3042 /* Make a struct route */
3043 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
3045 strncpy(thishop->hop, rr, len);
3046 thishop->hop[len] = '\0';
3047 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
3050 /* Link in at head so they end up in reverse order */
3051 thishop->next = head;
3053 /* If this was the first then it'll be the tail */
3054 if (!tail) tail = thishop;
3056 thishop->next = NULL;
3057 /* Link in at the end */
3059 tail->next = thishop;
3068 /* 2nd append the Contact: if there is one */
3069 /* Can be multiple Contact headers, comma separated values - we just take the first */
3070 contact = get_header(req, "Contact");
3071 if (strlen(contact)) {
3072 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
3073 /* Look for <: delimited address */
3074 c = strchr(contact, '<');
3078 len = strcspn(c, ">");
3080 /* No <> - just take the lot */
3081 c = contact; len = strlen(contact);
3083 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
3085 strncpy(thishop->hop, c, len);
3086 thishop->hop[len] = '\0';
3087 thishop->next = NULL;
3088 /* Goes at the end */
3090 tail->next = thishop;
3095 /* Store as new route */
3098 /* For debugging dump what we ended up with */
3100 list_route(p->route);
3103 static void md5_hash(char *output, char *input)
3105 struct MD5Context md5;
3106 unsigned char digest[16];
3110 MD5Update(&md5, input, strlen(input));
3111 MD5Final(digest, &md5);
3114 ptr += sprintf(ptr, "%2.2x", digest[x]);
3117 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)
3120 /* Always OK if no secret */
3121 if (!strlen(secret))
3123 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
3124 snprintf(randdata, randlen, "%08x", rand());
3125 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
3126 /* Schedule auto destroy in 15 seconds */
3127 sip_scheddestroy(p, 15000);
3130 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
3131 an example in the spec of just what it is you're doing a hash on. */
3137 char resp_hash[256];
3144 /* Find their response among the mess that we'r sent for comparison */
3145 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
3149 while (*c && (*c < 33)) c++;
3152 if (!strncasecmp(c, "response=", strlen("response="))) {
3153 c+= strlen("response=");
3156 if((c = strchr(c,'\"')))
3161 if((c = strchr(c,',')))
3165 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
3169 if((c = strchr(c,'\"')))
3173 if((c = strchr(c,',')))
3178 if ((z = strchr(c,' ')) || (z = strchr(c,','))) c=z;
3182 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
3183 if(strlen(resp_uri))
3184 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
3186 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
3187 md5_hash(a1_hash, a1);
3188 md5_hash(a2_hash, a2);
3189 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
3190 md5_hash(resp_hash, resp);
3192 /* resp_hash now has the expected response, compare the two */
3194 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
3198 /* Assume success ;-) */
3199 /* Eliminate random data */
3200 strcpy(randdata, "");
3205 static int cb_extensionstate(char *context, char* exten, int state, void *data)
3207 struct sip_pvt *p = data;
3209 sip_scheddestroy(p, 15000);
3214 transmit_state_notify(p, state, 1);
3217 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
3221 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
3224 struct sip_peer *peer;
3230 while(*t && (*t > 32) && (*t != ';'))
3234 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
3235 c = ditch_braces(tmp);
3236 /* Ditch ;user=phone */
3237 name = strchr(c, ';');
3241 if (!strncmp(c, "sip:", 4)) {
3245 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
3247 c = strchr(name, '@');
3250 strncpy(p->exten, name, sizeof(p->exten) - 1);
3252 ast_pthread_mutex_lock(&peerl.lock);
3255 if (!strcasecmp(peer->name, name) && peer->dynamic) {
3257 transmit_response(p, "100 Trying", req);
3258 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
3259 sip_cancel_destroy(p);
3260 if (parse_contact(p, peer, req)) {
3261 ast_log(LOG_WARNING, "Failed to parse contact info\n");
3263 /* Say OK and ask subsystem to retransmit msg counter */
3264 transmit_response_with_date(p, "200 OK", req);
3265 peer->lastmsgssent = -1;
3273 ast_pthread_mutex_unlock(&peerl.lock);
3275 ast_device_state_changed("SIP/%s", peer->name);
3278 transmit_response(p, "401 Unauthorized", &p->initreq);
3282 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
3284 char tmp[256] = "", *c, *a;
3285 struct sip_request *req;
3290 strncpy(tmp, get_header(req, "Diversion"), sizeof(tmp) - 1);
3293 c = ditch_braces(tmp);
3294 if (strncmp(c, "sip:", 4)) {
3295 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
3299 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3303 ast_verbose("RDNIS is %s\n", c);
3304 strncpy(p->rdnis, c, sizeof(p->rdnis) - 1);
3308 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
3310 char tmp[256] = "", *c, *a;
3311 struct sip_request *req;
3317 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
3318 c = ditch_braces(tmp);
3319 if (strncmp(c, "sip:", 4)) {
3320 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3324 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3328 ast_verbose("Looking for %s in %s\n", c, p->context);
3329 if (ast_exists_extension(NULL, p->context, c, 1, NULL) ||
3330 !strcmp(c, ast_pickup_ext())) {
3332 strncpy(p->exten, c, sizeof(p->exten) - 1);
3336 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL) ||
3337 !strncmp(c, ast_pickup_ext(),strlen(c))) {
3344 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
3346 char tmp[256] = "", *c, *a;
3347 char tmp2[256] = "", *c2, *a2;
3350 char tmp5[256] = ""; /* CallID to replace */
3351 struct sip_request *req;
3357 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
3358 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
3359 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
3360 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
3362 c = ditch_braces(tmp);
3363 c2 = ditch_braces(tmp2);
3366 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
3367 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3368 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
3373 if ((a = strchr(c, '?'))) {
3374 /* Search for arguemnts */
3377 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
3378 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
3379 if ((a = strchr(tmp5, '%'))) {
3380 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
3382 if ((a[1] == '4') && (a[2] == '0')) {
3384 memmove(a + 1, a+3, strlen(a + 3));
3387 if ((a = strchr(tmp5, '%')))
3392 if ((a = strchr(c, '@')))
3394 if ((a = strchr(c, ';')))
3398 if ((a2 = strchr(c2, '@')))
3401 if ((a2 = strchr(c2, ';')))
3406 ast_verbose("Looking for %s in %s\n", c, p->context);
3407 ast_verbose("Looking for %s in %s\n", c2, p->context);
3410 /* This is a supervised transfer */
3411 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
3413 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
3414 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
3415 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
3416 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
3417 p->refer_call = NULL;
3418 ast_pthread_mutex_lock(&iflock);
3419 /* Search interfaces and find the match */
3422 if (!strcmp(p2->callid, tmp5)) {
3423 /* Go ahead and lock it before returning */
3424 ast_pthread_mutex_lock(&p2->lock);
3430 ast_pthread_mutex_unlock(&iflock);
3434 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
3435 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3436 /* This is an unsupervised transfer */
3437 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
3438 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
3439 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
3440 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
3441 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
3442 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
3443 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
3444 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
3445 p->refer_call = NULL;
3447 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
3455 static int check_via(struct sip_pvt *p, struct sip_request *req)
3461 memset(via, 0, sizeof(via));
3462 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
3463 c = strchr(via, ';');
3466 c = strchr(via, ' ');
3470 while(*c && (*c < 33))
3472 if (strcmp(via, "SIP/2.0/UDP")) {
3473 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
3476 pt = strchr(c, ':');
3481 hp = gethostbyname(c);
3483 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
3486 memset(&p->sa, 0, sizeof(p->sa));
3487 p->sa.sin_family = AF_INET;
3488 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
3489 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
3492 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3494 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3499 static char *get_calleridname(char *input,char *output)
3501 char *end = strchr(input,'<');
3502 char *tmp = strchr(input,'\"');
3503 if (!end || (end == input)) return NULL;
3504 /* move away from "<" */
3506 /* we found "name" */
3507 if (tmp && tmp < end) {
3508 end = strchr(tmp+1,'\"');
3509 if (!end) return NULL;
3510 strncpy(output,tmp+1,(int)(end-tmp-1));
3512 /* we didn't find "name" */
3513 /* clear the empty characters in the begining*/
3514 while(*input && (*input < 33))
3516 /* clear the empty characters in the end */
3517 while(*end && (*end < 33) && end > input)
3520 strncpy(output,input,(int)(end-input)+1);
3526 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri, int reliable)
3528 struct sip_user *user;
3529 struct sip_peer *peer;
3530 char *of, from[256] = "", *c;
3533 char calleridname[50];
3536 while(*t && (*t > 32) && (*t != ';'))
3539 of = get_header(req, "From");
3540 strncpy(from, of, sizeof(from) - 1);
3541 memset(calleridname,0,sizeof(calleridname));
3542 get_calleridname(from,calleridname);
3543 of = ditch_braces(from);
3544 if (strncmp(of, "sip:", 4)) {
3545 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3548 /* Get just the username part */
3549 if ((c = strchr(of, '@')))
3551 if ((c = strchr(of, ':')))
3554 sprintf(p->callerid,"\"%s\" <%s>",calleridname,of);
3556 strncpy(p->callerid, of, sizeof(p->callerid) - 1);