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 <asterisk/causes.h>
42 #include <sys/socket.h>
43 #include <sys/ioctl.h>
50 #include <arpa/inet.h>
51 #include <sys/signal.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
56 #define IPTOS_MINCOST 0x02
59 /* #define VOCAL_DATA_HACK */
62 #define DEFAULT_DEFAULT_EXPIRY 120
63 #define DEFAULT_MAX_EXPIRY 3600
64 #define EXPIRY_GUARD_SECS 15
66 #define CALLERID_UNKNOWN "Unknown"
68 #define SIP_DTMF_RFC2833 (1 << 0)
69 #define SIP_DTMF_INBAND (1 << 1)
70 #define SIP_DTMF_INFO (1 << 2)
72 static int max_expiry = DEFAULT_MAX_EXPIRY;
73 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
75 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
76 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
77 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
79 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
80 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
82 static char *desc = "Session Initiation Protocol (SIP)";
83 static char *type = "sip";
84 static char *tdesc = "Session Initiation Protocol (SIP)";
85 static char *config = "sip.conf";
87 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
88 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
90 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
92 static char context[AST_MAX_EXTENSION] = "default";
94 static char language[MAX_LANGUAGE] = "";
96 static char callerid[AST_MAX_EXTENSION] = "asterisk";
98 static char fromdomain[AST_MAX_EXTENSION] = "";
100 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
102 static int srvlookup = 0;
104 static int pedanticsipchecking = 0;
106 static int usecnt =0;
107 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
109 /* Protect the interface list (of sip_pvt's) */
110 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
112 /* Protect the monitoring thread, so only one process can kill or start it, and not
113 when it's doing something critical. */
114 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
116 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
118 /* This is the thread for the monitor which checks for input on the channels
119 which are not currently in use. */
120 static pthread_t monitor_thread = 0;
122 static int restart_monitor(void);
124 /* Codecs that we support by default: */
125 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
126 static int noncodeccapability = AST_RTP_DTMF;
128 static char ourhost[256];
129 static struct in_addr __ourip;
132 static int sipdebug = 0;
136 static int videosupport = 0;
138 static int globaldtmfmode = SIP_DTMF_RFC2833;
141 static int expiry = 900;
143 static struct sched_context *sched;
144 static struct io_context *io;
145 /* The private structures of the sip channels are linked for
146 selecting outgoing channels */
148 #define SIP_MAX_HEADERS 64
149 #define SIP_MAX_LINES 64
153 #define DEC_OUT_USE 2
154 #define INC_OUT_USE 3
156 static struct sip_codec_pref {
158 struct sip_codec_pref *next;
162 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
163 char *rlPart2; /* The Request URI or Response Status */
165 int headers; /* SIP Headers */
166 char *header[SIP_MAX_HEADERS];
167 int lines; /* SDP Content */
168 char *line[SIP_MAX_LINES];
169 char data[SIP_MAX_PACKET];
175 struct sip_route *next;
179 static struct sip_pvt {
180 ast_mutex_t lock; /* Channel private lock */
181 char callid[80]; /* Global CallID */
182 char randdata[80]; /* Random data */
183 unsigned int ocseq; /* Current outgoing seqno */
184 unsigned int icseq; /* Current incoming seqno */
185 unsigned int callgroup;
186 unsigned int pickupgroup;
187 int lastinvite; /* Last Cseq of invite */
188 int alreadygone; /* Whether or not we've already been destroyed by or peer */
189 int needdestroy; /* if we need to be destroyed */
190 int capability; /* Special capability */
191 int jointcapability; /* Supported capability at both ends */
192 int noncodeccapability;
193 int outgoing; /* Outgoing or incoming call? */
194 int authtries; /* Times we've tried to authenticate */
195 int insecure; /* Don't check source port/ip */
196 int expiry; /* How long we take to expire */
197 int branch; /* One random number */
198 int canreinvite; /* Do we support reinvite */
199 int ringing; /* Have sent 180 ringing */
200 int progress; /* Have sent 183 message progress */
201 int tag; /* Another random number */
202 int nat; /* Whether to try to support NAT */
203 struct sockaddr_in sa; /* Our peer */
204 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
205 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
206 struct sockaddr_in recv; /* Received as */
207 struct in_addr ourip; /* Our IP */
208 struct ast_channel *owner; /* Who owns us */
209 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
210 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
211 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
212 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
213 struct sip_pvt *refer_call; /* Call we are referring */
214 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
215 char remote_party_id[256];
217 char context[AST_MAX_EXTENSION];
218 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
219 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
220 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
221 char language[MAX_LANGUAGE];
222 char rdnis[256]; /* Referring DNIS */
223 char theirtag[256]; /* Their tag */
226 char uri[256]; /* Original requested URI */
227 char peersecret[256];
228 char callerid[256]; /* Caller*ID */
229 int restrictcid; /* hide presentation from remote user */
231 char accountcode[20]; /* Account code */
232 char our_contact[256]; /* Our contact header */
233 char realm[256]; /* Authorization realm */
234 char nonce[256]; /* Authorization nonce */
235 char domain[256]; /* Authorization nonce */
236 int amaflags; /* AMA Flags */
237 int pendinginvite; /* Any pending invite */
238 int pendingbye; /* Need to send bye after we ack? */
239 struct sip_request initreq; /* Initial request */
241 int maxtime; /* Max time for first response */
242 int initid; /* Auto-congest ID if appropriate */
243 int autokillid; /* Auto-kill ID */
252 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
253 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
254 struct ast_rtp *rtp; /* RTP Session */
255 struct ast_rtp *vrtp; /* Video RTP session */
256 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
257 struct sip_pvt *next;
261 struct sip_pkt *next; /* Next packet */
262 int retrans; /* Retransmission number */
263 int seqno; /* Sequence number */
264 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
265 struct sip_pvt *owner; /* Owner call */
266 int retransid; /* Retransmission ID */
267 int packetlen; /* Length of packet */
272 /* Users who can access various contexts */
278 char accountcode[20];
279 unsigned int callgroup;
280 unsigned int pickupgroup;
293 struct sip_user *next;
299 char context[80]; /* JK02: peers need context too to allow parking etc */
305 char mailbox[AST_MAX_EXTENSION];
315 unsigned int callgroup;
316 unsigned int pickupgroup;
318 struct sockaddr_in addr;
322 struct sip_pvt *call; /* Call pointer */
323 int pokeexpire; /* When to expire poke */
324 int lastms; /* How long last response took (in ms), or -1 for no response */
325 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
326 struct timeval ps; /* Ping send time */
328 struct sockaddr_in defaddr;
332 struct sip_peer *next;
335 static struct ast_user_list {
336 struct sip_user *users;
338 } userl = { NULL, AST_MUTEX_INITIALIZER };
340 static struct ast_peer_list {
341 struct sip_peer *peers;
343 } peerl = { NULL, AST_MUTEX_INITIALIZER };
346 #define REG_STATE_UNREGISTERED 0
347 #define REG_STATE_REGSENT 1
348 #define REG_STATE_AUTHSENT 2
349 #define REG_STATE_REGISTERED 3
350 #define REG_STATE_REJECTED 4
351 #define REG_STATE_TIMEOUT 5
352 #define REG_STATE_NOAUTH 6
354 struct sip_registry {
355 ast_mutex_t lock; /* Channel private lock */
356 struct sockaddr_in addr; /* Who we connect to for registration purposes */
357 char username[80]; /* Who we are registering as */
358 char authuser[80]; /* Who we *authenticate* as */
360 char secret[80]; /* Password or key name in []'s */
361 char contact[80]; /* Contact extension */
363 int expire; /* Sched ID of expiration */
364 int timeout; /* sched id of sip_reg_timeout */
365 int refresh; /* How often to refresh */
366 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
368 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
369 char callid[80]; /* Global CallID for this registry */
370 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
371 struct sockaddr_in us; /* Who the server thinks we are */
372 struct sip_registry *next;
375 #define REINVITE_INVITE 1
376 #define REINVITE_UPDATE 2
378 static int sip_do_register(struct sip_registry *r);
379 static struct sip_registry *registrations;
381 static int sipsock = -1;
382 static int globalnat = 0;
383 static int globalcanreinvite = REINVITE_INVITE;
386 static struct sockaddr_in bindaddr;
388 static struct ast_frame *sip_read(struct ast_channel *ast);
389 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
390 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
391 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
392 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
393 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
394 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url,char *distinctive_ring, int init);
395 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
396 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
397 static int transmit_message_with_text(struct sip_pvt *p, char *text);
398 static int transmit_refer(struct sip_pvt *p, char *dest);
399 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *msg, int init);
400 static char *getsipuri(char *header);
401 static void free_old_route(struct sip_route *route);
402 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
403 static int find_user(struct sip_pvt *fup, int event);
405 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
409 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
411 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
413 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));
418 static void sip_destroy(struct sip_pvt *p);
420 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
422 if (bindaddr.sin_addr.s_addr)
423 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
425 return ast_ouraddrfor(them, us);
429 static int retrans_pkt(void *data)
431 struct sip_pkt *pkt=data;
433 ast_mutex_lock(&pkt->owner->lock);
434 if (pkt->retrans < MAX_RETRANS) {
438 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));
440 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));
442 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
445 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
447 while(pkt->owner->owner && ast_mutex_lock(&pkt->owner->owner->lock)) {
448 ast_mutex_unlock(&pkt->owner->lock);
450 ast_mutex_lock(&pkt->owner->lock);
452 if (pkt->owner->owner) {
453 /* XXX Potential deadlocK?? XXX */
454 ast_queue_hangup(pkt->owner->owner, 0);
455 ast_mutex_unlock(&pkt->owner->owner->lock);
457 /* If no owner, destroy now */
458 pkt->owner->needdestroy = 1;
462 ast_mutex_unlock(&pkt->owner->lock);
466 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
469 pkt = malloc(sizeof(struct sip_pkt) + len);
472 memset(pkt, 0, sizeof(struct sip_pkt));
473 memcpy(pkt->data, data, len);
474 pkt->packetlen = len;
475 pkt->next = p->packets;
479 /* Schedule retransmission */
480 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
481 pkt->next = p->packets;
483 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
484 if (!strncasecmp(pkt->data, "INVITE", 6)) {
485 /* Note this is a pending invite */
486 p->pendinginvite = seqno;
491 static int __sip_autodestruct(void *data)
493 struct sip_pvt *p = data;
495 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
497 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
498 ast_queue_hangup(p->owner, 0);
505 static int sip_scheddestroy(struct sip_pvt *p, int ms)
507 if (p->autokillid > -1)
508 ast_sched_del(sched, p->autokillid);
509 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
513 static int sip_cancel_destroy(struct sip_pvt *p)
515 if (p->autokillid > -1)
516 ast_sched_del(sched, p->autokillid);
521 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
523 struct sip_pkt *cur, *prev = NULL;
528 if ((cur->seqno == seqno) && (cur->resp == resp)) {
529 if (!resp && (seqno == p->pendinginvite)) {
530 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
531 p->pendinginvite = 0;
534 /* this is our baby */
536 prev->next = cur->next;
538 p->packets = cur->next;
539 if (cur->retransid > -1)
540 ast_sched_del(sched, cur->retransid);
548 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
552 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
558 if ((cur->seqno == seqno) && (cur->resp == resp)) {
559 /* this is our baby */
560 if (cur->retransid > -1)
561 ast_sched_del(sched, cur->retransid);
568 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");
572 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
577 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));
579 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));
582 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
584 res = __sip_xmit(p, req->data, req->len);
590 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
595 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));
597 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));
600 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
602 res = __sip_xmit(p, req->data, req->len);
606 static char *ditch_braces(char *tmp)
611 if ((n = strchr(tmp, '<')) ) {
613 while(*c && *c != '>') c++;
615 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
624 static int sip_sendtext(struct ast_channel *ast, char *text)
626 struct sip_pvt *p = ast->pvt->pvt;
628 ast_verbose("Sending text %s on %s\n", text, ast->name);
631 if (!text || !strlen(text))
634 ast_verbose("Really sending text %s on %s\n", text, ast->name);
635 transmit_message_with_text(p, text);
639 static int create_addr(struct sip_pvt *r, char *peer)
646 char host[256], *hostn;
648 r->sa.sin_family = AF_INET;
649 ast_mutex_lock(&peerl.lock);
652 if (!strcasecmp(p->name, peer)) {
654 r->capability = p->capability;
657 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
658 ast_rtp_setnat(r->rtp, r->nat);
661 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
662 ast_rtp_setnat(r->vrtp, r->nat);
664 strncpy(r->peername, p->username, sizeof(r->peername)-1);
665 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
666 strncpy(r->username, p->username, sizeof(r->username)-1);
667 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
668 if (!strlen(r->tohost)) {
669 if (p->addr.sin_addr.s_addr)
670 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
672 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
674 if (strlen(p->fromdomain))
675 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
676 if (strlen(p->fromuser))
677 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
678 r->insecure = p->insecure;
679 r->canreinvite = p->canreinvite;
680 r->maxtime = p->maxms;
681 r->callgroup = p->callgroup;
682 r->pickupgroup = p->pickupgroup;
684 r->dtmfmode = p->dtmfmode;
685 if (r->dtmfmode & SIP_DTMF_RFC2833)
686 r->noncodeccapability |= AST_RTP_DTMF;
688 r->noncodeccapability &= ~AST_RTP_DTMF;
690 strncpy(r->context, p->context,sizeof(r->context)-1);
691 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
692 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
693 if (p->addr.sin_addr.s_addr) {
694 r->sa.sin_addr = p->addr.sin_addr;
695 r->sa.sin_port = p->addr.sin_port;
697 r->sa.sin_addr = p->defaddr.sin_addr;
698 r->sa.sin_port = p->defaddr.sin_port;
700 memcpy(&r->recv, &r->sa, sizeof(r->recv));
706 ast_mutex_unlock(&peerl.lock);
708 if ((port=strchr(peer, ':'))) {
716 portno = DEFAULT_SIP_PORT;
721 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
722 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
728 hp = gethostbyname(hostn);
730 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
731 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
732 r->sa.sin_port = htons(portno);
733 memcpy(&r->recv, &r->sa, sizeof(r->recv));
736 ast_log(LOG_WARNING, "No such host: %s\n", peer);
745 static int auto_congest(void *nothing)
747 struct sip_pvt *p = nothing;
748 ast_mutex_lock(&p->lock);
751 if (!ast_mutex_trylock(&p->owner->lock)) {
752 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
753 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
754 ast_mutex_unlock(&p->owner->lock);
757 ast_mutex_unlock(&p->lock);
761 static void sip_prefs_free(void)
763 struct sip_codec_pref *cur, *next;
773 static void sip_pref_remove(int format)
775 struct sip_codec_pref *cur, *prev=NULL;
778 if (cur->codec == format) {
780 prev->next = cur->next;
791 static int sip_pref_append(int format)
793 struct sip_codec_pref *cur, *tmp;
794 sip_pref_remove(format);
795 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
798 memset(tmp, 0, sizeof(struct sip_codec_pref));
810 static int sip_codec_choose(int formats)
812 struct sip_codec_pref *cur;
813 formats &= (AST_FORMAT_MAX_AUDIO - 1);
816 if (formats & cur->codec)
820 return ast_best_codec(formats);
823 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
827 char *vxml_url = NULL;
828 char *distinctive_ring = NULL;
829 struct varshead *headp;
830 struct ast_var_t *current;
833 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
834 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
837 /* Check whether there is vxml_url, distinctive ring variables */
839 headp=&ast->varshead;
840 AST_LIST_TRAVERSE(headp,current,entries) {
841 /* Check whether there is a VXML_URL variable */
842 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
844 vxml_url = ast_var_value(current);
847 /* Check whether there is a ALERT_INFO variable */
848 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
850 distinctive_ring = ast_var_value(current);
857 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
858 res = find_user(p,INC_OUT_USE);
859 p->restrictcid = ast->restrictcid;
860 p->jointcapability = p->capability;
861 transmit_invite(p, "INVITE", 1, NULL, vxml_url,distinctive_ring, 1);
863 /* Initialize auto-congest time */
864 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
869 static void __sip_destroy(struct sip_pvt *p, int lockowner)
871 struct sip_pvt *cur, *prev = NULL;
874 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
876 ast_extension_state_del(p->stateid, NULL);
878 ast_sched_del(sched, p->initid);
879 if (p->autokillid > -1)
880 ast_sched_del(sched, p->autokillid);
883 ast_rtp_destroy(p->rtp);
886 ast_rtp_destroy(p->vrtp);
889 free_old_route(p->route);
893 /* Carefully unlink from registry */
894 struct sip_registry *reg;
897 if ((reg == p->registry) && (p->registry->call == p))
898 p->registry->call=NULL;
902 /* Unlink us from the owner if we have one */
905 ast_mutex_lock(&p->owner->lock);
906 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
907 p->owner->pvt->pvt = NULL;
909 ast_mutex_unlock(&p->owner->lock);
915 prev->next = cur->next;
924 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
927 ast_sched_del(sched, p->initid);
928 while((cp = p->packets)) {
929 p->packets = p->packets->next;
930 if (cp->retransid > -1)
931 ast_sched_del(sched, cp->retransid);
938 static int find_user(struct sip_pvt *fup, int event)
942 strncpy(name, fup->username, sizeof(name) - 1);
943 ast_mutex_lock(&userl.lock);
946 if (!strcasecmp(u->name, name)) {
952 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
953 ast_mutex_unlock(&userl.lock);
958 if ( u->inUse > 0 ) {
965 if (u->incominglimit > 0 ) {
966 if (u->inUse >= u->incominglimit) {
967 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
968 ast_mutex_unlock(&userl.lock);
973 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
976 if ( u->outUse > 0 ) {
983 if ( u->outgoinglimit > 0 ) {
984 if ( u->outUse >= u->outgoinglimit ) {
985 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
986 ast_mutex_unlock(&userl.lock);
993 ast_log(LOG_ERROR, "find_user(%s,%d) called with no event!\n",u->name,event);
995 ast_mutex_unlock(&userl.lock);
999 static void sip_destroy(struct sip_pvt *p)
1001 ast_mutex_lock(&iflock);
1002 __sip_destroy(p, 1);
1003 ast_mutex_unlock(&iflock);
1006 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
1009 static int sip_hangup(struct ast_channel *ast)
1011 struct sip_pvt *p = ast->pvt->pvt;
1013 int needdestroy = 0;
1015 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1016 if (!ast->pvt->pvt) {
1017 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1020 ast_mutex_lock(&p->lock);
1021 if ( p->outgoing ) {
1022 ast_log(LOG_DEBUG, "find_user(%s) - decrement outUse counter\n", p->username);
1023 find_user(p, DEC_OUT_USE);
1025 ast_log(LOG_DEBUG, "find_user(%s) - decrement inUse counter\n", p->username);
1026 find_user(p, DEC_IN_USE);
1028 /* Determine how to disconnect */
1029 if (p->owner != ast) {
1030 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1031 ast_mutex_unlock(&p->lock);
1034 if (!ast || (ast->_state != AST_STATE_UP))
1039 ast_dsp_free(p->vad);
1042 ast->pvt->pvt = NULL;
1044 ast_mutex_lock(&usecnt_lock);
1046 ast_mutex_unlock(&usecnt_lock);
1047 ast_update_use_count();
1050 /* Start the process if it's not already started */
1051 if (!p->alreadygone && strlen(p->initreq.data)) {
1054 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
1055 /* Actually don't destroy us yet, wait for the 487 on our original
1056 INVITE, but do set an autodestruct just in case. */
1058 sip_scheddestroy(p, 15000);
1060 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
1062 if (!p->pendinginvite) {
1064 transmit_request_with_auth(p, "BYE", 0, 1);
1066 /* Note we will need a BYE when this all settles out
1067 but we can't send one while we have "INVITE" outstanding. */
1072 p->needdestroy = needdestroy;
1073 ast_mutex_unlock(&p->lock);
1077 static int sip_answer(struct ast_channel *ast)
1081 struct sip_pvt *p = ast->pvt->pvt;
1084 if (ast->_state != AST_STATE_UP) {
1088 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1090 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1091 fmt=ast_getformatbyname(codec);
1094 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
1097 ast_setstate(ast, AST_STATE_UP);
1099 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1100 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1105 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1107 struct sip_pvt *p = ast->pvt->pvt;
1109 if (frame->frametype == AST_FRAME_VOICE) {
1110 if (!(frame->subclass & ast->nativeformats)) {
1111 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1112 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1116 ast_mutex_lock(&p->lock);
1118 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1119 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1122 res = ast_rtp_write(p->rtp, frame);
1124 ast_mutex_unlock(&p->lock);
1126 } else if (frame->frametype == AST_FRAME_VIDEO) {
1128 ast_mutex_lock(&p->lock);
1130 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1131 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1134 res = ast_rtp_write(p->vrtp, frame);
1136 ast_mutex_unlock(&p->lock);
1138 } else if (frame->frametype == AST_FRAME_IMAGE) {
1141 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1148 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1150 struct sip_pvt *p = newchan->pvt->pvt;
1151 ast_mutex_lock(&p->lock);
1152 if (p->owner != oldchan) {
1153 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1154 ast_mutex_unlock(&p->lock);
1158 ast_mutex_unlock(&p->lock);
1162 static int sip_senddigit(struct ast_channel *ast, char digit)
1164 struct sip_pvt *p = ast->pvt->pvt;
1165 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1166 transmit_info_with_digit(p, digit);
1168 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1169 ast_rtp_senddigit(p->rtp, digit);
1171 /* If in-band DTMF is desired, send that */
1172 if (p->dtmfmode & SIP_DTMF_INBAND)
1177 static int sip_transfer(struct ast_channel *ast, char *dest)
1179 struct sip_pvt *p = ast->pvt->pvt;
1181 res = transmit_refer(p, dest);
1185 static int sip_indicate(struct ast_channel *ast, int condition)
1187 struct sip_pvt *p = ast->pvt->pvt;
1189 case AST_CONTROL_RINGING:
1190 if (ast->_state == AST_STATE_RING) {
1191 if (!p->progress && !p->ringing) {
1192 transmit_response(p, "180 Ringing", &p->initreq);
1196 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1200 case AST_CONTROL_BUSY:
1201 if (ast->_state != AST_STATE_UP) {
1202 transmit_response(p, "486 Busy Here", &p->initreq);
1204 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1208 case AST_CONTROL_CONGESTION:
1209 if (ast->_state != AST_STATE_UP) {
1210 transmit_response(p, "503 Service Unavailable", &p->initreq);
1212 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1216 case AST_CONTROL_PROGRESS:
1217 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1218 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1226 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1234 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1236 struct ast_channel *tmp;
1238 tmp = ast_channel_alloc(1);
1240 /* Select our native format based on codec preference until we receive
1241 something from another device to the contrary. */
1242 if (i->jointcapability)
1243 tmp->nativeformats = sip_codec_choose(i->jointcapability);
1244 else if (i->capability)
1245 tmp->nativeformats = sip_codec_choose(i->capability);
1247 tmp->nativeformats = sip_codec_choose(capability);
1248 fmt = ast_best_codec(tmp->nativeformats);
1250 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1252 if (strchr(i->fromdomain,':'))
1254 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1258 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1261 if (i->dtmfmode & SIP_DTMF_INBAND) {
1262 i->vad = ast_dsp_new();
1263 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1265 tmp->fds[0] = ast_rtp_fd(i->rtp);
1266 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1268 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1269 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1271 ast_setstate(tmp, state);
1272 if (state == AST_STATE_RING)
1274 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1275 tmp->writeformat = fmt;
1276 tmp->pvt->rawwriteformat = fmt;
1277 tmp->readformat = fmt;
1278 tmp->pvt->rawreadformat = fmt;
1280 tmp->pvt->send_text = sip_sendtext;
1281 tmp->pvt->call = sip_call;
1282 tmp->pvt->hangup = sip_hangup;
1283 tmp->pvt->answer = sip_answer;
1284 tmp->pvt->read = sip_read;
1285 tmp->pvt->write = sip_write;
1286 tmp->pvt->write_video = sip_write;
1287 tmp->pvt->indicate = sip_indicate;
1288 tmp->pvt->transfer = sip_transfer;
1289 tmp->pvt->fixup = sip_fixup;
1290 tmp->pvt->send_digit = sip_senddigit;
1292 tmp->pvt->bridge = ast_rtp_bridge;
1294 tmp->callgroup = i->callgroup;
1295 tmp->pickupgroup = i->pickupgroup;
1296 tmp->restrictcid = i->restrictcid;
1297 if (strlen(i->accountcode))
1298 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1300 tmp->amaflags = i->amaflags;
1301 if (strlen(i->language))
1302 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1304 ast_mutex_lock(&usecnt_lock);
1306 ast_mutex_unlock(&usecnt_lock);
1307 ast_update_use_count();
1308 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1309 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1310 if (strlen(i->callerid))
1311 tmp->callerid = strdup(i->callerid);
1312 if (strlen(i->rdnis))
1313 tmp->rdnis = strdup(i->rdnis);
1315 if (state != AST_STATE_DOWN) {
1316 if (ast_pbx_start(tmp)) {
1317 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1323 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1327 static struct cfalias {
1331 { "Content-Type", "c" },
1332 { "Content-Encoding", "e" },
1336 { "Content-Length", "l" },
1342 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1343 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1344 char* r = line + nameLen + 1;
1345 while (*r && (*r < 33)) ++r;
1352 static char *get_sdp(struct sip_request *req, char *name) {
1354 int len = strlen(name);
1357 for (x=0; x<req->lines; x++) {
1358 r = get_sdp_by_line(req->line[x], name, len);
1359 if (r[0] != '\0') return r;
1364 static void sdpLineNum_iterator_init(int* iterator) {
1368 static char* get_sdp_iterate(int* iterator,
1369 struct sip_request *req, char *name) {
1370 int len = strlen(name);
1372 while (*iterator < req->lines) {
1373 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1374 if (r[0] != '\0') return r;
1379 static char *__get_header(struct sip_request *req, char *name, int *start)
1382 int len = strlen(name);
1384 for (x=*start;x<req->headers;x++) {
1385 if (!strncasecmp(req->header[x], name, len) &&
1386 (req->header[x][len] == ':')) {
1387 r = req->header[x] + len + 1;
1388 while(*r && (*r < 33))
1395 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1396 if (!strcasecmp(aliases[x].fullname, name))
1397 return __get_header(req, aliases[x].shortname, start);
1399 /* Don't return NULL, so get_header is always a valid pointer */
1403 static char *get_header(struct sip_request *req, char *name)
1406 return __get_header(req, name, &start);
1409 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1411 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1412 struct ast_frame *f;
1413 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1416 f = ast_rtp_read(p->rtp);
1419 f = ast_rtcp_read(p->rtp);
1422 f = ast_rtp_read(p->vrtp);
1425 f = ast_rtcp_read(p->vrtp);
1430 /* Don't send RFC2833 if we're not supposed to */
1431 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1434 /* We already hold the channel lock */
1435 if (f->frametype == AST_FRAME_VOICE) {
1436 if (f->subclass != p->owner->nativeformats) {
1437 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1438 p->owner->nativeformats = f->subclass;
1439 ast_set_read_format(p->owner, p->owner->readformat);
1440 ast_set_write_format(p->owner, p->owner->writeformat);
1442 if (p->dtmfmode & SIP_DTMF_INBAND) {
1443 f = ast_dsp_process(p->owner,p->vad,f,0);
1450 static struct ast_frame *sip_read(struct ast_channel *ast)
1452 struct ast_frame *fr;
1453 struct sip_pvt *p = ast->pvt->pvt;
1454 ast_mutex_lock(&p->lock);
1455 fr = sip_rtp_read(ast, p);
1456 ast_mutex_unlock(&p->lock);
1460 static void build_callid(char *callid, int len, struct in_addr ourip)
1467 res = snprintf(callid, len, "%08x", val);
1471 /* It's not important that we really use our right IP here... */
1472 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1475 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1479 p = malloc(sizeof(struct sip_pvt));
1482 /* Keep track of stuff */
1483 memset(p, 0, sizeof(struct sip_pvt));
1487 p->rtp = ast_rtp_new(sched, io, 1, 0);
1489 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1493 /* Start with 101 instead of 1 */
1496 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1500 ast_rtp_settos(p->rtp, tos);
1502 ast_rtp_settos(p->vrtp, tos);
1503 if (useglobalnat && sin) {
1504 /* Setup NAT structure according to global settings if we have an address */
1506 memcpy(&p->recv, sin, sizeof(p->recv));
1507 ast_rtp_setnat(p->rtp, p->nat);
1509 ast_rtp_setnat(p->vrtp, p->nat);
1511 ast_mutex_init(&p->lock);
1514 memcpy(&p->sa, sin, sizeof(p->sa));
1515 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1516 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1518 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1520 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1521 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1523 build_callid(p->callid, sizeof(p->callid), p->ourip);
1525 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1526 /* Assume reinvite OK and via INVITE */
1527 p->canreinvite = globalcanreinvite;
1528 p->dtmfmode = globaldtmfmode;
1529 p->capability = capability;
1530 if (p->dtmfmode & SIP_DTMF_RFC2833)
1531 p->noncodeccapability |= AST_RTP_DTMF;
1532 strncpy(p->context, context, sizeof(p->context) - 1);
1533 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1535 ast_mutex_lock(&iflock);
1538 ast_mutex_unlock(&iflock);
1540 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1544 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1552 callid = get_header(req, "Call-ID");
1554 if (pedanticsipchecking) {
1555 /* In principle Call-ID's uniquely identify a call, however some vendors
1556 (i.e. Pingtel) send multiple calls with the same Call-ID and different
1557 tags in order to simplify billing. The RFC does state that we have to
1558 compare tags in addition to the call-id, but this generate substantially
1559 more overhead which is totally unnecessary for the vast majority of sane
1560 SIP implementations, and thus Asterisk does not enable this behavior
1561 by default. Short version: You'll need this option to support conferencing
1563 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1565 c = strchr(tmp, ' ');
1568 if (!strcasecmp(cmd, "SIP/2.0")) {
1574 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1576 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1577 tag = strstr(tmp, "tag=");
1580 c = strchr(tag, ';');
1587 if (!strlen(callid)) {
1588 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1591 ast_mutex_lock(&iflock);
1594 if (!strcmp(p->callid, callid) &&
1595 (!pedanticsipchecking || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1596 /* Found the call */
1597 ast_mutex_lock(&p->lock);
1598 ast_mutex_unlock(&iflock);
1603 ast_mutex_unlock(&iflock);
1604 p = sip_alloc(callid, sin, 1);
1606 ast_mutex_lock(&p->lock);
1610 static int sip_register(char *value, int lineno)
1612 struct sip_registry *reg;
1613 char copy[256] = "";
1614 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1622 strncpy(copy, value, sizeof(copy)-1);
1625 hostname = strrchr(stringp, '@');
1630 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1631 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1635 username = strsep(&stringp, ":");
1637 secret = strsep(&stringp, ":");
1639 authuser = strsep(&stringp, ":");
1642 hostname = strsep(&stringp, "/");
1644 contact = strsep(&stringp, "/");
1645 if (!contact || !strlen(contact))
1648 hostname = strsep(&stringp, ":");
1649 porta = strsep(&stringp, ":");
1651 if (porta && !atoi(porta)) {
1652 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1655 hp = gethostbyname(hostname);
1657 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1660 reg = malloc(sizeof(struct sip_registry));
1662 memset(reg, 0, sizeof(struct sip_registry));
1663 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1665 strncpy(reg->username, username, sizeof(reg->username)-1);
1667 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1669 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1671 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1674 reg->refresh = default_expiry;
1675 reg->addr.sin_family = AF_INET;
1676 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1677 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1678 reg->next = registrations;
1679 reg->callid_valid = 0;
1681 registrations = reg;
1683 ast_log(LOG_ERROR, "Out of memory\n");
1689 static void parse(struct sip_request *req)
1691 /* Divide fields by NULL's */
1696 /* First header starts immediately */
1700 /* We've got a new header */
1704 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1706 if (!strlen(req->header[f])) {
1707 /* Line by itself means we're now in content */
1711 if (f >= SIP_MAX_HEADERS - 1) {
1712 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1715 req->header[f] = c + 1;
1716 } else if (*c == '\r') {
1717 /* Ignore but eliminate \r's */
1722 /* Check for last header */
1723 if (strlen(req->header[f]))
1726 /* Now we process any mime content */
1731 /* We've got a new line */
1734 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1736 if (f >= SIP_MAX_LINES - 1) {
1737 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1740 req->line[f] = c + 1;
1741 } else if (*c == '\r') {
1742 /* Ignore and eliminate \r's */
1747 /* Check for last line */
1748 if (strlen(req->line[f]))
1752 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1754 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1757 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1766 int peercapability, peernoncodeccapability;
1767 int vpeercapability=0, vpeernoncodeccapability=0;
1768 struct sockaddr_in sin;
1775 /* Get codec and RTP info from SDP */
1776 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1777 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1780 m = get_sdp(req, "m");
1781 c = get_sdp(req, "c");
1782 if (!strlen(m) || !strlen(c)) {
1783 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1786 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1787 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1790 /* XXX This could block for a long time, and block the main thread! XXX */
1791 hp = gethostbyname(host);
1793 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1796 sdpLineNum_iterator_init(&iterator);
1797 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
1798 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
1800 // Scan through the RTP payload types specified in a "m=" line:
1801 ast_rtp_pt_clear(p->rtp);
1803 while(strlen(codecs)) {
1804 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1805 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1809 ast_verbose("Found audio format %s\n", ast_getformatname(codec));
1810 ast_rtp_set_m_type(p->rtp, codec);
1812 /* Skip over any whitespace */
1813 while(*codecs && (*codecs < 33)) codecs++;
1816 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
1818 // Scan through the RTP payload types specified in a "m=" line:
1819 ast_rtp_pt_clear(p->vrtp);
1821 while(strlen(codecs)) {
1822 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1823 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1827 ast_verbose("Found video format %s\n", ast_getformatname(codec));
1828 ast_rtp_set_m_type(p->vrtp, codec);
1830 /* Skip over any whitespace */
1831 while(*codecs && (*codecs < 33)) codecs++;
1835 sin.sin_family = AF_INET;
1836 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1837 /* Setup audio port number */
1838 sin.sin_port = htons(portno);
1839 if (p->rtp && sin.sin_port)
1840 ast_rtp_set_peer(p->rtp, &sin);
1841 /* Setup video port number */
1842 sin.sin_port = htons(vportno);
1843 if (p->vrtp && sin.sin_port)
1844 ast_rtp_set_peer(p->vrtp, &sin);
1846 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1848 // Next, scan through each "a=rtpmap:" line, noting each
1849 // specified RTP payload type (with corresponding MIME subtype):
1850 sdpLineNum_iterator_init(&iterator);
1851 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1852 char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
1853 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1855 ast_verbose("Found description format %s\n", mimeSubtype);
1856 // Note: should really look at the 'freq' and '#chans' params too
1857 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1859 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
1862 // Now gather all of the codecs that were asked for:
1863 ast_rtp_get_current_formats(p->rtp,
1864 &peercapability, &peernoncodeccapability);
1866 ast_rtp_get_current_formats(p->vrtp,
1867 &vpeercapability, &vpeernoncodeccapability);
1868 p->jointcapability = p->capability & (peercapability | vpeercapability);
1869 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
1872 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
1873 p->capability, peercapability, vpeercapability, p->jointcapability);
1874 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1875 noncodeccapability, peernoncodeccapability,
1876 p->noncodeccapability);
1878 if (!p->jointcapability) {
1879 ast_log(LOG_WARNING, "No compatible codecs!\n");
1883 if (!(p->owner->nativeformats & p->jointcapability)) {
1884 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);
1885 p->owner->nativeformats = sip_codec_choose(p->jointcapability);
1886 ast_set_read_format(p->owner, p->owner->readformat);
1887 ast_set_write_format(p->owner, p->owner->writeformat);
1889 if (p->owner->bridge) {
1890 /* Turn on/off music on hold if we are holding/unholding */
1891 if (sin.sin_addr.s_addr) {
1892 ast_moh_stop(p->owner->bridge);
1894 ast_moh_start(p->owner->bridge, NULL);
1902 static int add_header(struct sip_request *req, char *var, char *value)
1904 if (req->len >= sizeof(req->data) - 4) {
1905 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
1909 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1912 req->header[req->headers] = req->data + req->len;
1913 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1914 req->len += strlen(req->header[req->headers]);
1915 if (req->headers < SIP_MAX_HEADERS)
1918 ast_log(LOG_WARNING, "Out of header space\n");
1924 static int add_blank_header(struct sip_request *req)
1926 if (req->len >= sizeof(req->data) - 4) {
1927 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1931 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1934 req->header[req->headers] = req->data + req->len;
1935 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1936 req->len += strlen(req->header[req->headers]);
1937 if (req->headers < SIP_MAX_HEADERS)
1940 ast_log(LOG_WARNING, "Out of header space\n");
1946 static int add_line(struct sip_request *req, char *line)
1948 if (req->len >= sizeof(req->data) - 4) {
1949 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1953 /* Add extra empty return */
1954 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1955 req->len += strlen(req->data + req->len);
1957 req->line[req->lines] = req->data + req->len;
1958 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1959 req->len += strlen(req->line[req->lines]);
1960 if (req->lines < SIP_MAX_LINES)
1963 ast_log(LOG_WARNING, "Out of line space\n");
1969 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1972 tmp = get_header(orig, field);
1974 /* Add what we're responding to */
1975 return add_header(req, field, tmp);
1977 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1981 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1987 tmp = __get_header(orig, field, &start);
1989 /* Add what we're responding to */
1990 add_header(req, field, tmp);
1995 return copied ? 0 : -1;
1998 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2005 tmp = __get_header(orig, field, &start);
2007 if (!copied && p->nat) {
2008 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2009 /* SLD: FIXME: Nice try, but the received= should not have a port */
2010 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2011 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
2013 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2014 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2017 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2018 add_header(req, field, new);
2020 /* Add what we're responding to */
2021 add_header(req, field, tmp);
2028 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2034 /* Add Route: header into request per learned route */
2035 static void add_route(struct sip_request *req, struct sip_route *route)
2038 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2044 n = strlen(route->hop);
2045 if ((n+3)>rem) break;
2051 strcpy(p, route->hop); p += n;
2054 route = route->next;
2057 add_header(req, "Route", r);
2060 static void set_destination(struct sip_pvt *p, char *uri)
2062 char *h, *maddr, hostname[256];
2066 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2067 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2070 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2072 /* Find and parse hostname */
2073 h = strchr(uri, '@');
2078 if (strncmp(h, "sip:", 4) == 0)
2080 else if (strncmp(h, "sips:", 5) == 0)
2083 hn = strcspn(h, ":;>");
2085 strncpy(hostname, h, hn); hostname[hn] = '\0';
2088 /* Is "port" present? if not default to 5060 */
2092 port = strtol(h, &h, 10);
2097 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2098 maddr = strstr(h, "maddr=");
2101 hn = strspn(maddr, "0123456789.");
2103 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2106 hp = gethostbyname(hostname);
2108 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2111 p->sa.sin_family = AF_INET;
2112 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2113 p->sa.sin_port = htons(port);
2115 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2118 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2120 /* Initialize a response */
2121 if (req->headers || req->len) {
2122 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2125 req->header[req->headers] = req->data + req->len;
2126 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2127 req->len += strlen(req->header[req->headers]);
2128 if (req->headers < SIP_MAX_HEADERS)
2131 ast_log(LOG_WARNING, "Out of header space\n");
2135 static int init_req(struct sip_request *req, char *resp, char *recip)
2137 /* Initialize a response */
2138 if (req->headers || req->len) {
2139 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2142 req->header[req->headers] = req->data + req->len;
2143 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2144 req->len += strlen(req->header[req->headers]);
2145 if (req->headers < SIP_MAX_HEADERS)
2148 ast_log(LOG_WARNING, "Out of header space\n");
2152 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2154 char newto[256] = "", *ot;
2155 memset(resp, 0, sizeof(*resp));
2156 init_resp(resp, msg, req);
2157 copy_via_headers(p, resp, req, "Via");
2158 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2159 copy_header(resp, req, "From");
2160 ot = get_header(req, "To");
2161 if (!strstr(ot, "tag=")) {
2162 /* Add the proper tag if we don't have it already. If they have specified
2163 their tag, use it. Otherwise, use our own tag */
2164 if (strlen(p->theirtag) && p->outgoing)
2165 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2166 else if (p->tag && !p->outgoing)
2167 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2169 strncpy(newto, ot, sizeof(newto) - 1);
2172 add_header(resp, "To", ot);
2173 copy_header(resp, req, "Call-ID");
2174 copy_header(resp, req, "CSeq");
2175 add_header(resp, "User-Agent", "Asterisk PBX");
2176 add_header(resp, "Allow", ALLOWED_METHODS);
2178 /* For registration responses, we also need expiry and
2182 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2183 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2184 add_header(resp, "Expires", tmp);
2185 add_header(resp, "Contact", contact);
2187 add_header(resp, "Contact", p->our_contact);
2192 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2194 struct sip_request *orig = &p->initreq;
2195 char stripped[80] ="";
2201 memset(req, 0, sizeof(struct sip_request));
2208 if (strlen(p->uri)) {
2212 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2214 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2216 c = strchr(stripped, '<');
2228 init_req(req, msg, c);
2230 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2232 add_header(req, "Via", p->via);
2234 set_destination(p, p->route->hop);
2235 add_route(req, p->route->next);
2238 ot = get_header(orig, "To");
2239 of = get_header(orig, "From");
2241 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2242 as our original request, including tag (or presumably lack thereof) */
2243 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2244 /* Add the proper tag if we don't have it already. If they have specified
2245 their tag, use it. Otherwise, use our own tag */
2246 if (p->outgoing && strlen(p->theirtag))
2247 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2248 else if (!p->outgoing)
2249 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2251 snprintf(newto, sizeof(newto), "%s", ot);
2256 add_header(req, "From", of);
2257 add_header(req, "To", ot);
2259 add_header(req, "From", ot);
2260 add_header(req, "To", of);
2262 add_header(req, "Contact", p->our_contact);
2263 copy_header(req, orig, "Call-ID");
2264 add_header(req, "CSeq", tmp);
2266 add_header(req, "User-Agent", "Asterisk PBX");
2270 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2272 struct sip_request resp;
2274 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2275 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2278 respprep(&resp, p, msg, req);
2279 add_header(&resp, "Content-Length", "0");
2280 add_blank_header(&resp);
2281 return send_response(p, &resp, reliable, seqno);
2284 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2286 return __transmit_response(p, msg, req, 0);
2288 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2290 return __transmit_response(p, msg, req, 1);
2293 static void append_date(struct sip_request *req)
2300 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2301 add_header(req, "Date", tmpdat);
2304 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2306 struct sip_request resp;
2307 respprep(&resp, p, msg, req);
2309 add_header(&resp, "Content-Length", "0");
2310 add_blank_header(&resp);
2311 return send_response(p, &resp, 0, 0);
2314 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2316 struct sip_request resp;
2317 respprep(&resp, p, msg, req);
2318 add_header(&resp, "Accept", "application/sdp");
2319 add_header(&resp, "Content-Length", "0");
2320 add_blank_header(&resp);
2321 return send_response(p, &resp, 0, 0);
2324 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2326 struct sip_request resp;
2329 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2330 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2333 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2334 respprep(&resp, p, msg, req);
2335 add_header(&resp, "Proxy-Authenticate", tmp);
2336 add_header(&resp, "Content-Length", "0");
2337 add_blank_header(&resp);
2338 return send_response(p, &resp, reliable, seqno);
2341 static int add_text(struct sip_request *req, char *text)
2343 /* XXX Convert \n's to \r\n's XXX */
2344 int len = strlen(text);
2346 snprintf(clen, sizeof(clen), "%d", len);
2347 add_header(req, "Content-Type", "text/plain");
2348 add_header(req, "Content-Length", clen);
2349 add_line(req, text);
2353 static int add_digit(struct sip_request *req, char digit)
2358 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2360 snprintf(clen, sizeof(clen), "%d", len);
2361 add_header(req, "Content-Type", "application/dtmf-relay");
2362 add_header(req, "Content-Length", clen);
2367 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2371 int alreadysent = 0;
2373 struct sockaddr_in sin;
2374 struct sockaddr_in vsin;
2375 struct sip_codec_pref *cur;
2386 struct sockaddr_in dest;
2387 struct sockaddr_in vdest;
2388 /* XXX We break with the "recommendation" and send our IP, in order that our
2389 peer doesn't have to gethostbyname() us XXX */
2392 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2395 ast_rtp_get_us(p->rtp, &sin);
2397 ast_rtp_get_us(p->vrtp, &vsin);
2399 if (p->redirip.sin_addr.s_addr) {
2400 dest.sin_port = p->redirip.sin_port;
2401 dest.sin_addr = p->redirip.sin_addr;
2403 ast_rtp_get_peer(rtp, &dest);
2405 dest.sin_addr = p->ourip;
2406 dest.sin_port = sin.sin_port;
2409 /* Determine video destination */
2411 if (p->vredirip.sin_addr.s_addr) {
2412 vdest.sin_port = p->vredirip.sin_port;
2413 vdest.sin_addr = p->vredirip.sin_addr;
2415 ast_rtp_get_peer(vrtp, &vdest);
2417 vdest.sin_addr = p->ourip;
2418 vdest.sin_port = vsin.sin_port;
2422 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2423 if (sipdebug && p->vrtp)
2424 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2425 snprintf(v, sizeof(v), "v=0\r\n");
2426 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2427 snprintf(s, sizeof(s), "s=session\r\n");
2428 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2429 snprintf(t, sizeof(t), "t=0 0\r\n");
2430 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2431 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2432 /* Start by sending our preferred codecs */
2435 if (p->jointcapability & cur->codec) {
2437 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2438 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2440 snprintf(costr, sizeof(costr), " %d", codec);
2441 if (cur->codec < AST_FORMAT_MAX_AUDIO) {
2443 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2447 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2452 alreadysent |= cur->codec;
2455 /* Now send any other common codecs, and non-codec formats: */
2456 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2457 if ((p->jointcapability & x) && !(alreadysent & x)) {
2459 ast_verbose("Answering with capability %d\n", x);
2460 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2462 snprintf(costr, sizeof(costr), " %d", codec);
2463 if (x < AST_FORMAT_MAX_AUDIO) {
2465 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2469 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2475 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2476 if (p->noncodeccapability & x) {
2478 ast_verbose("Answering with non-codec capability %d\n", x);
2479 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2481 snprintf(costr, sizeof(costr), " %d", codec);
2483 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2485 if (x == AST_RTP_DTMF) {
2486 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2487 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2496 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2498 len += strlen(m2) + strlen(a2);
2499 snprintf(costr, sizeof(costr), "%d", len);
2500 add_header(resp, "Content-Type", "application/sdp");
2501 add_header(resp, "Content-Length", costr);
2516 static void copy_request(struct sip_request *dst,struct sip_request *src)
2520 offset = ((void *)dst) - ((void *)src);
2521 /* First copy stuff */
2522 memcpy(dst, src, sizeof(*dst));
2523 /* Now fix pointer arithmetic */
2524 for (x=0;x<src->headers;x++)
2525 dst->header[x] += offset;
2526 for (x=0;x<src->lines;x++)
2527 dst->line[x] += offset;
2530 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2532 struct sip_request resp;
2534 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2535 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2538 respprep(&resp, p, msg, req);
2539 add_sdp(&resp, p, NULL, NULL);
2540 return send_response(p, &resp, retrans, seqno);
2543 static int determine_firstline_parts( struct sip_request *req ) {
2548 cmd= req->header[0];
2549 while(*cmd && (*cmd < 33)) {
2556 while(*e && (*e > 32)) {
2559 /* Get the command */
2565 while( *e && ( *e < 33 ) ) {
2572 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2573 /* We have a response */
2575 len= strlen( req->rlPart2 );
2576 if( len < 2 ) { return -1; }
2578 while( *e && *e<33 ) {
2583 /* We have a request */
2586 if( !*e ) { return -1; }
2589 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2592 while( isspace( *(--e) ) ) {}
2602 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2604 struct sip_request req;
2605 if (p->canreinvite == REINVITE_UPDATE)
2606 reqprep(&req, p, "UPDATE", 0);
2608 reqprep(&req, p, "INVITE", 0);
2609 add_header(&req, "Allow", ALLOWED_METHODS);
2610 add_sdp(&req, p, rtp, vrtp);
2611 /* Use this as the basis */
2612 copy_request(&p->initreq, &req);
2614 determine_firstline_parts(&p->initreq);
2615 p->lastinvite = p->ocseq;
2617 return send_request(p, &req, 1, p->ocseq);
2620 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
2622 char stripped[256]="";
2624 strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
2625 c = strchr(stripped, '<');
2637 strncpy(p->uri, c, sizeof(p->uri) - 1);
2640 static void build_contact(struct sip_pvt *p)
2642 /* Construct Contact: header */
2643 if (ourport != 5060)
2644 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2646 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2649 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2656 char *l = callerid, *n=NULL;
2657 if (p->owner && p->owner->callerid) {
2658 strcpy(cid, p->owner->callerid);
2659 ast_callerid_parse(cid, &n, &l);
2661 ast_shrink_phone_number(l);
2662 if (!l || !ast_isphonenumber(l))
2665 /* if user want's his callerid restricted */
2667 l = CALLERID_UNKNOWN;
2668 if (!n || !strlen(n))
2670 /* Allow user to be overridden */
2671 if (strlen(p->fromuser))
2674 if ((ourport != 5060) && !strlen(p->fromdomain))
2675 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);
2677 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2679 if (strlen(p->username)) {
2680 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2681 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2683 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2685 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2686 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2688 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2690 strncpy(p->uri, invite, sizeof(p->uri) - 1);
2691 /* If there is a VXML URL append it to the SIP URL */
2694 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2698 snprintf(to, sizeof(to), "<%s>", invite );
2700 memset(req, 0, sizeof(struct sip_request));
2701 init_req(req, cmd, invite);
2702 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2704 add_header(req, "Via", p->via);
2705 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2706 * OTOH, then we won't have anything in p->route anyway */
2707 add_header(req, "From", from);
2708 strncpy(p->exten, l, sizeof(p->exten) - 1);
2710 add_header(req, "To", to);
2711 add_header(req, "Contact", p->our_contact);
2712 add_header(req, "Call-ID", p->callid);
2713 add_header(req, "CSeq", tmp);
2714 add_header(req, "User-Agent", "Asterisk PBX");
2717 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url, char *distinctive_ring, int init)
2719 struct sip_request req;
2722 initreqprep(&req, p, cmd, vxml_url);
2724 reqprep(&req, p, cmd, 0);
2727 add_header(&req, "Proxy-Authorization", auth);
2729 if (distinctive_ring)
2731 add_header(&req, "Alert-info",distinctive_ring);
2733 add_header(&req, "Allow", ALLOWED_METHODS);
2735 add_sdp(&req, p, NULL, NULL);
2737 add_header(&req, "Content-Length", "0");
2738 add_blank_header(&req);
2741 if (!p->initreq.headers) {
2742 /* Use this as the basis */
2743 copy_request(&p->initreq, &req);
2745 determine_firstline_parts(&p->initreq);
2747 p->lastinvite = p->ocseq;
2748 return send_request(p, &req, 1, p->ocseq);
2751 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2754 char from[256], to[256];
2757 struct sip_request req;
2760 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2762 c = ditch_braces(from);
2763 if (strncmp(c, "sip:", 4)) {
2764 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2767 if ((a = strchr(c, ';'))) {
2772 reqprep(&req, p, "NOTIFY", 0);
2774 if (p->subscribed == 1) {
2775 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2777 c = ditch_braces(to);
2778 if (strncmp(c, "sip:", 4)) {
2779 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2782 if ((a = strchr(c, ';'))) {
2787 add_header(&req, "Content-Type", "application/xpidf+xml");
2789 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2791 else if (state==AST_EXTENSION_INUSE)
2797 sprintf(t, "<?xml version=\"1.0\"?>\n");
2798 t = tmp + strlen(tmp);
2799 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2800 t = tmp + strlen(tmp);
2801 sprintf(t, "<presence>\n");
2802 t = tmp + strlen(tmp);
2803 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2804 t = tmp + strlen(tmp);
2805 sprintf(t, "<atom id=\"%s\">\n", p->exten);
2806 t = tmp + strlen(tmp);
2807 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2808 t = tmp + strlen(tmp);
2809 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2810 t = tmp + strlen(tmp);
2811 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2812 t = tmp + strlen(tmp);
2813 sprintf(t, "</address>\n</atom>\n</presence>\n");
2815 add_header(&req, "Event", "dialog");
2816 add_header(&req, "Content-Type", "application/dialog-info+xml");
2819 sprintf(t, "<?xml version=\"1.0\"?>\n");
2820 t = tmp + strlen(tmp);
2821 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);
2822 t = tmp + strlen(tmp);
2823 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2824 t = tmp + strlen(tmp);
2825 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2826 t = tmp + strlen(tmp);
2827 sprintf(t, "</dialog>\n</dialog-info>\n");
2830 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2831 add_header(&req, "Content-Length", clen);
2832 add_line(&req, tmp);
2834 return send_request(p, &req, 1, p->ocseq);
2837 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2839 struct sip_request req;
2843 initreqprep(&req, p, "NOTIFY", NULL);
2844 add_header(&req, "Event", "message-summary");
2845 add_header(&req, "Content-Type", notifymime);
2847 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2848 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2849 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2850 add_header(&req, "Content-Length", clen);
2851 add_line(&req, tmp);
2852 add_line(&req, tmp2);
2854 if (!p->initreq.headers) {
2855 /* Use this as the basis */
2856 copy_request(&p->initreq, &req);
2858 determine_firstline_parts(&p->initreq);
2861 return send_request(p, &req, 1, p->ocseq);
2864 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
2866 static int sip_reregister(void *data)
2868 /* if we are here, we know that we need to reregister. */
2869 struct sip_registry *r=(struct sip_registry *)data;
2876 static int sip_do_register(struct sip_registry *r)
2879 ast_mutex_lock(&r->lock);
2880 res=transmit_register(r, "REGISTER", NULL, NULL);
2881 ast_mutex_unlock(&r->lock);
2885 static int sip_reg_timeout(void *data)
2887 /* if we are here, our registration timed out, so we'll just do it over */
2888 struct sip_registry *r=data;
2891 ast_mutex_lock(&r->lock);
2892 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
2894 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
2895 in the single SIP manager thread. */
2901 r->regstate=REG_STATE_UNREGISTERED;
2903 res=transmit_register(r, "REGISTER", NULL, NULL);
2904 ast_mutex_unlock(&r->lock);
2908 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
2910 struct sip_request req;
2917 /* exit if we are already in process with this registrar ?*/
2918 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2919 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2925 ast_log(LOG_WARNING, "Already have a call??\n");
2930 if (!r->callid_valid) {
2931 build_callid(r->callid, sizeof(r->callid), __ourip);
2932 r->callid_valid = 1;
2934 p=sip_alloc( r->callid, &r->addr, 0);
2936 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2942 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2943 if (strlen(r->authuser))
2944 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2946 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2947 strncpy(p->username, r->username, sizeof(p->username)-1);
2948 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2949 /* Always bind to our IP if specified */
2950 if (bindaddr.sin_addr.s_addr)
2951 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
2955 /* set up a timeout */
2957 if (r->timeout > -1) {
2958 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2959 ast_sched_del(sched, r->timeout);
2961 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2962 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2965 if (strchr(r->username, '@')) {
2966 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
2967 snprintf(to, sizeof(to), "<sip:%s>", r->username);
2969 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2970 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
2973 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2974 strncpy(p->uri, addr, sizeof(p->uri) - 1);
2976 memset(&req, 0, sizeof(req));
2977 init_req(&req, cmd, addr);
2979 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2980 p->ocseq = r->ocseq;
2982 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
2983 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2984 add_header(&req, "Via", via);
2985 add_header(&req, "From", from);
2986 add_header(&req, "To", to);
2987 add_header(&req, "Call-ID", p->callid);
2988 add_header(&req, "CSeq", tmp);
2989 add_header(&req, "User-Agent", "Asterisk PBX");
2991 add_header(&req, authheader, auth);
2993 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2994 add_header(&req, "Expires", tmp);
2995 add_header(&req, "Contact", p->our_contact);
2996 add_header(&req, "Event", "registration");
2997 add_header(&req, "Content-length", "0");
2998 add_blank_header(&req);
2999 copy_request(&p->initreq, &req);
3001 determine_firstline_parts(&p->initreq);
3002 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
3003 return send_request(p, &req, 1, p->ocseq);
3006 static int transmit_message_with_text(struct sip_pvt *p, char *text)
3008 struct sip_request req;
3009 reqprep(&req, p, "MESSAGE", 0);
3010 add_text(&req, text);
3011 return send_request(p, &req, 1, p->ocseq);
3014 static int transmit_refer(struct sip_pvt *p, char *dest)
3016 struct sip_request req;
3021 of = get_header(&p->initreq, "To");
3023 of = get_header(&p->initreq, "From");
3024 strncpy(from, of, sizeof(from) - 1);
3025 of = ditch_braces(from);
3026 strncpy(p->from,of,sizeof(p->from) - 1);
3027 if (strncmp(of, "sip:", 4)) {
3028 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3031 /* Get just the username part */
3032 if ((c = strchr(of, '@'))) {
3037 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
3039 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
3042 reqprep(&req, p, "REFER", 0);
3043 add_header(&req, "Refer-To", referto);
3044 add_header(&req, "Referred-By", callerid);
3045 return send_request(p, &req, 1, p->ocseq);
3048 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
3050 struct sip_request req;
3051 reqprep(&req, p, "INFO", 0);
3052 add_digit(&req, digit);
3053 return send_request(p, &req, 1, p->ocseq);
3056 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
3058 struct sip_request resp;
3059 reqprep(&resp, p, msg, seqno);
3060 add_header(&resp, "Content-Length", "0");
3061 add_blank_header(&resp);
3062 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3065 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
3067 struct sip_request resp;
3068 reqprep(&resp, p, msg, seqno);
3072 memset(digest,0,sizeof(digest));
3073 build_reply_digest(p, msg, digest, sizeof(digest));
3074 add_header(&resp, "Proxy-Authorization", digest);
3077 add_header(&resp, "Content-Length", "0");
3078 add_blank_header(&resp);
3079 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3082 static int expire_register(void *data)
3084 struct sip_peer *p = data;
3085 memset(&p->addr, 0, sizeof(p->addr));
3086 ast_db_del("SIP/Registry", p->name);
3088 ast_device_state_changed("SIP/%s", p->name);
3092 static int sip_poke_peer(struct sip_peer *peer);
3094 static void reg_source_db(struct sip_peer *p)
3100 if (!ast_db_get("SIP/Registry", p->name, data, sizeof(data))) {
3101 c = strchr(data, ':');
3105 if (inet_aton(data, &in)) {