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>
53 #include <sys/signal.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
57 #ifdef SIP_MYSQL_FRIENDS
59 #include <mysql/mysql.h>
62 #define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
64 #define IPTOS_MINCOST 0x02
67 /* #define VOCAL_DATA_HACK */
70 #define DEFAULT_DEFAULT_EXPIRY 120
71 #define DEFAULT_MAX_EXPIRY 3600
72 #define EXPIRY_GUARD_SECS 15
74 #define CALLERID_UNKNOWN "Unknown"
76 #define SIP_DTMF_RFC2833 (1 << 0)
77 #define SIP_DTMF_INBAND (1 << 1)
78 #define SIP_DTMF_INFO (1 << 2)
80 static int max_expiry = DEFAULT_MAX_EXPIRY;
81 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
83 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
84 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
85 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
87 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
88 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
91 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
93 static char mydbuser[80];
94 static char mydbpass[80];
95 static char mydbhost[80];
96 static char mydbname[80];
100 #define DEBUG_READ 0 /* Recieved data */
101 #define DEBUG_SEND 1 /* Transmit data */
103 static char *desc = "Session Initiation Protocol (SIP)";
104 static char *type = "SIP";
105 static char *tdesc = "Session Initiation Protocol (SIP)";
106 static char *config = "sip.conf";
108 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
109 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
111 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
113 static char context[AST_MAX_EXTENSION] = "default";
115 static char language[MAX_LANGUAGE] = "";
117 static char callerid[AST_MAX_EXTENSION] = "asterisk";
119 static char fromdomain[AST_MAX_EXTENSION] = "";
121 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
123 static int srvlookup = 0;
125 static int pedanticsipchecking = 0;
127 static int autocreatepeer = 0;
129 static int relaxdtmf = 0;
131 static int usecnt =0;
132 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
134 /* Protect the interface list (of sip_pvt's) */
135 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
137 /* Protect the monitoring thread, so only one process can kill or start it, and not
138 when it's doing something critical. */
139 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
141 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
143 /* This is the thread for the monitor which checks for input on the channels
144 which are not currently in use. */
145 static pthread_t monitor_thread = AST_PTHREADT_NULL;
147 static int restart_monitor(void);
149 /* Codecs that we support by default: */
150 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
151 static int noncodeccapability = AST_RTP_DTMF;
153 static char ourhost[256];
154 static struct in_addr __ourip;
157 static int sipdebug = 0;
158 static struct sockaddr_in debugaddr;
162 static int videosupport = 0;
164 static int globaldtmfmode = SIP_DTMF_RFC2833;
167 static int expiry = 900;
169 static struct sched_context *sched;
170 static struct io_context *io;
171 /* The private structures of the sip channels are linked for
172 selecting outgoing channels */
174 #define SIP_MAX_HEADERS 64
175 #define SIP_MAX_LINES 64
179 #define DEC_OUT_USE 2
180 #define INC_OUT_USE 3
182 static struct sip_codec_pref {
184 struct sip_codec_pref *next;
188 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
189 char *rlPart2; /* The Request URI or Response Status */
191 int headers; /* SIP Headers */
192 char *header[SIP_MAX_HEADERS];
193 int lines; /* SDP Content */
194 char *line[SIP_MAX_LINES];
195 char data[SIP_MAX_PACKET];
201 struct sip_route *next;
205 static struct sip_pvt {
206 ast_mutex_t lock; /* Channel private lock */
207 char callid[80]; /* Global CallID */
208 char randdata[80]; /* Random data */
209 unsigned int ocseq; /* Current outgoing seqno */
210 unsigned int icseq; /* Current incoming seqno */
211 unsigned int callgroup;
212 unsigned int pickupgroup;
213 int lastinvite; /* Last Cseq of invite */
214 int alreadygone; /* Whether or not we've already been destroyed by or peer */
215 int needdestroy; /* if we need to be destroyed */
216 int capability; /* Special capability */
217 int jointcapability; /* Supported capability at both ends */
218 int prefcodec; /* Preferred codec (outbound only) */
219 int noncodeccapability;
220 int outgoing; /* Outgoing or incoming call? */
221 int authtries; /* Times we've tried to authenticate */
222 int insecure; /* Don't check source port/ip */
223 int expiry; /* How long we take to expire */
224 int branch; /* One random number */
225 int canreinvite; /* Do we support reinvite */
226 int ringing; /* Have sent 180 ringing */
227 int progress; /* Have sent 183 message progress */
228 int tag; /* Another random number */
229 int nat; /* Whether to try to support NAT */
230 int sessionid; /* SDP Session ID */
231 int sessionversion; /* SDP Session Version */
232 struct sockaddr_in sa; /* Our peer */
233 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
234 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
235 struct sockaddr_in recv; /* Received as */
236 struct in_addr ourip; /* Our IP */
237 struct ast_channel *owner; /* Who owns us */
238 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
239 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
240 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
241 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
242 struct sip_pvt *refer_call; /* Call we are referring */
243 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
244 char remote_party_id[256];
246 char context[AST_MAX_EXTENSION];
247 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
248 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
249 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
250 char language[MAX_LANGUAGE];
251 char rdnis[256]; /* Referring DNIS */
252 char theirtag[256]; /* Their tag */
255 char uri[256]; /* Original requested URI */
256 char peersecret[256];
257 char peermd5secret[256];
258 char callerid[256]; /* Caller*ID */
259 int restrictcid; /* hide presentation from remote user */
261 char accountcode[20]; /* Account code */
262 char our_contact[256]; /* Our contact header */
263 char realm[256]; /* Authorization realm */
264 char nonce[256]; /* Authorization nonce */
265 char opaque[256]; /* Opaque nonsense */
266 char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
267 char domain[256]; /* Authorization nonce */
268 char lastmsg[256]; /* Last Message sent/received */
269 int amaflags; /* AMA Flags */
270 int pendinginvite; /* Any pending invite */
271 int pendingbye; /* Need to send bye after we ack? */
272 int gotrefer; /* Got a refer? */
273 struct sip_request initreq; /* Initial request */
275 int maxtime; /* Max time for first response */
276 int initid; /* Auto-congest ID if appropriate */
277 int autokillid; /* Auto-kill ID */
286 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
287 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
288 struct ast_rtp *rtp; /* RTP Session */
289 struct ast_rtp *vrtp; /* Video RTP session */
290 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
291 struct sip_pvt *next;
294 #define FLAG_RESPONSE (1 << 0)
295 #define FLAG_FATAL (1 << 1)
298 struct sip_pkt *next; /* Next packet */
299 int retrans; /* Retransmission number */
300 int seqno; /* Sequence number */
301 int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
302 struct sip_pvt *owner; /* Owner call */
303 int retransid; /* Retransmission ID */
304 int packetlen; /* Length of packet */
309 /* Users who can access various contexts */
316 char accountcode[20];
317 char language[MAX_LANGUAGE];
318 unsigned int callgroup;
319 unsigned int pickupgroup;
333 struct sip_user *next;
340 char context[80]; /* JK02: peers need context too to allow parking etc */
346 char mailbox[AST_MAX_EXTENSION];
356 unsigned int callgroup;
357 unsigned int pickupgroup;
359 struct sockaddr_in addr;
363 struct sip_pvt *call; /* Call pointer */
364 int pokeexpire; /* When to expire poke */
365 int lastms; /* How long last response took (in ms), or -1 for no response */
366 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
367 struct timeval ps; /* Ping send time */
369 struct sockaddr_in defaddr;
375 struct sip_peer *next;
378 static ast_mutex_t sip_reload_lock = AST_MUTEX_INITIALIZER;
379 static int sip_reloading = 0;
381 #define REG_STATE_UNREGISTERED 0
382 #define REG_STATE_REGSENT 1
383 #define REG_STATE_AUTHSENT 2
384 #define REG_STATE_REGISTERED 3
385 #define REG_STATE_REJECTED 4
386 #define REG_STATE_TIMEOUT 5
387 #define REG_STATE_NOAUTH 6
389 struct sip_registry {
390 struct sockaddr_in addr; /* Who we connect to for registration purposes */
391 char username[80]; /* Who we are registering as */
392 char authuser[80]; /* Who we *authenticate* as */
394 char secret[80]; /* Password or key name in []'s */
396 char contact[80]; /* Contact extension */
398 int expire; /* Sched ID of expiration */
399 int timeout; /* sched id of sip_reg_timeout */
400 int refresh; /* How often to refresh */
401 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
403 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
404 char callid[80]; /* Global CallID for this registry */
405 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
406 struct sockaddr_in us; /* Who the server thinks we are */
407 struct sip_registry *next;
410 static struct ast_user_list {
411 struct sip_user *users;
413 } userl = { NULL, AST_MUTEX_INITIALIZER };
415 static struct ast_peer_list {
416 struct sip_peer *peers;
418 } peerl = { NULL, AST_MUTEX_INITIALIZER };
420 static struct ast_register_list {
421 struct sip_registry *registrations;
424 } regl = { NULL, AST_MUTEX_INITIALIZER };
427 #define REINVITE_INVITE 1
428 #define REINVITE_UPDATE 2
430 static int __sip_do_register(struct sip_registry *r);
432 static int sipsock = -1;
433 static int globalnat = 0;
434 static int globalcanreinvite = REINVITE_INVITE;
437 static struct sockaddr_in bindaddr;
438 static struct sockaddr_in localnet;
439 static struct sockaddr_in localmask;
440 static struct sockaddr_in externip;
442 static struct ast_frame *sip_read(struct ast_channel *ast);
443 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
444 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
445 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
446 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
447 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
448 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
449 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
450 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
451 static int transmit_message_with_text(struct sip_pvt *p, char *text);
452 static int transmit_refer(struct sip_pvt *p, char *dest);
453 static struct sip_peer *temp_peer(char *name);
454 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
455 /* static char *getsipuri(char *header); */
456 static void free_old_route(struct sip_route *route);
457 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
458 static int update_user_counter(struct sip_pvt *fup, int event);
459 static void prune_peers(void);
460 static int sip_do_reload(void);
461 static int sip_debug_test_addr(struct sockaddr_in *addr);
462 static int sip_debug_test_pvt(struct sip_pvt *p);
464 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
468 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
470 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
472 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));
477 static void sip_destroy(struct sip_pvt *p);
479 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
482 check to see if them is contained in our localnet/mask,
483 if not, use our externip for us, otherwise use the
484 real internal address in bindaddr
486 if (localnet.sin_addr.s_addr && externip.sin_addr.s_addr &&
487 ((htonl(them->s_addr) & htonl(localnet.sin_addr.s_addr)) != htonl(localnet.sin_addr.s_addr)))
488 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
489 else if (bindaddr.sin_addr.s_addr)
490 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
492 return ast_ouraddrfor(them, us);
496 static int retrans_pkt(void *data)
498 struct sip_pkt *pkt=data;
500 ast_mutex_lock(&pkt->owner->lock);
501 if (pkt->retrans < MAX_RETRANS) {
503 if (sip_debug_test_pvt(pkt->owner)) {
505 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));
507 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));
509 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
512 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (pkt->flags & FLAG_FATAL) ? "Critical" : "Non-critical", (pkt->flags & FLAG_RESPONSE) ? "Response" : "Request");
514 if (pkt->flags & FLAG_FATAL) {
515 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
516 ast_mutex_unlock(&pkt->owner->lock);
518 ast_mutex_lock(&pkt->owner->lock);
520 if (pkt->owner->owner) {
521 /* XXX Potential deadlocK?? XXX */
522 ast_queue_hangup(pkt->owner->owner);
523 ast_mutex_unlock(&pkt->owner->owner->lock);
525 /* If no owner, destroy now */
526 pkt->owner->needdestroy = 1;
529 /* Okay, it's not fatal, just continue. XXX If we were nice, we'd free it now, rather than wait for the
530 end of the call XXX */
534 ast_mutex_unlock(&pkt->owner->lock);
538 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
541 pkt = malloc(sizeof(struct sip_pkt) + len);
544 memset(pkt, 0, sizeof(struct sip_pkt));
545 memcpy(pkt->data, data, len);
546 pkt->packetlen = len;
547 pkt->next = p->packets;
552 pkt->flags |= FLAG_FATAL;
553 /* Schedule retransmission */
554 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
555 pkt->next = p->packets;
557 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
558 if (!strncasecmp(pkt->data, "INVITE", 6)) {
559 /* Note this is a pending invite */
560 p->pendinginvite = seqno;
565 static int __sip_autodestruct(void *data)
567 struct sip_pvt *p = data;
569 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
571 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
572 ast_queue_hangup(p->owner);
579 static int sip_scheddestroy(struct sip_pvt *p, int ms)
581 if (sip_debug_test_pvt(p))
582 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
583 if (p->autokillid > -1)
584 ast_sched_del(sched, p->autokillid);
585 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
589 static int sip_cancel_destroy(struct sip_pvt *p)
591 if (p->autokillid > -1)
592 ast_sched_del(sched, p->autokillid);
597 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
599 struct sip_pkt *cur, *prev = NULL;
604 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
605 if (!resp && (seqno == p->pendinginvite)) {
606 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
607 p->pendinginvite = 0;
610 /* this is our baby */
612 prev->next = cur->next;
614 p->packets = cur->next;
615 if (cur->retransid > -1)
616 ast_sched_del(sched, cur->retransid);
624 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
628 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
634 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
635 /* this is our baby */
636 if (cur->retransid > -1)
637 ast_sched_del(sched, cur->retransid);
644 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");
648 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
651 if (sip_debug_test_pvt(p)) {
653 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));
655 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));
658 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
660 res = __sip_xmit(p, req->data, req->len);
666 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
669 if (sip_debug_test_pvt(p)) {
671 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));
673 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));
676 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
678 res = __sip_xmit(p, req->data, req->len);
682 static char *ditch_braces(char *tmp)
686 if ((n = strchr(tmp, '<')) ) {
688 while(*c && *c != '>') c++;
690 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
699 static int sip_sendtext(struct ast_channel *ast, char *text)
701 struct sip_pvt *p = ast->pvt->pvt;
702 if (sip_debug_test_pvt(p))
703 ast_verbose("Sending text %s on %s\n", text, ast->name);
706 if (!text || !strlen(text))
708 if (sip_debug_test_pvt(p))
709 ast_verbose("Really sending text %s on %s\n", text, ast->name);
710 transmit_message_with_text(p, text);
716 static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
718 if (mysql && (strlen(peer) < 128)) {
723 name = alloca(strlen(peer) * 2 + 1);
724 uname = alloca(strlen(username) * 2 + 1);
726 mysql_real_escape_string(mysql, name, peer, strlen(peer));
727 mysql_real_escape_string(mysql, uname, username, strlen(username));
728 snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"",
729 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
730 ast_mutex_lock(&mysqllock);
731 if (mysql_real_query(mysql, query, strlen(query)))
732 ast_log(LOG_WARNING, "Unable to update database\n");
734 ast_mutex_unlock(&mysqllock);
738 static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
743 p = malloc(sizeof(struct sip_peer));
744 memset(p, 0, sizeof(struct sip_peer));
745 if (mysql && (!peer || (strlen(peer) < 128))) {
750 time_t regseconds, nowtime;
755 name = alloca(strlen(peer) * 2 + 1);
756 mysql_real_escape_string(mysql, name, peer, strlen(peer));
759 snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
761 snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE name=\"%s\"", name);
762 ast_mutex_lock(&mysqllock);
763 mysql_query(mysql, query);
764 if ((result = mysql_store_result(mysql))) {
765 if ((rowval = mysql_fetch_row(result))) {
766 numfields = mysql_num_fields(result);
767 fields = mysql_fetch_fields(result);
769 for (x=0;x<numfields;x++) {
771 if (!strcasecmp(fields[x].name, "secret")) {
772 strncpy(p->secret, rowval[x], sizeof(p->secret));
773 } else if (!strcasecmp(fields[x].name, "name")) {
774 strncpy(p->name, rowval[x], sizeof(p->name) - 1);
775 } else if (!strcasecmp(fields[x].name, "context")) {
776 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
777 } else if (!strcasecmp(fields[x].name, "username")) {
778 strncpy(p->username, rowval[x], sizeof(p->username) - 1);
779 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
780 inet_aton(rowval[x], &p->addr.sin_addr);
781 } else if (!strcasecmp(fields[x].name, "port")) {
782 if (sscanf(rowval[x], "%i", &port) != 1)
784 p->addr.sin_port = htons(port);
785 } else if (!strcasecmp(fields[x].name, "regseconds")) {
786 if (sscanf(rowval[x], "%li", ®seconds) != 1)
792 if (nowtime > regseconds)
793 memset(&p->addr, 0, sizeof(p->addr));
795 mysql_free_result(result);
798 ast_mutex_unlock(&mysqllock);
805 p->capability = capability;
807 p->dtmfmode = globaldtmfmode;
815 #endif /* MYSQL_FRIENDS */
817 static void update_peer(struct sip_peer *p, int expiry)
821 mysql_update_peer(p->name, &p->addr, p->username, expiry);
826 static struct sip_peer *find_peer(char *peer, struct sockaddr_in *sin)
828 struct sip_peer *p = NULL;
832 /* Find by peer name */
834 if (!strcasecmp(p->name, peer)) {
843 if (!inaddrcmp(&p->addr, sin) ||
845 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))) {
854 p = mysql_peer(peer, sin);
861 static struct sip_user *find_user(char *name)
863 struct sip_user *u = NULL;
867 if (!strcasecmp(u->name, name)) {
876 static int sip_debug_test_addr(struct sockaddr_in *addr) {
877 /* See if we pass debug IP filter */
878 if (sipdebug == 0) return 0;
879 if (debugaddr.sin_addr.s_addr) {
880 if (((ntohs(debugaddr.sin_port) != 0) &&
881 (debugaddr.sin_port != addr->sin_port)) ||
882 (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
888 static int sip_debug_test_pvt(struct sip_pvt *p) {
889 return (sipdebug && sip_debug_test_addr((p->nat ? &p->recv : &p->sa)));
892 static int create_addr(struct sip_pvt *r, char *peer)
895 struct ast_hostent ahp;
900 char host[256], *hostn;
902 r->sa.sin_family = AF_INET;
903 ast_mutex_lock(&peerl.lock);
904 p = find_peer(peer, NULL);
908 r->capability = p->capability;
911 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
912 ast_rtp_setnat(r->rtp, r->nat);
915 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
916 ast_rtp_setnat(r->vrtp, r->nat);
918 strncpy(r->peername, p->username, sizeof(r->peername)-1);
919 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
920 strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
921 strncpy(r->username, p->username, sizeof(r->username)-1);
922 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
923 if (!strlen(r->tohost)) {
924 if (p->addr.sin_addr.s_addr)
925 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
927 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
929 if (strlen(p->fromdomain))
930 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
931 if (strlen(p->fromuser))
932 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
933 r->insecure = p->insecure;
934 r->canreinvite = p->canreinvite;
935 r->maxtime = p->maxms;
936 r->callgroup = p->callgroup;
937 r->pickupgroup = p->pickupgroup;
939 r->dtmfmode = p->dtmfmode;
940 if (r->dtmfmode & SIP_DTMF_RFC2833)
941 r->noncodeccapability |= AST_RTP_DTMF;
943 r->noncodeccapability &= ~AST_RTP_DTMF;
945 strncpy(r->context, p->context,sizeof(r->context)-1);
946 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
947 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
948 if (p->addr.sin_addr.s_addr) {
949 r->sa.sin_addr = p->addr.sin_addr;
950 r->sa.sin_port = p->addr.sin_port;
952 r->sa.sin_addr = p->defaddr.sin_addr;
953 r->sa.sin_port = p->defaddr.sin_port;
955 memcpy(&r->recv, &r->sa, sizeof(r->recv));
966 ast_mutex_unlock(&peerl.lock);
968 if ((port=strchr(peer, ':'))) {
976 portno = DEFAULT_SIP_PORT;
981 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
982 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
988 hp = ast_gethostbyname(hostn, &ahp);
990 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
991 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
992 r->sa.sin_port = htons(portno);
993 memcpy(&r->recv, &r->sa, sizeof(r->recv));
996 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1012 static int auto_congest(void *nothing)
1014 struct sip_pvt *p = nothing;
1015 ast_mutex_lock(&p->lock);
1018 if (!ast_mutex_trylock(&p->owner->lock)) {
1019 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1020 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1021 ast_mutex_unlock(&p->owner->lock);
1024 ast_mutex_unlock(&p->lock);
1028 static void sip_prefs_free(void)
1030 struct sip_codec_pref *cur, *next;
1040 static void sip_pref_remove(int format)
1042 struct sip_codec_pref *cur, *prev=NULL;
1045 if (cur->codec == format) {
1047 prev->next = cur->next;
1058 static int sip_pref_append(int format)
1060 struct sip_codec_pref *cur, *tmp;
1061 sip_pref_remove(format);
1062 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
1065 memset(tmp, 0, sizeof(struct sip_codec_pref));
1066 tmp->codec = format;
1077 static int sip_codec_choose(int formats)
1079 struct sip_codec_pref *cur;
1080 formats &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1083 if (formats & cur->codec)
1087 return ast_best_codec(formats);
1090 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1094 char *vxml_url = NULL;
1095 char *distinctive_ring = NULL;
1096 struct varshead *headp;
1097 struct ast_var_t *current;
1100 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1101 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1104 /* Check whether there is vxml_url, distinctive ring variables */
1106 headp=&ast->varshead;
1107 AST_LIST_TRAVERSE(headp,current,entries) {
1108 /* Check whether there is a VXML_URL variable */
1109 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
1111 vxml_url = ast_var_value(current);
1114 /* Check whether there is a ALERT_INFO variable */
1115 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
1117 distinctive_ring = ast_var_value(current);
1124 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1125 res = update_user_counter(p,INC_OUT_USE);
1127 p->restrictcid = ast->restrictcid;
1128 p->jointcapability = p->capability;
1129 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
1131 /* Initialize auto-congest time */
1132 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1138 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1140 struct sip_pvt *cur, *prev = NULL;
1142 if (sip_debug_test_pvt(p))
1143 ast_verbose("Destroying call '%s'\n", p->callid);
1144 if (p->stateid > -1)
1145 ast_extension_state_del(p->stateid, NULL);
1147 ast_sched_del(sched, p->initid);
1148 if (p->autokillid > -1)
1149 ast_sched_del(sched, p->autokillid);
1152 ast_rtp_destroy(p->rtp);
1155 ast_rtp_destroy(p->vrtp);
1158 free_old_route(p->route);
1162 /* Carefully unlink from registry */
1163 struct sip_registry *reg;
1164 ast_mutex_lock(®l.lock);
1165 reg = regl.registrations;
1167 if ((reg == p->registry) && (p->registry->call == p))
1168 p->registry->call=NULL;
1171 ast_mutex_unlock(®l.lock);
1173 /* Unlink us from the owner if we have one */
1176 ast_mutex_lock(&p->owner->lock);
1177 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1178 p->owner->pvt->pvt = NULL;
1180 ast_mutex_unlock(&p->owner->lock);
1186 prev->next = cur->next;
1195 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1198 ast_sched_del(sched, p->initid);
1199 while((cp = p->packets)) {
1200 p->packets = p->packets->next;
1201 if (cp->retransid > -1)
1202 ast_sched_del(sched, cp->retransid);
1209 static int update_user_counter(struct sip_pvt *fup, int event)
1211 char name[256] = "";
1213 strncpy(name, fup->username, sizeof(name) - 1);
1214 ast_mutex_lock(&userl.lock);
1215 u = find_user(name);
1217 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1218 ast_mutex_unlock(&userl.lock);
1222 /* incoming and outgoing affects the inUse counter */
1225 if ( u->inUse > 0 ) {
1233 if (u->incominglimit > 0 ) {
1234 if (u->inUse >= u->incominglimit) {
1235 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
1236 /* inc inUse as well */
1237 if ( event == INC_OUT_USE ) {
1240 ast_mutex_unlock(&userl.lock);
1245 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1247 /* we don't use these anymore
1249 if ( u->outUse > 0 ) {
1256 if ( u->outgoinglimit > 0 ) {
1257 if ( u->outUse >= u->outgoinglimit ) {
1258 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1259 ast_mutex_unlock(&userl.lock);
1267 ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",u->name,event);
1269 ast_mutex_unlock(&userl.lock);
1273 static void sip_destroy(struct sip_pvt *p)
1275 ast_mutex_lock(&iflock);
1276 __sip_destroy(p, 1);
1277 ast_mutex_unlock(&iflock);
1280 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1282 static int hangup_sip2cause(int cause)
1287 return AST_CAUSE_BUSY;
1289 return AST_CAUSE_NORMAL;
1295 static char *hangup_cause2sip(int cause)
1299 case AST_CAUSE_BUSY:
1308 static int sip_hangup(struct ast_channel *ast)
1310 struct sip_pvt *p = ast->pvt->pvt;
1312 int needdestroy = 0;
1314 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1315 if (!ast->pvt->pvt) {
1316 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1319 ast_mutex_lock(&p->lock);
1320 if ( p->outgoing ) {
1321 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
1322 update_user_counter(p, DEC_OUT_USE);
1324 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
1325 update_user_counter(p, DEC_IN_USE);
1327 /* Determine how to disconnect */
1328 if (p->owner != ast) {
1329 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1330 ast_mutex_unlock(&p->lock);
1333 if (!ast || (ast->_state != AST_STATE_UP))
1338 ast_dsp_free(p->vad);
1341 ast->pvt->pvt = NULL;
1343 ast_mutex_lock(&usecnt_lock);
1345 ast_mutex_unlock(&usecnt_lock);
1346 ast_update_use_count();
1349 /* Start the process if it's not already started */
1350 if (!p->alreadygone && strlen(p->initreq.data)) {
1353 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
1354 /* Actually don't destroy us yet, wait for the 487 on our original
1355 INVITE, but do set an autodestruct just in case. */
1357 sip_scheddestroy(p, 15000);
1358 if ( p->initid != -1 ) {
1359 /* channel still up - reverse dec of inUse counter
1360 only if the channel is not auto-congested */
1361 if ( p->outgoing ) {
1362 update_user_counter(p, INC_OUT_USE);
1365 update_user_counter(p, INC_IN_USE);
1370 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1371 transmit_response_reliable(p, res, &p->initreq, 1);
1373 transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
1376 if (!p->pendinginvite) {
1378 transmit_request_with_auth(p, "BYE", 0, 1, 1);
1380 /* Note we will need a BYE when this all settles out
1381 but we can't send one while we have "INVITE" outstanding. */
1386 p->needdestroy = needdestroy;
1387 ast_mutex_unlock(&p->lock);
1391 static int sip_answer(struct ast_channel *ast)
1395 struct sip_pvt *p = ast->pvt->pvt;
1398 if (ast->_state != AST_STATE_UP) {
1402 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1404 fmt=ast_getformatbyname(codec);
1406 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1407 p->jointcapability=fmt;
1408 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1411 ast_setstate(ast, AST_STATE_UP);
1413 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1414 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1419 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1421 struct sip_pvt *p = ast->pvt->pvt;
1423 if (frame->frametype == AST_FRAME_VOICE) {
1424 if (!(frame->subclass & ast->nativeformats)) {
1425 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1426 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1430 ast_mutex_lock(&p->lock);
1432 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1433 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1436 res = ast_rtp_write(p->rtp, frame);
1438 ast_mutex_unlock(&p->lock);
1440 } else if (frame->frametype == AST_FRAME_VIDEO) {
1442 ast_mutex_lock(&p->lock);
1444 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1445 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1448 res = ast_rtp_write(p->vrtp, frame);
1450 ast_mutex_unlock(&p->lock);
1452 } else if (frame->frametype == AST_FRAME_IMAGE) {
1455 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1462 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1464 struct sip_pvt *p = newchan->pvt->pvt;
1465 ast_mutex_lock(&p->lock);
1466 if (p->owner != oldchan) {
1467 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1468 ast_mutex_unlock(&p->lock);
1472 ast_mutex_unlock(&p->lock);
1476 static int sip_senddigit(struct ast_channel *ast, char digit)
1478 struct sip_pvt *p = ast->pvt->pvt;
1479 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1480 transmit_info_with_digit(p, digit);
1482 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1483 ast_rtp_senddigit(p->rtp, digit);
1485 /* If in-band DTMF is desired, send that */
1486 if (p->dtmfmode & SIP_DTMF_INBAND)
1491 static int sip_transfer(struct ast_channel *ast, char *dest)
1493 struct sip_pvt *p = ast->pvt->pvt;
1495 res = transmit_refer(p, dest);
1499 static int sip_indicate(struct ast_channel *ast, int condition)
1501 struct sip_pvt *p = ast->pvt->pvt;
1503 case AST_CONTROL_RINGING:
1504 if (ast->_state == AST_STATE_RING) {
1506 transmit_response(p, "180 Ringing", &p->initreq);
1510 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1514 case AST_CONTROL_BUSY:
1515 if (ast->_state != AST_STATE_UP) {
1516 transmit_response(p, "486 Busy Here", &p->initreq);
1518 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1522 case AST_CONTROL_CONGESTION:
1523 if (ast->_state != AST_STATE_UP) {
1524 transmit_response(p, "503 Service Unavailable", &p->initreq);
1526 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1530 case AST_CONTROL_PROGRESS:
1531 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1532 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1540 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1548 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1550 struct ast_channel *tmp;
1552 tmp = ast_channel_alloc(1);
1554 /* Select our native format based on codec preference until we receive
1555 something from another device to the contrary. */
1556 if (i->jointcapability)
1557 tmp->nativeformats = sip_codec_choose(i->jointcapability);
1558 else if (i->capability)
1559 tmp->nativeformats = sip_codec_choose(i->capability);
1561 tmp->nativeformats = sip_codec_choose(capability);
1562 fmt = ast_best_codec(tmp->nativeformats);
1564 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1566 if (strchr(i->fromdomain,':'))
1568 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1572 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1575 if (i->dtmfmode & SIP_DTMF_INBAND) {
1576 i->vad = ast_dsp_new();
1577 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1579 ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
1581 tmp->fds[0] = ast_rtp_fd(i->rtp);
1582 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1584 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1585 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1587 if (state == AST_STATE_RING)
1589 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1590 tmp->writeformat = fmt;
1591 tmp->pvt->rawwriteformat = fmt;
1592 tmp->readformat = fmt;
1593 tmp->pvt->rawreadformat = fmt;
1595 tmp->pvt->send_text = sip_sendtext;
1596 tmp->pvt->call = sip_call;
1597 tmp->pvt->hangup = sip_hangup;
1598 tmp->pvt->answer = sip_answer;
1599 tmp->pvt->read = sip_read;
1600 tmp->pvt->write = sip_write;
1601 tmp->pvt->write_video = sip_write;
1602 tmp->pvt->indicate = sip_indicate;
1603 tmp->pvt->transfer = sip_transfer;
1604 tmp->pvt->fixup = sip_fixup;
1605 tmp->pvt->send_digit = sip_senddigit;
1607 tmp->pvt->bridge = ast_rtp_bridge;
1609 tmp->callgroup = i->callgroup;
1610 tmp->pickupgroup = i->pickupgroup;
1611 tmp->restrictcid = i->restrictcid;
1612 if (strlen(i->accountcode))
1613 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1615 tmp->amaflags = i->amaflags;
1616 if (strlen(i->language))
1617 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1619 ast_mutex_lock(&usecnt_lock);
1621 ast_mutex_unlock(&usecnt_lock);
1622 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1623 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1624 if (strlen(i->callerid))
1625 tmp->callerid = strdup(i->callerid);
1626 if (strlen(i->rdnis))
1627 tmp->rdnis = strdup(i->rdnis);
1628 if (strlen(i->exten) && strcmp(i->exten, "s"))
1629 tmp->dnid = strdup(i->exten);
1631 if (strlen(i->domain)) {
1632 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1634 ast_setstate(tmp, state);
1635 if (state != AST_STATE_DOWN) {
1636 if (ast_pbx_start(tmp)) {
1637 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1643 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1647 static struct cfalias {
1651 { "Content-Type", "c" },
1652 { "Content-Encoding", "e" },
1656 { "Content-Length", "l" },
1662 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1663 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1664 char* r = line + nameLen + 1;
1665 while (*r && (*r < 33)) ++r;
1672 static char *get_sdp(struct sip_request *req, char *name) {
1674 int len = strlen(name);
1677 for (x=0; x<req->lines; x++) {
1678 r = get_sdp_by_line(req->line[x], name, len);
1679 if (r[0] != '\0') return r;
1684 static void sdpLineNum_iterator_init(int* iterator) {
1688 static char* get_sdp_iterate(int* iterator,
1689 struct sip_request *req, char *name) {
1690 int len = strlen(name);
1692 while (*iterator < req->lines) {
1693 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1694 if (r[0] != '\0') return r;
1699 static char *__get_header(struct sip_request *req, char *name, int *start)
1702 int len = strlen(name);
1704 for (x=*start;x<req->headers;x++) {
1705 if (!strncasecmp(req->header[x], name, len) &&
1706 (req->header[x][len] == ':')) {
1707 r = req->header[x] + len + 1;
1708 while(*r && (*r < 33))
1715 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1716 if (!strcasecmp(aliases[x].fullname, name))
1717 return __get_header(req, aliases[x].shortname, start);
1719 /* Don't return NULL, so get_header is always a valid pointer */
1723 static char *get_header(struct sip_request *req, char *name)
1726 return __get_header(req, name, &start);
1729 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1731 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1732 struct ast_frame *f;
1733 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1736 f = ast_rtp_read(p->rtp);
1739 f = ast_rtcp_read(p->rtp);
1742 f = ast_rtp_read(p->vrtp);
1745 f = ast_rtcp_read(p->vrtp);
1750 /* Don't send RFC2833 if we're not supposed to */
1751 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1754 /* We already hold the channel lock */
1755 if (f->frametype == AST_FRAME_VOICE) {
1756 if (f->subclass != p->owner->nativeformats) {
1757 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1758 p->owner->nativeformats = f->subclass;
1759 ast_set_read_format(p->owner, p->owner->readformat);
1760 ast_set_write_format(p->owner, p->owner->writeformat);
1762 if ((p->dtmfmode & SIP_DTMF_INBAND) && p->vad) {
1763 f = ast_dsp_process(p->owner,p->vad,f);
1764 if (f && (f->frametype == AST_FRAME_DTMF))
1765 ast_log(LOG_DEBUG, "Detected DTMF '%c'\n", f->subclass);
1772 static struct ast_frame *sip_read(struct ast_channel *ast)
1774 struct ast_frame *fr;
1775 struct sip_pvt *p = ast->pvt->pvt;
1776 ast_mutex_lock(&p->lock);
1777 fr = sip_rtp_read(ast, p);
1778 ast_mutex_unlock(&p->lock);
1782 static void build_callid(char *callid, int len, struct in_addr ourip)
1789 res = snprintf(callid, len, "%08x", val);
1793 /* It's not important that we really use our right IP here... */
1794 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1797 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1801 p = malloc(sizeof(struct sip_pvt));
1804 /* Keep track of stuff */
1805 memset(p, 0, sizeof(struct sip_pvt));
1809 p->rtp = ast_rtp_new(sched, io, 1, 0);
1811 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1815 /* Start with 101 instead of 1 */
1818 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1822 ast_rtp_settos(p->rtp, tos);
1824 ast_rtp_settos(p->vrtp, tos);
1825 if (useglobalnat && sin) {
1826 /* Setup NAT structure according to global settings if we have an address */
1828 memcpy(&p->recv, sin, sizeof(p->recv));
1829 ast_rtp_setnat(p->rtp, p->nat);
1831 ast_rtp_setnat(p->vrtp, p->nat);
1833 ast_mutex_init(&p->lock);
1836 memcpy(&p->sa, sin, sizeof(p->sa));
1837 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1838 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1840 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1842 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1843 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1845 build_callid(p->callid, sizeof(p->callid), p->ourip);
1847 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1848 /* Assume reinvite OK and via INVITE */
1849 p->canreinvite = globalcanreinvite;
1850 p->dtmfmode = globaldtmfmode;
1851 p->capability = capability;
1852 if (p->dtmfmode & SIP_DTMF_RFC2833)
1853 p->noncodeccapability |= AST_RTP_DTMF;
1854 strncpy(p->context, context, sizeof(p->context) - 1);
1855 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1857 ast_mutex_lock(&iflock);
1860 ast_mutex_unlock(&iflock);
1862 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1866 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1874 callid = get_header(req, "Call-ID");
1876 if (pedanticsipchecking) {
1877 /* In principle Call-ID's uniquely identify a call, however some vendors
1878 (i.e. Pingtel) send multiple calls with the same Call-ID and different
1879 tags in order to simplify billing. The RFC does state that we have to
1880 compare tags in addition to the call-id, but this generate substantially
1881 more overhead which is totally unnecessary for the vast majority of sane
1882 SIP implementations, and thus Asterisk does not enable this behavior
1883 by default. Short version: You'll need this option to support conferencing
1885 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1887 c = strchr(tmp, ' ');
1890 if (!strcasecmp(cmd, "SIP/2.0")) {
1896 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1898 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1899 tag = strstr(tmp, "tag=");
1902 c = strchr(tag, ';');
1909 if (!strlen(callid)) {
1910 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1913 ast_mutex_lock(&iflock);
1916 if (!strcmp(p->callid, callid) &&
1917 (!pedanticsipchecking || !tag || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1918 /* Found the call */
1919 ast_mutex_lock(&p->lock);
1920 ast_mutex_unlock(&iflock);
1925 ast_mutex_unlock(&iflock);
1926 p = sip_alloc(callid, sin, 1);
1928 ast_mutex_lock(&p->lock);
1932 static int sip_register(char *value, int lineno)
1934 struct sip_registry *reg;
1935 char copy[256] = "";
1936 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1942 struct ast_hostent ahp;
1945 strncpy(copy, value, sizeof(copy)-1);
1948 hostname = strrchr(stringp, '@');
1953 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1954 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1958 username = strsep(&stringp, ":");
1960 secret = strsep(&stringp, ":");
1962 authuser = strsep(&stringp, ":");
1965 hostname = strsep(&stringp, "/");
1967 contact = strsep(&stringp, "/");
1968 if (!contact || !strlen(contact))
1971 hostname = strsep(&stringp, ":");
1972 porta = strsep(&stringp, ":");
1974 if (porta && !atoi(porta)) {
1975 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1978 hp = ast_gethostbyname(hostname, &ahp);
1980 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1983 reg = malloc(sizeof(struct sip_registry));
1985 memset(reg, 0, sizeof(struct sip_registry));
1986 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1988 strncpy(reg->username, username, sizeof(reg->username)-1);
1990 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1992 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1994 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1997 reg->refresh = default_expiry;
1998 reg->addr.sin_family = AF_INET;
1999 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
2000 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
2001 reg->callid_valid = 0;
2003 ast_mutex_lock(®l.lock);
2004 reg->next = regl.registrations;
2005 regl.registrations = reg;
2006 ast_mutex_unlock(®l.lock);
2008 ast_log(LOG_ERROR, "Out of memory\n");
2014 static int lws2sws(char *msgbuf, int len)
2020 /* Eliminate all CRs */
2021 if (msgbuf[h] == '\r') {
2025 /* Check for end-of-line */
2026 if (msgbuf[h] == '\n') {
2027 /* Check for end-of-message */
2030 /* Check for a continuation line */
2031 if (msgbuf[h + 1] == ' ') {
2032 /* Merge continuation line */
2036 /* Propagate LF and start new line */
2037 msgbuf[t++] = msgbuf[h++];
2042 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
2047 msgbuf[t++] = msgbuf[h++];
2051 msgbuf[t++] = msgbuf[h++];
2059 static void parse(struct sip_request *req)
2061 /* Divide fields by NULL's */
2066 /* First header starts immediately */
2070 /* We've got a new header */
2074 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2076 if (!strlen(req->header[f])) {
2077 /* Line by itself means we're now in content */
2081 if (f >= SIP_MAX_HEADERS - 1) {
2082 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2085 req->header[f] = c + 1;
2086 } else if (*c == '\r') {
2087 /* Ignore but eliminate \r's */
2092 /* Check for last header */
2093 if (strlen(req->header[f]))
2096 /* Now we process any mime content */
2101 /* We've got a new line */
2104 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2106 if (f >= SIP_MAX_LINES - 1) {
2107 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2110 req->line[f] = c + 1;
2111 } else if (*c == '\r') {
2112 /* Ignore and eliminate \r's */
2117 /* Check for last line */
2118 if (strlen(req->line[f]))
2122 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2125 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2134 int peercapability, peernoncodeccapability;
2135 int vpeercapability=0, vpeernoncodeccapability=0;
2136 struct sockaddr_in sin;
2139 struct ast_hostent ahp;
2145 /* Get codec and RTP info from SDP */
2146 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2147 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2150 m = get_sdp(req, "m");
2151 c = get_sdp(req, "c");
2152 if (!strlen(m) || !strlen(c)) {
2153 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2156 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2157 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2160 /* XXX This could block for a long time, and block the main thread! XXX */
2161 hp = ast_gethostbyname(host, &ahp);
2163 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2166 sdpLineNum_iterator_init(&iterator);
2167 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2168 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
2170 /* Scan through the RTP payload types specified in a "m=" line: */
2171 ast_rtp_pt_clear(p->rtp);
2173 while(strlen(codecs)) {
2174 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2175 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2178 if (sip_debug_test_pvt(p))
2179 ast_verbose("Found RTP audio format %d\n", codec);
2180 ast_rtp_set_m_type(p->rtp, codec);
2182 /* Skip over any whitespace */
2183 while(*codecs && (*codecs < 33)) codecs++;
2187 ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
2189 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2191 /* Scan through the RTP payload types specified in a "m=" line: */
2193 while(strlen(codecs)) {
2194 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2195 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2198 if (sip_debug_test_pvt(p))
2199 ast_verbose("Found video format %s\n", ast_getformatname(codec));
2200 ast_rtp_set_m_type(p->vrtp, codec);
2202 /* Skip over any whitespace */
2203 while(*codecs && (*codecs < 33)) codecs++;
2207 sin.sin_family = AF_INET;
2208 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2209 /* Setup audio port number */
2210 sin.sin_port = htons(portno);
2211 if (p->rtp && sin.sin_port)
2212 ast_rtp_set_peer(p->rtp, &sin);
2213 /* Setup video port number */
2214 sin.sin_port = htons(vportno);
2215 if (p->vrtp && sin.sin_port)
2216 ast_rtp_set_peer(p->vrtp, &sin);
2218 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2220 /* Next, scan through each "a=rtpmap:" line, noting each
2221 * specified RTP payload type (with corresponding MIME subtype):
2223 sdpLineNum_iterator_init(&iterator);
2224 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2225 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2226 if (!strcasecmp(a, "sendonly")) {
2230 if (!strcasecmp(a, "sendrecv")) {
2233 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2234 if (sip_debug_test_pvt(p))
2235 ast_verbose("Found description format %s\n", mimeSubtype);
2236 /* Note: should really look at the 'freq' and '#chans' params too */
2237 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2239 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2242 /* Now gather all of the codecs that were asked for: */
2243 ast_rtp_get_current_formats(p->rtp,
2244 &peercapability, &peernoncodeccapability);
2246 ast_rtp_get_current_formats(p->vrtp,
2247 &vpeercapability, &vpeernoncodeccapability);
2248 p->jointcapability = p->capability & (peercapability | vpeercapability);
2249 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
2251 if (sip_debug_test_pvt(p)) {
2252 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
2253 p->capability, peercapability, vpeercapability, p->jointcapability);
2254 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
2255 noncodeccapability, peernoncodeccapability,
2256 p->noncodeccapability);
2258 if (!p->jointcapability) {
2259 ast_log(LOG_WARNING, "No compatible codecs!\n");
2263 if (!(p->owner->nativeformats & p->jointcapability)) {
2264 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);
2265 p->owner->nativeformats = sip_codec_choose(p->jointcapability);
2266 ast_set_read_format(p->owner, p->owner->readformat);
2267 ast_set_write_format(p->owner, p->owner->writeformat);
2269 if (p->owner->bridge) {
2270 /* Turn on/off music on hold if we are holding/unholding */
2271 if (sin.sin_addr.s_addr && !sendonly) {
2272 ast_moh_stop(p->owner->bridge);
2274 ast_moh_start(p->owner->bridge, NULL);
2282 static int add_header(struct sip_request *req, char *var, char *value)
2284 if (req->len >= sizeof(req->data) - 4) {
2285 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2289 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2292 req->header[req->headers] = req->data + req->len;
2293 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2294 req->len += strlen(req->header[req->headers]);
2295 if (req->headers < SIP_MAX_HEADERS)
2298 ast_log(LOG_WARNING, "Out of header space\n");
2304 static int add_blank_header(struct sip_request *req)
2306 if (req->len >= sizeof(req->data) - 4) {
2307 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2311 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2314 req->header[req->headers] = req->data + req->len;
2315 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2316 req->len += strlen(req->header[req->headers]);
2317 if (req->headers < SIP_MAX_HEADERS)
2320 ast_log(LOG_WARNING, "Out of header space\n");
2326 static int add_line(struct sip_request *req, char *line)
2328 if (req->len >= sizeof(req->data) - 4) {
2329 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2333 /* Add extra empty return */
2334 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2335 req->len += strlen(req->data + req->len);
2337 req->line[req->lines] = req->data + req->len;
2338 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2339 req->len += strlen(req->line[req->lines]);
2340 if (req->lines < SIP_MAX_LINES)
2343 ast_log(LOG_WARNING, "Out of line space\n");
2349 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2352 tmp = get_header(orig, field);
2354 /* Add what we're responding to */
2355 return add_header(req, field, tmp);
2357 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2361 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2367 tmp = __get_header(orig, field, &start);
2369 /* Add what we're responding to */
2370 add_header(req, field, tmp);
2375 return copied ? 0 : -1;
2378 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2385 tmp = __get_header(orig, field, &start);
2387 if (!copied && p->nat) {
2388 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2389 /* SLD: FIXME: Nice try, but the received= should not have a port */
2390 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2391 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
2393 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2394 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2397 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2398 add_header(req, field, new);
2400 /* Add what we're responding to */
2401 add_header(req, field, tmp);
2408 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2414 /* Add Route: header into request per learned route */
2415 static void add_route(struct sip_request *req, struct sip_route *route)
2418 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2424 n = strlen(route->hop);
2425 if ((n+3)>rem) break;
2431 strcpy(p, route->hop); p += n;
2434 route = route->next;
2437 add_header(req, "Route", r);
2440 static void set_destination(struct sip_pvt *p, char *uri)
2442 char *h, *maddr, hostname[256];
2445 struct ast_hostent ahp;
2447 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2448 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2450 if (sip_debug_test_pvt(p))
2451 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2453 /* Find and parse hostname */
2454 h = strchr(uri, '@');
2459 if (strncmp(h, "sip:", 4) == 0)
2461 else if (strncmp(h, "sips:", 5) == 0)
2464 hn = strcspn(h, ":;>");
2466 strncpy(hostname, h, hn); hostname[hn] = '\0';
2469 /* Is "port" present? if not default to 5060 */
2473 port = strtol(h, &h, 10);
2478 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2479 maddr = strstr(h, "maddr=");
2482 hn = strspn(maddr, "0123456789.");
2484 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2487 hp = ast_gethostbyname(hostname, &ahp);
2489 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2492 p->sa.sin_family = AF_INET;
2493 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2494 p->sa.sin_port = htons(port);
2495 if (sip_debug_test_pvt(p))
2496 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2499 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2501 /* Initialize a response */
2502 if (req->headers || req->len) {
2503 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2506 req->header[req->headers] = req->data + req->len;
2507 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2508 req->len += strlen(req->header[req->headers]);
2509 if (req->headers < SIP_MAX_HEADERS)
2512 ast_log(LOG_WARNING, "Out of header space\n");
2516 static int init_req(struct sip_request *req, char *resp, char *recip)
2518 /* Initialize a response */
2519 if (req->headers || req->len) {
2520 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2523 req->header[req->headers] = req->data + req->len;
2524 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2525 req->len += strlen(req->header[req->headers]);
2526 if (req->headers < SIP_MAX_HEADERS)
2529 ast_log(LOG_WARNING, "Out of header space\n");
2533 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2535 char newto[256] = "", *ot;
2536 memset(resp, 0, sizeof(*resp));
2537 init_resp(resp, msg, req);
2538 copy_via_headers(p, resp, req, "Via");
2539 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2540 copy_header(resp, req, "From");
2541 ot = get_header(req, "To");
2542 if (!strstr(ot, "tag=")) {
2543 /* Add the proper tag if we don't have it already. If they have specified
2544 their tag, use it. Otherwise, use our own tag */
2545 if (strlen(p->theirtag) && p->outgoing)
2546 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2547 else if (p->tag && !p->outgoing)
2548 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2550 strncpy(newto, ot, sizeof(newto) - 1);
2553 add_header(resp, "To", ot);
2554 copy_header(resp, req, "Call-ID");
2555 copy_header(resp, req, "CSeq");
2556 add_header(resp, "User-Agent", "Asterisk PBX");
2557 add_header(resp, "Allow", ALLOWED_METHODS);
2559 /* For registration responses, we also need expiry and
2563 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2564 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2565 add_header(resp, "Expires", tmp);
2566 add_header(resp, "Contact", contact);
2568 add_header(resp, "Contact", p->our_contact);
2573 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno, int newbranch)
2575 struct sip_request *orig = &p->initreq;
2576 char stripped[80] ="";
2582 memset(req, 0, sizeof(struct sip_request));
2584 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2592 p->branch ^= rand();
2593 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2596 if (strlen(p->uri)) {
2600 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2602 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2604 c = strchr(stripped, '<');
2616 init_req(req, msg, c);
2618 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2620 add_header(req, "Via", p->via);
2622 set_destination(p, p->route->hop);
2623 add_route(req, p->route->next);
2626 ot = get_header(orig, "To");
2627 of = get_header(orig, "From");
2629 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2630 as our original request, including tag (or presumably lack thereof) */
2631 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2632 /* Add the proper tag if we don't have it already. If they have specified
2633 their tag, use it. Otherwise, use our own tag */
2634 if (p->outgoing && strlen(p->theirtag))
2635 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2636 else if (!p->outgoing)
2637 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2639 snprintf(newto, sizeof(newto), "%s", ot);
2644 add_header(req, "From", of);
2645 add_header(req, "To", ot);
2647 add_header(req, "From", ot);
2648 add_header(req, "To", of);
2650 add_header(req, "Contact", p->our_contact);
2651 copy_header(req, orig, "Call-ID");
2652 add_header(req, "CSeq", tmp);
2654 add_header(req, "User-Agent", "Asterisk PBX");
2658 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2660 struct sip_request resp;
2662 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2663 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2666 respprep(&resp, p, msg, req);
2667 add_header(&resp, "Content-Length", "0");
2668 add_blank_header(&resp);
2669 return send_response(p, &resp, reliable, seqno);
2672 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2674 return __transmit_response(p, msg, req, 0);
2676 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
2678 return __transmit_response(p, msg, req, fatal ? 2 : 1);
2681 static void append_date(struct sip_request *req)
2688 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2689 add_header(req, "Date", tmpdat);
2692 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2694 struct sip_request resp;
2695 respprep(&resp, p, msg, req);
2697 add_header(&resp, "Content-Length", "0");
2698 add_blank_header(&resp);
2699 return send_response(p, &resp, 0, 0);
2702 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2704 struct sip_request resp;
2705 respprep(&resp, p, msg, req);
2706 add_header(&resp, "Accept", "application/sdp");
2707 add_header(&resp, "Content-Length", "0");
2708 add_blank_header(&resp);
2709 return send_response(p, &resp, 0, 0);
2712 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2714 struct sip_request resp;
2717 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2718 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2721 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2722 respprep(&resp, p, msg, req);
2723 add_header(&resp, "Proxy-Authenticate", tmp);
2724 add_header(&resp, "Content-Length", "0");
2725 add_blank_header(&resp);
2726 return send_response(p, &resp, reliable, seqno);
2729 static int add_text(struct sip_request *req, char *text)
2731 /* XXX Convert \n's to \r\n's XXX */
2732 int len = strlen(text);
2734 snprintf(clen, sizeof(clen), "%d", len);
2735 add_header(req, "Content-Type", "text/plain");
2736 add_header(req, "Content-Length", clen);
2737 add_line(req, text);
2741 static int add_digit(struct sip_request *req, char digit)
2746 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2748 snprintf(clen, sizeof(clen), "%d", len);
2749 add_header(req, "Content-Type", "application/dtmf-relay");
2750 add_header(req, "Content-Length", clen);
2755 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2759 int alreadysent = 0;
2761 struct sockaddr_in sin;
2762 struct sockaddr_in vsin;
2763 struct sip_codec_pref *cur;
2774 struct sockaddr_in dest;
2775 struct sockaddr_in vdest = { 0, };
2776 /* XXX We break with the "recommendation" and send our IP, in order that our
2777 peer doesn't have to ast_gethostbyname() us XXX */
2780 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2783 if (!p->sessionid) {
2784 p->sessionid = getpid();
2785 p->sessionversion = p->sessionid;
2787 p->sessionversion++;
2788 ast_rtp_get_us(p->rtp, &sin);
2790 ast_rtp_get_us(p->vrtp, &vsin);
2792 if (p->redirip.sin_addr.s_addr) {
2793 dest.sin_port = p->redirip.sin_port;
2794 dest.sin_addr = p->redirip.sin_addr;
2796 ast_rtp_get_peer(rtp, &dest);
2798 dest.sin_addr = p->ourip;
2799 dest.sin_port = sin.sin_port;
2802 /* Determine video destination */
2804 if (p->vredirip.sin_addr.s_addr) {
2805 vdest.sin_port = p->vredirip.sin_port;
2806 vdest.sin_addr = p->vredirip.sin_addr;
2808 ast_rtp_get_peer(vrtp, &vdest);
2810 vdest.sin_addr = p->ourip;
2811 vdest.sin_port = vsin.sin_port;
2814 if (sip_debug_test_pvt(p))
2815 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2816 if (sip_debug_test_pvt(p) && p->vrtp)
2817 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2818 snprintf(v, sizeof(v), "v=0\r\n");
2819 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
2820 snprintf(s, sizeof(s), "s=session\r\n");
2821 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2822 snprintf(t, sizeof(t), "t=0 0\r\n");
2823 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2824 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2825 if (p->jointcapability & p->prefcodec) {
2826 if (sip_debug_test_pvt(p))
2827 ast_verbose("Answering/Requesting with root capability %d\n", p->prefcodec);
2828 codec = ast_rtp_lookup_code(p->rtp, 1, p->prefcodec);
2830 snprintf(costr, sizeof(costr), " %d", codec);
2831 if (p->prefcodec <= AST_FORMAT_MAX_AUDIO) {
2832 strncat(m, costr, sizeof(m) - strlen(m));
2833 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2834 strncat(a, costr, sizeof(a));
2836 strncat(m2, costr, sizeof(m2) - strlen(m2));
2837 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2838 strncat(a2, costr, sizeof(a2));
2841 alreadysent |= p->prefcodec;
2843 /* Start by sending our preferred codecs */
2846 if (p->jointcapability & cur->codec) {
2847 if (sip_debug_test_pvt(p))
2848 ast_verbose("Answering/Requesting with preferred capability %d\n", cur->codec);
2849 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2851 snprintf(costr, sizeof(costr), " %d", codec);
2852 if (cur->codec <= AST_FORMAT_MAX_AUDIO) {
2853 strncat(m, costr, sizeof(m) - strlen(m));
2854 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2855 strncat(a, costr, sizeof(a));
2857 strncat(m2, costr, sizeof(m2) - strlen(m2));
2858 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2859 strncat(a2, costr, sizeof(a2));
2863 alreadysent |= cur->codec;
2866 /* Now send any other common codecs, and non-codec formats: */
2867 for (x = 1; x <= (videosupport ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
2868 if ((p->jointcapability & x) && !(alreadysent & x)) {
2869 if (sip_debug_test_pvt(p))
2870 ast_verbose("Answering with capability %d\n", x);
2871 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2873 snprintf(costr, sizeof(costr), " %d", codec);
2874 if (x <= AST_FORMAT_MAX_AUDIO) {
2875 strncat(m, costr, sizeof(m) - strlen(m));
2876 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2877 strncat(a, costr, sizeof(a) - strlen(a));
2879 strncat(m2, costr, sizeof(m2) - strlen(m2));
2880 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2881 strncat(a2, costr, sizeof(a2) - strlen(a2));
2886 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2887 if (p->noncodeccapability & x) {
2888 if (sip_debug_test_pvt(p))
2889 ast_verbose("Answering with non-codec capability %d\n", x);
2890 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2892 snprintf(costr, sizeof(costr), " %d", codec);
2893 strncat(m, costr, sizeof(m) - strlen(m));
2894 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2895 strncat(a, costr, sizeof(a) - strlen(a));
2896 if (x == AST_RTP_DTMF) {
2897 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2898 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2900 strncat(a, costr, sizeof(a) - strlen(a));
2905 strncat(a, "a=silenceSupp:off - - - -\r\n", sizeof(a) - strlen(a));
2906 if (strlen(m) < sizeof(m) - 2)
2908 if (strlen(m2) < sizeof(m2) - 2)
2910 if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
2911 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
2912 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2913 if ((p->vrtp) && (p->jointcapability & VIDEO_CODEC_MASK)) /* only if video response is appropriate */
2914 len += strlen(m2) + strlen(a2);
2915 snprintf(costr, sizeof(costr), "%d", len);
2916 add_header(resp, "Content-Type", "application/sdp");
2917 add_header(resp, "Content-Length", costr);
2925 if ((p->vrtp) && (p->jointcapability & VIDEO_CODEC_MASK)) { /* only if video response is appropriate */
2932 static void copy_request(struct sip_request *dst,struct sip_request *src)
2936 offset = ((void *)dst) - ((void *)src);
2937 /* First copy stuff */
2938 memcpy(dst, src, sizeof(*dst));
2939 /* Now fix pointer arithmetic */
2940 for (x=0;x<src->headers;x++)
2941 dst->header[x] += offset;
2942 for (x=0;x<src->lines;x++)
2943 dst->line[x] += offset;
2946 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2948 struct sip_request resp;
2950 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2951 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2954 respprep(&resp, p, msg, req);
2955 add_sdp(&resp, p, NULL, NULL);
2956 return send_response(p, &resp, retrans, seqno);
2959 static int determine_firstline_parts( struct sip_request *req ) {
2964 cmd= req->header[0];
2965 while(*cmd && (*cmd < 33)) {
2972 while(*e && (*e > 32)) {
2975 /* Get the command */
2981 while( *e && ( *e < 33 ) ) {
2988 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2989 /* We have a response */
2991 len= strlen( req->rlPart2 );
2992 if( len < 2 ) { return -1; }
2994 while( *e && *e<33 ) {
2999 /* We have a request */
3002 if( !*e ) { return -1; }
3005 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3008 while( isspace( *(--e) ) ) {}
3018 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
3020 struct sip_request req;
3021 if (p->canreinvite == REINVITE_UPDATE)
3022 reqprep(&req, p, "UPDATE", 0, 1);
3024 reqprep(&req, p, "INVITE", 0, 1);
3026 add_header(&req, "Allow", ALLOWED_METHODS);
3027 add_sdp(&req, p, rtp, vrtp);
3028 /* Use this as the basis */
3029 copy_request(&p->initreq, &req);
3031 if (sip_debug_test_pvt(p))
3032 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3033 determine_firstline_parts(&p->initreq);
3034 p->lastinvite = p->ocseq;
3036 return send_request(p, &req, 1, p->ocseq);
3039 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
3041 char stripped[256]="";
3043 strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
3044 c = strchr(stripped, '<');
3056 strncpy(p->uri, c, sizeof(p->uri) - 1);
3059 static void build_contact(struct sip_pvt *p)
3061 /* Construct Contact: header */
3062 if (ourport != 5060)
3063 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
3065 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
3068 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
3075 char *l = callerid, *n=NULL;
3077 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
3079 if (p->owner && p->owner->callerid) {
3080 strcpy(cid, p->owner->callerid);
3081 ast_callerid_parse(cid, &n, &l);
3083 ast_shrink_phone_number(l);
3084 if (!l || !ast_isphonenumber(l))
3087 /* if user want's his callerid restricted */
3088 if (p->restrictcid) {
3089 l = CALLERID_UNKNOWN;
3092 if (!n || !strlen(n))
3094 /* Allow user to be overridden */
3095 if (strlen(p->fromuser))
3098 if ((ourport != 5060) && !strlen(p->fromdomain))
3099 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);
3101 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
3103 if (strlen(p->username)) {
3104 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
3105 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
3107 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
3109 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
3110 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
3112 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
3114 strncpy(p->uri, invite, sizeof(p->uri) - 1);
3115 /* If there is a VXML URL append it to the SIP URL */
3118 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
3122 snprintf(to, sizeof(to), "<%s>", invite );
3124 memset(req, 0, sizeof(struct sip_request));
3125 init_req(req, cmd, invite);
3126 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
3128 add_header(req, "Via", p->via);
3129 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
3130 * OTOH, then we won't have anything in p->route anyway */
3131 add_header(req, "From", from);
3132 strncpy(p->exten, l, sizeof(p->exten) - 1);
3134 add_header(req, "To", to);
3135 add_header(req, "Contact", p->our_contact);
3136 add_header(req, "Call-ID", p->callid);
3137 add_header(req, "CSeq", tmp);
3138 add_header(req, "User-Agent", "Asterisk PBX");
3141 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, int init)
3143 struct sip_request req;
3146 /* Bump branch even on initial requests */
3147 p->branch ^= rand();
3148 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
3149 initreqprep(&req, p, cmd, vxml_url);
3151 reqprep(&req, p, cmd, 0, 1);
3154 add_header(&req, authheader, auth);
3156 if (!strcasecmp(cmd, "REFER")) {
3157 if (strlen(p->refer_to))
3158 add_header(&req, "Refer-To", p->refer_to);
3159 if (strlen(p->referred_by))
3160 add_header(&req, "Referred-By", p->referred_by);
3163 if (distinctive_ring)
3165 add_header(&req, "Alert-info",distinctive_ring);
3167 add_header(&req, "Allow", ALLOWED_METHODS);
3169 add_sdp(&req, p, NULL, NULL);
3171 add_header(&req, "Content-Length", "0");
3172 add_blank_header(&req);
3175 if (!p->initreq.headers) {
3176 /* Use this as the basis */
3177 copy_request(&p->initreq, &req);
3179 if (sip_debug_test_pvt(p))
3180 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3181 determine_firstline_parts(&p->initreq);
3183 p->lastinvite = p->ocseq;
3184 return send_request(p, &req, init ? 2 : 1, p->ocseq);
3187 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
3190 char from[256], to[256];
3193 struct sip_request req;
3196 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
3198 c = ditch_braces(from);
3199 if (strncmp(c, "sip:", 4)) {
3200 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3203 if ((a = strchr(c, ';'))) {
3208 reqprep(&req, p, "NOTIFY", 0, 1);
3210 if (p->subscribed == 1) {
3211 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
3213 c = ditch_braces(to);
3214 if (strncmp(c, "sip:", 4)) {
3215 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3218 if ((a = strchr(c, ';'))) {
3223 add_header(&req, "Content-Type", "application/xpidf+xml");
3225 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
3227 else if (state==AST_EXTENSION_INUSE)
3233 sprintf(t, "<?xml version=\"1.0\"?>\n");
3234 t = tmp + strlen(tmp);
3235 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
3236 t = tmp + strlen(tmp);
3237 sprintf(t, "<presence>\n");
3238 t = tmp + strlen(tmp);
3239 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
3240 t = tmp + strlen(tmp);
3241 sprintf(t, "<atom id=\"%s\">\n", p->exten);
3242 t = tmp + strlen(tmp);
3243 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
3244 t = tmp + strlen(tmp);
3245 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
3246 t = tmp + strlen(tmp);
3247 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
3248 t = tmp + strlen(tmp);
3249 sprintf(t, "</address>\n</atom>\n</presence>\n");
3251 add_header(&req, "Event", "dialog");
3252 add_header(&req, "Content-Type", "application/dialog-info+xml");
3255 sprintf(t, "<?xml version=\"1.0\"?>\n");
3256 t = tmp + strlen(tmp);
3257 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);
3258 t = tmp + strlen(tmp);
3259 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
3260 t = tmp + strlen(tmp);
3261 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
3262 t = tmp + strlen(tmp);
3263 sprintf(t, "</dialog>\n</dialog-info>\n");
3265 if (t > tmp + sizeof(tmp))
3266 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
3268 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
3269 add_header(&req, "Content-Length", clen);
3270 add_line(&req, tmp);
3272 return send_request(p, &req, 1, p->ocseq);
3275 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
3277 struct sip_request req;
3281 initreqprep(&req, p, "NOTIFY", NULL);
3282 add_header(&req, "Event", "message-summary");
3283 add_header(&req, "Content-Type", notifymime);
3285 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
3286 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
3287 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
3288 add_header(&req, "Content-Length", clen);
3289 add_line(&req, tmp);
3290 add_line(&req, tmp2);
3292 if (!p->initreq.headers) {
3293 /* Use this as the basis */
3294 copy_request(&p->initreq, &req);
3296 if (sip_debug_test_pvt(p))
3297 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3298 determine_firstline_parts(&p->initreq);
3301 return send_request(p, &req, 1, p->ocseq);
3304 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
3306 static int sip_reregister(void *data)
3308 /* if we are here, we know that we need to reregister. */
3309 struct sip_registry *r=(struct sip_registry *)data;
3310 ast_mutex_lock(®l.lock);
3312 __sip_do_register(r);
3313 ast_mutex_unlock(®l.lock);
3318 static int __sip_do_register(struct sip_registry *r)
3321 res=transmit_register(r, "REGISTER", NULL, NULL);
3325 static int sip_reg_timeout(void *data)
3327 /* if we are here, our registration timed out, so we'll just do it over */
3328 struct sip_registry *r=data;
3331 ast_mutex_lock(®l.lock);
3332 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
3334 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
3335 in the single SIP manager thread. */
3341 r->regstate=REG_STATE_UNREGISTERED;
3343 res=transmit_register(r, "REGISTER", NULL, NULL);
3344 ast_mutex_unlock(®l.lock);
3348 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
3350 struct sip_request req;
3357 struct ast_hostent ahp;
3360 /* exit if we are already in process with this registrar ?*/
3361 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
3362 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
3368 ast_log(LOG_WARNING, "Already have a call??\n");
3373 if (!r->callid_valid) {
3374 build_callid(r->callid, sizeof(r->callid), __ourip);
3375 r->callid_valid = 1;
3377 p=sip_alloc( r->callid, &r->addr, 0);
3379 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
3385 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
3386 strncpy(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret)-1);
3387 if (strlen(r->authuser))
3388 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
3390 strncpy(p->peername, r->username, sizeof(p->peername)-1);
3391 strncpy(p->username, r->username, sizeof(p->username)-1);
3392 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
3395 check which address we should use in our contact header
3396 based on whether the remote host is on the external or
3397 internal network so we can register through nat
3399 if ((hp = ast_gethostbyname(r->hostname, &ahp))) {
3400 if (ast_sip_ouraddrfor((struct in_addr *)hp->h_addr, &p->ourip))
3401 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
3406 /* set up a timeout */
3408 if (r->timeout > -1) {
3409 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
3410 ast_sched_del(sched, r->timeout);
3412 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
3413 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
3416 if (strchr(r->username, '@')) {
3417 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
3418 snprintf(to, sizeof(to), "<sip:%s>", r->username);
3420 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
3421 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
3424 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
3425 strncpy(p->uri, addr, sizeof(p->uri) - 1);
3427 p->branch ^= rand();
3429 memset(&req, 0, sizeof(req));
3430 init_req(&req, cmd, addr);
3432 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
3433 p->ocseq = r->ocseq;
3435 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
3436 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
3437 add_header(&req, "Via", via);
3438 add_header(&req, "From", from);
3439 add_header(&req, "To", to);
3440 add_header(&req, "Call-ID", p->callid);
3441 add_header(&req, "CSeq", tmp);
3442 add_header(&req, "User-Agent", "Asterisk PBX");
3444 add_header(&req, authheader, auth);
3446 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
3447 add_header(&req, "Expires", tmp);
3448 add_header(&req, "Contact", p->our_contact);
3449 add_header(&req, "Event", "registration");
3450 add_header(&req, "Content-Length", "0");
3451 add_blank_header(&req);
3452 copy_request(&p->initreq, &req);
3454 if (sip_debug_test_pvt(p))
3455 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3456 determine_firstline_parts(&p->initreq);
3457 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
3458 return send_request(p, &req, 2, p->ocseq);
3461 static int transmit_message_with_text(struct sip_pvt *p, char *text)
3463 struct sip_request req;
3464 reqprep(&req, p, "MESSAGE", 0, 1);
3465 add_text(&req, text);
3466 return send_request(p, &req, 1, p->ocseq);
3469 static int transmit_refer(struct sip_pvt *p, char *dest)
3471 struct sip_request req;
3476 of = get_header(&p->initreq, "To");
3478 of = get_header(&p->initreq, "From");
3479 strncpy(from, of, sizeof(from) - 1);
3480 of = ditch_braces(from);
3481 strncpy(p->from,of,sizeof(p->from) - 1);
3482 if (strncmp(of, "sip:", 4)) {
3483 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3486 /* Get just the username part */
3487 if ((c = strchr(of, '@'))) {
3492 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
3494 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
3497 /* save in case we get 407 challenge */
3498 strncpy(p->refer_to, referto, sizeof(p->refer_to) - 1);
3499 strncpy(p->referred_by, p->our_contact, sizeof(p->referred_by) - 1);
3501 reqprep(&req, p, "REFER", 0, 1);
3502 add_header(&req, "Refer-To", referto);
3503 if (strlen(p->our_contact))
3504 add_header(&req, "Referred-By", p->our_contact);
3505 add_blank_header(&req);
3506 return send_request(p, &req, 1, p->ocseq);
3509 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
3511 struct sip_request req;
3512 reqprep(&req, p, "INFO", 0, 1);
3513 add_digit(&req, digit);
3514 return send_request(p, &req, 1, p->ocseq);
3517 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable, int newbranch)
3519 struct sip_request resp;
3520 reqprep(&resp, p, msg, seqno, newbranch);
3521 add_header(&resp, "Content-Length", "0");
3522 add_blank_header(&resp);
3523 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3526 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable, int newbranch)
3528 struct sip_request resp;
3529 reqprep(&resp, p, msg, seqno, newbranch);
3533 memset(digest,0,sizeof(digest));