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 <asterisk/astdb.h>
41 #include <sys/socket.h>
42 #include <sys/ioctl.h>
49 #include <arpa/inet.h>
50 #include <sys/signal.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/ip.h>
55 #define IPTOS_MINCOST 0x02
58 /* #define VOCAL_DATA_HACK */
61 #define DEFAULT_DEFAULT_EXPIRY 120
62 #define DEFAULT_MAX_EXPIRY 3600
63 #define EXPIRY_GUARD_SECS 15
65 #define CALLERID_UNKNOWN "Unknown"
67 #define SIP_DTMF_RFC2833 (1 << 0)
68 #define SIP_DTMF_INBAND (1 << 1)
69 #define SIP_DTMF_INFO (1 << 2)
71 static int max_expiry = DEFAULT_MAX_EXPIRY;
72 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
74 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
75 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
76 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
78 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
79 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
81 static char *desc = "Session Initiation Protocol (SIP)";
82 static char *type = "sip";
83 static char *tdesc = "Session Initiation Protocol (SIP)";
84 static char *config = "sip.conf";
86 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
87 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
89 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
91 static char context[AST_MAX_EXTENSION] = "default";
93 static char language[MAX_LANGUAGE] = "";
95 static char callerid[AST_MAX_EXTENSION] = "asterisk";
97 static char fromdomain[AST_MAX_EXTENSION] = "";
99 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
101 static int srvlookup = 0;
103 static int pedanticsipchecking = 0;
105 static int usecnt =0;
106 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
108 /* Protect the interface list (of sip_pvt's) */
109 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
111 /* Protect the monitoring thread, so only one process can kill or start it, and not
112 when it's doing something critical. */
113 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
115 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
117 /* This is the thread for the monitor which checks for input on the channels
118 which are not currently in use. */
119 static pthread_t monitor_thread = 0;
121 static int restart_monitor(void);
123 /* Codecs that we support by default: */
124 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
125 static int noncodeccapability = AST_RTP_DTMF;
127 static char ourhost[256];
128 static struct in_addr __ourip;
131 static int sipdebug = 0;
135 static int videosupport = 0;
137 static int globaldtmfmode = SIP_DTMF_RFC2833;
140 static int expiry = 900;
142 static struct sched_context *sched;
143 static struct io_context *io;
144 /* The private structures of the sip channels are linked for
145 selecting outgoing channels */
147 #define SIP_MAX_HEADERS 64
148 #define SIP_MAX_LINES 64
152 #define DEC_OUT_USE 2
153 #define INC_OUT_USE 3
155 static struct sip_codec_pref {
157 struct sip_codec_pref *next;
161 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
162 char *rlPart2; /* The Request URI or Response Status */
164 int headers; /* SIP Headers */
165 char *header[SIP_MAX_HEADERS];
166 int lines; /* SDP Content */
167 char *line[SIP_MAX_LINES];
168 char data[SIP_MAX_PACKET];
174 struct sip_route *next;
178 static struct sip_pvt {
179 ast_mutex_t lock; /* Channel private lock */
180 char callid[80]; /* Global CallID */
181 char randdata[80]; /* Random data */
182 unsigned int ocseq; /* Current outgoing seqno */
183 unsigned int icseq; /* Current incoming seqno */
184 unsigned int callgroup;
185 unsigned int pickupgroup;
186 int lastinvite; /* Last Cseq of invite */
187 int alreadygone; /* Whether or not we've already been destroyed by or peer */
188 int needdestroy; /* if we need to be destroyed */
189 int capability; /* Special capability */
190 int jointcapability; /* Supported capability at both ends */
191 int noncodeccapability;
192 int outgoing; /* Outgoing or incoming call? */
193 int authtries; /* Times we've tried to authenticate */
194 int insecure; /* Don't check source port/ip */
195 int expiry; /* How long we take to expire */
196 int branch; /* One random number */
197 int canreinvite; /* Do we support reinvite */
198 int ringing; /* Have sent 180 ringing */
199 int progress; /* Have sent 183 message progress */
200 int tag; /* Another random number */
201 int nat; /* Whether to try to support NAT */
202 struct sockaddr_in sa; /* Our peer */
203 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
204 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
205 struct sockaddr_in recv; /* Received as */
206 struct in_addr ourip; /* Our IP */
207 struct ast_channel *owner; /* Who owns us */
208 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
209 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
210 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
211 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
212 struct sip_pvt *refer_call; /* Call we are referring */
213 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
214 char remote_party_id[256];
216 char context[AST_MAX_EXTENSION];
217 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
218 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
219 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
220 char language[MAX_LANGUAGE];
221 char rdnis[256]; /* Referring DNIS */
222 char theirtag[256]; /* Their tag */
225 char uri[81]; /* Original requested URI */
227 char callerid[256]; /* Caller*ID */
228 int restrictcid; /* hide presentation from remote user */
230 char accountcode[20]; /* Account code */
231 char our_contact[256]; /* Our contact header */
232 char realm[256]; /* Authorization realm */
233 char nonce[256]; /* Authorization nonce */
234 char domain[256]; /* Authorization nonce */
235 int amaflags; /* AMA Flags */
236 int pendinginvite; /* Any pending invite */
237 int pendingbye; /* Need to send bye after we ack? */
238 struct sip_request initreq; /* Initial request */
240 int maxtime; /* Max time for first response */
241 int initid; /* Auto-congest ID if appropriate */
242 int autokillid; /* Auto-kill ID */
251 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
252 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
253 struct ast_rtp *rtp; /* RTP Session */
254 struct ast_rtp *vrtp; /* Video RTP session */
255 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
256 struct sip_pvt *next;
260 struct sip_pkt *next; /* Next packet */
261 int retrans; /* Retransmission number */
262 int seqno; /* Sequence number */
263 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
264 struct sip_pvt *owner; /* Owner call */
265 int retransid; /* Retransmission ID */
266 int packetlen; /* Length of packet */
271 /* Users who can access various contexts */
277 char accountcode[20];
278 unsigned int callgroup;
279 unsigned int pickupgroup;
292 struct sip_user *next;
298 char context[80]; /* JK02: peers need context too to allow parking etc */
304 char mailbox[AST_MAX_EXTENSION];
314 unsigned int callgroup;
315 unsigned int pickupgroup;
317 struct sockaddr_in addr;
321 struct sip_pvt *call; /* Call pointer */
322 int pokeexpire; /* When to expire poke */
323 int lastms; /* How long last response took (in ms), or -1 for no response */
324 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
325 struct timeval ps; /* Ping send time */
327 struct sockaddr_in defaddr;
331 struct sip_peer *next;
334 static struct ast_user_list {
335 struct sip_user *users;
337 } userl = { NULL, AST_MUTEX_INITIALIZER };
339 static struct ast_peer_list {
340 struct sip_peer *peers;
342 } peerl = { NULL, AST_MUTEX_INITIALIZER };
345 #define REG_STATE_UNREGISTERED 0
346 #define REG_STATE_REGSENT 1
347 #define REG_STATE_AUTHSENT 2
348 #define REG_STATE_REGISTERED 3
349 #define REG_STATE_REJECTED 4
350 #define REG_STATE_TIMEOUT 5
351 #define REG_STATE_NOAUTH 6
353 struct sip_registry {
354 ast_mutex_t lock; /* Channel private lock */
355 struct sockaddr_in addr; /* Who we connect to for registration purposes */
356 char username[80]; /* Who we are registering as */
357 char authuser[80]; /* Who we *authenticate* as */
359 char secret[80]; /* Password or key name in []'s */
360 char contact[80]; /* Contact extension */
362 int expire; /* Sched ID of expiration */
363 int timeout; /* sched id of sip_reg_timeout */
364 int refresh; /* How often to refresh */
365 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
367 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
368 char callid[80]; /* Global CallID for this registry */
369 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
370 struct sockaddr_in us; /* Who the server thinks we are */
371 struct sip_registry *next;
374 #define REINVITE_INVITE 1
375 #define REINVITE_UPDATE 2
377 static int sip_do_register(struct sip_registry *r);
378 static struct sip_registry *registrations;
380 static int sipsock = -1;
381 static int globalnat = 0;
382 static int globalcanreinvite = REINVITE_INVITE;
385 static struct sockaddr_in bindaddr;
387 static struct ast_frame *sip_read(struct ast_channel *ast);
388 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
389 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
390 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
391 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
392 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
393 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url,char *distinctive_ring, int init);
394 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
395 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
396 static int transmit_message_with_text(struct sip_pvt *p, char *text);
397 static int transmit_refer(struct sip_pvt *p, char *dest);
398 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *msg, int init);
399 static char *getsipuri(char *header);
400 static void free_old_route(struct sip_route *route);
401 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
402 static int find_user(struct sip_pvt *fup, int event);
404 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
408 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
410 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
412 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));
417 static void sip_destroy(struct sip_pvt *p);
419 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
421 if (bindaddr.sin_addr.s_addr)
422 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
424 return ast_ouraddrfor(them, us);
428 static int retrans_pkt(void *data)
430 struct sip_pkt *pkt=data;
432 ast_mutex_lock(&pkt->owner->lock);
433 if (pkt->retrans < MAX_RETRANS) {
437 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));
439 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));
441 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
444 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
446 while(pkt->owner->owner && ast_mutex_lock(&pkt->owner->owner->lock)) {
447 ast_mutex_unlock(&pkt->owner->lock);
449 ast_mutex_lock(&pkt->owner->lock);
451 if (pkt->owner->owner) {
452 /* XXX Potential deadlocK?? XXX */
453 ast_queue_hangup(pkt->owner->owner, 0);
454 ast_mutex_unlock(&pkt->owner->owner->lock);
456 /* If no owner, destroy now */
457 pkt->owner->needdestroy = 1;
461 ast_mutex_unlock(&pkt->owner->lock);
465 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
468 pkt = malloc(sizeof(struct sip_pkt) + len);
471 memset(pkt, 0, sizeof(struct sip_pkt));
472 memcpy(pkt->data, data, len);
473 pkt->packetlen = len;
474 pkt->next = p->packets;
478 /* Schedule retransmission */
479 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
480 pkt->next = p->packets;
482 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
483 if (!strncasecmp(pkt->data, "INVITE", 6)) {
484 /* Note this is a pending invite */
485 p->pendinginvite = seqno;
490 static int __sip_autodestruct(void *data)
492 struct sip_pvt *p = data;
494 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
496 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
497 ast_queue_hangup(p->owner, 0);
504 static int sip_scheddestroy(struct sip_pvt *p, int ms)
506 if (p->autokillid > -1)
507 ast_sched_del(sched, p->autokillid);
508 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
512 static int sip_cancel_destroy(struct sip_pvt *p)
514 if (p->autokillid > -1)
515 ast_sched_del(sched, p->autokillid);
520 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
522 struct sip_pkt *cur, *prev = NULL;
527 if ((cur->seqno == seqno) && (cur->resp == resp)) {
528 if (!resp && (seqno == p->pendinginvite)) {
529 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
530 p->pendinginvite = 0;
533 /* this is our baby */
535 prev->next = cur->next;
537 p->packets = cur->next;
538 if (cur->retransid > -1)
539 ast_sched_del(sched, cur->retransid);
547 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
551 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
557 if ((cur->seqno == seqno) && (cur->resp == resp)) {
558 /* this is our baby */
559 if (cur->retransid > -1)
560 ast_sched_del(sched, cur->retransid);
567 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
571 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
576 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));
578 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));
581 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
583 res = __sip_xmit(p, req->data, req->len);
589 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
594 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));
596 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));
599 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
601 res = __sip_xmit(p, req->data, req->len);
605 static char *ditch_braces(char *tmp)
610 if ((n = strchr(tmp, '<')) ) {
612 while(*c && *c != '>') c++;
614 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
623 static int sip_sendtext(struct ast_channel *ast, char *text)
625 struct sip_pvt *p = ast->pvt->pvt;
627 ast_verbose("Sending text %s on %s\n", text, ast->name);
630 if (!text || !strlen(text))
633 ast_verbose("Really sending text %s on %s\n", text, ast->name);
634 transmit_message_with_text(p, text);
638 static int create_addr(struct sip_pvt *r, char *peer)
645 char host[256], *hostn;
647 r->sa.sin_family = AF_INET;
648 ast_mutex_lock(&peerl.lock);
651 if (!strcasecmp(p->name, peer)) {
653 r->capability = p->capability;
656 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
657 ast_rtp_setnat(r->rtp, r->nat);
660 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
661 ast_rtp_setnat(r->vrtp, r->nat);
663 strncpy(r->peername, p->username, sizeof(r->peername)-1);
664 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
665 strncpy(r->username, p->username, sizeof(r->username)-1);
666 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
667 if (!strlen(r->tohost)) {
668 if (p->addr.sin_addr.s_addr)
669 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
671 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
673 if (strlen(p->fromdomain))
674 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
675 if (strlen(p->fromuser))
676 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
677 r->insecure = p->insecure;
678 r->canreinvite = p->canreinvite;
679 r->maxtime = p->maxms;
680 r->callgroup = p->callgroup;
681 r->pickupgroup = p->pickupgroup;
683 r->dtmfmode = p->dtmfmode;
684 if (r->dtmfmode & SIP_DTMF_RFC2833)
685 r->noncodeccapability |= AST_RTP_DTMF;
687 r->noncodeccapability &= ~AST_RTP_DTMF;
689 strncpy(r->context, p->context,sizeof(r->context)-1);
690 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
691 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
692 if (p->addr.sin_addr.s_addr) {
693 r->sa.sin_addr = p->addr.sin_addr;
694 r->sa.sin_port = p->addr.sin_port;
696 r->sa.sin_addr = p->defaddr.sin_addr;
697 r->sa.sin_port = p->defaddr.sin_port;
699 memcpy(&r->recv, &r->sa, sizeof(r->recv));
705 ast_mutex_unlock(&peerl.lock);
707 if ((port=strchr(peer, ':'))) {
715 portno = DEFAULT_SIP_PORT;
720 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
721 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
727 hp = gethostbyname(hostn);
729 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
730 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
731 r->sa.sin_port = htons(portno);
732 memcpy(&r->recv, &r->sa, sizeof(r->recv));
735 ast_log(LOG_WARNING, "No such host: %s\n", peer);
744 static int auto_congest(void *nothing)
746 struct sip_pvt *p = nothing;
747 ast_mutex_lock(&p->lock);
750 if (!ast_mutex_trylock(&p->owner->lock)) {
751 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
752 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
753 ast_mutex_unlock(&p->owner->lock);
756 ast_mutex_unlock(&p->lock);
760 static void sip_prefs_free(void)
762 struct sip_codec_pref *cur, *next;
772 static void sip_pref_remove(int format)
774 struct sip_codec_pref *cur, *prev=NULL;
777 if (cur->codec == format) {
779 prev->next = cur->next;
790 static int sip_pref_append(int format)
792 struct sip_codec_pref *cur, *tmp;
793 sip_pref_remove(format);
794 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
797 memset(tmp, 0, sizeof(struct sip_codec_pref));
809 static int sip_codec_choose(int formats)
811 struct sip_codec_pref *cur;
812 formats &= (AST_FORMAT_MAX_AUDIO - 1);
815 if (formats & cur->codec)
819 return ast_best_codec(formats);
822 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
826 char *vxml_url = NULL;
827 char *distinctive_ring = NULL;
828 struct varshead *headp;
829 struct ast_var_t *current;
832 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
833 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
836 /* Check whether there is vxml_url, distinctive ring variables */
838 headp=&ast->varshead;
839 AST_LIST_TRAVERSE(headp,current,entries) {
840 /* Check whether there is a VXML_URL variable */
841 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
843 vxml_url = ast_var_value(current);
846 /* Check whether there is a ALERT_INFO variable */
847 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
849 distinctive_ring = ast_var_value(current);
856 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
857 res = find_user(p,INC_OUT_USE);
858 p->restrictcid = ast->restrictcid;
859 transmit_invite(p, "INVITE", 1, NULL, vxml_url,distinctive_ring, 1);
861 /* Initialize auto-congest time */
862 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
867 static void __sip_destroy(struct sip_pvt *p, int lockowner)
869 struct sip_pvt *cur, *prev = NULL;
872 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
874 ast_extension_state_del(p->stateid, NULL);
876 ast_sched_del(sched, p->initid);
877 if (p->autokillid > -1)
878 ast_sched_del(sched, p->autokillid);
881 ast_rtp_destroy(p->rtp);
884 ast_rtp_destroy(p->vrtp);
887 free_old_route(p->route);
891 p->registry->call=NULL;
893 /* Unlink us from the owner if we have one */
896 ast_mutex_lock(&p->owner->lock);
897 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
898 p->owner->pvt->pvt = NULL;
900 ast_mutex_unlock(&p->owner->lock);
906 prev->next = cur->next;
915 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
918 ast_sched_del(sched, p->initid);
919 while((cp = p->packets)) {
920 p->packets = p->packets->next;
921 if (cp->retransid > -1)
922 ast_sched_del(sched, cp->retransid);
929 static int find_user(struct sip_pvt *fup, int event)
933 strncpy(name, fup->username, sizeof(name) - 1);
934 ast_mutex_lock(&userl.lock);
937 if (!strcasecmp(u->name, name)) {
943 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
944 ast_mutex_unlock(&userl.lock);
949 if ( u->inUse > 0 ) {
956 if (u->incominglimit > 0 ) {
957 if (u->inUse >= u->incominglimit) {
958 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
959 ast_mutex_unlock(&userl.lock);
964 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
967 if ( u->outUse > 0 ) {
974 if ( u->outgoinglimit > 0 ) {
975 if ( u->outUse >= u->outgoinglimit ) {
976 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
977 ast_mutex_unlock(&userl.lock);
984 ast_log(LOG_ERROR, "find_user(%s,%d) called with no event!\n",u->name,event);
986 ast_mutex_unlock(&userl.lock);
990 static void sip_destroy(struct sip_pvt *p)
992 ast_mutex_lock(&iflock);
994 ast_mutex_unlock(&iflock);
997 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
1000 static int sip_hangup(struct ast_channel *ast)
1002 struct sip_pvt *p = ast->pvt->pvt;
1004 int needdestroy = 0;
1006 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1007 if (!ast->pvt->pvt) {
1008 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1011 ast_mutex_lock(&p->lock);
1012 if ( p->outgoing ) {
1013 ast_log(LOG_DEBUG, "find_user(%s) - decrement outUse counter\n", p->username);
1014 find_user(p, DEC_OUT_USE);
1016 ast_log(LOG_DEBUG, "find_user(%s) - decrement inUse counter\n", p->username);
1017 find_user(p, DEC_IN_USE);
1019 /* Determine how to disconnect */
1020 if (p->owner != ast) {
1021 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1022 ast_mutex_unlock(&p->lock);
1025 if (!ast || (ast->_state != AST_STATE_UP))
1030 ast_dsp_free(p->vad);
1033 ast->pvt->pvt = NULL;
1036 /* Start the process if it's not already started */
1037 if (!p->alreadygone && strlen(p->initreq.data)) {
1040 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
1041 /* Actually don't destroy us yet, wait for the 487 on our original
1042 INVITE, but do set an autodestruct just in case. */
1044 sip_scheddestroy(p, 15000);
1046 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
1048 if (!p->pendinginvite) {
1050 transmit_request_with_auth(p, "BYE", 0, 1);
1052 /* Note we will need a BYE when this all settles out
1053 but we can't send one while we have "INVITE" outstanding. */
1058 p->needdestroy = needdestroy;
1059 ast_mutex_unlock(&p->lock);
1063 static int sip_answer(struct ast_channel *ast)
1067 struct sip_pvt *p = ast->pvt->pvt;
1070 if (ast->_state != AST_STATE_UP) {
1074 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1076 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1077 fmt=ast_getformatbyname(codec);
1080 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
1083 ast_setstate(ast, AST_STATE_UP);
1085 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1086 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1091 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1093 struct sip_pvt *p = ast->pvt->pvt;
1095 if (frame->frametype == AST_FRAME_VOICE) {
1096 if (!(frame->subclass & ast->nativeformats)) {
1097 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1098 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1102 ast_mutex_lock(&p->lock);
1104 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1105 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1108 res = ast_rtp_write(p->rtp, frame);
1110 ast_mutex_unlock(&p->lock);
1112 } else if (frame->frametype == AST_FRAME_VIDEO) {
1114 ast_mutex_lock(&p->lock);
1116 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1117 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1120 res = ast_rtp_write(p->vrtp, frame);
1122 ast_mutex_unlock(&p->lock);
1124 } else if (frame->frametype == AST_FRAME_IMAGE) {
1127 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1134 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1136 struct sip_pvt *p = newchan->pvt->pvt;
1137 ast_mutex_lock(&p->lock);
1138 if (p->owner != oldchan) {
1139 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1140 ast_mutex_unlock(&p->lock);
1144 ast_mutex_unlock(&p->lock);
1148 static int sip_senddigit(struct ast_channel *ast, char digit)
1150 struct sip_pvt *p = ast->pvt->pvt;
1151 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1152 transmit_info_with_digit(p, digit);
1154 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1155 ast_rtp_senddigit(p->rtp, digit);
1157 /* If in-band DTMF is desired, send that */
1158 if (p->dtmfmode & SIP_DTMF_INBAND)
1163 static int sip_transfer(struct ast_channel *ast, char *dest)
1165 struct sip_pvt *p = ast->pvt->pvt;
1167 res = transmit_refer(p, dest);
1171 static int sip_indicate(struct ast_channel *ast, int condition)
1173 struct sip_pvt *p = ast->pvt->pvt;
1175 case AST_CONTROL_RINGING:
1176 if (ast->_state == AST_STATE_RING) {
1177 if (!p->progress && !p->ringing) {
1178 transmit_response(p, "180 Ringing", &p->initreq);
1182 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1186 case AST_CONTROL_BUSY:
1187 if (ast->_state != AST_STATE_UP) {
1188 transmit_response(p, "486 Busy Here", &p->initreq);
1190 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1194 case AST_CONTROL_CONGESTION:
1195 if (ast->_state != AST_STATE_UP) {
1196 transmit_response(p, "503 Service Unavailable", &p->initreq);
1198 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1202 case AST_CONTROL_PROGRESS:
1203 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1204 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1212 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1220 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1222 struct ast_channel *tmp;
1224 tmp = ast_channel_alloc(1);
1226 /* Select our native format based on codec preference until we receive
1227 something from another device to the contrary. */
1228 if (i->jointcapability)
1229 tmp->nativeformats = sip_codec_choose(i->jointcapability);
1230 else if (i->capability)
1231 tmp->nativeformats = sip_codec_choose(i->capability);
1233 tmp->nativeformats = sip_codec_choose(capability);
1234 fmt = ast_best_codec(tmp->nativeformats);
1236 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1238 if (strchr(i->fromdomain,':'))
1240 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1244 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1247 if (i->dtmfmode & SIP_DTMF_INBAND) {
1248 i->vad = ast_dsp_new();
1249 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1251 tmp->fds[0] = ast_rtp_fd(i->rtp);
1252 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1254 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1255 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1257 ast_setstate(tmp, state);
1258 if (state == AST_STATE_RING)
1260 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1261 tmp->writeformat = fmt;
1262 tmp->pvt->rawwriteformat = fmt;
1263 tmp->readformat = fmt;
1264 tmp->pvt->rawreadformat = fmt;
1266 tmp->pvt->send_text = sip_sendtext;
1267 tmp->pvt->call = sip_call;
1268 tmp->pvt->hangup = sip_hangup;
1269 tmp->pvt->answer = sip_answer;
1270 tmp->pvt->read = sip_read;
1271 tmp->pvt->write = sip_write;
1272 tmp->pvt->write_video = sip_write;
1273 tmp->pvt->indicate = sip_indicate;
1274 tmp->pvt->transfer = sip_transfer;
1275 tmp->pvt->fixup = sip_fixup;
1276 tmp->pvt->send_digit = sip_senddigit;
1278 tmp->pvt->bridge = ast_rtp_bridge;
1280 tmp->callgroup = i->callgroup;
1281 tmp->pickupgroup = i->pickupgroup;
1282 tmp->restrictcid = i->restrictcid;
1283 if (strlen(i->accountcode))
1284 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1286 tmp->amaflags = i->amaflags;
1287 if (strlen(i->language))
1288 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1290 ast_mutex_lock(&usecnt_lock);
1292 ast_mutex_unlock(&usecnt_lock);
1293 ast_update_use_count();
1294 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1295 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1296 if (strlen(i->callerid))
1297 tmp->callerid = strdup(i->callerid);
1298 if (strlen(i->rdnis))
1299 tmp->rdnis = strdup(i->rdnis);
1301 if (state != AST_STATE_DOWN) {
1302 if (ast_pbx_start(tmp)) {
1303 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1309 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1313 static struct cfalias {
1317 { "Content-Type", "c" },
1318 { "Content-Encoding", "e" },
1322 { "Content-Length", "l" },
1328 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1329 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1330 char* r = line + nameLen + 1;
1331 while (*r && (*r < 33)) ++r;
1338 static char *get_sdp(struct sip_request *req, char *name) {
1340 int len = strlen(name);
1343 for (x=0; x<req->lines; x++) {
1344 r = get_sdp_by_line(req->line[x], name, len);
1345 if (r[0] != '\0') return r;
1350 static void sdpLineNum_iterator_init(int* iterator) {
1354 static char* get_sdp_iterate(int* iterator,
1355 struct sip_request *req, char *name) {
1356 int len = strlen(name);
1358 while (*iterator < req->lines) {
1359 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1360 if (r[0] != '\0') return r;
1365 static char *__get_header(struct sip_request *req, char *name, int *start)
1368 int len = strlen(name);
1370 for (x=*start;x<req->headers;x++) {
1371 if (!strncasecmp(req->header[x], name, len) &&
1372 (req->header[x][len] == ':')) {
1373 r = req->header[x] + len + 1;
1374 while(*r && (*r < 33))
1381 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1382 if (!strcasecmp(aliases[x].fullname, name))
1383 return __get_header(req, aliases[x].shortname, start);
1385 /* Don't return NULL, so get_header is always a valid pointer */
1389 static char *get_header(struct sip_request *req, char *name)
1392 return __get_header(req, name, &start);
1395 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1397 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1398 struct ast_frame *f;
1399 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1402 f = ast_rtp_read(p->rtp);
1405 f = ast_rtcp_read(p->rtp);
1408 f = ast_rtp_read(p->vrtp);
1411 f = ast_rtcp_read(p->vrtp);
1416 /* Don't send RFC2833 if we're not supposed to */
1417 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1420 /* We already hold the channel lock */
1421 if (f->frametype == AST_FRAME_VOICE) {
1422 if (f->subclass != p->owner->nativeformats) {
1423 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1424 p->owner->nativeformats = f->subclass;
1425 ast_set_read_format(p->owner, p->owner->readformat);
1426 ast_set_write_format(p->owner, p->owner->writeformat);
1428 if (p->dtmfmode & SIP_DTMF_INBAND) {
1429 f = ast_dsp_process(p->owner,p->vad,f,0);
1436 static struct ast_frame *sip_read(struct ast_channel *ast)
1438 struct ast_frame *fr;
1439 struct sip_pvt *p = ast->pvt->pvt;
1440 ast_mutex_lock(&p->lock);
1441 fr = sip_rtp_read(ast, p);
1442 ast_mutex_unlock(&p->lock);
1446 static void build_callid(char *callid, int len, struct in_addr ourip)
1453 res = snprintf(callid, len, "%08x", val);
1457 /* It's not important that we really use our right IP here... */
1458 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1461 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1465 p = malloc(sizeof(struct sip_pvt));
1468 /* Keep track of stuff */
1469 memset(p, 0, sizeof(struct sip_pvt));
1473 p->rtp = ast_rtp_new(sched, io, 1, 0);
1475 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1479 /* Start with 101 instead of 1 */
1482 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1486 ast_rtp_settos(p->rtp, tos);
1488 ast_rtp_settos(p->vrtp, tos);
1489 if (useglobalnat && sin) {
1490 /* Setup NAT structure according to global settings if we have an address */
1492 memcpy(&p->recv, sin, sizeof(p->recv));
1493 ast_rtp_setnat(p->rtp, p->nat);
1495 ast_rtp_setnat(p->vrtp, p->nat);
1497 ast_mutex_init(&p->lock);
1500 memcpy(&p->sa, sin, sizeof(p->sa));
1501 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1502 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1504 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1506 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1507 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1509 build_callid(p->callid, sizeof(p->callid), p->ourip);
1511 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1512 /* Assume reinvite OK and via INVITE */
1513 p->canreinvite = globalcanreinvite;
1514 p->dtmfmode = globaldtmfmode;
1515 p->capability = capability;
1516 if (p->dtmfmode & SIP_DTMF_RFC2833)
1517 p->noncodeccapability |= AST_RTP_DTMF;
1518 strncpy(p->context, context, sizeof(p->context) - 1);
1519 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1521 ast_mutex_lock(&iflock);
1524 ast_mutex_unlock(&iflock);
1526 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1530 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1538 callid = get_header(req, "Call-ID");
1540 if (pedanticsipchecking) {
1541 /* In principle Call-ID's uniquely identify a call, however some vendors
1542 (i.e. Pingtel) send multiple calls with the same Call-ID and different
1543 tags in order to simplify billing. The RFC does state that we have to
1544 compare tags in addition to the call-id, but this generate substantially
1545 more overhead which is totally unnecessary for the vast majority of sane
1546 SIP implementations, and thus Asterisk does not enable this behavior
1547 by default. Short version: You'll need this option to support conferencing
1549 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1551 c = strchr(tmp, ' ');
1554 if (!strcasecmp(cmd, "SIP/2.0")) {
1560 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1562 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1563 tag = strstr(tmp, "tag=");
1566 c = strchr(tag, ';');
1573 if (!strlen(callid)) {
1574 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1577 ast_mutex_lock(&iflock);
1580 if (!strcmp(p->callid, callid) &&
1581 (!pedanticsipchecking || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1582 /* Found the call */
1583 ast_mutex_lock(&p->lock);
1584 ast_mutex_unlock(&iflock);
1589 ast_mutex_unlock(&iflock);
1590 p = sip_alloc(callid, sin, 1);
1592 ast_mutex_lock(&p->lock);
1596 static int sip_register(char *value, int lineno)
1598 struct sip_registry *reg;
1599 char copy[256] = "";
1600 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1608 strncpy(copy, value, sizeof(copy)-1);
1611 hostname = strrchr(stringp, '@');
1616 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1617 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1621 username = strsep(&stringp, ":");
1623 secret = strsep(&stringp, ":");
1625 authuser = strsep(&stringp, ":");
1628 hostname = strsep(&stringp, "/");
1630 contact = strsep(&stringp, "/");
1631 if (!contact || !strlen(contact))
1634 hostname = strsep(&stringp, ":");
1635 porta = strsep(&stringp, ":");
1637 if (porta && !atoi(porta)) {
1638 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1641 hp = gethostbyname(hostname);
1643 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1646 reg = malloc(sizeof(struct sip_registry));
1648 memset(reg, 0, sizeof(struct sip_registry));
1649 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1651 strncpy(reg->username, username, sizeof(reg->username)-1);
1653 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1655 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1657 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1660 reg->refresh = default_expiry;
1661 reg->addr.sin_family = AF_INET;
1662 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1663 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1664 reg->next = registrations;
1665 reg->callid_valid = 0;
1667 registrations = reg;
1669 ast_log(LOG_ERROR, "Out of memory\n");
1675 static void parse(struct sip_request *req)
1677 /* Divide fields by NULL's */
1682 /* First header starts immediately */
1686 /* We've got a new header */
1690 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1692 if (!strlen(req->header[f])) {
1693 /* Line by itself means we're now in content */
1697 if (f >= SIP_MAX_HEADERS - 1) {
1698 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1701 req->header[f] = c + 1;
1702 } else if (*c == '\r') {
1703 /* Ignore but eliminate \r's */
1708 /* Check for last header */
1709 if (strlen(req->header[f]))
1712 /* Now we process any mime content */
1717 /* We've got a new line */
1720 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1722 if (f >= SIP_MAX_LINES - 1) {
1723 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1726 req->line[f] = c + 1;
1727 } else if (*c == '\r') {
1728 /* Ignore and eliminate \r's */
1733 /* Check for last line */
1734 if (strlen(req->line[f]))
1738 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1740 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1743 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1752 int peercapability, peernoncodeccapability;
1753 int vpeercapability=0, vpeernoncodeccapability=0;
1754 struct sockaddr_in sin;
1761 /* Get codec and RTP info from SDP */
1762 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1763 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1766 m = get_sdp(req, "m");
1767 c = get_sdp(req, "c");
1768 if (!strlen(m) || !strlen(c)) {
1769 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1772 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1773 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1776 /* XXX This could block for a long time, and block the main thread! XXX */
1777 hp = gethostbyname(host);
1779 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1782 sdpLineNum_iterator_init(&iterator);
1783 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
1784 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
1786 // Scan through the RTP payload types specified in a "m=" line:
1787 ast_rtp_pt_clear(p->rtp);
1789 while(strlen(codecs)) {
1790 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1791 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1795 ast_verbose("Found audio format %s\n", ast_getformatname(codec));
1796 ast_rtp_set_m_type(p->rtp, codec);
1798 /* Skip over any whitespace */
1799 while(*codecs && (*codecs < 33)) codecs++;
1802 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
1804 // Scan through the RTP payload types specified in a "m=" line:
1805 ast_rtp_pt_clear(p->vrtp);
1807 while(strlen(codecs)) {
1808 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1809 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1813 ast_verbose("Found video format %s\n", ast_getformatname(codec));
1814 ast_rtp_set_m_type(p->vrtp, codec);
1816 /* Skip over any whitespace */
1817 while(*codecs && (*codecs < 33)) codecs++;
1821 sin.sin_family = AF_INET;
1822 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1823 /* Setup audio port number */
1824 sin.sin_port = htons(portno);
1825 if (p->rtp && sin.sin_port)
1826 ast_rtp_set_peer(p->rtp, &sin);
1827 /* Setup video port number */
1828 sin.sin_port = htons(vportno);
1829 if (p->vrtp && sin.sin_port)
1830 ast_rtp_set_peer(p->vrtp, &sin);
1832 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1834 // Next, scan through each "a=rtpmap:" line, noting each
1835 // specified RTP payload type (with corresponding MIME subtype):
1836 sdpLineNum_iterator_init(&iterator);
1837 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1838 char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
1839 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1841 ast_verbose("Found description format %s\n", mimeSubtype);
1842 // Note: should really look at the 'freq' and '#chans' params too
1843 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1845 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
1848 // Now gather all of the codecs that were asked for:
1849 ast_rtp_get_current_formats(p->rtp,
1850 &peercapability, &peernoncodeccapability);
1852 ast_rtp_get_current_formats(p->vrtp,
1853 &vpeercapability, &vpeernoncodeccapability);
1854 p->jointcapability = p->capability & (peercapability | vpeercapability);
1855 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
1858 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
1859 p->capability, peercapability, vpeercapability, p->jointcapability);
1860 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1861 noncodeccapability, peernoncodeccapability,
1862 p->noncodeccapability);
1864 if (!p->jointcapability) {
1865 ast_log(LOG_WARNING, "No compatible codecs!\n");
1869 if (!(p->owner->nativeformats & p->jointcapability)) {
1870 ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->jointcapability, p->owner->nativeformats);
1871 p->owner->nativeformats = sip_codec_choose(p->jointcapability);
1872 ast_set_read_format(p->owner, p->owner->readformat);
1873 ast_set_write_format(p->owner, p->owner->writeformat);
1875 if (p->owner->bridge) {
1876 /* Turn on/off music on hold if we are holding/unholding */
1877 if (sin.sin_addr.s_addr) {
1878 ast_moh_stop(p->owner->bridge);
1880 ast_moh_start(p->owner->bridge, NULL);
1888 static int add_header(struct sip_request *req, char *var, char *value)
1890 if (req->len >= sizeof(req->data) - 4) {
1891 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
1895 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1898 req->header[req->headers] = req->data + req->len;
1899 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1900 req->len += strlen(req->header[req->headers]);
1901 if (req->headers < SIP_MAX_HEADERS)
1904 ast_log(LOG_WARNING, "Out of header space\n");
1910 static int add_blank_header(struct sip_request *req)
1912 if (req->len >= sizeof(req->data) - 4) {
1913 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1917 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1920 req->header[req->headers] = req->data + req->len;
1921 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1922 req->len += strlen(req->header[req->headers]);
1923 if (req->headers < SIP_MAX_HEADERS)
1926 ast_log(LOG_WARNING, "Out of header space\n");
1932 static int add_line(struct sip_request *req, char *line)
1934 if (req->len >= sizeof(req->data) - 4) {
1935 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1939 /* Add extra empty return */
1940 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1941 req->len += strlen(req->data + req->len);
1943 req->line[req->lines] = req->data + req->len;
1944 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1945 req->len += strlen(req->line[req->lines]);
1946 if (req->lines < SIP_MAX_LINES)
1949 ast_log(LOG_WARNING, "Out of line space\n");
1955 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1958 tmp = get_header(orig, field);
1960 /* Add what we're responding to */
1961 return add_header(req, field, tmp);
1963 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1967 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1973 tmp = __get_header(orig, field, &start);
1975 /* Add what we're responding to */
1976 add_header(req, field, tmp);
1981 return copied ? 0 : -1;
1984 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1991 tmp = __get_header(orig, field, &start);
1993 if (!copied && p->nat) {
1994 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
1995 /* SLD: FIXME: Nice try, but the received= should not have a port */
1996 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1997 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
1999 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2000 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2003 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2004 add_header(req, field, new);
2006 /* Add what we're responding to */
2007 add_header(req, field, tmp);
2014 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2020 /* Add Route: header into request per learned route */
2021 static void add_route(struct sip_request *req, struct sip_route *route)
2024 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2030 n = strlen(route->hop);
2031 if ((n+3)>rem) break;
2037 strcpy(p, route->hop); p += n;
2040 route = route->next;
2043 add_header(req, "Route", r);
2046 static void set_destination(struct sip_pvt *p, char *uri)
2048 char *h, *maddr, hostname[256];
2052 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2053 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2056 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2058 /* Find and parse hostname */
2059 h = strchr(uri, '@');
2064 if (strncmp(h, "sip:", 4) == 0)
2066 else if (strncmp(h, "sips:", 5) == 0)
2069 hn = strcspn(h, ":;>");
2071 strncpy(hostname, h, hn); hostname[hn] = '\0';
2074 /* Is "port" present? if not default to 5060 */
2078 port = strtol(h, &h, 10);
2083 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2084 maddr = strstr(h, "maddr=");
2087 hn = strspn(maddr, "0123456789.");
2089 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2092 hp = gethostbyname(hostname);
2094 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2097 p->sa.sin_family = AF_INET;
2098 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2099 p->sa.sin_port = htons(port);
2101 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2104 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2106 /* Initialize a response */
2107 if (req->headers || req->len) {
2108 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2111 req->header[req->headers] = req->data + req->len;
2112 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2113 req->len += strlen(req->header[req->headers]);
2114 if (req->headers < SIP_MAX_HEADERS)
2117 ast_log(LOG_WARNING, "Out of header space\n");
2121 static int init_req(struct sip_request *req, char *resp, char *recip)
2123 /* Initialize a response */
2124 if (req->headers || req->len) {
2125 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2128 req->header[req->headers] = req->data + req->len;
2129 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2130 req->len += strlen(req->header[req->headers]);
2131 if (req->headers < SIP_MAX_HEADERS)
2134 ast_log(LOG_WARNING, "Out of header space\n");
2138 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2140 char newto[256] = "", *ot;
2141 memset(resp, 0, sizeof(*resp));
2142 init_resp(resp, msg, req);
2143 copy_via_headers(p, resp, req, "Via");
2144 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2145 copy_header(resp, req, "From");
2146 ot = get_header(req, "To");
2147 if (!strstr(ot, "tag=")) {
2148 /* Add the proper tag if we don't have it already. If they have specified
2149 their tag, use it. Otherwise, use our own tag */
2150 if (strlen(p->theirtag) && p->outgoing)
2151 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2152 else if (p->tag && !p->outgoing)
2153 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2155 strncpy(newto, ot, sizeof(newto) - 1);
2158 add_header(resp, "To", ot);
2159 copy_header(resp, req, "Call-ID");
2160 copy_header(resp, req, "CSeq");
2161 add_header(resp, "User-Agent", "Asterisk PBX");
2162 add_header(resp, "Allow", ALLOWED_METHODS);
2164 /* For registration responses, we also need expiry and
2168 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2169 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2170 add_header(resp, "Expires", tmp);
2171 add_header(resp, "Contact", contact);
2173 add_header(resp, "Contact", p->our_contact);
2178 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2180 struct sip_request *orig = &p->initreq;
2181 char stripped[80] ="";
2187 memset(req, 0, sizeof(struct sip_request));
2194 if (strlen(p->uri)) {
2198 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2200 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2202 c = strchr(stripped, '<');
2214 init_req(req, msg, c);
2216 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2218 add_header(req, "Via", p->via);
2220 set_destination(p, p->route->hop);
2221 add_route(req, p->route->next);
2224 ot = get_header(orig, "To");
2225 of = get_header(orig, "From");
2227 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2228 as our original request, including tag (or presumably lack thereof) */
2229 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2230 /* Add the proper tag if we don't have it already. If they have specified
2231 their tag, use it. Otherwise, use our own tag */
2232 if (p->outgoing && strlen(p->theirtag))
2233 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2234 else if (!p->outgoing)
2235 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2237 snprintf(newto, sizeof(newto), "%s", ot);
2242 add_header(req, "From", of);
2243 add_header(req, "To", ot);
2245 add_header(req, "From", ot);
2246 add_header(req, "To", of);
2248 add_header(req, "Contact", p->our_contact);
2249 copy_header(req, orig, "Call-ID");
2250 add_header(req, "CSeq", tmp);
2252 add_header(req, "User-Agent", "Asterisk PBX");
2256 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2258 struct sip_request resp;
2260 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2261 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2264 respprep(&resp, p, msg, req);
2265 add_header(&resp, "Content-Length", "0");
2266 add_blank_header(&resp);
2267 return send_response(p, &resp, reliable, seqno);
2270 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2272 return __transmit_response(p, msg, req, 0);
2274 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2276 return __transmit_response(p, msg, req, 1);
2279 static void append_date(struct sip_request *req)
2286 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2287 add_header(req, "Date", tmpdat);
2290 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2292 struct sip_request resp;
2293 respprep(&resp, p, msg, req);
2295 add_header(&resp, "Content-Length", "0");
2296 add_blank_header(&resp);
2297 return send_response(p, &resp, 0, 0);
2300 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2302 struct sip_request resp;
2303 respprep(&resp, p, msg, req);
2304 add_header(&resp, "Accept", "application/sdp");
2305 add_header(&resp, "Content-Length", "0");
2306 add_blank_header(&resp);
2307 return send_response(p, &resp, 0, 0);
2310 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2312 struct sip_request resp;
2315 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2316 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2319 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2320 respprep(&resp, p, msg, req);
2321 add_header(&resp, "Proxy-Authenticate", tmp);
2322 add_header(&resp, "Content-Length", "0");
2323 add_blank_header(&resp);
2324 return send_response(p, &resp, reliable, seqno);
2327 static int add_text(struct sip_request *req, char *text)
2329 /* XXX Convert \n's to \r\n's XXX */
2330 int len = strlen(text);
2332 snprintf(clen, sizeof(clen), "%d", len);
2333 add_header(req, "Content-Type", "text/plain");
2334 add_header(req, "Content-Length", clen);
2335 add_line(req, text);
2339 static int add_digit(struct sip_request *req, char digit)
2344 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2346 snprintf(clen, sizeof(clen), "%d", len);
2347 add_header(req, "Content-Type", "application/dtmf-relay");
2348 add_header(req, "Content-Length", clen);
2353 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2357 int alreadysent = 0;
2359 struct sockaddr_in sin;
2360 struct sockaddr_in vsin;
2361 struct sip_codec_pref *cur;
2372 struct sockaddr_in dest;
2373 struct sockaddr_in vdest;
2374 /* XXX We break with the "recommendation" and send our IP, in order that our
2375 peer doesn't have to gethostbyname() us XXX */
2378 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2381 ast_rtp_get_us(p->rtp, &sin);
2383 ast_rtp_get_us(p->vrtp, &vsin);
2385 if (p->redirip.sin_addr.s_addr) {
2386 dest.sin_port = p->redirip.sin_port;
2387 dest.sin_addr = p->redirip.sin_addr;
2389 ast_rtp_get_peer(rtp, &dest);
2391 dest.sin_addr = p->ourip;
2392 dest.sin_port = sin.sin_port;
2395 /* Determine video destination */
2397 if (p->vredirip.sin_addr.s_addr) {
2398 vdest.sin_port = p->vredirip.sin_port;
2399 vdest.sin_addr = p->vredirip.sin_addr;
2401 ast_rtp_get_peer(vrtp, &vdest);
2403 vdest.sin_addr = p->ourip;
2404 vdest.sin_port = vsin.sin_port;
2408 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2409 if (sipdebug && p->vrtp)
2410 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2411 snprintf(v, sizeof(v), "v=0\r\n");
2412 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2413 snprintf(s, sizeof(s), "s=session\r\n");
2414 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2415 snprintf(t, sizeof(t), "t=0 0\r\n");
2416 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2417 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2418 /* Start by sending our preferred codecs */
2421 if (p->capability & cur->codec) {
2423 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2424 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2426 snprintf(costr, sizeof(costr), " %d", codec);
2427 if (cur->codec < AST_FORMAT_MAX_AUDIO) {
2429 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2433 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2438 alreadysent |= cur->codec;
2441 /* Now send any other common codecs, and non-codec formats: */
2442 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2443 if ((p->capability & x) && !(alreadysent & x)) {
2445 ast_verbose("Answering with capability %d\n", x);
2446 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2448 snprintf(costr, sizeof(costr), " %d", codec);
2449 if (x < AST_FORMAT_MAX_AUDIO) {
2451 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2455 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2461 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2462 if (p->noncodeccapability & x) {
2464 ast_verbose("Answering with non-codec capability %d\n", x);
2465 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2467 snprintf(costr, sizeof(costr), " %d", codec);
2469 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2471 if (x == AST_RTP_DTMF) {
2472 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2473 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2482 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2484 len += strlen(m2) + strlen(a2);
2485 snprintf(costr, sizeof(costr), "%d", len);
2486 add_header(resp, "Content-Type", "application/sdp");
2487 add_header(resp, "Content-Length", costr);
2502 static void copy_request(struct sip_request *dst,struct sip_request *src)
2506 offset = ((void *)dst) - ((void *)src);
2507 /* First copy stuff */
2508 memcpy(dst, src, sizeof(*dst));
2509 /* Now fix pointer arithmetic */
2510 for (x=0;x<src->headers;x++)
2511 dst->header[x] += offset;
2512 for (x=0;x<src->lines;x++)
2513 dst->line[x] += offset;
2516 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2518 struct sip_request resp;
2520 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2521 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2524 respprep(&resp, p, msg, req);
2525 add_sdp(&resp, p, NULL, NULL);
2526 return send_response(p, &resp, retrans, seqno);
2529 static int determine_firstline_parts( struct sip_request *req ) {
2534 cmd= req->header[0];
2535 while(*cmd && (*cmd < 33)) {
2542 while(*e && (*e > 32)) {
2545 /* Get the command */
2551 while( *e && ( *e < 33 ) ) {
2558 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2559 /* We have a response */
2561 len= strlen( req->rlPart2 );
2562 if( len < 2 ) { return -1; }
2564 while( *e && *e<33 ) {
2569 /* We have a request */
2572 if( !*e ) { return -1; }
2575 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2578 while( isspace( *(--e) ) ) {}
2588 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2590 struct sip_request req;
2591 if (p->canreinvite == REINVITE_UPDATE)
2592 reqprep(&req, p, "UPDATE", 0);
2594 reqprep(&req, p, "INVITE", 0);
2595 add_header(&req, "Allow", ALLOWED_METHODS);
2596 add_sdp(&req, p, rtp, vrtp);
2597 /* Use this as the basis */
2598 copy_request(&p->initreq, &req);
2600 determine_firstline_parts(&p->initreq);
2601 p->lastinvite = p->ocseq;
2603 return send_request(p, &req, 1, p->ocseq);
2606 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
2608 char stripped[256]="";
2610 strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
2611 c = strchr(stripped, '<');
2623 strncpy(p->uri, c, sizeof(p->uri) - 1);
2626 static void build_contact(struct sip_pvt *p)
2628 /* Construct Contact: header */
2629 if (ourport != 5060)
2630 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2632 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2635 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2642 char *l = callerid, *n=NULL;
2643 if (p->owner && p->owner->callerid) {
2644 strcpy(cid, p->owner->callerid);
2645 ast_callerid_parse(cid, &n, &l);
2647 ast_shrink_phone_number(l);
2648 if (!l || !ast_isphonenumber(l))
2651 /* if user want's his callerid restricted */
2653 l = CALLERID_UNKNOWN;
2654 if (!n || !strlen(n))
2656 /* Allow user to be overridden */
2657 if (strlen(p->fromuser))
2660 if ((ourport != 5060) && !strlen(p->fromdomain))
2661 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);
2663 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2665 if (strlen(p->username)) {
2666 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2667 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2669 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2671 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2672 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2674 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2676 strncpy(p->uri, invite, sizeof(p->uri) - 1);
2677 /* If there is a VXML URL append it to the SIP URL */
2680 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2684 snprintf(to, sizeof(to), "<%s>", invite );
2686 memset(req, 0, sizeof(struct sip_request));
2687 init_req(req, cmd, invite);
2688 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2690 add_header(req, "Via", p->via);
2691 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2692 * OTOH, then we won't have anything in p->route anyway */
2693 add_header(req, "From", from);
2694 strncpy(p->exten, l, sizeof(p->exten) - 1);
2696 add_header(req, "To", to);
2697 add_header(req, "Contact", p->our_contact);
2698 add_header(req, "Call-ID", p->callid);
2699 add_header(req, "CSeq", tmp);
2700 add_header(req, "User-Agent", "Asterisk PBX");
2703 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url, char *distinctive_ring, int init)
2705 struct sip_request req;
2708 initreqprep(&req, p, cmd, vxml_url);
2710 reqprep(&req, p, cmd, 0);
2713 add_header(&req, "Proxy-Authorization", auth);
2715 if (distinctive_ring)
2717 add_header(&req, "Alert-info",distinctive_ring);
2719 add_header(&req, "Allow", ALLOWED_METHODS);
2721 add_sdp(&req, p, NULL, NULL);
2723 add_header(&req, "Content-Length", "0");
2724 add_blank_header(&req);
2727 if (!p->initreq.headers) {
2728 /* Use this as the basis */
2729 copy_request(&p->initreq, &req);
2731 determine_firstline_parts(&p->initreq);
2733 p->lastinvite = p->ocseq;
2734 return send_request(p, &req, 1, p->ocseq);
2737 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2740 char from[256], to[256];
2743 struct sip_request req;
2746 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2748 c = ditch_braces(from);
2749 if (strncmp(c, "sip:", 4)) {
2750 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2753 if ((a = strchr(c, ';'))) {
2758 reqprep(&req, p, "NOTIFY", 0);
2760 if (p->subscribed == 1) {
2761 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2763 c = ditch_braces(to);
2764 if (strncmp(c, "sip:", 4)) {
2765 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2768 if ((a = strchr(c, ';'))) {
2773 add_header(&req, "Content-Type", "application/xpidf+xml");
2775 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2777 else if (state==AST_EXTENSION_INUSE)
2783 sprintf(t, "<?xml version=\"1.0\"?>\n");
2784 t = tmp + strlen(tmp);
2785 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2786 t = tmp + strlen(tmp);
2787 sprintf(t, "<presence>\n");
2788 t = tmp + strlen(tmp);
2789 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2790 t = tmp + strlen(tmp);
2791 sprintf(t, "<atom id=\"%s\">\n", p->exten);
2792 t = tmp + strlen(tmp);
2793 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2794 t = tmp + strlen(tmp);
2795 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2796 t = tmp + strlen(tmp);
2797 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2798 t = tmp + strlen(tmp);
2799 sprintf(t, "</address>\n</atom>\n</presence>\n");
2801 add_header(&req, "Event", "dialog");
2802 add_header(&req, "Content-Type", "application/dialog-info+xml");
2805 sprintf(t, "<?xml version=\"1.0\"?>\n");
2806 t = tmp + strlen(tmp);
2807 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);
2808 t = tmp + strlen(tmp);
2809 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2810 t = tmp + strlen(tmp);
2811 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2812 t = tmp + strlen(tmp);
2813 sprintf(t, "</dialog>\n</dialog-info>\n");
2816 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2817 add_header(&req, "Content-Length", clen);
2818 add_line(&req, tmp);
2820 return send_request(p, &req, 1, p->ocseq);
2823 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2825 struct sip_request req;
2829 initreqprep(&req, p, "NOTIFY", NULL);
2830 add_header(&req, "Event", "message-summary");
2831 add_header(&req, "Content-Type", notifymime);
2833 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2834 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2835 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2836 add_header(&req, "Content-Length", clen);
2837 add_line(&req, tmp);
2838 add_line(&req, tmp2);
2840 if (!p->initreq.headers) {
2841 /* Use this as the basis */
2842 copy_request(&p->initreq, &req);
2844 determine_firstline_parts(&p->initreq);
2847 return send_request(p, &req, 1, p->ocseq);
2850 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
2852 static int sip_reregister(void *data)
2854 /* if we are here, we know that we need to reregister. */
2855 struct sip_registry *r=(struct sip_registry *)data;
2862 static int sip_do_register(struct sip_registry *r)
2865 ast_mutex_lock(&r->lock);
2866 res=transmit_register(r, "REGISTER", NULL, NULL);
2867 ast_mutex_unlock(&r->lock);
2871 static int sip_reg_timeout(void *data)
2873 /* if we are here, our registration timed out, so we'll just do it over */
2874 struct sip_registry *r=data;
2877 ast_mutex_lock(&r->lock);
2878 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
2880 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
2881 in the single SIP manager thread. */
2887 r->regstate=REG_STATE_UNREGISTERED;
2889 res=transmit_register(r, "REGISTER", NULL, NULL);
2890 ast_mutex_unlock(&r->lock);
2894 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
2896 struct sip_request req;
2903 /* exit if we are already in process with this registrar ?*/
2904 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2905 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2911 ast_log(LOG_WARNING, "Already have a call??\n");
2916 if (!r->callid_valid) {
2917 build_callid(r->callid, sizeof(r->callid), __ourip);
2918 r->callid_valid = 1;
2920 p=sip_alloc( r->callid, &r->addr, 0);
2922 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2928 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2929 if (strlen(r->authuser))
2930 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2932 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2933 strncpy(p->username, r->username, sizeof(p->username)-1);
2934 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2935 /* Always bind to our IP if specified */
2936 if (bindaddr.sin_addr.s_addr)
2937 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
2941 /* set up a timeout */
2943 if (r->timeout > -1) {
2944 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2945 ast_sched_del(sched, r->timeout);
2947 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2948 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2951 if (strchr(r->username, '@')) {
2952 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
2953 snprintf(to, sizeof(to), "<sip:%s>", r->username);
2955 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2956 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
2959 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2960 strncpy(p->uri, addr, sizeof(p->uri) - 1);
2962 memset(&req, 0, sizeof(req));
2963 init_req(&req, cmd, addr);
2965 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2966 p->ocseq = r->ocseq;
2968 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2969 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2970 add_header(&req, "Via", via);
2971 add_header(&req, "From", from);
2972 add_header(&req, "To", to);
2973 add_header(&req, "Call-ID", p->callid);
2974 add_header(&req, "CSeq", tmp);
2975 add_header(&req, "User-Agent", "Asterisk PBX");
2977 add_header(&req, authheader, auth);
2979 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2980 add_header(&req, "Expires", tmp);
2981 add_header(&req, "Contact", p->our_contact);
2982 add_header(&req, "Event", "registration");
2983 add_header(&req, "Content-length", "0");
2984 add_blank_header(&req);
2985 copy_request(&p->initreq, &req);
2987 determine_firstline_parts(&p->initreq);
2988 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2989 return send_request(p, &req, 1, p->ocseq);
2992 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2994 struct sip_request req;
2995 reqprep(&req, p, "MESSAGE", 0);
2996 add_text(&req, text);
2997 return send_request(p, &req, 1, p->ocseq);
3000 static int transmit_refer(struct sip_pvt *p, char *dest)
3002 struct sip_request req;
3007 of = get_header(&p->initreq, "To");
3009 of = get_header(&p->initreq, "From");
3010 strncpy(from, of, sizeof(from) - 1);
3011 of = ditch_braces(from);
3012 strncpy(p->from,of,sizeof(p->from) - 1);
3013 if (strncmp(of, "sip:", 4)) {
3014 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3017 /* Get just the username part */
3018 if ((c = strchr(of, '@'))) {
3023 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
3025 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
3028 reqprep(&req, p, "REFER", 0);
3029 add_header(&req, "Refer-To", referto);
3030 add_header(&req, "Referred-By", callerid);
3031 return send_request(p, &req, 1, p->ocseq);
3034 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
3036 struct sip_request req;
3037 reqprep(&req, p, "INFO", 0);
3038 add_digit(&req, digit);
3039 return send_request(p, &req, 1, p->ocseq);
3042 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
3044 struct sip_request resp;
3045 reqprep(&resp, p, msg, seqno);
3046 add_header(&resp, "Content-Length", "0");
3047 add_blank_header(&resp);
3048 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3051 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
3053 struct sip_request resp;
3054 reqprep(&resp, p, msg, seqno);
3058 memset(digest,0,sizeof(digest));
3059 build_reply_digest(p, msg, digest, sizeof(digest));
3060 add_header(&resp, "Proxy-Authorization", digest);
3063 add_header(&resp, "Content-Length", "0");
3064 add_blank_header(&resp);
3065 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3068 static int expire_register(void *data)
3070 struct sip_peer *p = data;
3071 memset(&p->addr, 0, sizeof(p->addr));
3072 ast_db_del("SIP/Registry", p->name);
3074 ast_device_state_changed("SIP/%s", p->name);
3078 static int sip_poke_peer(struct sip_peer *peer);
3080 static void reg_source_db(struct sip_peer *p)
3086 if (!ast_db_get("SIP/Registry", p->name, data, sizeof(data))) {
3087 c = strchr(data, ':');
3091 if (inet_aton(data, &in)) {
3096 ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding '%s' at %s:%d for %d\n", p->name,
3097 inet_ntoa(in), atoi(c), atoi(d));
3100 memset(&p->addr, 0, sizeof(p->addr));
3101 p->addr.sin_family = AF_INET;
3102 p->addr.sin_addr = in;
3103 p->addr.sin_port = htons(atoi(c));
3105 ast_sched_del(sched, p->expire);
3106 p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, (void *)p);
3114 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
3116 char contact[80]= "";
3118 char *expires = get_header(req, "Expires");
3119 int expiry = atoi(expires);
3123 struct sockaddr_in oldsin;
3124 if (!strlen(expires)) {
3125 expires = strstr(get_header(req, "Contact"), "expires=");
3127 if (sscanf(expires + 8, "%d;", &expiry) != 1)
3128 expiry = default_expiry;
3130 /* Nothing has been specified */
3131 expiry = default_expiry;
3134 /* Look for brackets */
3135 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
3138 if ((n=strchr(c, '<'))) {
3141 /* Lose the part after the > */
3145 if (!strcasecmp(c, "*") || !expiry) {
3146 /* This means remove all registrations and return OK */
3147 memset(&p->addr, 0, sizeof(p->addr));
3149 ast_sched_del(sched, p->expire);
3151 if (option_verbose > 2)
3152 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->name);
3155 /* Make sure it's a SIP URL */
3156 if (strncasecmp(c, "sip:", 4)) {
3157 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
3173 pt = strchr(n, ':');
3179 port = DEFAULT_SIP_PORT;
3180 memcpy(&oldsin, &p->addr, sizeof(oldsin));
3182 /* XXX This could block for a long time XXX */
3183 hp = gethostbyname(n);
3185 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
3188 p->addr.sin_family = AF_INET;
3189 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
3190 p->addr.sin_port = htons(port);
3192 /* Don't trust the contact field. Just use what they came to us
3194 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
3197 strncpy(p->username, c, sizeof(p->username) - 1);
3199 strcpy(p->username, "");
3201 ast_sched_del(sched, p->expire);
3202 if ((expiry < 1) || (expiry > max_expiry))
3203 expiry = max_expiry;
3204 p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
3205 pvt->expiry = expiry;
3206 if (inaddrcmp(&p->addr, &oldsin)) {
3208 snprintf(data, sizeof(data), "%s:%d:%d", inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expiry);
3209 ast_db_put("SIP/Registry", p->name, data);
3210 if (option_verbose > 2)
3211 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->name, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expiry);
3216 static void free_old_route(struct sip_route *route)
3218 struct sip_route *next;
3226 static void list_route(struct sip_route *route)
3229 ast_verbose("list_route: no route\n");
3233 ast_verbose("list_route: hop: <%s>\n", route->hop);
3234 route = route->next;
3238 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
3240 struct sip_route *thishop, *head, *tail;
3243 char *rr, *contact, *c;
3246 free_old_route(p->route);
3249 /* We build up head, then assign it to p->route when we're done */
3250 head = NULL; tail = head;
3251 /* 1st we pass through all the hops in any Record-Route headers */
3253 /* Each Record-Route header */
3254 rr = __get_header(req, "Record-Route", &start);
3255 if (*rr == '\0') break;
3257 /* Each route entry */
3259 rr = strchr(rr, '<');
3260 if (!rr) break; /* No more hops */
3262 len = strcspn(rr, ">");
3263 /* Make a struct route */
3264 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
3266 strncpy(thishop->hop, rr, len);
3267 thishop->hop[len] = '\0';
3268 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
3271 /* Link in at head so they end up in reverse order */
3272 thishop->next = head;
3274 /* If this was the first then it'll be the tail */
3275 if (!tail) tail = thishop;
3277 thishop->next = NULL;
3278 /* Link in at the end */
3280 tail->next = thishop;
3289 /* 2nd append the Contact: if there is one */
3290 /* Can be multiple Contact headers, comma separated values - we just take the first */
3291 contact = get_header(req, "Contact");
3292 if (strlen(contact)) {
3293 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
3294 /* Look for <: delimited address */
3295 c = strchr(contact, '<');
3299 len = strcspn(c, ">");
3301 /* No <> - just take the lot */
3302 c = contact; len = strlen(contact);
3304 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
3306 strncpy(thishop->hop, c, len);
3307 thishop->hop[len] = '\0';
3308 thishop->next = NULL;
3309 /* Goes at the end */
3311 tail->next = thishop;
3316 /* Store as new route */
3319 /* For debugging dump what we ended up with */
3321 list_route(p->route);
3324 static void md5_hash(char *output, char *input)
3326 struct MD5Context md5;
3327 unsigned char digest[16];
3331 MD5Update(&md5, input, strlen(input));
3332 MD5Final(digest, &md5);
3335 ptr += sprintf(ptr, "%2.2x", digest[x]);
3338 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)
3341 /* Always OK if no secret */
3342 if (!strlen(secret))
3344 if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
3345 snprintf(randdata, randlen, "%08x", rand());
3346 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
3347 /* Schedule auto destroy in 15 seconds */
3348 sip_scheddestroy(p, 15000);
3351 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
3352 an example in the spec of just what it is you're doing a hash on. */
3358 char resp_hash[256];
3365 /* Find their response among the mess that we'r sent for comparison */
3366 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
3370 while (*c && (*c < 33)) c++;
3373 if (!strncasecmp(c, "response=", strlen("response="))) {
3374 c+= strlen("response=");
3377 if((c = strchr(c,'\"')))
3382 if((c = strchr(c,',')))
3386 } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
3390 if((c = strchr(c,'\"')))
3394 if((c = strchr(c,',')))
3399 if ((z = strchr(c,' ')) || (z = strchr(c,','))) c=z;
3403 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
3404 if(strlen(resp_uri))
3405 snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
3407 snprintf(a2, sizeof(a2), "%s:%s", method, uri);
3408 md5_hash(a1_hash, a1);
3409 md5_hash(a2_hash, a2);
3410 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
3411 md5_hash(resp_hash, resp);
3413 /* resp_hash now has the expected response, compare the two */
3415 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
3419 /* Assume success ;-) */
3420 /* Eliminate random data */
3421 strcpy(randdata, "");
3426 static int cb_extensionstate(char *context, char* exten, int state, void *data)
3428 struct sip_pvt *p = data;
3430 sip_scheddestroy(p, 15000);
3435 transmit_state_notify(p, state, 1);
3438 ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
3442 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
3445 struct sip_peer *peer;
3451 while(*t && (*t > 32) && (*t != ';'))
3455 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
3456 c = ditch_braces(tmp);
3457 /* Ditch ;user=phone */
3458 name = strchr(c, ';');
3462 if (!strncmp(c, "sip:", 4)) {
3466 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
3468 c = strchr(name, '@');
3471 strncpy(p->exten, name, sizeof(p->exten) - 1);
3473 ast_mutex_lock(&peerl.lock);
3476 if (!strcasecmp(peer->name, name) && peer->dynamic) {
3478 transmit_response(p, "100 Trying", req);
3479 if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
3480 sip_cancel_destroy(p);
3481 if (parse_contact(p, peer, req)) {
3482 ast_log(LOG_WARNING, "Failed to parse contact info\n");
3484 /* Say OK and ask subsystem to retransmit msg counter */
3485 transmit_response_with_date(p, "200 OK", req);
3486 peer->lastmsgssent = -1;
3494 ast_mutex_unlock(&peerl.lock);
3496 ast_device_state_changed("SIP/%s", peer->name);
3499 transmit_response(p, "401 Unauthorized", &p->initreq);
3503 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
3505 char tmp[256] = "", *c, *a;
3506 struct sip_request *req;
3511 strncpy(tmp, get_header(req, "Diversion"), sizeof(tmp) - 1);
3514 c = ditch_braces(tmp);
3515 if (strncmp(c, "sip:", 4)) {
3516 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
3520 if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3524 ast_verbose("RDNIS is %s\n", c);
3525 strncpy(p->rdnis, c, sizeof(p->rdnis) - 1);
3529 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
3531 char tmp[256] = "", *c, *a;
3532 struct sip_request *req;