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 autocreatepeer = 0;
108 static int usecnt =0;
109 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
111 /* Protect the interface list (of sip_pvt's) */
112 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
114 /* Protect the monitoring thread, so only one process can kill or start it, and not
115 when it's doing something critical. */
116 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
118 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
120 /* This is the thread for the monitor which checks for input on the channels
121 which are not currently in use. */
122 static pthread_t monitor_thread = 0;
124 static int restart_monitor(void);
126 /* Codecs that we support by default: */
127 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
128 static int noncodeccapability = AST_RTP_DTMF;
130 static char ourhost[256];
131 static struct in_addr __ourip;
134 static int sipdebug = 0;
138 static int videosupport = 0;
140 static int globaldtmfmode = SIP_DTMF_RFC2833;
143 static int expiry = 900;
145 static struct sched_context *sched;
146 static struct io_context *io;
147 /* The private structures of the sip channels are linked for
148 selecting outgoing channels */
150 #define SIP_MAX_HEADERS 64
151 #define SIP_MAX_LINES 64
155 #define DEC_OUT_USE 2
156 #define INC_OUT_USE 3
158 static struct sip_codec_pref {
160 struct sip_codec_pref *next;
164 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
165 char *rlPart2; /* The Request URI or Response Status */
167 int headers; /* SIP Headers */
168 char *header[SIP_MAX_HEADERS];
169 int lines; /* SDP Content */
170 char *line[SIP_MAX_LINES];
171 char data[SIP_MAX_PACKET];
177 struct sip_route *next;
181 static struct sip_pvt {
182 ast_mutex_t lock; /* Channel private lock */
183 char callid[80]; /* Global CallID */
184 char randdata[80]; /* Random data */
185 unsigned int ocseq; /* Current outgoing seqno */
186 unsigned int icseq; /* Current incoming seqno */
187 unsigned int callgroup;
188 unsigned int pickupgroup;
189 int lastinvite; /* Last Cseq of invite */
190 int alreadygone; /* Whether or not we've already been destroyed by or peer */
191 int needdestroy; /* if we need to be destroyed */
192 int capability; /* Special capability */
193 int jointcapability; /* Supported capability at both ends */
194 int noncodeccapability;
195 int outgoing; /* Outgoing or incoming call? */
196 int authtries; /* Times we've tried to authenticate */
197 int insecure; /* Don't check source port/ip */
198 int expiry; /* How long we take to expire */
199 int branch; /* One random number */
200 int canreinvite; /* Do we support reinvite */
201 int ringing; /* Have sent 180 ringing */
202 int progress; /* Have sent 183 message progress */
203 int tag; /* Another random number */
204 int nat; /* Whether to try to support NAT */
205 int sessionid; /* SDP Session ID */
206 int sessionversion; /* SDP Session Version */
207 struct sockaddr_in sa; /* Our peer */
208 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
209 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
210 struct sockaddr_in recv; /* Received as */
211 struct in_addr ourip; /* Our IP */
212 struct ast_channel *owner; /* Who owns us */
213 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
214 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
215 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
216 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
217 struct sip_pvt *refer_call; /* Call we are referring */
218 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
219 char remote_party_id[256];
221 char context[AST_MAX_EXTENSION];
222 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
223 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
224 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
225 char language[MAX_LANGUAGE];
226 char rdnis[256]; /* Referring DNIS */
227 char theirtag[256]; /* Their tag */
230 char uri[256]; /* Original requested URI */
231 char peersecret[256];
232 char peermd5secret[256];
233 char callerid[256]; /* Caller*ID */
234 int restrictcid; /* hide presentation from remote user */
236 char accountcode[20]; /* Account code */
237 char our_contact[256]; /* Our contact header */
238 char realm[256]; /* Authorization realm */
239 char nonce[256]; /* Authorization nonce */
240 char domain[256]; /* Authorization nonce */
241 char lastmsg[256]; /* Last Message sent/received */
242 int amaflags; /* AMA Flags */
243 int pendinginvite; /* Any pending invite */
244 int pendingbye; /* Need to send bye after we ack? */
245 int gotrefer; /* Got a refer? */
246 struct sip_request initreq; /* Initial request */
248 int maxtime; /* Max time for first response */
249 int initid; /* Auto-congest ID if appropriate */
250 int autokillid; /* Auto-kill ID */
259 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
260 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
261 struct ast_rtp *rtp; /* RTP Session */
262 struct ast_rtp *vrtp; /* Video RTP session */
263 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
264 struct sip_pvt *next;
268 struct sip_pkt *next; /* Next packet */
269 int retrans; /* Retransmission number */
270 int seqno; /* Sequence number */
271 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
272 struct sip_pvt *owner; /* Owner call */
273 int retransid; /* Retransmission ID */
274 int packetlen; /* Length of packet */
279 /* Users who can access various contexts */
286 char accountcode[20];
287 char language[MAX_LANGUAGE];
288 unsigned int callgroup;
289 unsigned int pickupgroup;
303 struct sip_user *next;
310 char context[80]; /* JK02: peers need context too to allow parking etc */
316 char mailbox[AST_MAX_EXTENSION];
326 unsigned int callgroup;
327 unsigned int pickupgroup;
329 struct sockaddr_in addr;
333 struct sip_pvt *call; /* Call pointer */
334 int pokeexpire; /* When to expire poke */
335 int lastms; /* How long last response took (in ms), or -1 for no response */
336 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
337 struct timeval ps; /* Ping send time */
339 struct sockaddr_in defaddr;
344 struct sip_peer *next;
347 static struct ast_user_list {
348 struct sip_user *users;
350 } userl = { NULL, AST_MUTEX_INITIALIZER };
352 static struct ast_peer_list {
353 struct sip_peer *peers;
355 } peerl = { NULL, AST_MUTEX_INITIALIZER };
358 #define REG_STATE_UNREGISTERED 0
359 #define REG_STATE_REGSENT 1
360 #define REG_STATE_AUTHSENT 2
361 #define REG_STATE_REGISTERED 3
362 #define REG_STATE_REJECTED 4
363 #define REG_STATE_TIMEOUT 5
364 #define REG_STATE_NOAUTH 6
366 struct sip_registry {
367 ast_mutex_t lock; /* Channel private lock */
368 struct sockaddr_in addr; /* Who we connect to for registration purposes */
369 char username[80]; /* Who we are registering as */
370 char authuser[80]; /* Who we *authenticate* as */
372 char secret[80]; /* Password or key name in []'s */
374 char contact[80]; /* Contact extension */
376 int expire; /* Sched ID of expiration */
377 int timeout; /* sched id of sip_reg_timeout */
378 int refresh; /* How often to refresh */
379 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
381 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
382 char callid[80]; /* Global CallID for this registry */
383 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
384 struct sockaddr_in us; /* Who the server thinks we are */
385 struct sip_registry *next;
388 #define REINVITE_INVITE 1
389 #define REINVITE_UPDATE 2
391 static int sip_do_register(struct sip_registry *r);
392 static struct sip_registry *registrations;
394 static int sipsock = -1;
395 static int globalnat = 0;
396 static int globalcanreinvite = REINVITE_INVITE;
397 static int use_external_ip = 0;
399 static struct sockaddr_in bindaddr;
401 static struct ast_frame *sip_read(struct ast_channel *ast);
402 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
403 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
404 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
405 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
406 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
407 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
408 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
409 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
410 static int transmit_message_with_text(struct sip_pvt *p, char *text);
411 static int transmit_refer(struct sip_pvt *p, char *dest);
412 static struct sip_peer *temp_peer(char *name);
413 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
414 static char *getsipuri(char *header);
415 static void free_old_route(struct sip_route *route);
416 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
417 static int find_user(struct sip_pvt *fup, int event);
418 static void prune_peers(void);
420 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
424 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
426 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
428 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));
433 static void sip_destroy(struct sip_pvt *p);
435 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
437 if (use_external_ip) {
440 if (bindaddr.sin_addr.s_addr)
441 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
443 return ast_ouraddrfor(them, us);
448 static int retrans_pkt(void *data)
450 struct sip_pkt *pkt=data;
452 ast_mutex_lock(&pkt->owner->lock);
453 if (pkt->retrans < MAX_RETRANS) {
457 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));
459 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));
461 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
464 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
466 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
467 ast_mutex_unlock(&pkt->owner->lock);
469 ast_mutex_lock(&pkt->owner->lock);
471 if (pkt->owner->owner) {
472 /* XXX Potential deadlocK?? XXX */
473 ast_queue_hangup(pkt->owner->owner, 0);
474 ast_mutex_unlock(&pkt->owner->owner->lock);
476 /* If no owner, destroy now */
477 pkt->owner->needdestroy = 1;
481 ast_mutex_unlock(&pkt->owner->lock);
485 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
488 pkt = malloc(sizeof(struct sip_pkt) + len);
491 memset(pkt, 0, sizeof(struct sip_pkt));
492 memcpy(pkt->data, data, len);
493 pkt->packetlen = len;
494 pkt->next = p->packets;
498 /* Schedule retransmission */
499 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
500 pkt->next = p->packets;
502 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
503 if (!strncasecmp(pkt->data, "INVITE", 6)) {
504 /* Note this is a pending invite */
505 p->pendinginvite = seqno;
510 static int __sip_autodestruct(void *data)
512 struct sip_pvt *p = data;
514 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
516 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
517 ast_queue_hangup(p->owner, 0);
524 static int sip_scheddestroy(struct sip_pvt *p, int ms)
526 if (p->autokillid > -1)
527 ast_sched_del(sched, p->autokillid);
528 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
532 static int sip_cancel_destroy(struct sip_pvt *p)
534 if (p->autokillid > -1)
535 ast_sched_del(sched, p->autokillid);
540 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
542 struct sip_pkt *cur, *prev = NULL;
547 if ((cur->seqno == seqno) && (cur->resp == resp)) {
548 if (!resp && (seqno == p->pendinginvite)) {
549 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
550 p->pendinginvite = 0;
553 /* this is our baby */
555 prev->next = cur->next;
557 p->packets = cur->next;
558 if (cur->retransid > -1)
559 ast_sched_del(sched, cur->retransid);
567 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
571 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
577 if ((cur->seqno == seqno) && (cur->resp == resp)) {
578 /* this is our baby */
579 if (cur->retransid > -1)
580 ast_sched_del(sched, cur->retransid);
587 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");
591 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
596 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));
598 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));
601 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
603 res = __sip_xmit(p, req->data, req->len);
609 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
614 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));
616 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));
619 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
621 res = __sip_xmit(p, req->data, req->len);
625 static char *ditch_braces(char *tmp)
630 if ((n = strchr(tmp, '<')) ) {
632 while(*c && *c != '>') c++;
634 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
643 static int sip_sendtext(struct ast_channel *ast, char *text)
645 struct sip_pvt *p = ast->pvt->pvt;
647 ast_verbose("Sending text %s on %s\n", text, ast->name);
650 if (!text || !strlen(text))
653 ast_verbose("Really sending text %s on %s\n", text, ast->name);
654 transmit_message_with_text(p, text);
658 static int create_addr(struct sip_pvt *r, char *peer)
665 char host[256], *hostn;
667 r->sa.sin_family = AF_INET;
668 ast_mutex_lock(&peerl.lock);
671 if (!strcasecmp(p->name, peer)) {
673 r->capability = p->capability;
676 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
677 ast_rtp_setnat(r->rtp, r->nat);
680 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
681 ast_rtp_setnat(r->vrtp, r->nat);
683 strncpy(r->peername, p->username, sizeof(r->peername)-1);
684 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
685 strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
686 strncpy(r->username, p->username, sizeof(r->username)-1);
687 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
688 if (!strlen(r->tohost)) {
689 if (p->addr.sin_addr.s_addr)
690 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
692 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
694 if (strlen(p->fromdomain))
695 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
696 if (strlen(p->fromuser))
697 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
698 r->insecure = p->insecure;
699 r->canreinvite = p->canreinvite;
700 r->maxtime = p->maxms;
701 r->callgroup = p->callgroup;
702 r->pickupgroup = p->pickupgroup;
704 r->dtmfmode = p->dtmfmode;
705 if (r->dtmfmode & SIP_DTMF_RFC2833)
706 r->noncodeccapability |= AST_RTP_DTMF;
708 r->noncodeccapability &= ~AST_RTP_DTMF;
710 strncpy(r->context, p->context,sizeof(r->context)-1);
711 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
712 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
713 if (p->addr.sin_addr.s_addr) {
714 r->sa.sin_addr = p->addr.sin_addr;
715 r->sa.sin_port = p->addr.sin_port;
717 r->sa.sin_addr = p->defaddr.sin_addr;
718 r->sa.sin_port = p->defaddr.sin_port;
720 memcpy(&r->recv, &r->sa, sizeof(r->recv));
726 ast_mutex_unlock(&peerl.lock);
728 if ((port=strchr(peer, ':'))) {
736 portno = DEFAULT_SIP_PORT;
741 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
742 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
748 hp = gethostbyname(hostn);
750 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
751 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
752 r->sa.sin_port = htons(portno);
753 memcpy(&r->recv, &r->sa, sizeof(r->recv));
756 ast_log(LOG_WARNING, "No such host: %s\n", peer);
765 static int auto_congest(void *nothing)
767 struct sip_pvt *p = nothing;
768 ast_mutex_lock(&p->lock);
771 if (!ast_mutex_trylock(&p->owner->lock)) {
772 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
773 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
774 ast_mutex_unlock(&p->owner->lock);
777 ast_mutex_unlock(&p->lock);
781 static void sip_prefs_free(void)
783 struct sip_codec_pref *cur, *next;
793 static void sip_pref_remove(int format)
795 struct sip_codec_pref *cur, *prev=NULL;
798 if (cur->codec == format) {
800 prev->next = cur->next;
811 static int sip_pref_append(int format)
813 struct sip_codec_pref *cur, *tmp;
814 sip_pref_remove(format);
815 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
818 memset(tmp, 0, sizeof(struct sip_codec_pref));
830 static int sip_codec_choose(int formats)
832 struct sip_codec_pref *cur;
833 formats &= (AST_FORMAT_MAX_AUDIO - 1);
836 if (formats & cur->codec)
840 return ast_best_codec(formats);
843 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
847 char *vxml_url = NULL;
848 char *distinctive_ring = NULL;
849 struct varshead *headp;
850 struct ast_var_t *current;
853 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
854 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
857 /* Check whether there is vxml_url, distinctive ring variables */
859 headp=&ast->varshead;
860 AST_LIST_TRAVERSE(headp,current,entries) {
861 /* Check whether there is a VXML_URL variable */
862 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
864 vxml_url = ast_var_value(current);
867 /* Check whether there is a ALERT_INFO variable */
868 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
870 distinctive_ring = ast_var_value(current);
877 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
878 res = find_user(p,INC_OUT_USE);
880 p->restrictcid = ast->restrictcid;
881 p->jointcapability = p->capability;
882 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
884 /* Initialize auto-congest time */
885 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
891 static void __sip_destroy(struct sip_pvt *p, int lockowner)
893 struct sip_pvt *cur, *prev = NULL;
896 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
898 ast_extension_state_del(p->stateid, NULL);
900 ast_sched_del(sched, p->initid);
901 if (p->autokillid > -1)
902 ast_sched_del(sched, p->autokillid);
905 ast_rtp_destroy(p->rtp);
908 ast_rtp_destroy(p->vrtp);
911 free_old_route(p->route);
915 /* Carefully unlink from registry */
916 struct sip_registry *reg;
919 if ((reg == p->registry) && (p->registry->call == p))
920 p->registry->call=NULL;
924 /* Unlink us from the owner if we have one */
927 ast_mutex_lock(&p->owner->lock);
928 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
929 p->owner->pvt->pvt = NULL;
931 ast_mutex_unlock(&p->owner->lock);
937 prev->next = cur->next;
946 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
949 ast_sched_del(sched, p->initid);
950 while((cp = p->packets)) {
951 p->packets = p->packets->next;
952 if (cp->retransid > -1)
953 ast_sched_del(sched, cp->retransid);
960 static int find_user(struct sip_pvt *fup, int event)
964 strncpy(name, fup->username, sizeof(name) - 1);
965 ast_mutex_lock(&userl.lock);
968 if (!strcasecmp(u->name, name)) {
974 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
975 ast_mutex_unlock(&userl.lock);
979 /* incoming and outgoing affects the inUse counter */
982 if ( u->inUse > 0 ) {
990 if (u->incominglimit > 0 ) {
991 if (u->inUse >= u->incominglimit) {
992 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
993 ast_mutex_unlock(&userl.lock);
994 /* inc inUse as well */
995 if ( event == INC_OUT_USE ) {
1002 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1004 /* we don't use these anymore
1006 if ( u->outUse > 0 ) {
1013 if ( u->outgoinglimit > 0 ) {
1014 if ( u->outUse >= u->outgoinglimit ) {
1015 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1016 ast_mutex_unlock(&userl.lock);
1024 ast_log(LOG_ERROR, "find_user(%s,%d) called with no event!\n",u->name,event);
1026 ast_mutex_unlock(&userl.lock);
1030 static void sip_destroy(struct sip_pvt *p)
1032 ast_mutex_lock(&iflock);
1033 __sip_destroy(p, 1);
1034 ast_mutex_unlock(&iflock);
1037 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
1039 static int hangup_sip2cause(int cause)
1044 return AST_CAUSE_BUSY;
1046 return AST_CAUSE_NORMAL;
1052 static char *hangup_cause2sip(int cause)
1056 case AST_CAUSE_BUSY:
1065 static int sip_hangup(struct ast_channel *ast)
1067 struct sip_pvt *p = ast->pvt->pvt;
1069 int needdestroy = 0;
1071 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1072 if (!ast->pvt->pvt) {
1073 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1076 ast_mutex_lock(&p->lock);
1077 if ( p->outgoing ) {
1078 ast_log(LOG_DEBUG, "find_user(%s) - decrement outUse counter\n", p->username);
1079 find_user(p, DEC_OUT_USE);
1081 ast_log(LOG_DEBUG, "find_user(%s) - decrement inUse counter\n", p->username);
1082 find_user(p, DEC_IN_USE);
1084 /* Determine how to disconnect */
1085 if (p->owner != ast) {
1086 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1087 ast_mutex_unlock(&p->lock);
1090 if (!ast || (ast->_state != AST_STATE_UP))
1095 ast_dsp_free(p->vad);
1098 ast->pvt->pvt = NULL;
1100 ast_mutex_lock(&usecnt_lock);
1102 ast_mutex_unlock(&usecnt_lock);
1103 ast_update_use_count();
1106 /* Start the process if it's not already started */
1107 if (!p->alreadygone && strlen(p->initreq.data)) {
1110 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
1111 /* Actually don't destroy us yet, wait for the 487 on our original
1112 INVITE, but do set an autodestruct just in case. */
1114 sip_scheddestroy(p, 15000);
1115 if ( p->initid != -1 ) {
1116 /* channel still up - reverse dec of inUse counter
1117 only if the channel is not auto-congested */
1118 if ( p->outgoing ) {
1119 find_user(p, INC_OUT_USE);
1122 find_user(p, INC_IN_USE);
1127 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1128 transmit_response_reliable(p, res, &p->initreq);
1130 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
1133 if (!p->pendinginvite) {
1135 transmit_request_with_auth(p, "BYE", 0, 1);
1137 /* Note we will need a BYE when this all settles out
1138 but we can't send one while we have "INVITE" outstanding. */
1143 p->needdestroy = needdestroy;
1144 ast_mutex_unlock(&p->lock);
1148 static int sip_answer(struct ast_channel *ast)
1152 struct sip_pvt *p = ast->pvt->pvt;
1155 if (ast->_state != AST_STATE_UP) {
1159 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1161 fmt=ast_getformatbyname(codec);
1163 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1164 p->jointcapability=fmt;
1165 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1168 ast_setstate(ast, AST_STATE_UP);
1170 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1171 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1176 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1178 struct sip_pvt *p = ast->pvt->pvt;
1180 if (frame->frametype == AST_FRAME_VOICE) {
1181 if (!(frame->subclass & ast->nativeformats)) {
1182 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1183 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1187 ast_mutex_lock(&p->lock);
1189 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1190 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1193 res = ast_rtp_write(p->rtp, frame);
1195 ast_mutex_unlock(&p->lock);
1197 } else if (frame->frametype == AST_FRAME_VIDEO) {
1199 ast_mutex_lock(&p->lock);
1201 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1202 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1205 res = ast_rtp_write(p->vrtp, frame);
1207 ast_mutex_unlock(&p->lock);
1209 } else if (frame->frametype == AST_FRAME_IMAGE) {
1212 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1219 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1221 struct sip_pvt *p = newchan->pvt->pvt;
1222 ast_mutex_lock(&p->lock);
1223 if (p->owner != oldchan) {
1224 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1225 ast_mutex_unlock(&p->lock);
1229 ast_mutex_unlock(&p->lock);
1233 static int sip_senddigit(struct ast_channel *ast, char digit)
1235 struct sip_pvt *p = ast->pvt->pvt;
1236 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1237 transmit_info_with_digit(p, digit);
1239 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1240 ast_rtp_senddigit(p->rtp, digit);
1242 /* If in-band DTMF is desired, send that */
1243 if (p->dtmfmode & SIP_DTMF_INBAND)
1248 static int sip_transfer(struct ast_channel *ast, char *dest)
1250 struct sip_pvt *p = ast->pvt->pvt;
1252 res = transmit_refer(p, dest);
1256 static int sip_indicate(struct ast_channel *ast, int condition)
1258 struct sip_pvt *p = ast->pvt->pvt;
1260 case AST_CONTROL_RINGING:
1261 if (ast->_state == AST_STATE_RING) {
1262 if (!p->progress && !p->ringing) {
1263 transmit_response(p, "180 Ringing", &p->initreq);
1267 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1271 case AST_CONTROL_BUSY:
1272 if (ast->_state != AST_STATE_UP) {
1273 transmit_response(p, "486 Busy Here", &p->initreq);
1275 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1279 case AST_CONTROL_CONGESTION:
1280 if (ast->_state != AST_STATE_UP) {
1281 transmit_response(p, "503 Service Unavailable", &p->initreq);
1283 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1287 case AST_CONTROL_PROGRESS:
1288 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1289 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1297 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1305 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1307 struct ast_channel *tmp;
1309 tmp = ast_channel_alloc(1);
1311 /* Select our native format based on codec preference until we receive
1312 something from another device to the contrary. */
1313 if (i->jointcapability)
1314 tmp->nativeformats = sip_codec_choose(i->jointcapability);
1315 else if (i->capability)
1316 tmp->nativeformats = sip_codec_choose(i->capability);
1318 tmp->nativeformats = sip_codec_choose(capability);
1319 fmt = ast_best_codec(tmp->nativeformats);
1321 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1323 if (strchr(i->fromdomain,':'))
1325 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1329 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1332 if (i->dtmfmode & SIP_DTMF_INBAND) {
1333 i->vad = ast_dsp_new();
1334 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1336 tmp->fds[0] = ast_rtp_fd(i->rtp);
1337 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1339 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1340 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1342 ast_setstate(tmp, state);
1343 if (state == AST_STATE_RING)
1345 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1346 tmp->writeformat = fmt;
1347 tmp->pvt->rawwriteformat = fmt;
1348 tmp->readformat = fmt;
1349 tmp->pvt->rawreadformat = fmt;
1351 tmp->pvt->send_text = sip_sendtext;
1352 tmp->pvt->call = sip_call;
1353 tmp->pvt->hangup = sip_hangup;
1354 tmp->pvt->answer = sip_answer;
1355 tmp->pvt->read = sip_read;
1356 tmp->pvt->write = sip_write;
1357 tmp->pvt->write_video = sip_write;
1358 tmp->pvt->indicate = sip_indicate;
1359 tmp->pvt->transfer = sip_transfer;
1360 tmp->pvt->fixup = sip_fixup;
1361 tmp->pvt->send_digit = sip_senddigit;
1363 tmp->pvt->bridge = ast_rtp_bridge;
1365 tmp->callgroup = i->callgroup;
1366 tmp->pickupgroup = i->pickupgroup;
1367 tmp->restrictcid = i->restrictcid;
1368 if (strlen(i->accountcode))
1369 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1371 tmp->amaflags = i->amaflags;
1372 if (strlen(i->language))
1373 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1375 ast_mutex_lock(&usecnt_lock);
1377 ast_mutex_unlock(&usecnt_lock);
1378 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1379 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1380 if (strlen(i->callerid))
1381 tmp->callerid = strdup(i->callerid);
1382 if (strlen(i->rdnis))
1383 tmp->rdnis = strdup(i->rdnis);
1385 if (strlen(i->domain)) {
1386 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1389 if (state != AST_STATE_DOWN) {
1390 if (ast_pbx_start(tmp)) {
1391 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1397 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1401 static struct cfalias {
1405 { "Content-Type", "c" },
1406 { "Content-Encoding", "e" },
1410 { "Content-Length", "l" },
1416 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1417 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1418 char* r = line + nameLen + 1;
1419 while (*r && (*r < 33)) ++r;
1426 static char *get_sdp(struct sip_request *req, char *name) {
1428 int len = strlen(name);
1431 for (x=0; x<req->lines; x++) {
1432 r = get_sdp_by_line(req->line[x], name, len);
1433 if (r[0] != '\0') return r;
1438 static void sdpLineNum_iterator_init(int* iterator) {
1442 static char* get_sdp_iterate(int* iterator,
1443 struct sip_request *req, char *name) {
1444 int len = strlen(name);
1446 while (*iterator < req->lines) {
1447 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1448 if (r[0] != '\0') return r;
1453 static char *__get_header(struct sip_request *req, char *name, int *start)
1456 int len = strlen(name);
1458 for (x=*start;x<req->headers;x++) {
1459 if (!strncasecmp(req->header[x], name, len) &&
1460 (req->header[x][len] == ':')) {
1461 r = req->header[x] + len + 1;
1462 while(*r && (*r < 33))
1469 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1470 if (!strcasecmp(aliases[x].fullname, name))
1471 return __get_header(req, aliases[x].shortname, start);
1473 /* Don't return NULL, so get_header is always a valid pointer */
1477 static char *get_header(struct sip_request *req, char *name)
1480 return __get_header(req, name, &start);
1483 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1485 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1486 struct ast_frame *f;
1487 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1490 f = ast_rtp_read(p->rtp);
1493 f = ast_rtcp_read(p->rtp);
1496 f = ast_rtp_read(p->vrtp);
1499 f = ast_rtcp_read(p->vrtp);
1504 /* Don't send RFC2833 if we're not supposed to */
1505 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1508 /* We already hold the channel lock */
1509 if (f->frametype == AST_FRAME_VOICE) {
1510 if (f->subclass != p->owner->nativeformats) {
1511 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1512 p->owner->nativeformats = f->subclass;
1513 ast_set_read_format(p->owner, p->owner->readformat);
1514 ast_set_write_format(p->owner, p->owner->writeformat);
1516 if (p->dtmfmode & SIP_DTMF_INBAND) {
1517 f = ast_dsp_process(p->owner,p->vad,f,0);
1524 static struct ast_frame *sip_read(struct ast_channel *ast)
1526 struct ast_frame *fr;
1527 struct sip_pvt *p = ast->pvt->pvt;
1528 ast_mutex_lock(&p->lock);
1529 fr = sip_rtp_read(ast, p);
1530 ast_mutex_unlock(&p->lock);
1534 static void build_callid(char *callid, int len, struct in_addr ourip)
1541 res = snprintf(callid, len, "%08x", val);
1545 /* It's not important that we really use our right IP here... */
1546 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1549 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1553 p = malloc(sizeof(struct sip_pvt));
1556 /* Keep track of stuff */
1557 memset(p, 0, sizeof(struct sip_pvt));
1561 p->rtp = ast_rtp_new(sched, io, 1, 0);
1563 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1567 /* Start with 101 instead of 1 */
1570 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1574 ast_rtp_settos(p->rtp, tos);
1576 ast_rtp_settos(p->vrtp, tos);
1577 if (useglobalnat && sin) {
1578 /* Setup NAT structure according to global settings if we have an address */
1580 memcpy(&p->recv, sin, sizeof(p->recv));
1581 ast_rtp_setnat(p->rtp, p->nat);
1583 ast_rtp_setnat(p->vrtp, p->nat);
1585 ast_mutex_init(&p->lock);
1588 memcpy(&p->sa, sin, sizeof(p->sa));
1589 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1590 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1592 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1594 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1595 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1597 build_callid(p->callid, sizeof(p->callid), p->ourip);
1599 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1600 /* Assume reinvite OK and via INVITE */
1601 p->canreinvite = globalcanreinvite;
1602 p->dtmfmode = globaldtmfmode;
1603 p->capability = capability;
1604 if (p->dtmfmode & SIP_DTMF_RFC2833)
1605 p->noncodeccapability |= AST_RTP_DTMF;
1606 strncpy(p->context, context, sizeof(p->context) - 1);
1607 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1609 ast_mutex_lock(&iflock);
1612 ast_mutex_unlock(&iflock);
1614 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1618 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1626 callid = get_header(req, "Call-ID");
1628 if (pedanticsipchecking) {
1629 /* In principle Call-ID's uniquely identify a call, however some vendors
1630 (i.e. Pingtel) send multiple calls with the same Call-ID and different
1631 tags in order to simplify billing. The RFC does state that we have to
1632 compare tags in addition to the call-id, but this generate substantially
1633 more overhead which is totally unnecessary for the vast majority of sane
1634 SIP implementations, and thus Asterisk does not enable this behavior
1635 by default. Short version: You'll need this option to support conferencing
1637 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1639 c = strchr(tmp, ' ');
1642 if (!strcasecmp(cmd, "SIP/2.0")) {
1648 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1650 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1651 tag = strstr(tmp, "tag=");
1654 c = strchr(tag, ';');
1661 if (!strlen(callid)) {
1662 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1665 ast_mutex_lock(&iflock);
1668 if (!strcmp(p->callid, callid) &&
1669 (!pedanticsipchecking || !tag || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1670 /* Found the call */
1671 ast_mutex_lock(&p->lock);
1672 ast_mutex_unlock(&iflock);
1677 ast_mutex_unlock(&iflock);
1678 p = sip_alloc(callid, sin, 1);
1680 ast_mutex_lock(&p->lock);
1684 static int sip_register(char *value, int lineno)
1686 struct sip_registry *reg;
1687 char copy[256] = "";
1688 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1696 strncpy(copy, value, sizeof(copy)-1);
1699 hostname = strrchr(stringp, '@');
1704 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1705 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1709 username = strsep(&stringp, ":");
1711 secret = strsep(&stringp, ":");
1713 authuser = strsep(&stringp, ":");
1716 hostname = strsep(&stringp, "/");
1718 contact = strsep(&stringp, "/");
1719 if (!contact || !strlen(contact))
1722 hostname = strsep(&stringp, ":");
1723 porta = strsep(&stringp, ":");
1725 if (porta && !atoi(porta)) {
1726 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1729 hp = gethostbyname(hostname);
1731 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1734 reg = malloc(sizeof(struct sip_registry));
1736 memset(reg, 0, sizeof(struct sip_registry));
1737 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1739 strncpy(reg->username, username, sizeof(reg->username)-1);
1741 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1743 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1745 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1748 reg->refresh = default_expiry;
1749 reg->addr.sin_family = AF_INET;
1750 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1751 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1752 reg->next = registrations;
1753 reg->callid_valid = 0;
1755 registrations = reg;
1757 ast_log(LOG_ERROR, "Out of memory\n");
1763 static void parse(struct sip_request *req)
1765 /* Divide fields by NULL's */
1770 /* First header starts immediately */
1774 /* We've got a new header */
1778 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1780 if (!strlen(req->header[f])) {
1781 /* Line by itself means we're now in content */
1785 if (f >= SIP_MAX_HEADERS - 1) {
1786 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1789 req->header[f] = c + 1;
1790 } else if (*c == '\r') {
1791 /* Ignore but eliminate \r's */
1796 /* Check for last header */
1797 if (strlen(req->header[f]))
1800 /* Now we process any mime content */
1805 /* We've got a new line */
1808 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1810 if (f >= SIP_MAX_LINES - 1) {
1811 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1814 req->line[f] = c + 1;
1815 } else if (*c == '\r') {
1816 /* Ignore and eliminate \r's */
1821 /* Check for last line */
1822 if (strlen(req->line[f]))
1826 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1828 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1831 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1840 int peercapability, peernoncodeccapability;
1841 int vpeercapability=0, vpeernoncodeccapability=0;
1842 struct sockaddr_in sin;
1850 /* Get codec and RTP info from SDP */
1851 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1852 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1855 m = get_sdp(req, "m");
1856 c = get_sdp(req, "c");
1857 if (!strlen(m) || !strlen(c)) {
1858 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1861 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1862 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1865 /* XXX This could block for a long time, and block the main thread! XXX */
1866 hp = gethostbyname(host);
1868 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1871 sdpLineNum_iterator_init(&iterator);
1872 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
1873 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
1875 // Scan through the RTP payload types specified in a "m=" line:
1876 ast_rtp_pt_clear(p->rtp);
1878 while(strlen(codecs)) {
1879 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1880 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1884 ast_verbose("Found audio format %s\n", ast_getformatname(codec));
1885 ast_rtp_set_m_type(p->rtp, codec);
1887 /* Skip over any whitespace */
1888 while(*codecs && (*codecs < 33)) codecs++;
1891 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
1893 // Scan through the RTP payload types specified in a "m=" line:
1894 ast_rtp_pt_clear(p->vrtp);
1896 while(strlen(codecs)) {
1897 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1898 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1902 ast_verbose("Found video format %s\n", ast_getformatname(codec));
1903 ast_rtp_set_m_type(p->vrtp, codec);
1905 /* Skip over any whitespace */
1906 while(*codecs && (*codecs < 33)) codecs++;
1910 sin.sin_family = AF_INET;
1911 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1912 /* Setup audio port number */
1913 sin.sin_port = htons(portno);
1914 if (p->rtp && sin.sin_port)
1915 ast_rtp_set_peer(p->rtp, &sin);
1916 /* Setup video port number */
1917 sin.sin_port = htons(vportno);
1918 if (p->vrtp && sin.sin_port)
1919 ast_rtp_set_peer(p->vrtp, &sin);
1921 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1923 // Next, scan through each "a=rtpmap:" line, noting each
1924 // specified RTP payload type (with corresponding MIME subtype):
1925 sdpLineNum_iterator_init(&iterator);
1926 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1927 char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
1928 if (!strcasecmp(a, "sendonly")) {
1932 if (!strcasecmp(a, "sendrecv")) {
1935 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1937 ast_verbose("Found description format %s\n", mimeSubtype);
1938 // Note: should really look at the 'freq' and '#chans' params too
1939 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1941 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
1944 // Now gather all of the codecs that were asked for:
1945 ast_rtp_get_current_formats(p->rtp,
1946 &peercapability, &peernoncodeccapability);
1948 ast_rtp_get_current_formats(p->vrtp,
1949 &vpeercapability, &vpeernoncodeccapability);
1950 p->jointcapability = p->capability & (peercapability | vpeercapability);
1951 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
1954 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
1955 p->capability, peercapability, vpeercapability, p->jointcapability);
1956 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1957 noncodeccapability, peernoncodeccapability,
1958 p->noncodeccapability);
1960 if (!p->jointcapability) {
1961 ast_log(LOG_WARNING, "No compatible codecs!\n");
1965 if (!(p->owner->nativeformats & p->jointcapability)) {
1966 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);
1967 p->owner->nativeformats = sip_codec_choose(p->jointcapability);
1968 ast_set_read_format(p->owner, p->owner->readformat);
1969 ast_set_write_format(p->owner, p->owner->writeformat);
1971 if (p->owner->bridge) {
1972 /* Turn on/off music on hold if we are holding/unholding */
1973 if (sin.sin_addr.s_addr && !sendonly) {
1974 ast_moh_stop(p->owner->bridge);
1976 ast_moh_start(p->owner->bridge, NULL);
1984 static int add_header(struct sip_request *req, char *var, char *value)
1986 if (req->len >= sizeof(req->data) - 4) {
1987 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
1991 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1994 req->header[req->headers] = req->data + req->len;
1995 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1996 req->len += strlen(req->header[req->headers]);
1997 if (req->headers < SIP_MAX_HEADERS)
2000 ast_log(LOG_WARNING, "Out of header space\n");
2006 static int add_blank_header(struct sip_request *req)
2008 if (req->len >= sizeof(req->data) - 4) {
2009 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2013 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2016 req->header[req->headers] = req->data + req->len;
2017 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2018 req->len += strlen(req->header[req->headers]);
2019 if (req->headers < SIP_MAX_HEADERS)
2022 ast_log(LOG_WARNING, "Out of header space\n");
2028 static int add_line(struct sip_request *req, char *line)
2030 if (req->len >= sizeof(req->data) - 4) {
2031 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2035 /* Add extra empty return */
2036 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2037 req->len += strlen(req->data + req->len);
2039 req->line[req->lines] = req->data + req->len;
2040 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2041 req->len += strlen(req->line[req->lines]);
2042 if (req->lines < SIP_MAX_LINES)
2045 ast_log(LOG_WARNING, "Out of line space\n");
2051 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2054 tmp = get_header(orig, field);
2056 /* Add what we're responding to */
2057 return add_header(req, field, tmp);
2059 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2063 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2069 tmp = __get_header(orig, field, &start);
2071 /* Add what we're responding to */
2072 add_header(req, field, tmp);
2077 return copied ? 0 : -1;
2080 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2087 tmp = __get_header(orig, field, &start);
2089 if (!copied && p->nat) {
2090 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2091 /* SLD: FIXME: Nice try, but the received= should not have a port */
2092 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2093 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
2095 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2096 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2099 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2100 add_header(req, field, new);
2102 /* Add what we're responding to */
2103 add_header(req, field, tmp);
2110 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2116 /* Add Route: header into request per learned route */
2117 static void add_route(struct sip_request *req, struct sip_route *route)
2120 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2126 n = strlen(route->hop);
2127 if ((n+3)>rem) break;
2133 strcpy(p, route->hop); p += n;
2136 route = route->next;
2139 add_header(req, "Route", r);
2142 static void set_destination(struct sip_pvt *p, char *uri)
2144 char *h, *maddr, hostname[256];
2148 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2149 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2152 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2154 /* Find and parse hostname */
2155 h = strchr(uri, '@');
2160 if (strncmp(h, "sip:", 4) == 0)
2162 else if (strncmp(h, "sips:", 5) == 0)
2165 hn = strcspn(h, ":;>");
2167 strncpy(hostname, h, hn); hostname[hn] = '\0';
2170 /* Is "port" present? if not default to 5060 */
2174 port = strtol(h, &h, 10);
2179 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2180 maddr = strstr(h, "maddr=");
2183 hn = strspn(maddr, "0123456789.");
2185 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2188 hp = gethostbyname(hostname);
2190 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2193 p->sa.sin_family = AF_INET;
2194 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2195 p->sa.sin_port = htons(port);
2197 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2200 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2202 /* Initialize a response */
2203 if (req->headers || req->len) {
2204 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2207 req->header[req->headers] = req->data + req->len;
2208 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2209 req->len += strlen(req->header[req->headers]);
2210 if (req->headers < SIP_MAX_HEADERS)
2213 ast_log(LOG_WARNING, "Out of header space\n");
2217 static int init_req(struct sip_request *req, char *resp, char *recip)
2219 /* Initialize a response */
2220 if (req->headers || req->len) {
2221 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2224 req->header[req->headers] = req->data + req->len;
2225 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2226 req->len += strlen(req->header[req->headers]);
2227 if (req->headers < SIP_MAX_HEADERS)
2230 ast_log(LOG_WARNING, "Out of header space\n");
2234 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2236 char newto[256] = "", *ot;
2237 memset(resp, 0, sizeof(*resp));
2238 init_resp(resp, msg, req);
2239 copy_via_headers(p, resp, req, "Via");
2240 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2241 copy_header(resp, req, "From");
2242 ot = get_header(req, "To");
2243 if (!strstr(ot, "tag=")) {
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 (strlen(p->theirtag) && p->outgoing)
2247 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2248 else if (p->tag && !p->outgoing)
2249 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2251 strncpy(newto, ot, sizeof(newto) - 1);
2254 add_header(resp, "To", ot);
2255 copy_header(resp, req, "Call-ID");
2256 copy_header(resp, req, "CSeq");
2257 add_header(resp, "User-Agent", "Asterisk PBX");
2258 add_header(resp, "Allow", ALLOWED_METHODS);
2260 /* For registration responses, we also need expiry and
2264 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2265 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2266 add_header(resp, "Expires", tmp);
2267 add_header(resp, "Contact", contact);
2269 add_header(resp, "Contact", p->our_contact);
2274 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2276 struct sip_request *orig = &p->initreq;
2277 char stripped[80] ="";
2283 memset(req, 0, sizeof(struct sip_request));
2285 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2292 if (strlen(p->uri)) {
2296 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2298 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2300 c = strchr(stripped, '<');
2312 init_req(req, msg, c);
2314 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2316 add_header(req, "Via", p->via);
2318 set_destination(p, p->route->hop);
2319 add_route(req, p->route->next);
2322 ot = get_header(orig, "To");
2323 of = get_header(orig, "From");
2325 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2326 as our original request, including tag (or presumably lack thereof) */
2327 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2328 /* Add the proper tag if we don't have it already. If they have specified
2329 their tag, use it. Otherwise, use our own tag */
2330 if (p->outgoing && strlen(p->theirtag))
2331 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2332 else if (!p->outgoing)
2333 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2335 snprintf(newto, sizeof(newto), "%s", ot);
2340 add_header(req, "From", of);
2341 add_header(req, "To", ot);
2343 add_header(req, "From", ot);
2344 add_header(req, "To", of);
2346 add_header(req, "Contact", p->our_contact);
2347 copy_header(req, orig, "Call-ID");
2348 add_header(req, "CSeq", tmp);
2350 add_header(req, "User-Agent", "Asterisk PBX");
2354 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2356 struct sip_request resp;
2358 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2359 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2362 respprep(&resp, p, msg, req);
2363 add_header(&resp, "Content-Length", "0");
2364 add_blank_header(&resp);
2365 return send_response(p, &resp, reliable, seqno);
2368 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2370 return __transmit_response(p, msg, req, 0);
2372 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2374 return __transmit_response(p, msg, req, 1);
2377 static void append_date(struct sip_request *req)
2384 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2385 add_header(req, "Date", tmpdat);
2388 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2390 struct sip_request resp;
2391 respprep(&resp, p, msg, req);
2393 add_header(&resp, "Content-Length", "0");
2394 add_blank_header(&resp);
2395 return send_response(p, &resp, 0, 0);
2398 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2400 struct sip_request resp;
2401 respprep(&resp, p, msg, req);
2402 add_header(&resp, "Accept", "application/sdp");
2403 add_header(&resp, "Content-Length", "0");
2404 add_blank_header(&resp);
2405 return send_response(p, &resp, 0, 0);
2408 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2410 struct sip_request resp;
2413 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2414 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2417 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2418 respprep(&resp, p, msg, req);
2419 add_header(&resp, "Proxy-Authenticate", tmp);
2420 add_header(&resp, "Content-Length", "0");
2421 add_blank_header(&resp);
2422 return send_response(p, &resp, reliable, seqno);
2425 static int add_text(struct sip_request *req, char *text)
2427 /* XXX Convert \n's to \r\n's XXX */
2428 int len = strlen(text);
2430 snprintf(clen, sizeof(clen), "%d", len);
2431 add_header(req, "Content-Type", "text/plain");
2432 add_header(req, "Content-Length", clen);
2433 add_line(req, text);
2437 static int add_digit(struct sip_request *req, char digit)
2442 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2444 snprintf(clen, sizeof(clen), "%d", len);
2445 add_header(req, "Content-Type", "application/dtmf-relay");
2446 add_header(req, "Content-Length", clen);
2451 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2455 int alreadysent = 0;
2457 struct sockaddr_in sin;
2458 struct sockaddr_in vsin;
2459 struct sip_codec_pref *cur;
2470 struct sockaddr_in dest;
2471 struct sockaddr_in vdest;
2472 /* XXX We break with the "recommendation" and send our IP, in order that our
2473 peer doesn't have to gethostbyname() us XXX */
2476 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2479 if (!p->sessionid) {
2480 p->sessionid = getpid();
2481 p->sessionversion = p->sessionid;
2483 p->sessionversion++;
2484 ast_rtp_get_us(p->rtp, &sin);
2486 ast_rtp_get_us(p->vrtp, &vsin);
2488 if (p->redirip.sin_addr.s_addr) {
2489 dest.sin_port = p->redirip.sin_port;
2490 dest.sin_addr = p->redirip.sin_addr;
2492 ast_rtp_get_peer(rtp, &dest);
2494 dest.sin_addr = p->ourip;
2495 dest.sin_port = sin.sin_port;
2498 /* Determine video destination */
2500 if (p->vredirip.sin_addr.s_addr) {
2501 vdest.sin_port = p->vredirip.sin_port;
2502 vdest.sin_addr = p->vredirip.sin_addr;
2504 ast_rtp_get_peer(vrtp, &vdest);
2506 vdest.sin_addr = p->ourip;
2507 vdest.sin_port = vsin.sin_port;
2511 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2512 if (sipdebug && p->vrtp)
2513 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2514 snprintf(v, sizeof(v), "v=0\r\n");
2515 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
2516 snprintf(s, sizeof(s), "s=session\r\n");
2517 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2518 snprintf(t, sizeof(t), "t=0 0\r\n");
2519 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2520 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2521 /* Start by sending our preferred codecs */
2524 if (p->jointcapability & cur->codec) {
2526 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2527 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2529 snprintf(costr, sizeof(costr), " %d", codec);
2530 if (cur->codec < AST_FORMAT_MAX_AUDIO) {
2532 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2536 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2541 alreadysent |= cur->codec;
2544 /* Now send any other common codecs, and non-codec formats: */
2545 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2546 if ((p->jointcapability & x) && !(alreadysent & x)) {
2548 ast_verbose("Answering with capability %d\n", x);
2549 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2551 snprintf(costr, sizeof(costr), " %d", codec);
2552 if (x < AST_FORMAT_MAX_AUDIO) {
2554 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2558 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2564 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2565 if (p->noncodeccapability & x) {
2567 ast_verbose("Answering with non-codec capability %d\n", x);
2568 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2570 snprintf(costr, sizeof(costr), " %d", codec);
2572 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2574 if (x == AST_RTP_DTMF) {
2575 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2576 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2585 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2587 len += strlen(m2) + strlen(a2);
2588 snprintf(costr, sizeof(costr), "%d", len);
2589 add_header(resp, "Content-Type", "application/sdp");
2590 add_header(resp, "Content-Length", costr);
2605 static void copy_request(struct sip_request *dst,struct sip_request *src)
2609 offset = ((void *)dst) - ((void *)src);
2610 /* First copy stuff */
2611 memcpy(dst, src, sizeof(*dst));
2612 /* Now fix pointer arithmetic */
2613 for (x=0;x<src->headers;x++)
2614 dst->header[x] += offset;
2615 for (x=0;x<src->lines;x++)
2616 dst->line[x] += offset;
2619 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2621 struct sip_request resp;
2623 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2624 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2627 respprep(&resp, p, msg, req);
2628 add_sdp(&resp, p, NULL, NULL);
2629 return send_response(p, &resp, retrans, seqno);
2632 static int determine_firstline_parts( struct sip_request *req ) {
2637 cmd= req->header[0];
2638 while(*cmd && (*cmd < 33)) {
2645 while(*e && (*e > 32)) {
2648 /* Get the command */
2654 while( *e && ( *e < 33 ) ) {
2661 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2662 /* We have a response */
2664 len= strlen( req->rlPart2 );
2665 if( len < 2 ) { return -1; }
2667 while( *e && *e<33 ) {
2672 /* We have a request */
2675 if( !*e ) { return -1; }
2678 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2681 while( isspace( *(--e) ) ) {}
2691 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2693 struct sip_request req;
2694 if (p->canreinvite == REINVITE_UPDATE)
2695 reqprep(&req, p, "UPDATE", 0);
2697 reqprep(&req, p, "INVITE", 0);
2698 add_header(&req, "Allow", ALLOWED_METHODS);
2699 add_sdp(&req, p, rtp, vrtp);
2700 /* Use this as the basis */
2701 copy_request(&p->initreq, &req);
2703 determine_firstline_parts(&p->initreq);
2704 p->lastinvite = p->ocseq;
2706 return send_request(p, &req, 1, p->ocseq);
2709 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
2711 char stripped[256]="";
2713 strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
2714 c = strchr(stripped, '<');
2726 strncpy(p->uri, c, sizeof(p->uri) - 1);
2729 static void build_contact(struct sip_pvt *p)
2731 /* Construct Contact: header */
2732 if (ourport != 5060)
2733 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2735 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2738 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2745 char *l = callerid, *n=NULL;
2747 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
2749 if (p->owner && p->owner->callerid) {
2750 strcpy(cid, p->owner->callerid);
2751 ast_callerid_parse(cid, &n, &l);
2753 ast_shrink_phone_number(l);
2754 if (!l || !ast_isphonenumber(l))
2757 /* if user want's his callerid restricted */
2759 l = CALLERID_UNKNOWN;
2760 if (!n || !strlen(n))
2762 /* Allow user to be overridden */
2763 if (strlen(p->fromuser))
2766 if ((ourport != 5060) && !strlen(p->fromdomain))
2767 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);
2769 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2771 if (strlen(p->username)) {
2772 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2773 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2775 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2777 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2778 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2780 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2782 strncpy(p->uri, invite, sizeof(p->uri) - 1);
2783 /* If there is a VXML URL append it to the SIP URL */
2786 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2790 snprintf(to, sizeof(to), "<%s>", invite );
2792 memset(req, 0, sizeof(struct sip_request));
2793 init_req(req, cmd, invite);
2794 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2796 add_header(req, "Via", p->via);
2797 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2798 * OTOH, then we won't have anything in p->route anyway */
2799 add_header(req, "From", from);
2800 strncpy(p->exten, l, sizeof(p->exten) - 1);
2802 add_header(req, "To", to);
2803 add_header(req, "Contact", p->our_contact);
2804 add_header(req, "Call-ID", p->callid);
2805 add_header(req, "CSeq", tmp);
2806 add_header(req, "User-Agent", "Asterisk PBX");
2809 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, int init)
2811 struct sip_request req;
2814 initreqprep(&req, p, cmd, vxml_url);
2816 reqprep(&req, p, cmd, 0);
2819 add_header(&req, authheader, auth);
2821 if (!strcasecmp(cmd, "REFER")) {
2822 if (strlen(p->refer_to))
2823 add_header(&req, "Refer-To", p->refer_to);
2824 if (strlen(p->referred_by))
2825 add_header(&req, "Referred-By", p->referred_by);
2828 if (distinctive_ring)
2830 add_header(&req, "Alert-info",distinctive_ring);
2832 add_header(&req, "Allow", ALLOWED_METHODS);
2834 add_sdp(&req, p, NULL, NULL);
2836 add_header(&req, "Content-Length", "0");
2837 add_blank_header(&req);
2840 if (!p->initreq.headers) {
2841 /* Use this as the basis */
2842 copy_request(&p->initreq, &req);
2844 determine_firstline_parts(&p->initreq);
2846 p->lastinvite = p->ocseq;
2847 return send_request(p, &req, 1, p->ocseq);
2850 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2853 char from[256], to[256];
2856 struct sip_request req;
2859 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2861 c = ditch_braces(from);
2862 if (strncmp(c, "sip:", 4)) {
2863 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2866 if ((a = strchr(c, ';'))) {
2871 reqprep(&req, p, "NOTIFY", 0);
2873 if (p->subscribed == 1) {
2874 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2876 c = ditch_braces(to);
2877 if (strncmp(c, "sip:", 4)) {
2878 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
2881 if ((a = strchr(c, ';'))) {
2886 add_header(&req, "Content-Type", "application/xpidf+xml");
2888 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2890 else if (state==AST_EXTENSION_INUSE)
2896 sprintf(t, "<?xml version=\"1.0\"?>\n");
2897 t = tmp + strlen(tmp);
2898 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2899 t = tmp + strlen(tmp);
2900 sprintf(t, "<presence>\n");
2901 t = tmp + strlen(tmp);
2902 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2903 t = tmp + strlen(tmp);
2904 sprintf(t, "<atom id=\"%s\">\n", p->exten);
2905 t = tmp + strlen(tmp);
2906 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2907 t = tmp + strlen(tmp);
2908 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2909 t = tmp + strlen(tmp);
2910 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2911 t = tmp + strlen(tmp);
2912 sprintf(t, "</address>\n</atom>\n</presence>\n");
2914 add_header(&req, "Event", "dialog");
2915 add_header(&req, "Content-Type", "application/dialog-info+xml");
2918 sprintf(t, "<?xml version=\"1.0\"?>\n");
2919 t = tmp + strlen(tmp);
2920 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);
2921 t = tmp + strlen(tmp);
2922 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2923 t = tmp + strlen(tmp);
2924 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2925 t = tmp + strlen(tmp);
2926 sprintf(t, "</dialog>\n</dialog-info>\n");
2929 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2930 add_header(&req, "Content-Length", clen);
2931 add_line(&req, tmp);
2933 return send_request(p, &req, 1, p->ocseq);
2936 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2938 struct sip_request req;
2942 initreqprep(&req, p, "NOTIFY", NULL);
2943 add_header(&req, "Event", "message-summary");
2944 add_header(&req, "Content-Type", notifymime);
2946 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2947 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2948 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2949 add_header(&req, "Content-Length", clen);
2950 add_line(&req, tmp);
2951 add_line(&req, tmp2);
2953 if (!p->initreq.headers) {
2954 /* Use this as the basis */
2955 copy_request(&p->initreq, &req);
2957 determine_firstline_parts(&p->initreq);
2960 return send_request(p, &req, 1, p->ocseq);
2963 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
2965 static int sip_reregister(void *data)
2967 /* if we are here, we know that we need to reregister. */
2968 struct sip_registry *r=(struct sip_registry *)data;
2975 static int sip_do_register(struct sip_registry *r)
2978 ast_mutex_lock(&r->lock);
2979 res=transmit_register(r, "REGISTER", NULL, NULL);
2980 ast_mutex_unlock(&r->lock);
2984 static int sip_reg_timeout(void *data)
2986 /* if we are here, our registration timed out, so we'll just do it over */
2987 struct sip_registry *r=data;
2990 ast_mutex_lock(&r->lock);
2991 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
2993 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
2994 in the single SIP manager thread. */
3000 r->regstate=REG_STATE_UNREGISTERED;
3002 res=transmit_register(r, "REGISTER", NULL, NULL);
3003 ast_mutex_unlock(&r->lock);
3007 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
3009 struct sip_request req;
3016 /* exit if we are already in process with this registrar ?*/
3017 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
3018 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
3024 ast_log(LOG_WARNING, "Already have a call??\n");
3029 if (!r->callid_valid) {
3030 build_callid(r->callid, sizeof(r->callid), __ourip);
3031 r->callid_valid = 1;
3033 p=sip_alloc( r->callid, &r->addr, 0);
3035 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
3041 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
3042 strncpy(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret)-1);
3043 if (strlen(r->authuser))
3044 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
3046 strncpy(p->peername, r->username, sizeof(p->peername)-1);
3047 strncpy(p->username, r->username, sizeof(p->username)-1);
3048 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
3049 /* Always bind to our IP if specified */
3050 if (!use_external_ip && bindaddr.sin_addr.s_addr)
3051 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
3055 /* set up a timeout */
3057 if (r->timeout > -1) {
3058 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
3059 ast_sched_del(sched, r->timeout);
3061 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
3062 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
3065 if (strchr(r->username, '@')) {
3066 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
3067 snprintf(to, sizeof(to), "<sip:%s>", r->username);
3069 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
3070 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
3073 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
3074 strncpy(p->uri, addr, sizeof(p->uri) - 1);
3076 memset(&req, 0, sizeof(req));
3077 init_req(&req, cmd, addr);
3079 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
3080 p->ocseq = r->ocseq;
3082 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
3083 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
3084 add_header(&req, "Via", via);
3085 add_header(&req, "From", from);
3086 add_header(&req, "To", to);
3087 add_header(&req, "Call-ID", p->callid);
3088 add_header(&req, "CSeq", tmp);
3089 add_header(&req, "User-Agent", "Asterisk PBX");