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 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
88 static char context[AST_MAX_EXTENSION] = "default";
90 static char language[MAX_LANGUAGE] = "";
92 static char callerid[AST_MAX_EXTENSION] = "asterisk";
94 static char fromdomain[AST_MAX_EXTENSION] = "";
96 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
98 static int srvlookup = 0;
100 static int pedanticsipchecking = 0;
102 static int usecnt =0;
103 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
105 /* Protect the interface list (of sip_pvt's) */
106 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
108 /* Protect the monitoring thread, so only one process can kill or start it, and not
109 when it's doing something critical. */
110 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
112 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
114 /* This is the thread for the monitor which checks for input on the channels
115 which are not currently in use. */
116 static pthread_t monitor_thread = 0;
118 static int restart_monitor(void);
120 /* Codecs that we support by default: */
121 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
122 static int noncodeccapability = AST_RTP_DTMF;
124 static char ourhost[256];
125 static struct in_addr __ourip;
128 static int sipdebug = 0;
132 static int videosupport = 0;
134 static int globaldtmfmode = SIP_DTMF_RFC2833;
137 static int expiry = 900;
139 static struct sched_context *sched;
140 static struct io_context *io;
141 /* The private structures of the sip channels are linked for
142 selecting outgoing channels */
144 #define SIP_MAX_HEADERS 64
145 #define SIP_MAX_LINES 64
147 static struct sip_codec_pref {
149 struct sip_codec_pref *next;
153 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
154 char *rlPart2; /* The Request URI or Response Status */
156 int headers; /* SIP Headers */
157 char *header[SIP_MAX_HEADERS];
158 int lines; /* SDP Content */
159 char *line[SIP_MAX_LINES];
160 char data[SIP_MAX_PACKET];
166 struct sip_route *next;
170 static struct sip_pvt {
171 ast_mutex_t lock; /* Channel private lock */
172 char callid[80]; /* Global CallID */
173 char randdata[80]; /* Random data */
174 unsigned int ocseq; /* Current outgoing seqno */
175 unsigned int icseq; /* Current incoming seqno */
176 unsigned int callgroup;
177 unsigned int pickupgroup;
178 int lastinvite; /* Last Cseq of invite */
179 int alreadygone; /* Whether or not we've already been destroyed by or peer */
180 int needdestroy; /* if we need to be destroyed */
181 int capability; /* Special capability */
182 int noncodeccapability;
183 int outgoing; /* Outgoing or incoming call? */
184 int authtries; /* Times we've tried to authenticate */
185 int insecure; /* Don't check source port/ip */
186 int expiry; /* How long we take to expire */
187 int branch; /* One random number */
188 int canreinvite; /* Do we support reinvite */
189 int ringing; /* Have sent 180 ringing */
190 int progress; /* Have sent 183 message progress */
191 int tag; /* Another random number */
192 int nat; /* Whether to try to support NAT */
193 struct sockaddr_in sa; /* Our peer */
194 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
195 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
196 struct sockaddr_in recv; /* Received as */
197 struct in_addr ourip; /* Our IP */
198 struct ast_channel *owner; /* Who owns us */
199 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
200 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
201 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
202 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
203 struct sip_pvt *refer_call; /* Call we are referring */
204 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
205 char remote_party_id[256];
207 char context[AST_MAX_EXTENSION];
208 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
209 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
210 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
211 char language[MAX_LANGUAGE];
212 char rdnis[256]; /* Referring DNIS */
213 char theirtag[256]; /* Their tag */
216 char uri[81]; /* Original requested URI */
218 char callerid[256]; /* Caller*ID */
220 char accountcode[20]; /* Account code */
221 char our_contact[256]; /* Our contact header */
222 char realm[256]; /* Authorization realm */
223 char nonce[256]; /* Authorization nonce */
224 int amaflags; /* AMA Flags */
225 int pendinginvite; /* Any pending invite */
226 int pendingbye; /* Need to send bye after we ack? */
227 struct sip_request initreq; /* Initial request */
229 int maxtime; /* Max time for first response */
230 int initid; /* Auto-congest ID if appropriate */
231 int autokillid; /* Auto-kill ID */
240 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
241 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
242 struct ast_rtp *rtp; /* RTP Session */
243 struct ast_rtp *vrtp; /* Video RTP session */
244 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
245 struct sip_pvt *next;
249 struct sip_pkt *next; /* Next packet */
250 int retrans; /* Retransmission number */
251 int seqno; /* Sequence number */
252 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
253 struct sip_pvt *owner; /* Owner call */
254 int retransid; /* Retransmission ID */
255 int packetlen; /* Length of packet */
260 /* Users who can access various contexts */
266 char accountcode[20];
267 unsigned int callgroup;
268 unsigned int pickupgroup;
278 struct sip_user *next;
284 char context[80]; /* JK02: peers need context too to allow parking etc */
290 char mailbox[AST_MAX_EXTENSION];
300 unsigned int callgroup;
301 unsigned int pickupgroup;
303 struct sockaddr_in addr;
307 struct sip_pvt *call; /* Call pointer */
308 int pokeexpire; /* When to expire poke */
309 int lastms; /* How long last response took (in ms), or -1 for no response */
310 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
311 struct timeval ps; /* Ping send time */
313 struct sockaddr_in defaddr;
317 struct sip_peer *next;
320 static struct ast_user_list {
321 struct sip_user *users;
323 } userl = { NULL, AST_MUTEX_INITIALIZER };
325 static struct ast_peer_list {
326 struct sip_peer *peers;
328 } peerl = { NULL, AST_MUTEX_INITIALIZER };
331 #define REG_STATE_UNREGISTERED 0
332 #define REG_STATE_REGSENT 1
333 #define REG_STATE_AUTHSENT 2
334 #define REG_STATE_REGISTERED 3
335 #define REG_STATE_REJECTED 4
336 #define REG_STATE_TIMEOUT 5
337 #define REG_STATE_NOAUTH 6
339 struct sip_registry {
340 ast_mutex_t lock; /* Channel private lock */
341 struct sockaddr_in addr; /* Who we connect to for registration purposes */
342 char username[80]; /* Who we are registering as */
343 char authuser[80]; /* Who we *authenticate* as */
345 char secret[80]; /* Password or key name in []'s */
346 char contact[80]; /* Contact extension */
348 int expire; /* Sched ID of expiration */
349 int timeout; /* sched id of sip_reg_timeout */
350 int refresh; /* How often to refresh */
351 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
353 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
354 char callid[80]; /* Global CallID for this registry */
355 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
356 struct sockaddr_in us; /* Who the server thinks we are */
357 struct sip_registry *next;
360 #define REINVITE_INVITE 1
361 #define REINVITE_UPDATE 2
363 static int sip_do_register(struct sip_registry *r);
364 static struct sip_registry *registrations;
366 static int sipsock = -1;
367 static int globalnat = 0;
368 static int globalcanreinvite = REINVITE_INVITE;
371 static struct sockaddr_in bindaddr;
373 static struct ast_frame *sip_read(struct ast_channel *ast);
374 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
375 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
376 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
377 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
378 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
379 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url,char *distinctive_ring);
380 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
381 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
382 static int transmit_message_with_text(struct sip_pvt *p, char *text);
383 static int transmit_refer(struct sip_pvt *p, char *dest);
384 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
385 static char *getsipuri(char *header);
386 static void free_old_route(struct sip_route *route);
387 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
389 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
393 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
395 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
397 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));
402 static void sip_destroy(struct sip_pvt *p);
404 static int retrans_pkt(void *data)
406 struct sip_pkt *pkt=data;
408 ast_mutex_lock(&pkt->owner->lock);
409 if (1 /* !p->owner->needdestroy */) {
410 if (pkt->retrans < MAX_RETRANS) {
414 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));
416 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));
418 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
421 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
423 if (pkt->owner->owner) {
424 /* XXX Potential deadlocK?? XXX */
425 ast_queue_hangup(pkt->owner->owner, 1);
427 /* If no owner, destroy now */
428 ast_mutex_unlock(&pkt->owner->lock);
429 sip_destroy(pkt->owner);
434 /* Don't bother retransmitting. It's about to be killed anyway */
436 if (pkt->owner->owner) {
437 /* XXX Potential deadlocK?? XXX */
438 ast_queue_hangup(pkt->owner->owner, 1);
440 /* If no owner, destroy now */
441 ast_mutex_unlock(&pkt->owner->lock);
442 sip_destroy(pkt->owner);
447 ast_mutex_unlock(&pkt->owner->lock);
451 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
454 pkt = malloc(sizeof(struct sip_pkt) + len);
457 memset(pkt, 0, sizeof(struct sip_pkt));
458 memcpy(pkt->data, data, len);
459 pkt->packetlen = len;
460 pkt->next = p->packets;
464 /* Schedule retransmission */
465 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
466 pkt->next = p->packets;
468 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
469 if (!strncasecmp(pkt->data, "INVITE", 6)) {
470 /* Note this is a pending invite */
471 p->pendinginvite = seqno;
476 static int __sip_autodestruct(void *data)
478 struct sip_pvt *p = data;
480 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
482 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
483 ast_queue_hangup(p->owner, 0);
490 static int sip_scheddestroy(struct sip_pvt *p, int ms)
492 if (p->autokillid > -1)
493 ast_sched_del(sched, p->autokillid);
494 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
498 static int sip_cancel_destroy(struct sip_pvt *p)
500 if (p->autokillid > -1)
501 ast_sched_del(sched, p->autokillid);
506 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
508 struct sip_pkt *cur, *prev = NULL;
513 if ((cur->seqno == seqno) && (cur->resp == resp)) {
514 if (!resp && (seqno == p->pendinginvite)) {
515 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
516 p->pendinginvite = 0;
519 /* this is our baby */
521 prev->next = cur->next;
523 p->packets = cur->next;
524 if (cur->retransid > -1)
525 ast_sched_del(sched, cur->retransid);
533 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
537 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
542 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));
544 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));
547 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
549 res = __sip_xmit(p, req->data, req->len);
555 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
560 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));
562 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));
565 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
567 res = __sip_xmit(p, req->data, req->len);
571 static char *ditch_braces(char *tmp)
576 if ((n = strchr(tmp, '<')) ) {
578 while(*c && *c != '>') c++;
580 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
589 static int sip_sendtext(struct ast_channel *ast, char *text)
591 struct sip_pvt *p = ast->pvt->pvt;
593 ast_verbose("Sending text %s on %s\n", text, ast->name);
596 if (!text || !strlen(text))
599 ast_verbose("Really sending text %s on %s\n", text, ast->name);
600 transmit_message_with_text(p, text);
604 static int create_addr(struct sip_pvt *r, char *peer)
611 char host[256], *hostn;
613 r->sa.sin_family = AF_INET;
614 ast_mutex_lock(&peerl.lock);
617 if (!strcasecmp(p->name, peer)) {
619 r->capability = p->capability;
622 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
623 ast_rtp_setnat(r->rtp, r->nat);
626 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
627 ast_rtp_setnat(r->vrtp, r->nat);
629 strncpy(r->peername, p->username, sizeof(r->peername)-1);
630 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
631 strncpy(r->username, p->username, sizeof(r->username)-1);
632 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
633 if (!strlen(r->tohost)) {
634 if (p->addr.sin_addr.s_addr)
635 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
637 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
639 if (strlen(p->fromdomain))
640 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
641 if (strlen(p->fromuser))
642 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
643 r->insecure = p->insecure;
644 r->canreinvite = p->canreinvite;
645 r->maxtime = p->maxms;
646 r->callgroup = p->callgroup;
647 r->pickupgroup = p->pickupgroup;
649 r->dtmfmode = p->dtmfmode;
650 if (r->dtmfmode & SIP_DTMF_RFC2833)
651 r->noncodeccapability |= AST_RTP_DTMF;
653 r->noncodeccapability &= ~AST_RTP_DTMF;
655 strncpy(r->context, p->context,sizeof(r->context)-1);
656 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
657 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
658 if (p->addr.sin_addr.s_addr) {
659 r->sa.sin_addr = p->addr.sin_addr;
660 r->sa.sin_port = p->addr.sin_port;
662 r->sa.sin_addr = p->defaddr.sin_addr;
663 r->sa.sin_port = p->defaddr.sin_port;
665 memcpy(&r->recv, &r->sa, sizeof(r->recv));
671 ast_mutex_unlock(&peerl.lock);
673 if ((port=strchr(peer, ':'))) {
681 portno = DEFAULT_SIP_PORT;
686 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
687 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
693 hp = gethostbyname(hostn);
695 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
696 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
697 r->sa.sin_port = htons(portno);
698 memcpy(&r->recv, &r->sa, sizeof(r->recv));
701 ast_log(LOG_WARNING, "No such host: %s\n", peer);
710 static int auto_congest(void *nothing)
712 struct sip_pvt *p = nothing;
713 ast_mutex_lock(&p->lock);
716 if (!ast_mutex_trylock(&p->owner->lock)) {
717 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
718 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
719 ast_mutex_unlock(&p->owner->lock);
722 ast_mutex_unlock(&p->lock);
726 static void sip_prefs_free(void)
728 struct sip_codec_pref *cur, *next;
738 static void sip_pref_remove(int format)
740 struct sip_codec_pref *cur, *prev=NULL;
743 if (cur->codec == format) {
745 prev->next = cur->next;
756 static int sip_pref_append(int format)
758 struct sip_codec_pref *cur, *tmp;
759 sip_pref_remove(format);
760 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
763 memset(tmp, 0, sizeof(struct sip_codec_pref));
775 static int sip_codec_choose(int formats)
777 struct sip_codec_pref *cur;
778 formats &= (AST_FORMAT_MAX_AUDIO - 1);
781 if (formats & cur->codec)
785 return ast_best_codec(formats);
788 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
792 char *vxml_url = NULL;
793 char *distinctive_ring = NULL;
794 struct varshead *headp;
795 struct ast_var_t *current;
798 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
799 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
802 /* Check whether there is vxml_url, distinctive ring variables */
804 headp=&ast->varshead;
805 AST_LIST_TRAVERSE(headp,current,entries) {
806 /* Check whether there is a VXML_URL variable */
807 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
809 vxml_url = ast_var_value(current);
812 /* Check whether there is a ALERT_INFO variable */
813 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
815 distinctive_ring = ast_var_value(current);
822 transmit_invite(p, "INVITE", 1, NULL, vxml_url,distinctive_ring);
824 /* Initialize auto-congest time */
825 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
830 static void __sip_destroy(struct sip_pvt *p, int lockowner)
832 struct sip_pvt *cur, *prev = NULL;
835 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
837 ast_extension_state_del(p->stateid, NULL);
839 ast_sched_del(sched, p->initid);
840 if (p->autokillid > -1)
841 ast_sched_del(sched, p->autokillid);
844 ast_rtp_destroy(p->rtp);
847 ast_rtp_destroy(p->vrtp);
850 free_old_route(p->route);
854 p->registry->call=NULL;
856 /* Unlink us from the owner if we have one */
859 ast_mutex_lock(&p->owner->lock);
860 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
861 p->owner->pvt->pvt = NULL;
863 ast_mutex_unlock(&p->owner->lock);
869 prev->next = cur->next;
878 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
881 ast_sched_del(sched, p->initid);
882 while((cp = p->packets)) {
883 p->packets = p->packets->next;
884 if (cp->retransid > -1)
885 ast_sched_del(sched, cp->retransid);
892 static int find_user(struct sip_pvt *fup, int event)
896 strncpy(name, fup->username, sizeof(name) - 1);
897 ast_mutex_lock(&userl.lock);
900 if (!strcasecmp(u->name, name)) {
906 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
907 ast_mutex_unlock(&userl.lock);
911 if ( u->inUse > 0 ) {
912 u->inUse = u->inUse - 1;
917 if (u->incominglimit > 0 ) {
918 if (u->inUse >= u->incominglimit) {
919 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
920 ast_mutex_unlock(&userl.lock);
925 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
927 ast_mutex_unlock(&userl.lock);
931 static void sip_destroy(struct sip_pvt *p)
933 ast_mutex_lock(&iflock);
935 ast_mutex_unlock(&iflock);
938 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
941 static int sip_hangup(struct ast_channel *ast)
943 struct sip_pvt *p = ast->pvt->pvt;
947 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
948 if (!ast->pvt->pvt) {
949 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
952 ast_mutex_lock(&p->lock);
953 ast_log(LOG_DEBUG, "find_user(%s)\n", p->username);
955 /* Determine how to disconnect */
956 if (p->owner != ast) {
957 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
958 ast_mutex_unlock(&p->lock);
961 if (!ast || (ast->_state != AST_STATE_UP))
966 ast_dsp_free(p->vad);
969 ast->pvt->pvt = NULL;
972 /* Start the process if it's not already started */
973 if (!p->alreadygone && strlen(p->initreq.data)) {
976 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
977 /* Actually don't destroy us yet, wait for the 487 on our original
978 INVITE, but do set an autodestruct just in case. */
980 sip_scheddestroy(p, 15000);
982 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
984 if (!p->pendinginvite) {
986 transmit_request_with_auth(p, "BYE", 0, 1);
988 /* Note we will need a BYE when this all settles out
989 but we can't send one while we have "INVITE" outstanding. */
994 p->needdestroy = needdestroy;
995 ast_mutex_unlock(&p->lock);
999 static int sip_answer(struct ast_channel *ast)
1003 struct sip_pvt *p = ast->pvt->pvt;
1006 if (ast->_state != AST_STATE_UP) {
1010 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1012 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1013 fmt=ast_getformatbyname(codec);
1016 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
1019 ast_setstate(ast, AST_STATE_UP);
1021 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1022 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1027 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1029 struct sip_pvt *p = ast->pvt->pvt;
1031 if (frame->frametype == AST_FRAME_VOICE) {
1032 if (!(frame->subclass & ast->nativeformats)) {
1033 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1034 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1038 ast_mutex_lock(&p->lock);
1040 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1041 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1044 res = ast_rtp_write(p->rtp, frame);
1046 ast_mutex_unlock(&p->lock);
1048 } else if (frame->frametype == AST_FRAME_VIDEO) {
1050 ast_mutex_lock(&p->lock);
1052 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1053 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1056 res = ast_rtp_write(p->vrtp, frame);
1058 ast_mutex_unlock(&p->lock);
1060 } else if (frame->frametype == AST_FRAME_IMAGE) {
1063 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1070 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1072 struct sip_pvt *p = newchan->pvt->pvt;
1073 ast_mutex_lock(&p->lock);
1074 if (p->owner != oldchan) {
1075 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1076 ast_mutex_unlock(&p->lock);
1080 ast_mutex_unlock(&p->lock);
1084 static int sip_senddigit(struct ast_channel *ast, char digit)
1086 struct sip_pvt *p = ast->pvt->pvt;
1087 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1088 transmit_info_with_digit(p, digit);
1090 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1091 ast_rtp_senddigit(p->rtp, digit);
1093 /* If in-band DTMF is desired, send that */
1094 if (p->dtmfmode & SIP_DTMF_INBAND)
1099 static int sip_transfer(struct ast_channel *ast, char *dest)
1101 struct sip_pvt *p = ast->pvt->pvt;
1103 res = transmit_refer(p, dest);
1107 static int sip_indicate(struct ast_channel *ast, int condition)
1109 struct sip_pvt *p = ast->pvt->pvt;
1111 case AST_CONTROL_RINGING:
1112 if (ast->_state == AST_STATE_RING) {
1113 if (!p->progress && !p->ringing) {
1114 transmit_response(p, "180 Ringing", &p->initreq);
1118 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1122 case AST_CONTROL_BUSY:
1123 if (ast->_state != AST_STATE_UP) {
1124 transmit_response(p, "486 Busy Here", &p->initreq);
1126 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1130 case AST_CONTROL_CONGESTION:
1131 if (ast->_state != AST_STATE_UP) {
1132 transmit_response(p, "503 Service Unavailable", &p->initreq);
1134 ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1138 case AST_CONTROL_PROGRESS:
1139 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1140 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1148 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1156 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1158 struct ast_channel *tmp;
1160 tmp = ast_channel_alloc(1);
1162 /* Select our native format based on codec preference until we receive
1163 something from another device to the contrary. */
1165 tmp->nativeformats = sip_codec_choose(i->capability);
1167 tmp->nativeformats = sip_codec_choose(capability);
1168 fmt = ast_best_codec(tmp->nativeformats);
1170 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1172 if (strchr(i->from,':'))
1174 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->from,':')+1, (int)(i));
1178 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->from, (int)(i));
1181 if (i->dtmfmode & SIP_DTMF_INBAND) {
1182 i->vad = ast_dsp_new();
1183 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1185 tmp->fds[0] = ast_rtp_fd(i->rtp);
1186 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1188 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1189 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1191 ast_setstate(tmp, state);
1192 if (state == AST_STATE_RING)
1194 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1195 tmp->writeformat = fmt;
1196 tmp->pvt->rawwriteformat = fmt;
1197 tmp->readformat = fmt;
1198 tmp->pvt->rawreadformat = fmt;
1200 tmp->pvt->send_text = sip_sendtext;
1201 tmp->pvt->call = sip_call;
1202 tmp->pvt->hangup = sip_hangup;
1203 tmp->pvt->answer = sip_answer;
1204 tmp->pvt->read = sip_read;
1205 tmp->pvt->write = sip_write;
1206 tmp->pvt->write_video = sip_write;
1207 tmp->pvt->indicate = sip_indicate;
1208 tmp->pvt->transfer = sip_transfer;
1209 tmp->pvt->fixup = sip_fixup;
1210 tmp->pvt->send_digit = sip_senddigit;
1212 tmp->pvt->bridge = ast_rtp_bridge;
1214 tmp->callgroup = i->callgroup;
1215 tmp->pickupgroup = i->pickupgroup;
1216 if (strlen(i->accountcode))
1217 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1219 tmp->amaflags = i->amaflags;
1220 if (strlen(i->language))
1221 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1223 ast_mutex_lock(&usecnt_lock);
1225 ast_mutex_unlock(&usecnt_lock);
1226 ast_update_use_count();
1227 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1228 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1229 if (strlen(i->callerid))
1230 tmp->callerid = strdup(i->callerid);
1231 if (strlen(i->rdnis))
1232 tmp->rdnis = strdup(i->rdnis);
1234 if (state != AST_STATE_DOWN) {
1235 if (ast_pbx_start(tmp)) {
1236 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1242 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1246 static struct cfalias {
1250 { "Content-Type", "c" },
1251 { "Content-Encoding", "e" },
1255 { "Content-Length", "l" },
1261 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1262 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1263 char* r = line + nameLen + 1;
1264 while (*r && (*r < 33)) ++r;
1271 static char *get_sdp(struct sip_request *req, char *name) {
1273 int len = strlen(name);
1276 for (x=0; x<req->lines; x++) {
1277 r = get_sdp_by_line(req->line[x], name, len);
1278 if (r[0] != '\0') return r;
1283 static void sdpLineNum_iterator_init(int* iterator) {
1287 static char* get_sdp_iterate(int* iterator,
1288 struct sip_request *req, char *name) {
1289 int len = strlen(name);
1291 while (*iterator < req->lines) {
1292 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1293 if (r[0] != '\0') return r;
1298 static char *__get_header(struct sip_request *req, char *name, int *start)
1301 int len = strlen(name);
1303 for (x=*start;x<req->headers;x++) {
1304 if (!strncasecmp(req->header[x], name, len) &&
1305 (req->header[x][len] == ':')) {
1306 r = req->header[x] + len + 1;
1307 while(*r && (*r < 33))
1314 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1315 if (!strcasecmp(aliases[x].fullname, name))
1316 return __get_header(req, aliases[x].shortname, start);
1318 /* Don't return NULL, so get_header is always a valid pointer */
1322 static char *get_header(struct sip_request *req, char *name)
1325 return __get_header(req, name, &start);
1328 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1330 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1331 struct ast_frame *f;
1332 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1335 f = ast_rtp_read(p->rtp);
1338 f = ast_rtcp_read(p->rtp);
1341 f = ast_rtp_read(p->vrtp);
1344 f = ast_rtcp_read(p->vrtp);
1349 /* Don't send RFC2833 if we're not supposed to */
1350 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1353 /* We already hold the channel lock */
1354 if (f->frametype == AST_FRAME_VOICE) {
1355 if (f->subclass != p->owner->nativeformats) {
1356 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1357 p->owner->nativeformats = f->subclass;
1358 ast_set_read_format(p->owner, p->owner->readformat);
1359 ast_set_write_format(p->owner, p->owner->writeformat);
1361 if (p->dtmfmode & SIP_DTMF_INBAND) {
1362 f = ast_dsp_process(p->owner,p->vad,f,0);
1369 static struct ast_frame *sip_read(struct ast_channel *ast)
1371 struct ast_frame *fr;
1372 struct sip_pvt *p = ast->pvt->pvt;
1373 ast_mutex_lock(&p->lock);
1374 fr = sip_rtp_read(ast, p);
1375 ast_mutex_unlock(&p->lock);
1379 static void build_callid(char *callid, int len, struct in_addr ourip)
1386 res = snprintf(callid, len, "%08x", val);
1390 /* It's not important that we really use our right IP here... */
1391 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1394 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1398 p = malloc(sizeof(struct sip_pvt));
1401 /* Keep track of stuff */
1402 memset(p, 0, sizeof(struct sip_pvt));
1406 p->rtp = ast_rtp_new(sched, io, 1, 0);
1408 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1412 /* Start with 101 instead of 1 */
1415 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1419 ast_rtp_settos(p->rtp, tos);
1421 ast_rtp_settos(p->vrtp, tos);
1422 if (useglobalnat && sin) {
1423 /* Setup NAT structure according to global settings if we have an address */
1425 memcpy(&p->recv, sin, sizeof(p->recv));
1426 ast_rtp_setnat(p->rtp, p->nat);
1428 ast_rtp_setnat(p->vrtp, p->nat);
1430 ast_mutex_init(&p->lock);
1433 memcpy(&p->sa, sin, sizeof(p->sa));
1434 if (ast_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1435 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1437 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1439 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1440 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1442 build_callid(p->callid, sizeof(p->callid), p->ourip);
1444 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1445 /* Assume reinvite OK and via INVITE */
1446 p->canreinvite = globalcanreinvite;
1447 p->dtmfmode = globaldtmfmode;
1448 if (p->dtmfmode & SIP_DTMF_RFC2833)
1449 p->noncodeccapability |= AST_RTP_DTMF;
1450 strncpy(p->context, context, sizeof(p->context) - 1);
1451 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1453 ast_mutex_lock(&iflock);
1456 ast_mutex_unlock(&iflock);
1458 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1462 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1470 callid = get_header(req, "Call-ID");
1472 if (pedanticsipchecking) {
1473 /* In principle Call-ID's uniquely identify a call, however some vendors
1474 (i.e. Pingtel) send multiple calls with the same Call-ID and different
1475 tags in order to simplify billing. The RFC does state that we have to
1476 compare tags in addition to the call-id, but this generate substantially
1477 more overhead which is totally unnecessary for the vast majority of sane
1478 SIP implementations, and thus Asterisk does not enable this behavior
1479 by default. Short version: You'll need this option to support conferencing
1481 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1483 c = strchr(tmp, ' ');
1486 if (!strcasecmp(cmd, "SIP/2.0")) {
1492 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1494 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1495 tag = strstr(tmp, "tag=");
1498 c = strchr(tag, ';');
1505 if (!strlen(callid)) {
1506 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1509 ast_mutex_lock(&iflock);
1512 if (!strcmp(p->callid, callid) &&
1513 (!pedanticsipchecking || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1514 /* Found the call */
1515 ast_mutex_lock(&p->lock);
1516 ast_mutex_unlock(&iflock);
1521 ast_mutex_unlock(&iflock);
1522 p = sip_alloc(callid, sin, 1);
1524 ast_mutex_lock(&p->lock);
1528 static int sip_register(char *value, int lineno)
1530 struct sip_registry *reg;
1531 char copy[256] = "";
1532 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1540 strncpy(copy, value, sizeof(copy)-1);
1543 hostname = strrchr(stringp, '@');
1548 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1549 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port] at line %d", lineno);
1553 username = strsep(&stringp, ":");
1555 secret = strsep(&stringp, ":");
1557 authuser = strsep(&stringp, ":");
1560 hostname = strsep(&stringp, "/");
1562 contact = strsep(&stringp, "/");
1563 if (!contact || !strlen(contact))
1566 hostname = strsep(&stringp, ":");
1567 porta = strsep(&stringp, ":");
1569 if (porta && !atoi(porta)) {
1570 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1573 hp = gethostbyname(hostname);
1575 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1578 reg = malloc(sizeof(struct sip_registry));
1580 memset(reg, 0, sizeof(struct sip_registry));
1581 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1583 strncpy(reg->username, username, sizeof(reg->username)-1);
1585 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1587 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1589 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1592 reg->refresh = default_expiry;
1593 reg->addr.sin_family = AF_INET;
1594 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1595 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1596 reg->next = registrations;
1597 reg->callid_valid = 0;
1599 registrations = reg;
1601 ast_log(LOG_ERROR, "Out of memory\n");
1607 static void parse(struct sip_request *req)
1609 /* Divide fields by NULL's */
1614 /* First header starts immediately */
1618 /* We've got a new header */
1622 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1624 if (!strlen(req->header[f])) {
1625 /* Line by itself means we're now in content */
1629 if (f >= SIP_MAX_HEADERS - 1) {
1630 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1633 req->header[f] = c + 1;
1634 } else if (*c == '\r') {
1635 /* Ignore but eliminate \r's */
1640 /* Check for last header */
1641 if (strlen(req->header[f]))
1644 /* Now we process any mime content */
1649 /* We've got a new line */
1652 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1654 if (f >= SIP_MAX_LINES - 1) {
1655 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1658 req->line[f] = c + 1;
1659 } else if (*c == '\r') {
1660 /* Ignore and eliminate \r's */
1665 /* Check for last line */
1666 if (strlen(req->line[f]))
1670 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1672 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1675 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1684 int peercapability, peernoncodeccapability;
1685 int vpeercapability=0, vpeernoncodeccapability=0;
1686 struct sockaddr_in sin;
1693 /* Get codec and RTP info from SDP */
1694 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1695 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1698 m = get_sdp(req, "m");
1699 c = get_sdp(req, "c");
1700 if (!strlen(m) || !strlen(c)) {
1701 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1704 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1705 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1708 /* XXX This could block for a long time, and block the main thread! XXX */
1709 hp = gethostbyname(host);
1711 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1714 sdpLineNum_iterator_init(&iterator);
1715 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
1716 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
1718 // Scan through the RTP payload types specified in a "m=" line:
1719 ast_rtp_pt_clear(p->rtp);
1721 while(strlen(codecs)) {
1722 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1723 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1727 ast_verbose("Found audio format %d\n", codec);
1728 ast_rtp_set_m_type(p->rtp, codec);
1730 /* Skip over any whitespace */
1731 while(*codecs && (*codecs < 33)) codecs++;
1734 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
1736 // Scan through the RTP payload types specified in a "m=" line:
1737 ast_rtp_pt_clear(p->vrtp);
1739 while(strlen(codecs)) {
1740 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1741 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1745 ast_verbose("Found video format %d\n", codec);
1746 ast_rtp_set_m_type(p->vrtp, codec);
1748 /* Skip over any whitespace */
1749 while(*codecs && (*codecs < 33)) codecs++;
1753 sin.sin_family = AF_INET;
1754 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1755 /* Setup audio port number */
1756 sin.sin_port = htons(portno);
1757 if (p->rtp && sin.sin_port)
1758 ast_rtp_set_peer(p->rtp, &sin);
1759 /* Setup video port number */
1760 sin.sin_port = htons(vportno);
1761 if (p->vrtp && sin.sin_port)
1762 ast_rtp_set_peer(p->vrtp, &sin);
1764 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1766 // Next, scan through each "a=rtpmap:" line, noting each
1767 // specified RTP payload type (with corresponding MIME subtype):
1768 sdpLineNum_iterator_init(&iterator);
1769 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1770 char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
1771 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1773 ast_verbose("Found description format %s\n", mimeSubtype);
1774 // Note: should really look at the 'freq' and '#chans' params too
1775 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1777 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
1780 // Now gather all of the codecs that were asked for:
1781 ast_rtp_get_current_formats(p->rtp,
1782 &peercapability, &peernoncodeccapability);
1784 ast_rtp_get_current_formats(p->vrtp,
1785 &vpeercapability, &vpeernoncodeccapability);
1786 p->capability = capability & (peercapability | vpeercapability);
1787 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
1790 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
1791 capability, peercapability, vpeercapability, p->capability);
1792 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1793 noncodeccapability, peernoncodeccapability,
1794 p->noncodeccapability);
1796 if (!p->capability) {
1797 ast_log(LOG_WARNING, "No compatible codecs!\n");
1801 if (!(p->owner->nativeformats & p->capability)) {
1802 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);
1803 p->owner->nativeformats = sip_codec_choose(p->capability);
1804 ast_set_read_format(p->owner, p->owner->readformat);
1805 ast_set_write_format(p->owner, p->owner->writeformat);
1807 if (p->owner->bridge) {
1808 /* Turn on/off music on hold if we are holding/unholding */
1809 if (sin.sin_addr.s_addr) {
1810 ast_moh_stop(p->owner->bridge);
1812 ast_moh_start(p->owner->bridge, NULL);
1820 static int add_header(struct sip_request *req, char *var, char *value)
1822 if (req->len >= sizeof(req->data) - 4) {
1823 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
1827 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1830 req->header[req->headers] = req->data + req->len;
1831 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1832 req->len += strlen(req->header[req->headers]);
1833 if (req->headers < SIP_MAX_HEADERS)
1836 ast_log(LOG_WARNING, "Out of header space\n");
1842 static int add_blank_header(struct sip_request *req)
1844 if (req->len >= sizeof(req->data) - 4) {
1845 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1849 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1852 req->header[req->headers] = req->data + req->len;
1853 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1854 req->len += strlen(req->header[req->headers]);
1855 if (req->headers < SIP_MAX_HEADERS)
1858 ast_log(LOG_WARNING, "Out of header space\n");
1864 static int add_line(struct sip_request *req, char *line)
1866 if (req->len >= sizeof(req->data) - 4) {
1867 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1871 /* Add extra empty return */
1872 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1873 req->len += strlen(req->data + req->len);
1875 req->line[req->lines] = req->data + req->len;
1876 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1877 req->len += strlen(req->line[req->lines]);
1878 if (req->lines < SIP_MAX_LINES)
1881 ast_log(LOG_WARNING, "Out of line space\n");
1887 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1890 tmp = get_header(orig, field);
1892 /* Add what we're responding to */
1893 return add_header(req, field, tmp);
1895 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1899 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1905 tmp = __get_header(orig, field, &start);
1907 /* Add what we're responding to */
1908 add_header(req, field, tmp);
1913 return copied ? 0 : -1;
1916 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1923 tmp = __get_header(orig, field, &start);
1925 if (!copied && p->nat) {
1926 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
1927 /* SLD: FIXME: Nice try, but the received= should not have a port */
1928 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1929 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
1931 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1932 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1935 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1936 add_header(req, field, new);
1938 /* Add what we're responding to */
1939 add_header(req, field, tmp);
1946 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1952 /* Add Route: header into request per learned route */
1953 static void add_route(struct sip_request *req, struct sip_route *route)
1956 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1962 n = strlen(route->hop);
1963 if ((n+3)>rem) break;
1969 strcpy(p, route->hop); p += n;
1972 route = route->next;
1975 add_header(req, "Route", r);
1978 static void set_destination(struct sip_pvt *p, char *uri)
1980 char *h, *maddr, hostname[256];
1984 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1985 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1988 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1990 /* Find and parse hostname */
1991 h = strchr(uri, '@');
1996 if (strncmp(h, "sip:", 4) == 0)
1998 else if (strncmp(h, "sips:", 5) == 0)
2001 hn = strcspn(h, ":;>");
2003 strncpy(hostname, h, hn); hostname[hn] = '\0';
2006 /* Is "port" present? if not default to 5060 */
2010 port = strtol(h, &h, 10);
2015 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2016 maddr = strstr(h, "maddr=");
2019 hn = strspn(maddr, "0123456789.");
2021 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2024 hp = gethostbyname(hostname);
2026 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2029 p->sa.sin_family = AF_INET;
2030 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2031 p->sa.sin_port = htons(port);
2033 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2036 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2038 /* Initialize a response */
2039 if (req->headers || req->len) {
2040 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2043 req->header[req->headers] = req->data + req->len;
2044 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2045 req->len += strlen(req->header[req->headers]);
2046 if (req->headers < SIP_MAX_HEADERS)
2049 ast_log(LOG_WARNING, "Out of header space\n");
2053 static int init_req(struct sip_request *req, char *resp, char *recip)
2055 /* Initialize a response */
2056 if (req->headers || req->len) {
2057 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2060 req->header[req->headers] = req->data + req->len;
2061 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2062 req->len += strlen(req->header[req->headers]);
2063 if (req->headers < SIP_MAX_HEADERS)
2066 ast_log(LOG_WARNING, "Out of header space\n");
2070 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2072 char newto[256] = "", *ot;
2073 memset(resp, 0, sizeof(*resp));
2074 init_resp(resp, msg, req);
2075 copy_via_headers(p, resp, req, "Via");
2076 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2077 copy_header(resp, req, "From");
2078 ot = get_header(req, "To");
2079 if (!strstr(ot, "tag=")) {
2080 /* Add the proper tag if we don't have it already. If they have specified
2081 their tag, use it. Otherwise, use our own tag */
2082 if (strlen(p->theirtag) && p->outgoing)
2083 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2084 else if (p->tag && !p->outgoing)
2085 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2087 strncpy(newto, ot, sizeof(newto) - 1);
2090 add_header(resp, "To", ot);
2091 copy_header(resp, req, "Call-ID");
2092 copy_header(resp, req, "CSeq");
2093 add_header(resp, "User-Agent", "Asterisk PBX");
2094 add_header(resp, "Allow", ALLOWED_METHODS);
2096 /* For registration responses, we also need expiry and
2100 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2101 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2102 add_header(resp, "Expires", tmp);
2103 add_header(resp, "Contact", contact);
2105 add_header(resp, "Contact", p->our_contact);
2110 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2112 struct sip_request *orig = &p->initreq;
2113 char stripped[80] ="";
2119 memset(req, 0, sizeof(struct sip_request));
2127 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2129 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2131 c = strchr(stripped, '<');
2143 init_req(req, msg, c);
2145 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2147 add_header(req, "Via", p->via);
2149 set_destination(p, p->route->hop);
2150 add_route(req, p->route->next);
2153 ot = get_header(orig, "To");
2154 of = get_header(orig, "From");
2156 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2157 as our original request, including tag (or presumably lack thereof) */
2158 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2159 /* Add the proper tag if we don't have it already. If they have specified
2160 their tag, use it. Otherwise, use our own tag */
2161 if (p->outgoing && strlen(p->theirtag))
2162 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2163 else if (!p->outgoing)
2164 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2166 snprintf(newto, sizeof(newto), "%s", ot);
2171 add_header(req, "From", of);
2172 add_header(req, "To", ot);
2174 add_header(req, "From", ot);
2175 add_header(req, "To", of);
2177 add_header(req, "Contact", p->our_contact);
2178 copy_header(req, orig, "Call-ID");
2179 add_header(req, "CSeq", tmp);
2181 add_header(req, "User-Agent", "Asterisk PBX");
2185 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2187 struct sip_request resp;
2189 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2190 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2193 respprep(&resp, p, msg, req);
2194 add_header(&resp, "Content-Length", "0");
2195 add_blank_header(&resp);
2196 return send_response(p, &resp, reliable, seqno);
2199 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2201 return __transmit_response(p, msg, req, 0);
2203 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2205 return __transmit_response(p, msg, req, 1);
2208 static void append_date(struct sip_request *req)
2215 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2216 add_header(req, "Date", tmpdat);
2219 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2221 struct sip_request resp;
2222 respprep(&resp, p, msg, req);
2224 add_header(&resp, "Content-Length", "0");
2225 add_blank_header(&resp);
2226 return send_response(p, &resp, 0, 0);
2229 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2231 struct sip_request resp;
2232 respprep(&resp, p, msg, req);
2233 add_header(&resp, "Accept", "application/sdp");
2234 add_header(&resp, "Content-Length", "0");
2235 add_blank_header(&resp);
2236 return send_response(p, &resp, 0, 0);
2239 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2241 struct sip_request resp;
2244 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2245 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2248 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2249 respprep(&resp, p, msg, req);
2250 add_header(&resp, "Proxy-Authenticate", tmp);
2251 add_header(&resp, "Content-Length", "0");
2252 add_blank_header(&resp);
2253 return send_response(p, &resp, reliable, seqno);
2256 static int add_text(struct sip_request *req, char *text)
2258 /* XXX Convert \n's to \r\n's XXX */
2259 int len = strlen(text);
2261 snprintf(clen, sizeof(clen), "%d", len);
2262 add_header(req, "Content-Type", "text/plain");
2263 add_header(req, "Content-Length", clen);
2264 add_line(req, text);
2268 static int add_digit(struct sip_request *req, char digit)
2273 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2275 snprintf(clen, sizeof(clen), "%d", len);
2276 add_header(req, "Content-Type", "application/dtmf-relay");
2277 add_header(req, "Content-Length", clen);
2282 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2286 int alreadysent = 0;
2288 struct sockaddr_in sin;
2289 struct sockaddr_in vsin;
2290 struct sip_codec_pref *cur;
2301 struct sockaddr_in dest;
2302 struct sockaddr_in vdest;
2303 /* XXX We break with the "recommendation" and send our IP, in order that our
2304 peer doesn't have to gethostbyname() us XXX */
2307 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2310 ast_rtp_get_us(p->rtp, &sin);
2312 ast_rtp_get_us(p->vrtp, &vsin);
2314 if (p->redirip.sin_addr.s_addr) {
2315 dest.sin_port = p->redirip.sin_port;
2316 dest.sin_addr = p->redirip.sin_addr;
2318 ast_rtp_get_peer(rtp, &dest);
2320 dest.sin_addr = p->ourip;
2321 dest.sin_port = sin.sin_port;
2324 /* Determine video destination */
2326 if (p->vredirip.sin_addr.s_addr) {
2327 vdest.sin_port = p->vredirip.sin_port;
2328 vdest.sin_addr = p->vredirip.sin_addr;
2330 ast_rtp_get_peer(vrtp, &vdest);
2332 vdest.sin_addr = p->ourip;
2333 vdest.sin_port = vsin.sin_port;
2337 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2338 if (sipdebug && p->vrtp)
2339 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2340 snprintf(v, sizeof(v), "v=0\r\n");
2341 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2342 snprintf(s, sizeof(s), "s=session\r\n");
2343 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2344 snprintf(t, sizeof(t), "t=0 0\r\n");
2345 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2346 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2347 /* Start by sending our preferred codecs */
2350 if (p->capability & cur->codec) {
2352 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2353 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2355 snprintf(costr, sizeof(costr), " %d", codec);
2356 if (cur->codec < AST_FORMAT_MAX_AUDIO) {
2358 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2362 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2367 alreadysent |= cur->codec;
2370 /* Now send any other common codecs, and non-codec formats: */
2371 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2372 if ((p->capability & x) && !(alreadysent & x)) {
2374 ast_verbose("Answering with capability %d\n", x);
2375 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2377 snprintf(costr, sizeof(costr), " %d", codec);
2378 if (x < AST_FORMAT_MAX_AUDIO) {
2380 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2384 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2390 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2391 if (p->noncodeccapability & x) {
2393 ast_verbose("Answering with non-codec capability %d\n", x);
2394 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2396 snprintf(costr, sizeof(costr), " %d", codec);
2398 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2400 if (x == AST_RTP_DTMF) {
2401 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2402 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2411 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2413 len += strlen(m2) + strlen(a2);
2414 snprintf(costr, sizeof(costr), "%d", len);
2415 add_header(resp, "Content-Type", "application/sdp");
2416 add_header(resp, "Content-Length", costr);
2431 static void copy_request(struct sip_request *dst,struct sip_request *src)
2435 offset = ((void *)dst) - ((void *)src);
2436 /* First copy stuff */
2437 memcpy(dst, src, sizeof(*dst));
2438 /* Now fix pointer arithmetic */
2439 for (x=0;x<src->headers;x++)
2440 dst->header[x] += offset;
2441 for (x=0;x<src->lines;x++)
2442 dst->line[x] += offset;
2445 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2447 struct sip_request resp;
2449 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2450 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2453 respprep(&resp, p, msg, req);
2454 add_sdp(&resp, p, NULL, NULL);
2455 return send_response(p, &resp, retrans, seqno);
2458 static int determine_firstline_parts( struct sip_request *req ) {
2463 cmd= req->header[0];
2464 while(*cmd && (*cmd < 33)) {
2471 while(*e && (*e > 32)) {
2474 /* Get the command */
2480 while( *e && ( *e < 33 ) ) {
2487 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2488 /* We have a response */
2490 len= strlen( req->rlPart2 );
2491 if( len < 2 ) { return -1; }
2493 while( *e && *e<33 ) {
2498 /* We have a request */
2501 if( !*e ) { return -1; }
2504 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2507 while( isspace( *(--e) ) ) {}
2517 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2519 struct sip_request req;
2520 if (p->canreinvite == REINVITE_UPDATE)
2521 reqprep(&req, p, "UPDATE", 0);
2523 reqprep(&req, p, "INVITE", 0);
2524 add_header(&req, "Allow", ALLOWED_METHODS);
2525 add_sdp(&req, p, rtp, vrtp);
2526 /* Use this as the basis */
2527 copy_request(&p->initreq, &req);
2529 determine_firstline_parts(&p->initreq);
2530 p->lastinvite = p->ocseq;
2532 return send_request(p, &req, 1, p->ocseq);
2535 static void build_contact(struct sip_pvt *p)
2537 /* Construct Contact: header */
2538 if (ourport != 5060)
2539 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2541 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2544 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2551 char *l = callerid, *n=NULL;
2552 if (p->owner && p->owner->callerid) {
2553 strcpy(cid, p->owner->callerid);
2554 ast_callerid_parse(cid, &n, &l);
2556 ast_shrink_phone_number(l);
2557 if (!l || !ast_isphonenumber(l))
2560 if (!n || !strlen(n))
2562 /* Allow user to be overridden */
2563 if (strlen(p->fromuser))
2566 if ((ourport != 5060) && !strlen(p->fromdomain))
2567 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);
2569 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2571 if (strlen(p->username)) {
2572 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2573 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2575 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2577 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2578 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2580 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2582 strncpy(p->uri, invite, sizeof(p->uri) - 1);
2583 /* If there is a VXML URL append it to the SIP URL */
2586 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2590 snprintf(to, sizeof(to), "<%s>", invite );
2592 memset(req, 0, sizeof(struct sip_request));
2593 init_req(req, cmd, invite);
2594 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2596 add_header(req, "Via", p->via);
2597 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2598 * OTOH, then we won't have anything in p->route anyway */
2599 add_header(req, "From", from);
2600 strncpy(p->exten, l, sizeof(p->exten) - 1);
2602 add_header(req, "To", to);
2603 add_header(req, "Contact", p->our_contact);
2604 add_header(req, "Call-ID", p->callid);
2605 add_header(req, "CSeq", tmp);
2606 add_header(req, "User-Agent", "Asterisk PBX");
2609 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url, char *distinctive_ring)
2611 struct sip_request req;
2612 initreqprep(&req, p, cmd, vxml_url);
2614 add_header(&req, "Proxy-Authorization", auth);
2616 if (distinctive_ring)
2618 add_header(&req, "Alert-info",distinctive_ring);
2620 add_header(&req, "Allow", ALLOWED_METHODS);
2622 add_sdp(&req, p, NULL, NULL);
2624 add_header(&req, "Content-Length", "0");
2625 add_blank_header(&req);
2628 if (!p->initreq.headers) {
2629 /* Use this as the basis */
2630 copy_request(&p->initreq, &req);
2632 determine_firstline_parts(&p->initreq);
2634 p->lastinvite = p->ocseq;
2635 return send_request(p, &req, 1, p->ocseq);
2638 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2641 char from[256], to[256];
2644 struct sip_request req;
2647 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2649 c = ditch_braces(from);
2650 if (strncmp(c, "sip:", 4)) {
2651 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2654 if ((a = strchr(c, ';'))) {
2659 reqprep(&req, p, "NOTIFY", 0);
2661 if (p->subscribed == 1) {
2662 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2664 c = ditch_braces(to);
2665 if (strncmp(c, "sip:", 4)) {
2666 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2669 if ((a = strchr(c, ';'))) {
2674 add_header(&req, "Content-Type", "application/xpidf+xml");
2676 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2678 else if (state==AST_EXTENSION_INUSE)
2684 sprintf(t, "<?xml version=\"1.0\"?>\n");
2685 t = tmp + strlen(tmp);
2686 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2687 t = tmp + strlen(tmp);
2688 sprintf(t, "<presence>\n");
2689 t = tmp + strlen(tmp);
2690 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2691 t = tmp + strlen(tmp);
2692 sprintf(t, "<atom id=\"%s\">\n", p->exten);
2693 t = tmp + strlen(tmp);
2694 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2695 t = tmp + strlen(tmp);
2696 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2697 t = tmp + strlen(tmp);
2698 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2699 t = tmp + strlen(tmp);
2700 sprintf(t, "</address>\n</atom>\n</presence>\n");
2702 add_header(&req, "Event", "dialog");
2703 add_header(&req, "Content-Type", "application/dialog-info+xml");
2706 sprintf(t, "<?xml version=\"1.0\"?>\n");
2707 t = tmp + strlen(tmp);
2708 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);
2709 t = tmp + strlen(tmp);
2710 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2711 t = tmp + strlen(tmp);
2712 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2713 t = tmp + strlen(tmp);
2714 sprintf(t, "</dialog>\n</dialog-info>\n");
2717 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2718 add_header(&req, "Content-Length", clen);
2719 add_line(&req, tmp);
2721 return send_request(p, &req, 1, p->ocseq);
2724 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2726 struct sip_request req;
2730 initreqprep(&req, p, "NOTIFY", NULL);
2731 add_header(&req, "Event", "message-summary");
2732 add_header(&req, "Content-Type", notifymime);
2734 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2735 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2736 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2737 add_header(&req, "Content-Length", clen);
2738 add_line(&req, tmp);
2739 add_line(&req, tmp2);
2741 if (!p->initreq.headers) {
2742 /* Use this as the basis */
2743 copy_request(&p->initreq, &req);
2745 determine_firstline_parts(&p->initreq);
2748 return send_request(p, &req, 1, p->ocseq);
2751 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2753 static int sip_reregister(void *data)
2755 /* if we are here, we know that we need to reregister. */
2756 struct sip_registry *r=(struct sip_registry *)data;
2763 static int sip_do_register(struct sip_registry *r)
2766 ast_mutex_lock(&r->lock);
2767 res=transmit_register(r, "REGISTER", NULL);
2768 ast_mutex_unlock(&r->lock);
2772 static int sip_reg_timeout(void *data)
2774 /* if we are here, our registration timed out, so we'll just do it over */
2775 struct sip_registry *r=data;
2778 ast_mutex_lock(&r->lock);
2779 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
2781 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
2782 in the single SIP manager thread. */
2788 r->regstate=REG_STATE_UNREGISTERED;
2790 res=transmit_register(r, "REGISTER", NULL);
2791 ast_mutex_unlock(&r->lock);
2795 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2797 struct sip_request req;
2804 /* exit if we are already in process with this registrar ?*/
2805 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2806 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2812 ast_log(LOG_WARNING, "Already have a call??\n");
2817 if (!r->callid_valid) {
2818 build_callid(r->callid, sizeof(r->callid), __ourip);
2819 r->callid_valid = 1;
2821 p=sip_alloc( r->callid, &r->addr, 0);
2823 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2829 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2830 if (strlen(r->authuser))
2831 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2833 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2834 strncpy(p->username, r->username, sizeof(p->username)-1);
2835 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2836 /* Always bind to our IP if specified */
2837 if (bindaddr.sin_addr.s_addr)
2838 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
2842 /* set up a timeout */
2844 if (r->timeout > -1) {
2845 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2846 ast_sched_del(sched, r->timeout);
2848 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2849 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2852 if (strchr(r->username, '@')) {
2853 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
2854 snprintf(to, sizeof(to), "<sip:%s>", r->username);
2856 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2857 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
2860 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2861 strncpy(p->uri, addr, sizeof(p->uri) - 1);
2863 memset(&req, 0, sizeof(req));
2864 init_req(&req, cmd, addr);
2866 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2867 p->ocseq = r->ocseq;
2869 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2870 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2871 add_header(&req, "Via", via);
2872 add_header(&req, "From", from);
2873 add_header(&req, "To", to);
2874 add_header(&req, "Call-ID", p->callid);
2875 add_header(&req, "CSeq", tmp);
2876 add_header(&req, "User-Agent", "Asterisk PBX");
2878 add_header(&req, "Authorization", auth);
2880 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2881 add_header(&req, "Expires", tmp);
2882 add_header(&req, "Contact", p->our_contact);
2883 add_header(&req, "Event", "registration");
2884 add_header(&req, "Content-length", "0");
2885 add_blank_header(&req);
2886 copy_request(&p->initreq, &req);
2888 determine_firstline_parts(&p->initreq);
2889 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2890 return send_request(p, &req, 1, p->ocseq);
2893 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2895 struct sip_request req;
2896 reqprep(&req, p, "MESSAGE", 0);
2897 add_text(&req, text);
2898 return send_request(p, &req, 1, p->ocseq);
2901 static int transmit_refer(struct sip_pvt *p, char *dest)
2903 struct sip_request req;
2908 of = get_header(&p->initreq, "To");
2910 of = get_header(&p->initreq, "From");
2911 strncpy(from, of, sizeof(from) - 1);
2912 of = ditch_braces(from);
2913 strncpy(p->from,of,sizeof(p->from) - 1);
2914 if (strncmp(of, "sip:", 4)) {
2915 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2918 /* Get just the username part */
2919 if ((c = strchr(of, '@'))) {
2924 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
2926 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
2929 reqprep(&req, p, "REFER", 0);
2930 add_header(&req, "Refer-To", referto);
2931 add_header(&req, "Referred-By", callerid);
2932 return send_request(p, &req, 1, p->ocseq);
2935 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2937 struct sip_request req;
2938 reqprep(&req, p, "INFO", 0);
2939 add_digit(&req, digit);
2940 return send_request(p, &req, 1, p->ocseq);
2943 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
2945 struct sip_request resp;
2946 reqprep(&resp, p, msg, seqno);
2947 add_header(&resp, "Content-Length", "0");
2948 add_blank_header(&resp);
2949 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2952 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
2954 struct sip_request resp;
2955 reqprep(&resp, p, msg, seqno);
2959 memset(digest,0,sizeof(digest));
2960 build_reply_digest(p, msg, digest, sizeof(digest));
2961 add_header(&resp, "Proxy-Authorization", digest);
2964 add_header(&resp, "Content-Length", "0");
2965 add_blank_header(&resp);
2966 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2969 static int expire_register(void *data)
2971 struct sip_peer *p = data;
2972 memset(&p->addr, 0, sizeof(p->addr));
2974 ast_device_state_changed("SIP/%s", p->name);
2978 static int sip_poke_peer(struct sip_peer *peer);
2980 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2982 char contact[80]= "";
2983 char *expires = get_header(req, "Expires");
2984 int expiry = atoi(expires);
2988 struct sockaddr_in oldsin;
2989 if (!strlen(expires)) {
2990 expires = strstr(get_header(req, "Contact"), "expires=");
2992 if (sscanf(expires + 8, "%d;", &expiry) != 1)
2993 expiry = default_expiry;
2995 /* Nothing has been specified */
2996 expiry = default_expiry;
2999 /* Look for brackets */
3000 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
3003 if ((n=strchr(c, '<'))) {
3006 /* Lose the part after the > */
3010 if (!strcasecmp(c, "*") || !expiry) {
3011 /* This means remove all registrations and return OK */
3012 memset(&p->addr, 0, sizeof(p->addr));
3014 ast_sched_del(sched, p->expire);
3016 if (option_verbose > 2)
3017 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
3020 /* Make sure it's a SIP URL */
3021 if (strncasecmp(c, "sip:", 4)) {
3022 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
3038 pt = strchr(n, ':');
3044 port = DEFAULT_SIP_PORT;
3045 memcpy(&oldsin, &p->addr, sizeof(oldsin));
3047 /* XXX This could block for a long time XXX */
3048 hp = gethostbyname(n);
3050 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
3053 p->addr.sin_family = AF_INET;
3054 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
3055 p->addr.sin_port = htons(port);
3057 /* Don't trust the contact field. Just use what they came to us
3059 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
3062 strncpy(p->username, c, sizeof(p->username) - 1);
3064 strcpy(p->username, "");
3066 ast_sched_del(sched, p->expire);
3067 if ((expiry < 1) || (expiry > max_expiry))
3068 expiry = max_expiry;
3069 p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
3070 pvt->expiry = expiry;
3071 if (inaddrcmp(&p->addr, &oldsin)) {
3073 if (option_verbose > 2)
3074 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);
3079 static void free_old_route(struct sip_route *route)
3081 struct sip_route *next;
3089 static void list_route(struct sip_route *route)
3092 ast_verbose("list_route: no route\n");
3096 ast_verbose("list_route: hop: <%s>\n", route->hop);
3097 route = route->next;
3101 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
3103 struct sip_route *thishop, *head, *tail;
3106 char *rr, *contact, *c;
3109 free_old_route(p->route);
3112 /* We build up head, then assign it to p->route when we're done */
3113 head = NULL; tail = head;
3114 /* 1st we pass through all the hops in any Record-Route headers */
3116 /* Each Record-Route header */
3117 rr = __get_header(req, "Record-Route", &start);
3118 if (*rr == '\0') break;
3120 /* Each route entry */
3122 rr = strchr(rr, '<');
3123 if (!rr) break; /* No more hops */
3125 len = strcspn(rr, ">");
3126 /* Make a struct route */
3127 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
3129 strncpy(thishop->hop, rr, len);
3130 thishop->hop[len] = '\0';
3131 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
3134 /* Link in at head so they end up in reverse order */
3135 thishop->next = head;
3137 /* If this was the first then it'll be the tail */
3138 if (!tail) tail = thishop;
3140 thishop->next = NULL;
3141 /* Link in at the end */
3143 tail->next = thishop;
3152 /* 2nd append the Contact: if there is one */
3153 /* Can be multiple Contact headers, comma separated values - we just take the first */
3154 contact = get_header(req, "Contact");
3155 if (strlen(contact)) {
3156 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
3157 /* Look for <: delimited address */
3158 c = strchr(contact, '<');
3162 len = strcspn(c, ">");
3164 /* No <> - just take the lot */
3165 c = contact; len = strlen(contact);
3167 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
3169 strncpy(thishop->hop, c, len);
3170 thishop->hop[len] = '\0';
3171 thishop->next = NULL;
3172 /* Goes at the end */
3174 tail->next = thishop;
3179 /* Store as new route */
3182 /* For debugging dump what we ended up with */
3184 list_route(p->route);
3187 static void md5_hash(char *output, char *input)
3189 struct MD5Context md5;
3190 unsigned char digest[16];
3194 MD5Update(&md5, input, strlen(input));
3195 MD5Final(digest, &md5);
3198 ptr += sprintf(ptr, "%2.2x", digest[x]);
3201 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)
3204 /* Always OK if no secret */
3205 if (!strlen(secret))
3207 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
3208 snprintf(randdata, randlen, "%08x", rand());
3209 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
3210 /* Schedule auto destroy in 15 seconds */
3211 sip_scheddestroy(p, 15000);
3214 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
3215 an example in the spec of just what it is you're doing a hash on. */
3221 char resp_hash[256];
3228 /* Find their response among the mess that we'r sent for comparison */
3229 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
3233 while (*c && (*c < 33)) c++;
3236 if (!strncasecmp(c, "response=", strlen("response="))) {
3237 c+= strlen("response=");
3240 if((c = strchr(c,'\"')))
3245 if((c = strchr(c,',')))
3249 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
3253 if((c = strchr(c,'\"')))
3257 if((c = strchr(c,',')))
3262 if ((z = strchr(c,' ')) || (z = strchr(c,','))) c=z;
3266 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
3267 if(strlen(resp_uri))
3268 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
3270 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
3271 md5_hash(a1_hash, a1);
3272 md5_hash(a2_hash, a2);
3273 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
3274 md5_hash(resp_hash, resp);
3276 /* resp_hash now has the expected response, compare the two */
3278 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
3282 /* Assume success ;-) */
3283 /* Eliminate random data */
3284 strcpy(randdata, "");
3289 static int cb_extensionstate(char *context, char* exten, int state, void *data)
3291 struct sip_pvt *p = data;
3293 sip_scheddestroy(p, 15000);
3298 transmit_state_notify(p, state, 1);
3301 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
3305 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
3308 struct sip_peer *peer;
3314 while(*t && (*t > 32) && (*t != ';'))
3318 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
3319 c = ditch_braces(tmp);
3320 /* Ditch ;user=phone */
3321 name = strchr(c, ';');
3325 if (!strncmp(c, "sip:", 4)) {
3329 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
3331 c = strchr(name, '@');
3334 strncpy(p->exten, name, sizeof(p->exten) - 1);
3336 ast_mutex_lock(&peerl.lock);
3339 if (!strcasecmp(peer->name, name) && peer->dynamic) {
3341 transmit_response(p, "100 Trying", req);
3342 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
3343 sip_cancel_destroy(p);
3344 if (parse_contact(p, peer, req)) {
3345 ast_log(LOG_WARNING, "Failed to parse contact info\n");
3347 /* Say OK and ask subsystem to retransmit msg counter */
3348 transmit_response_with_date(p, "200 OK", req);
3349 peer->lastmsgssent = -1;
3357 ast_mutex_unlock(&peerl.lock);
3359 ast_device_state_changed("SIP/%s", peer->name);
3362 transmit_response(p, "401 Unauthorized", &p->initreq);
3366 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
3368 char tmp[256] = "", *c, *a;
3369 struct sip_request *req;
3374 strncpy(tmp, get_header(req, "Diversion"), sizeof(tmp) - 1);
3377 c = ditch_braces(tmp);
3378 if (strncmp(c, "sip:", 4)) {
3379 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
3383 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3387 ast_verbose("RDNIS is %s\n", c);
3388 strncpy(p->rdnis, c, sizeof(p->rdnis) - 1);
3392 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
3394 char tmp[256] = "", *c, *a;
3395 struct sip_request *req;
3401 strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
3402 c = ditch_braces(tmp);
3403 if (strncmp(c, "sip:", 4)) {
3404 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3408 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3412 ast_verbose("Looking for %s in %s\n", c, p->context);
3413 if (ast_exists_extension(NULL, p->context, c, 1, NULL) ||
3414 !strcmp(c, ast_pickup_ext())) {
3416 strncpy(p->exten, c, sizeof(p->exten) - 1);
3420 if (ast_canmatch_extension(NULL, p->context, c, 1, NULL) ||
3421 !strncmp(c, ast_pickup_ext(),strlen(c))) {
3428 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
3430 char tmp[256] = "", *c, *a;
3431 char tmp2[256] = "", *c2, *a2;
3434 char tmp5[256] = ""; /* CallID to replace */
3435 struct sip_request *req;
3441 strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
3442 strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
3443 strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
3444 strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
3446 c = ditch_braces(tmp);
3447 c2 = ditch_braces(tmp2);
3450 if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
3451 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3452 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
3457 if ((a = strchr(c, '?'))) {
3458 /* Search for arguemnts */
3461 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
3462 strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
3463 if ((a = strchr(tmp5, '%'))) {
3464 /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
3466 if ((a[1] == '4') && (a[2] == '0')) {
3468 memmove(a + 1, a+3, strlen(a + 3));
3471 if ((a = strchr(tmp5, '%')))
3476 if ((a = strchr(c, '@')))
3478 if ((a = strchr(c, ';')))
3482 if ((a2 = strchr(c2, '@')))
3485 if ((a2 = strchr(c2, ';')))
3490 ast_verbose("Looking for %s in %s\n", c, p->context);
3491 ast_verbose("Looking for %s in %s\n", c2, p->context);
3494 /* This is a supervised transfer */
3495 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
3497 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
3498 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
3499 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
3500 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
3501 p->refer_call = NULL;
3502 ast_mutex_lock(&iflock);
3503 /* Search interfaces and find the match */
3506 if (!strcmp(p2->callid, tmp5)) {
3507 /* Go ahead and lock it before returning */
3508 ast_mutex_lock(&p2->lock);
3514 ast_mutex_unlock(&iflock);
3518 ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
3519 } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3520 /* This is an unsupervised transfer */
3521 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
3522 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
3523 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
3524 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
3525 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
3526 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
3527 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
3528 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
3529 p->refer_call = NULL;
3531 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
3539 static int check_via(struct sip_pvt *p, struct sip_request *req)
3545 memset(via, 0, sizeof(via));
3546 strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
3547 c = strchr(via, ';');
3550 c = strchr(via, ' ');
3554 while(*c && (*c < 33))
3556 if (strcmp(via, "SIP/2.0/UDP")) {
3557 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);