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];
99 static char *desc = "Session Initiation Protocol (SIP)";
100 static char *type = "SIP";
101 static char *tdesc = "Session Initiation Protocol (SIP)";
102 static char *config = "sip.conf";
104 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
105 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
107 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
109 static char context[AST_MAX_EXTENSION] = "default";
111 static char language[MAX_LANGUAGE] = "";
113 static char callerid[AST_MAX_EXTENSION] = "asterisk";
115 static char fromdomain[AST_MAX_EXTENSION] = "";
117 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
119 static int srvlookup = 0;
121 static int pedanticsipchecking = 0;
123 static int autocreatepeer = 0;
125 static int usecnt =0;
126 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
128 /* Protect the interface list (of sip_pvt's) */
129 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
131 /* Protect the monitoring thread, so only one process can kill or start it, and not
132 when it's doing something critical. */
133 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
135 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
137 /* This is the thread for the monitor which checks for input on the channels
138 which are not currently in use. */
139 static pthread_t monitor_thread = AST_PTHREADT_NULL;
141 static int restart_monitor(void);
143 /* Codecs that we support by default: */
144 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
145 static int noncodeccapability = AST_RTP_DTMF;
147 static char ourhost[256];
148 static struct in_addr __ourip;
151 static int sipdebug = 0;
155 static int videosupport = 0;
157 static int globaldtmfmode = SIP_DTMF_RFC2833;
160 static int expiry = 900;
162 static struct sched_context *sched;
163 static struct io_context *io;
164 /* The private structures of the sip channels are linked for
165 selecting outgoing channels */
167 #define SIP_MAX_HEADERS 64
168 #define SIP_MAX_LINES 64
172 #define DEC_OUT_USE 2
173 #define INC_OUT_USE 3
175 static struct sip_codec_pref {
177 struct sip_codec_pref *next;
181 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
182 char *rlPart2; /* The Request URI or Response Status */
184 int headers; /* SIP Headers */
185 char *header[SIP_MAX_HEADERS];
186 int lines; /* SDP Content */
187 char *line[SIP_MAX_LINES];
188 char data[SIP_MAX_PACKET];
194 struct sip_route *next;
198 static struct sip_pvt {
199 ast_mutex_t lock; /* Channel private lock */
200 char callid[80]; /* Global CallID */
201 char randdata[80]; /* Random data */
202 unsigned int ocseq; /* Current outgoing seqno */
203 unsigned int icseq; /* Current incoming seqno */
204 unsigned int callgroup;
205 unsigned int pickupgroup;
206 int lastinvite; /* Last Cseq of invite */
207 int alreadygone; /* Whether or not we've already been destroyed by or peer */
208 int needdestroy; /* if we need to be destroyed */
209 int capability; /* Special capability */
210 int jointcapability; /* Supported capability at both ends */
211 int prefcodec; /* Preferred codec (outbound only) */
212 int noncodeccapability;
213 int outgoing; /* Outgoing or incoming call? */
214 int authtries; /* Times we've tried to authenticate */
215 int insecure; /* Don't check source port/ip */
216 int expiry; /* How long we take to expire */
217 int branch; /* One random number */
218 int canreinvite; /* Do we support reinvite */
219 int ringing; /* Have sent 180 ringing */
220 int progress; /* Have sent 183 message progress */
221 int tag; /* Another random number */
222 int nat; /* Whether to try to support NAT */
223 int sessionid; /* SDP Session ID */
224 int sessionversion; /* SDP Session Version */
225 struct sockaddr_in sa; /* Our peer */
226 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
227 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
228 struct sockaddr_in recv; /* Received as */
229 struct in_addr ourip; /* Our IP */
230 struct ast_channel *owner; /* Who owns us */
231 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
232 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
233 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
234 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
235 struct sip_pvt *refer_call; /* Call we are referring */
236 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
237 char remote_party_id[256];
239 char context[AST_MAX_EXTENSION];
240 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
241 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
242 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
243 char language[MAX_LANGUAGE];
244 char rdnis[256]; /* Referring DNIS */
245 char theirtag[256]; /* Their tag */
248 char uri[256]; /* Original requested URI */
249 char peersecret[256];
250 char peermd5secret[256];
251 char callerid[256]; /* Caller*ID */
252 int restrictcid; /* hide presentation from remote user */
254 char accountcode[20]; /* Account code */
255 char our_contact[256]; /* Our contact header */
256 char realm[256]; /* Authorization realm */
257 char nonce[256]; /* Authorization nonce */
258 char opaque[256]; /* Opaque nonsense */
259 char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
260 char domain[256]; /* Authorization nonce */
261 char lastmsg[256]; /* Last Message sent/received */
262 int amaflags; /* AMA Flags */
263 int pendinginvite; /* Any pending invite */
264 int pendingbye; /* Need to send bye after we ack? */
265 int gotrefer; /* Got a refer? */
266 struct sip_request initreq; /* Initial request */
268 int maxtime; /* Max time for first response */
269 int initid; /* Auto-congest ID if appropriate */
270 int autokillid; /* Auto-kill ID */
279 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
280 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
281 struct ast_rtp *rtp; /* RTP Session */
282 struct ast_rtp *vrtp; /* Video RTP session */
283 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
284 struct sip_pvt *next;
287 #define FLAG_RESPONSE (1 << 0)
288 #define FLAG_FATAL (1 << 1)
291 struct sip_pkt *next; /* Next packet */
292 int retrans; /* Retransmission number */
293 int seqno; /* Sequence number */
294 int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
295 struct sip_pvt *owner; /* Owner call */
296 int retransid; /* Retransmission ID */
297 int packetlen; /* Length of packet */
302 /* Users who can access various contexts */
309 char accountcode[20];
310 char language[MAX_LANGUAGE];
311 unsigned int callgroup;
312 unsigned int pickupgroup;
326 struct sip_user *next;
333 char context[80]; /* JK02: peers need context too to allow parking etc */
339 char mailbox[AST_MAX_EXTENSION];
349 unsigned int callgroup;
350 unsigned int pickupgroup;
352 struct sockaddr_in addr;
356 struct sip_pvt *call; /* Call pointer */
357 int pokeexpire; /* When to expire poke */
358 int lastms; /* How long last response took (in ms), or -1 for no response */
359 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
360 struct timeval ps; /* Ping send time */
362 struct sockaddr_in defaddr;
368 struct sip_peer *next;
371 static ast_mutex_t sip_reload_lock = AST_MUTEX_INITIALIZER;
372 static int sip_reloading = 0;
374 #define REG_STATE_UNREGISTERED 0
375 #define REG_STATE_REGSENT 1
376 #define REG_STATE_AUTHSENT 2
377 #define REG_STATE_REGISTERED 3
378 #define REG_STATE_REJECTED 4
379 #define REG_STATE_TIMEOUT 5
380 #define REG_STATE_NOAUTH 6
382 struct sip_registry {
383 struct sockaddr_in addr; /* Who we connect to for registration purposes */
384 char username[80]; /* Who we are registering as */
385 char authuser[80]; /* Who we *authenticate* as */
387 char secret[80]; /* Password or key name in []'s */
389 char contact[80]; /* Contact extension */
391 int expire; /* Sched ID of expiration */
392 int timeout; /* sched id of sip_reg_timeout */
393 int refresh; /* How often to refresh */
394 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
396 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
397 char callid[80]; /* Global CallID for this registry */
398 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
399 struct sockaddr_in us; /* Who the server thinks we are */
400 struct sip_registry *next;
403 static struct ast_user_list {
404 struct sip_user *users;
406 } userl = { NULL, AST_MUTEX_INITIALIZER };
408 static struct ast_peer_list {
409 struct sip_peer *peers;
411 } peerl = { NULL, AST_MUTEX_INITIALIZER };
413 static struct ast_register_list {
414 struct sip_registry *registrations;
417 } regl = { NULL, AST_MUTEX_INITIALIZER };
420 #define REINVITE_INVITE 1
421 #define REINVITE_UPDATE 2
423 static int __sip_do_register(struct sip_registry *r);
425 static int sipsock = -1;
426 static int globalnat = 0;
427 static int globalcanreinvite = REINVITE_INVITE;
430 static struct sockaddr_in bindaddr;
431 static struct sockaddr_in localnet;
432 static struct sockaddr_in localmask;
433 static struct sockaddr_in externip;
435 static struct ast_frame *sip_read(struct ast_channel *ast);
436 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
437 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
438 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
439 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
440 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
441 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
442 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
443 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
444 static int transmit_message_with_text(struct sip_pvt *p, char *text);
445 static int transmit_refer(struct sip_pvt *p, char *dest);
446 static struct sip_peer *temp_peer(char *name);
447 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
448 /* static char *getsipuri(char *header); */
449 static void free_old_route(struct sip_route *route);
450 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
451 static int update_user_counter(struct sip_pvt *fup, int event);
452 static void prune_peers(void);
453 static int sip_do_reload(void);
455 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
459 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
461 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
463 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));
468 static void sip_destroy(struct sip_pvt *p);
470 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
473 check to see if them is contained in our localnet/mask,
474 if not, use our externip for us, otherwise use the
475 real internal address in bindaddr
477 if (localnet.sin_addr.s_addr && externip.sin_addr.s_addr &&
478 ((htonl(them->s_addr) & htonl(localnet.sin_addr.s_addr)) != htonl(localnet.sin_addr.s_addr)))
479 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
480 else if (bindaddr.sin_addr.s_addr)
481 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
483 return ast_ouraddrfor(them, us);
487 static int retrans_pkt(void *data)
489 struct sip_pkt *pkt=data;
491 ast_mutex_lock(&pkt->owner->lock);
492 if (pkt->retrans < MAX_RETRANS) {
496 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));
498 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));
500 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
503 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");
505 if (pkt->flags & FLAG_FATAL) {
506 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
507 ast_mutex_unlock(&pkt->owner->lock);
509 ast_mutex_lock(&pkt->owner->lock);
511 if (pkt->owner->owner) {
512 /* XXX Potential deadlocK?? XXX */
513 ast_queue_hangup(pkt->owner->owner);
514 ast_mutex_unlock(&pkt->owner->owner->lock);
516 /* If no owner, destroy now */
517 pkt->owner->needdestroy = 1;
520 /* Okay, it's not fatal, just continue. XXX If we were nice, we'd free it now, rather than wait for the
521 end of the call XXX */
525 ast_mutex_unlock(&pkt->owner->lock);
529 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
532 pkt = malloc(sizeof(struct sip_pkt) + len);
535 memset(pkt, 0, sizeof(struct sip_pkt));
536 memcpy(pkt->data, data, len);
537 pkt->packetlen = len;
538 pkt->next = p->packets;
543 pkt->flags |= FLAG_FATAL;
544 /* Schedule retransmission */
545 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
546 pkt->next = p->packets;
548 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
549 if (!strncasecmp(pkt->data, "INVITE", 6)) {
550 /* Note this is a pending invite */
551 p->pendinginvite = seqno;
556 static int __sip_autodestruct(void *data)
558 struct sip_pvt *p = data;
560 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
562 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
563 ast_queue_hangup(p->owner);
570 static int sip_scheddestroy(struct sip_pvt *p, int ms)
573 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
574 if (p->autokillid > -1)
575 ast_sched_del(sched, p->autokillid);
576 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
580 static int sip_cancel_destroy(struct sip_pvt *p)
582 if (p->autokillid > -1)
583 ast_sched_del(sched, p->autokillid);
588 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
590 struct sip_pkt *cur, *prev = NULL;
595 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
596 if (!resp && (seqno == p->pendinginvite)) {
597 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
598 p->pendinginvite = 0;
601 /* this is our baby */
603 prev->next = cur->next;
605 p->packets = cur->next;
606 if (cur->retransid > -1)
607 ast_sched_del(sched, cur->retransid);
615 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
619 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
625 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
626 /* this is our baby */
627 if (cur->retransid > -1)
628 ast_sched_del(sched, cur->retransid);
635 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");
639 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
644 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));
646 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));
649 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
651 res = __sip_xmit(p, req->data, req->len);
657 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
662 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));
664 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));
667 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
669 res = __sip_xmit(p, req->data, req->len);
673 static char *ditch_braces(char *tmp)
677 if ((n = strchr(tmp, '<')) ) {
679 while(*c && *c != '>') c++;
681 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
690 static int sip_sendtext(struct ast_channel *ast, char *text)
692 struct sip_pvt *p = ast->pvt->pvt;
694 ast_verbose("Sending text %s on %s\n", text, ast->name);
697 if (!text || !strlen(text))
700 ast_verbose("Really sending text %s on %s\n", text, ast->name);
701 transmit_message_with_text(p, text);
707 static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
709 if (mysql && (strlen(peer) < 128)) {
714 name = alloca(strlen(peer) * 2 + 1);
715 uname = alloca(strlen(username) * 2 + 1);
717 mysql_real_escape_string(mysql, name, peer, strlen(peer));
718 mysql_real_escape_string(mysql, uname, username, strlen(username));
719 snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"",
720 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
721 ast_mutex_lock(&mysqllock);
722 if (mysql_real_query(mysql, query, strlen(query)))
723 ast_log(LOG_WARNING, "Unable to update database\n");
725 ast_mutex_unlock(&mysqllock);
729 static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
734 p = malloc(sizeof(struct sip_peer));
735 memset(p, 0, sizeof(struct sip_peer));
736 if (mysql && (!peer || (strlen(peer) < 128))) {
741 time_t regseconds, nowtime;
746 name = alloca(strlen(peer) * 2 + 1);
747 mysql_real_escape_string(mysql, name, peer, strlen(peer));
750 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));
752 snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE name=\"%s\"", name);
753 ast_mutex_lock(&mysqllock);
754 mysql_query(mysql, query);
755 if ((result = mysql_store_result(mysql))) {
756 if ((rowval = mysql_fetch_row(result))) {
757 numfields = mysql_num_fields(result);
758 fields = mysql_fetch_fields(result);
760 for (x=0;x<numfields;x++) {
762 if (!strcasecmp(fields[x].name, "secret")) {
763 strncpy(p->secret, rowval[x], sizeof(p->secret));
764 } else if (!strcasecmp(fields[x].name, "name")) {
765 strncpy(p->name, rowval[x], sizeof(p->name) - 1);
766 } else if (!strcasecmp(fields[x].name, "context")) {
767 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
768 } else if (!strcasecmp(fields[x].name, "username")) {
769 strncpy(p->username, rowval[x], sizeof(p->username) - 1);
770 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
771 inet_aton(rowval[x], &p->addr.sin_addr);
772 } else if (!strcasecmp(fields[x].name, "port")) {
773 if (sscanf(rowval[x], "%i", &port) != 1)
775 p->addr.sin_port = htons(port);
776 } else if (!strcasecmp(fields[x].name, "regseconds")) {
777 if (sscanf(rowval[x], "%li", ®seconds) != 1)
783 if (nowtime > regseconds)
784 memset(&p->addr, 0, sizeof(p->addr));
786 mysql_free_result(result);
789 ast_mutex_unlock(&mysqllock);
796 p->capability = capability;
798 p->dtmfmode = globaldtmfmode;
806 #endif /* MYSQL_FRIENDS */
808 static void update_peer(struct sip_peer *p, int expiry)
812 mysql_update_peer(p->name, &p->addr, p->username, expiry);
817 static struct sip_peer *find_peer(char *peer, struct sockaddr_in *sin)
819 struct sip_peer *p = NULL;
823 /* Find by peer name */
825 if (!strcasecmp(p->name, peer)) {
834 if (!inaddrcmp(&p->addr, sin) ||
836 (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))) {
845 p = mysql_peer(peer, sin);
852 static struct sip_user *find_user(char *name)
854 struct sip_user *u = NULL;
858 if (!strcasecmp(u->name, name)) {
867 static int create_addr(struct sip_pvt *r, char *peer)
870 struct ast_hostent ahp;
875 char host[256], *hostn;
877 r->sa.sin_family = AF_INET;
878 ast_mutex_lock(&peerl.lock);
879 p = find_peer(peer, NULL);
883 r->capability = p->capability;
886 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
887 ast_rtp_setnat(r->rtp, r->nat);
890 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
891 ast_rtp_setnat(r->vrtp, r->nat);
893 strncpy(r->peername, p->username, sizeof(r->peername)-1);
894 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
895 strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
896 strncpy(r->username, p->username, sizeof(r->username)-1);
897 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
898 if (!strlen(r->tohost)) {
899 if (p->addr.sin_addr.s_addr)
900 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
902 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
904 if (strlen(p->fromdomain))
905 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
906 if (strlen(p->fromuser))
907 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
908 r->insecure = p->insecure;
909 r->canreinvite = p->canreinvite;
910 r->maxtime = p->maxms;
911 r->callgroup = p->callgroup;
912 r->pickupgroup = p->pickupgroup;
914 r->dtmfmode = p->dtmfmode;
915 if (r->dtmfmode & SIP_DTMF_RFC2833)
916 r->noncodeccapability |= AST_RTP_DTMF;
918 r->noncodeccapability &= ~AST_RTP_DTMF;
920 strncpy(r->context, p->context,sizeof(r->context)-1);
921 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
922 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
923 if (p->addr.sin_addr.s_addr) {
924 r->sa.sin_addr = p->addr.sin_addr;
925 r->sa.sin_port = p->addr.sin_port;
927 r->sa.sin_addr = p->defaddr.sin_addr;
928 r->sa.sin_port = p->defaddr.sin_port;
930 memcpy(&r->recv, &r->sa, sizeof(r->recv));
941 ast_mutex_unlock(&peerl.lock);
943 if ((port=strchr(peer, ':'))) {
951 portno = DEFAULT_SIP_PORT;
956 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
957 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
963 hp = ast_gethostbyname(hostn, &ahp);
965 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
966 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
967 r->sa.sin_port = htons(portno);
968 memcpy(&r->recv, &r->sa, sizeof(r->recv));
971 ast_log(LOG_WARNING, "No such host: %s\n", peer);
987 static int auto_congest(void *nothing)
989 struct sip_pvt *p = nothing;
990 ast_mutex_lock(&p->lock);
993 if (!ast_mutex_trylock(&p->owner->lock)) {
994 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
995 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
996 ast_mutex_unlock(&p->owner->lock);
999 ast_mutex_unlock(&p->lock);
1003 static void sip_prefs_free(void)
1005 struct sip_codec_pref *cur, *next;
1015 static void sip_pref_remove(int format)
1017 struct sip_codec_pref *cur, *prev=NULL;
1020 if (cur->codec == format) {
1022 prev->next = cur->next;
1033 static int sip_pref_append(int format)
1035 struct sip_codec_pref *cur, *tmp;
1036 sip_pref_remove(format);
1037 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
1040 memset(tmp, 0, sizeof(struct sip_codec_pref));
1041 tmp->codec = format;
1052 static int sip_codec_choose(int formats)
1054 struct sip_codec_pref *cur;
1055 formats &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1058 if (formats & cur->codec)
1062 return ast_best_codec(formats);
1065 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1069 char *vxml_url = NULL;
1070 char *distinctive_ring = NULL;
1071 struct varshead *headp;
1072 struct ast_var_t *current;
1075 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1076 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1079 /* Check whether there is vxml_url, distinctive ring variables */
1081 headp=&ast->varshead;
1082 AST_LIST_TRAVERSE(headp,current,entries) {
1083 /* Check whether there is a VXML_URL variable */
1084 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
1086 vxml_url = ast_var_value(current);
1089 /* Check whether there is a ALERT_INFO variable */
1090 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
1092 distinctive_ring = ast_var_value(current);
1099 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1100 res = update_user_counter(p,INC_OUT_USE);
1102 p->restrictcid = ast->restrictcid;
1103 p->jointcapability = p->capability;
1104 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
1106 /* Initialize auto-congest time */
1107 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1113 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1115 struct sip_pvt *cur, *prev = NULL;
1118 ast_verbose("Destroying call '%s'\n", p->callid);
1119 if (p->stateid > -1)
1120 ast_extension_state_del(p->stateid, NULL);
1122 ast_sched_del(sched, p->initid);
1123 if (p->autokillid > -1)
1124 ast_sched_del(sched, p->autokillid);
1127 ast_rtp_destroy(p->rtp);
1130 ast_rtp_destroy(p->vrtp);
1133 free_old_route(p->route);
1137 /* Carefully unlink from registry */
1138 struct sip_registry *reg;
1139 ast_mutex_lock(®l.lock);
1140 reg = regl.registrations;
1142 if ((reg == p->registry) && (p->registry->call == p))
1143 p->registry->call=NULL;
1146 ast_mutex_unlock(®l.lock);
1148 /* Unlink us from the owner if we have one */
1151 ast_mutex_lock(&p->owner->lock);
1152 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1153 p->owner->pvt->pvt = NULL;
1155 ast_mutex_unlock(&p->owner->lock);
1161 prev->next = cur->next;
1170 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1173 ast_sched_del(sched, p->initid);
1174 while((cp = p->packets)) {
1175 p->packets = p->packets->next;
1176 if (cp->retransid > -1)
1177 ast_sched_del(sched, cp->retransid);
1184 static int update_user_counter(struct sip_pvt *fup, int event)
1186 char name[256] = "";
1188 strncpy(name, fup->username, sizeof(name) - 1);
1189 ast_mutex_lock(&userl.lock);
1190 u = find_user(name);
1192 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1193 ast_mutex_unlock(&userl.lock);
1197 /* incoming and outgoing affects the inUse counter */
1200 if ( u->inUse > 0 ) {
1208 if (u->incominglimit > 0 ) {
1209 if (u->inUse >= u->incominglimit) {
1210 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
1211 /* inc inUse as well */
1212 if ( event == INC_OUT_USE ) {
1215 ast_mutex_unlock(&userl.lock);
1220 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1222 /* we don't use these anymore
1224 if ( u->outUse > 0 ) {
1231 if ( u->outgoinglimit > 0 ) {
1232 if ( u->outUse >= u->outgoinglimit ) {
1233 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1234 ast_mutex_unlock(&userl.lock);
1242 ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",u->name,event);
1244 ast_mutex_unlock(&userl.lock);
1248 static void sip_destroy(struct sip_pvt *p)
1250 ast_mutex_lock(&iflock);
1251 __sip_destroy(p, 1);
1252 ast_mutex_unlock(&iflock);
1255 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1257 static int hangup_sip2cause(int cause)
1262 return AST_CAUSE_BUSY;
1264 return AST_CAUSE_NORMAL;
1270 static char *hangup_cause2sip(int cause)
1274 case AST_CAUSE_BUSY:
1283 static int sip_hangup(struct ast_channel *ast)
1285 struct sip_pvt *p = ast->pvt->pvt;
1287 int needdestroy = 0;
1289 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1290 if (!ast->pvt->pvt) {
1291 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1294 ast_mutex_lock(&p->lock);
1295 if ( p->outgoing ) {
1296 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
1297 update_user_counter(p, DEC_OUT_USE);
1299 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
1300 update_user_counter(p, DEC_IN_USE);
1302 /* Determine how to disconnect */
1303 if (p->owner != ast) {
1304 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1305 ast_mutex_unlock(&p->lock);
1308 if (!ast || (ast->_state != AST_STATE_UP))
1313 ast_dsp_free(p->vad);
1316 ast->pvt->pvt = NULL;
1318 ast_mutex_lock(&usecnt_lock);
1320 ast_mutex_unlock(&usecnt_lock);
1321 ast_update_use_count();
1324 /* Start the process if it's not already started */
1325 if (!p->alreadygone && strlen(p->initreq.data)) {
1328 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
1329 /* Actually don't destroy us yet, wait for the 487 on our original
1330 INVITE, but do set an autodestruct just in case. */
1332 sip_scheddestroy(p, 15000);
1333 if ( p->initid != -1 ) {
1334 /* channel still up - reverse dec of inUse counter
1335 only if the channel is not auto-congested */
1336 if ( p->outgoing ) {
1337 update_user_counter(p, INC_OUT_USE);
1340 update_user_counter(p, INC_IN_USE);
1345 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1346 transmit_response_reliable(p, res, &p->initreq, 1);
1348 transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
1351 if (!p->pendinginvite) {
1353 transmit_request_with_auth(p, "BYE", 0, 1, 1);
1355 /* Note we will need a BYE when this all settles out
1356 but we can't send one while we have "INVITE" outstanding. */
1361 p->needdestroy = needdestroy;
1362 ast_mutex_unlock(&p->lock);
1366 static int sip_answer(struct ast_channel *ast)
1370 struct sip_pvt *p = ast->pvt->pvt;
1373 if (ast->_state != AST_STATE_UP) {
1377 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1379 fmt=ast_getformatbyname(codec);
1381 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1382 p->jointcapability=fmt;
1383 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1386 ast_setstate(ast, AST_STATE_UP);
1388 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1389 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1394 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1396 struct sip_pvt *p = ast->pvt->pvt;
1398 if (frame->frametype == AST_FRAME_VOICE) {
1399 if (!(frame->subclass & ast->nativeformats)) {
1400 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1401 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1405 ast_mutex_lock(&p->lock);
1407 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1408 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1411 res = ast_rtp_write(p->rtp, frame);
1413 ast_mutex_unlock(&p->lock);
1415 } else if (frame->frametype == AST_FRAME_VIDEO) {
1417 ast_mutex_lock(&p->lock);
1419 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1420 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1423 res = ast_rtp_write(p->vrtp, frame);
1425 ast_mutex_unlock(&p->lock);
1427 } else if (frame->frametype == AST_FRAME_IMAGE) {
1430 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1437 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1439 struct sip_pvt *p = newchan->pvt->pvt;
1440 ast_mutex_lock(&p->lock);
1441 if (p->owner != oldchan) {
1442 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1443 ast_mutex_unlock(&p->lock);
1447 ast_mutex_unlock(&p->lock);
1451 static int sip_senddigit(struct ast_channel *ast, char digit)
1453 struct sip_pvt *p = ast->pvt->pvt;
1454 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1455 transmit_info_with_digit(p, digit);
1457 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1458 ast_rtp_senddigit(p->rtp, digit);
1460 /* If in-band DTMF is desired, send that */
1461 if (p->dtmfmode & SIP_DTMF_INBAND)
1466 static int sip_transfer(struct ast_channel *ast, char *dest)
1468 struct sip_pvt *p = ast->pvt->pvt;
1470 res = transmit_refer(p, dest);
1474 static int sip_indicate(struct ast_channel *ast, int condition)
1476 struct sip_pvt *p = ast->pvt->pvt;
1478 case AST_CONTROL_RINGING:
1479 if (ast->_state == AST_STATE_RING) {
1481 transmit_response(p, "180 Ringing", &p->initreq);
1485 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1489 case AST_CONTROL_BUSY:
1490 if (ast->_state != AST_STATE_UP) {
1491 transmit_response(p, "486 Busy Here", &p->initreq);
1493 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1497 case AST_CONTROL_CONGESTION:
1498 if (ast->_state != AST_STATE_UP) {
1499 transmit_response(p, "503 Service Unavailable", &p->initreq);
1501 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1505 case AST_CONTROL_PROGRESS:
1506 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1507 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1515 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1523 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1525 struct ast_channel *tmp;
1527 tmp = ast_channel_alloc(1);
1529 /* Select our native format based on codec preference until we receive
1530 something from another device to the contrary. */
1531 if (i->jointcapability)
1532 tmp->nativeformats = sip_codec_choose(i->jointcapability);
1533 else if (i->capability)
1534 tmp->nativeformats = sip_codec_choose(i->capability);
1536 tmp->nativeformats = sip_codec_choose(capability);
1537 fmt = ast_best_codec(tmp->nativeformats);
1539 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1541 if (strchr(i->fromdomain,':'))
1543 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1547 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1550 if (i->dtmfmode & SIP_DTMF_INBAND) {
1551 i->vad = ast_dsp_new();
1552 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1554 tmp->fds[0] = ast_rtp_fd(i->rtp);
1555 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1557 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1558 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1560 if (state == AST_STATE_RING)
1562 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1563 tmp->writeformat = fmt;
1564 tmp->pvt->rawwriteformat = fmt;
1565 tmp->readformat = fmt;
1566 tmp->pvt->rawreadformat = fmt;
1568 tmp->pvt->send_text = sip_sendtext;
1569 tmp->pvt->call = sip_call;
1570 tmp->pvt->hangup = sip_hangup;
1571 tmp->pvt->answer = sip_answer;
1572 tmp->pvt->read = sip_read;
1573 tmp->pvt->write = sip_write;
1574 tmp->pvt->write_video = sip_write;
1575 tmp->pvt->indicate = sip_indicate;
1576 tmp->pvt->transfer = sip_transfer;
1577 tmp->pvt->fixup = sip_fixup;
1578 tmp->pvt->send_digit = sip_senddigit;
1580 tmp->pvt->bridge = ast_rtp_bridge;
1582 tmp->callgroup = i->callgroup;
1583 tmp->pickupgroup = i->pickupgroup;
1584 tmp->restrictcid = i->restrictcid;
1585 if (strlen(i->accountcode))
1586 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1588 tmp->amaflags = i->amaflags;
1589 if (strlen(i->language))
1590 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1592 ast_mutex_lock(&usecnt_lock);
1594 ast_mutex_unlock(&usecnt_lock);
1595 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1596 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1597 if (strlen(i->callerid))
1598 tmp->callerid = strdup(i->callerid);
1599 if (strlen(i->rdnis))
1600 tmp->rdnis = strdup(i->rdnis);
1601 if (strlen(i->exten) && strcmp(i->exten, "s"))
1602 tmp->dnid = strdup(i->exten);
1604 if (strlen(i->domain)) {
1605 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1607 ast_setstate(tmp, state);
1608 if (state != AST_STATE_DOWN) {
1609 if (ast_pbx_start(tmp)) {
1610 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1616 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1620 static struct cfalias {
1624 { "Content-Type", "c" },
1625 { "Content-Encoding", "e" },
1629 { "Content-Length", "l" },
1635 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1636 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1637 char* r = line + nameLen + 1;
1638 while (*r && (*r < 33)) ++r;
1645 static char *get_sdp(struct sip_request *req, char *name) {
1647 int len = strlen(name);
1650 for (x=0; x<req->lines; x++) {
1651 r = get_sdp_by_line(req->line[x], name, len);
1652 if (r[0] != '\0') return r;
1657 static void sdpLineNum_iterator_init(int* iterator) {
1661 static char* get_sdp_iterate(int* iterator,
1662 struct sip_request *req, char *name) {
1663 int len = strlen(name);
1665 while (*iterator < req->lines) {
1666 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1667 if (r[0] != '\0') return r;
1672 static char *__get_header(struct sip_request *req, char *name, int *start)
1675 int len = strlen(name);
1677 for (x=*start;x<req->headers;x++) {
1678 if (!strncasecmp(req->header[x], name, len) &&
1679 (req->header[x][len] == ':')) {
1680 r = req->header[x] + len + 1;
1681 while(*r && (*r < 33))
1688 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1689 if (!strcasecmp(aliases[x].fullname, name))
1690 return __get_header(req, aliases[x].shortname, start);
1692 /* Don't return NULL, so get_header is always a valid pointer */
1696 static char *get_header(struct sip_request *req, char *name)
1699 return __get_header(req, name, &start);
1702 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1704 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1705 struct ast_frame *f;
1706 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1709 f = ast_rtp_read(p->rtp);
1712 f = ast_rtcp_read(p->rtp);
1715 f = ast_rtp_read(p->vrtp);
1718 f = ast_rtcp_read(p->vrtp);
1723 /* Don't send RFC2833 if we're not supposed to */
1724 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1727 /* We already hold the channel lock */
1728 if (f->frametype == AST_FRAME_VOICE) {
1729 if (f->subclass != p->owner->nativeformats) {
1730 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1731 p->owner->nativeformats = f->subclass;
1732 ast_set_read_format(p->owner, p->owner->readformat);
1733 ast_set_write_format(p->owner, p->owner->writeformat);
1735 if ((p->dtmfmode & SIP_DTMF_INBAND) && p->vad) {
1736 f = ast_dsp_process(p->owner,p->vad,f);
1743 static struct ast_frame *sip_read(struct ast_channel *ast)
1745 struct ast_frame *fr;
1746 struct sip_pvt *p = ast->pvt->pvt;
1747 ast_mutex_lock(&p->lock);
1748 fr = sip_rtp_read(ast, p);
1749 ast_mutex_unlock(&p->lock);
1753 static void build_callid(char *callid, int len, struct in_addr ourip)
1760 res = snprintf(callid, len, "%08x", val);
1764 /* It's not important that we really use our right IP here... */
1765 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1768 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1772 p = malloc(sizeof(struct sip_pvt));
1775 /* Keep track of stuff */
1776 memset(p, 0, sizeof(struct sip_pvt));
1780 p->rtp = ast_rtp_new(sched, io, 1, 0);
1782 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1786 /* Start with 101 instead of 1 */
1789 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1793 ast_rtp_settos(p->rtp, tos);
1795 ast_rtp_settos(p->vrtp, tos);
1796 if (useglobalnat && sin) {
1797 /* Setup NAT structure according to global settings if we have an address */
1799 memcpy(&p->recv, sin, sizeof(p->recv));
1800 ast_rtp_setnat(p->rtp, p->nat);
1802 ast_rtp_setnat(p->vrtp, p->nat);
1804 ast_mutex_init(&p->lock);
1807 memcpy(&p->sa, sin, sizeof(p->sa));
1808 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1809 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1811 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1813 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1814 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1816 build_callid(p->callid, sizeof(p->callid), p->ourip);
1818 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1819 /* Assume reinvite OK and via INVITE */
1820 p->canreinvite = globalcanreinvite;
1821 p->dtmfmode = globaldtmfmode;
1822 p->capability = capability;
1823 if (p->dtmfmode & SIP_DTMF_RFC2833)
1824 p->noncodeccapability |= AST_RTP_DTMF;
1825 strncpy(p->context, context, sizeof(p->context) - 1);
1826 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1828 ast_mutex_lock(&iflock);
1831 ast_mutex_unlock(&iflock);
1833 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1837 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1845 callid = get_header(req, "Call-ID");
1847 if (pedanticsipchecking) {
1848 /* In principle Call-ID's uniquely identify a call, however some vendors
1849 (i.e. Pingtel) send multiple calls with the same Call-ID and different
1850 tags in order to simplify billing. The RFC does state that we have to
1851 compare tags in addition to the call-id, but this generate substantially
1852 more overhead which is totally unnecessary for the vast majority of sane
1853 SIP implementations, and thus Asterisk does not enable this behavior
1854 by default. Short version: You'll need this option to support conferencing
1856 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1858 c = strchr(tmp, ' ');
1861 if (!strcasecmp(cmd, "SIP/2.0")) {
1867 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1869 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1870 tag = strstr(tmp, "tag=");
1873 c = strchr(tag, ';');
1880 if (!strlen(callid)) {
1881 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1884 ast_mutex_lock(&iflock);
1887 if (!strcmp(p->callid, callid) &&
1888 (!pedanticsipchecking || !tag || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1889 /* Found the call */
1890 ast_mutex_lock(&p->lock);
1891 ast_mutex_unlock(&iflock);
1896 ast_mutex_unlock(&iflock);
1897 p = sip_alloc(callid, sin, 1);
1899 ast_mutex_lock(&p->lock);
1903 static int sip_register(char *value, int lineno)
1905 struct sip_registry *reg;
1906 char copy[256] = "";
1907 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1913 struct ast_hostent ahp;
1916 strncpy(copy, value, sizeof(copy)-1);
1919 hostname = strrchr(stringp, '@');
1924 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1925 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1929 username = strsep(&stringp, ":");
1931 secret = strsep(&stringp, ":");
1933 authuser = strsep(&stringp, ":");
1936 hostname = strsep(&stringp, "/");
1938 contact = strsep(&stringp, "/");
1939 if (!contact || !strlen(contact))
1942 hostname = strsep(&stringp, ":");
1943 porta = strsep(&stringp, ":");
1945 if (porta && !atoi(porta)) {
1946 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1949 hp = ast_gethostbyname(hostname, &ahp);
1951 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1954 reg = malloc(sizeof(struct sip_registry));
1956 memset(reg, 0, sizeof(struct sip_registry));
1957 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1959 strncpy(reg->username, username, sizeof(reg->username)-1);
1961 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1963 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1965 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1968 reg->refresh = default_expiry;
1969 reg->addr.sin_family = AF_INET;
1970 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1971 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1972 reg->callid_valid = 0;
1974 ast_mutex_lock(®l.lock);
1975 reg->next = regl.registrations;
1976 regl.registrations = reg;
1977 ast_mutex_unlock(®l.lock);
1979 ast_log(LOG_ERROR, "Out of memory\n");
1985 static int lws2sws(char *msgbuf, int len)
1991 /* Eliminate all CRs */
1992 if (msgbuf[h] == '\r') {
1996 /* Check for end-of-line */
1997 if (msgbuf[h] == '\n') {
1998 /* Check for end-of-message */
2001 /* Check for a continuation line */
2002 if (msgbuf[h + 1] == ' ') {
2003 /* Merge continuation line */
2007 /* Propagate LF and start new line */
2008 msgbuf[t++] = msgbuf[h++];
2013 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
2018 msgbuf[t++] = msgbuf[h++];
2022 msgbuf[t++] = msgbuf[h++];
2030 static void parse(struct sip_request *req)
2032 /* Divide fields by NULL's */
2037 /* First header starts immediately */
2041 /* We've got a new header */
2045 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2047 if (!strlen(req->header[f])) {
2048 /* Line by itself means we're now in content */
2052 if (f >= SIP_MAX_HEADERS - 1) {
2053 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2056 req->header[f] = c + 1;
2057 } else if (*c == '\r') {
2058 /* Ignore but eliminate \r's */
2063 /* Check for last header */
2064 if (strlen(req->header[f]))
2067 /* Now we process any mime content */
2072 /* We've got a new line */
2075 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2077 if (f >= SIP_MAX_LINES - 1) {
2078 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2081 req->line[f] = c + 1;
2082 } else if (*c == '\r') {
2083 /* Ignore and eliminate \r's */
2088 /* Check for last line */
2089 if (strlen(req->line[f]))
2093 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
2095 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2098 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2107 int peercapability, peernoncodeccapability;
2108 int vpeercapability=0, vpeernoncodeccapability=0;
2109 struct sockaddr_in sin;
2112 struct ast_hostent ahp;
2118 /* Get codec and RTP info from SDP */
2119 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2120 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2123 m = get_sdp(req, "m");
2124 c = get_sdp(req, "c");
2125 if (!strlen(m) || !strlen(c)) {
2126 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2129 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2130 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2133 /* XXX This could block for a long time, and block the main thread! XXX */
2134 hp = ast_gethostbyname(host, &ahp);
2136 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2139 sdpLineNum_iterator_init(&iterator);
2140 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2141 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
2143 /* Scan through the RTP payload types specified in a "m=" line: */
2144 ast_rtp_pt_clear(p->rtp);
2146 while(strlen(codecs)) {
2147 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2148 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2152 ast_verbose("Found audio format %s\n", ast_getformatname(codec));
2153 ast_rtp_set_m_type(p->rtp, codec);
2155 /* Skip over any whitespace */
2156 while(*codecs && (*codecs < 33)) codecs++;
2160 ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
2162 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2164 /* Scan through the RTP payload types specified in a "m=" line: */
2166 while(strlen(codecs)) {
2167 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2168 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2172 ast_verbose("Found video format %s\n", ast_getformatname(codec));
2173 ast_rtp_set_m_type(p->vrtp, codec);
2175 /* Skip over any whitespace */
2176 while(*codecs && (*codecs < 33)) codecs++;
2180 sin.sin_family = AF_INET;
2181 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2182 /* Setup audio port number */
2183 sin.sin_port = htons(portno);
2184 if (p->rtp && sin.sin_port)
2185 ast_rtp_set_peer(p->rtp, &sin);
2186 /* Setup video port number */
2187 sin.sin_port = htons(vportno);
2188 if (p->vrtp && sin.sin_port)
2189 ast_rtp_set_peer(p->vrtp, &sin);
2191 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2193 /* Next, scan through each "a=rtpmap:" line, noting each
2194 * specified RTP payload type (with corresponding MIME subtype):
2196 sdpLineNum_iterator_init(&iterator);
2197 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2198 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2199 if (!strcasecmp(a, "sendonly")) {
2203 if (!strcasecmp(a, "sendrecv")) {
2206 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2208 ast_verbose("Found description format %s\n", mimeSubtype);
2209 /* Note: should really look at the 'freq' and '#chans' params too */
2210 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2212 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2215 /* Now gather all of the codecs that were asked for: */
2216 ast_rtp_get_current_formats(p->rtp,
2217 &peercapability, &peernoncodeccapability);
2219 ast_rtp_get_current_formats(p->vrtp,
2220 &vpeercapability, &vpeernoncodeccapability);
2221 p->jointcapability = p->capability & (peercapability | vpeercapability);
2222 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
2225 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
2226 p->capability, peercapability, vpeercapability, p->jointcapability);
2227 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
2228 noncodeccapability, peernoncodeccapability,
2229 p->noncodeccapability);
2231 if (!p->jointcapability) {
2232 ast_log(LOG_WARNING, "No compatible codecs!\n");
2236 if (!(p->owner->nativeformats & p->jointcapability)) {
2237 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);
2238 p->owner->nativeformats = sip_codec_choose(p->jointcapability);
2239 ast_set_read_format(p->owner, p->owner->readformat);
2240 ast_set_write_format(p->owner, p->owner->writeformat);
2242 if (p->owner->bridge) {
2243 /* Turn on/off music on hold if we are holding/unholding */
2244 if (sin.sin_addr.s_addr && !sendonly) {
2245 ast_moh_stop(p->owner->bridge);
2247 ast_moh_start(p->owner->bridge, NULL);
2255 static int add_header(struct sip_request *req, char *var, char *value)
2257 if (req->len >= sizeof(req->data) - 4) {
2258 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2262 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2265 req->header[req->headers] = req->data + req->len;
2266 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2267 req->len += strlen(req->header[req->headers]);
2268 if (req->headers < SIP_MAX_HEADERS)
2271 ast_log(LOG_WARNING, "Out of header space\n");
2277 static int add_blank_header(struct sip_request *req)
2279 if (req->len >= sizeof(req->data) - 4) {
2280 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2284 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2287 req->header[req->headers] = req->data + req->len;
2288 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2289 req->len += strlen(req->header[req->headers]);
2290 if (req->headers < SIP_MAX_HEADERS)
2293 ast_log(LOG_WARNING, "Out of header space\n");
2299 static int add_line(struct sip_request *req, char *line)
2301 if (req->len >= sizeof(req->data) - 4) {
2302 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2306 /* Add extra empty return */
2307 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2308 req->len += strlen(req->data + req->len);
2310 req->line[req->lines] = req->data + req->len;
2311 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2312 req->len += strlen(req->line[req->lines]);
2313 if (req->lines < SIP_MAX_LINES)
2316 ast_log(LOG_WARNING, "Out of line space\n");
2322 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2325 tmp = get_header(orig, field);
2327 /* Add what we're responding to */
2328 return add_header(req, field, tmp);
2330 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2334 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2340 tmp = __get_header(orig, field, &start);
2342 /* Add what we're responding to */
2343 add_header(req, field, tmp);
2348 return copied ? 0 : -1;
2351 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2358 tmp = __get_header(orig, field, &start);
2360 if (!copied && p->nat) {
2361 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2362 /* SLD: FIXME: Nice try, but the received= should not have a port */
2363 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2364 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
2366 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2367 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2370 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2371 add_header(req, field, new);
2373 /* Add what we're responding to */
2374 add_header(req, field, tmp);
2381 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2387 /* Add Route: header into request per learned route */
2388 static void add_route(struct sip_request *req, struct sip_route *route)
2391 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2397 n = strlen(route->hop);
2398 if ((n+3)>rem) break;
2404 strcpy(p, route->hop); p += n;
2407 route = route->next;
2410 add_header(req, "Route", r);
2413 static void set_destination(struct sip_pvt *p, char *uri)
2415 char *h, *maddr, hostname[256];
2418 struct ast_hostent ahp;
2420 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2421 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2424 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2426 /* Find and parse hostname */
2427 h = strchr(uri, '@');
2432 if (strncmp(h, "sip:", 4) == 0)
2434 else if (strncmp(h, "sips:", 5) == 0)
2437 hn = strcspn(h, ":;>");
2439 strncpy(hostname, h, hn); hostname[hn] = '\0';
2442 /* Is "port" present? if not default to 5060 */
2446 port = strtol(h, &h, 10);
2451 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2452 maddr = strstr(h, "maddr=");
2455 hn = strspn(maddr, "0123456789.");
2457 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2460 hp = ast_gethostbyname(hostname, &ahp);
2462 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2465 p->sa.sin_family = AF_INET;
2466 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2467 p->sa.sin_port = htons(port);
2469 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2472 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2474 /* Initialize a response */
2475 if (req->headers || req->len) {
2476 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2479 req->header[req->headers] = req->data + req->len;
2480 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2481 req->len += strlen(req->header[req->headers]);
2482 if (req->headers < SIP_MAX_HEADERS)
2485 ast_log(LOG_WARNING, "Out of header space\n");
2489 static int init_req(struct sip_request *req, char *resp, char *recip)
2491 /* Initialize a response */
2492 if (req->headers || req->len) {
2493 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2496 req->header[req->headers] = req->data + req->len;
2497 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2498 req->len += strlen(req->header[req->headers]);
2499 if (req->headers < SIP_MAX_HEADERS)
2502 ast_log(LOG_WARNING, "Out of header space\n");
2506 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2508 char newto[256] = "", *ot;
2509 memset(resp, 0, sizeof(*resp));
2510 init_resp(resp, msg, req);
2511 copy_via_headers(p, resp, req, "Via");
2512 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2513 copy_header(resp, req, "From");
2514 ot = get_header(req, "To");
2515 if (!strstr(ot, "tag=")) {
2516 /* Add the proper tag if we don't have it already. If they have specified
2517 their tag, use it. Otherwise, use our own tag */
2518 if (strlen(p->theirtag) && p->outgoing)
2519 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2520 else if (p->tag && !p->outgoing)
2521 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2523 strncpy(newto, ot, sizeof(newto) - 1);
2526 add_header(resp, "To", ot);
2527 copy_header(resp, req, "Call-ID");
2528 copy_header(resp, req, "CSeq");
2529 add_header(resp, "User-Agent", "Asterisk PBX");
2530 add_header(resp, "Allow", ALLOWED_METHODS);
2532 /* For registration responses, we also need expiry and
2536 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2537 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2538 add_header(resp, "Expires", tmp);
2539 add_header(resp, "Contact", contact);
2541 add_header(resp, "Contact", p->our_contact);
2546 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno, int newbranch)
2548 struct sip_request *orig = &p->initreq;
2549 char stripped[80] ="";
2555 memset(req, 0, sizeof(struct sip_request));
2557 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2565 p->branch ^= rand();
2566 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2569 if (strlen(p->uri)) {
2573 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2575 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2577 c = strchr(stripped, '<');
2589 init_req(req, msg, c);
2591 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2593 add_header(req, "Via", p->via);
2595 set_destination(p, p->route->hop);
2596 add_route(req, p->route->next);
2599 ot = get_header(orig, "To");
2600 of = get_header(orig, "From");
2602 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2603 as our original request, including tag (or presumably lack thereof) */
2604 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2605 /* Add the proper tag if we don't have it already. If they have specified
2606 their tag, use it. Otherwise, use our own tag */
2607 if (p->outgoing && strlen(p->theirtag))
2608 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2609 else if (!p->outgoing)
2610 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2612 snprintf(newto, sizeof(newto), "%s", ot);
2617 add_header(req, "From", of);
2618 add_header(req, "To", ot);
2620 add_header(req, "From", ot);
2621 add_header(req, "To", of);
2623 add_header(req, "Contact", p->our_contact);
2624 copy_header(req, orig, "Call-ID");
2625 add_header(req, "CSeq", tmp);
2627 add_header(req, "User-Agent", "Asterisk PBX");
2631 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2633 struct sip_request resp;
2635 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2636 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2639 respprep(&resp, p, msg, req);
2640 add_header(&resp, "Content-Length", "0");
2641 add_blank_header(&resp);
2642 return send_response(p, &resp, reliable, seqno);
2645 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2647 return __transmit_response(p, msg, req, 0);
2649 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
2651 return __transmit_response(p, msg, req, fatal ? 2 : 1);
2654 static void append_date(struct sip_request *req)
2661 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2662 add_header(req, "Date", tmpdat);
2665 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2667 struct sip_request resp;
2668 respprep(&resp, p, msg, req);
2670 add_header(&resp, "Content-Length", "0");
2671 add_blank_header(&resp);
2672 return send_response(p, &resp, 0, 0);
2675 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2677 struct sip_request resp;
2678 respprep(&resp, p, msg, req);
2679 add_header(&resp, "Accept", "application/sdp");
2680 add_header(&resp, "Content-Length", "0");
2681 add_blank_header(&resp);
2682 return send_response(p, &resp, 0, 0);
2685 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2687 struct sip_request resp;
2690 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2691 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2694 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2695 respprep(&resp, p, msg, req);
2696 add_header(&resp, "Proxy-Authenticate", tmp);
2697 add_header(&resp, "Content-Length", "0");
2698 add_blank_header(&resp);
2699 return send_response(p, &resp, reliable, seqno);
2702 static int add_text(struct sip_request *req, char *text)
2704 /* XXX Convert \n's to \r\n's XXX */
2705 int len = strlen(text);
2707 snprintf(clen, sizeof(clen), "%d", len);
2708 add_header(req, "Content-Type", "text/plain");
2709 add_header(req, "Content-Length", clen);
2710 add_line(req, text);
2714 static int add_digit(struct sip_request *req, char digit)
2719 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2721 snprintf(clen, sizeof(clen), "%d", len);
2722 add_header(req, "Content-Type", "application/dtmf-relay");
2723 add_header(req, "Content-Length", clen);
2728 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2732 int alreadysent = 0;
2734 struct sockaddr_in sin;
2735 struct sockaddr_in vsin;
2736 struct sip_codec_pref *cur;
2747 struct sockaddr_in dest;
2748 struct sockaddr_in vdest = { 0, };
2749 /* XXX We break with the "recommendation" and send our IP, in order that our
2750 peer doesn't have to ast_gethostbyname() us XXX */
2753 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2756 if (!p->sessionid) {
2757 p->sessionid = getpid();
2758 p->sessionversion = p->sessionid;
2760 p->sessionversion++;
2761 ast_rtp_get_us(p->rtp, &sin);
2763 ast_rtp_get_us(p->vrtp, &vsin);
2765 if (p->redirip.sin_addr.s_addr) {
2766 dest.sin_port = p->redirip.sin_port;
2767 dest.sin_addr = p->redirip.sin_addr;
2769 ast_rtp_get_peer(rtp, &dest);
2771 dest.sin_addr = p->ourip;
2772 dest.sin_port = sin.sin_port;
2775 /* Determine video destination */
2777 if (p->vredirip.sin_addr.s_addr) {
2778 vdest.sin_port = p->vredirip.sin_port;
2779 vdest.sin_addr = p->vredirip.sin_addr;
2781 ast_rtp_get_peer(vrtp, &vdest);
2783 vdest.sin_addr = p->ourip;
2784 vdest.sin_port = vsin.sin_port;
2788 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2789 if (sipdebug && p->vrtp)
2790 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2791 snprintf(v, sizeof(v), "v=0\r\n");
2792 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
2793 snprintf(s, sizeof(s), "s=session\r\n");
2794 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2795 snprintf(t, sizeof(t), "t=0 0\r\n");
2796 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2797 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2798 if (p->jointcapability & p->prefcodec) {
2800 ast_verbose("Answering/Requesting with root capability %d\n", p->prefcodec);
2801 codec = ast_rtp_lookup_code(p->rtp, 1, p->prefcodec);
2803 snprintf(costr, sizeof(costr), " %d", codec);
2804 if (p->prefcodec <= AST_FORMAT_MAX_AUDIO) {
2805 strncat(m, costr, sizeof(m) - strlen(m));
2806 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2807 strncat(a, costr, sizeof(a));
2809 strncat(m2, costr, sizeof(m2) - strlen(m2));
2810 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2811 strncat(a2, costr, sizeof(a2));
2814 alreadysent |= p->prefcodec;
2816 /* Start by sending our preferred codecs */
2819 if (p->jointcapability & cur->codec) {
2821 ast_verbose("Answering/Requesting with preferred capability %d\n", cur->codec);
2822 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2824 snprintf(costr, sizeof(costr), " %d", codec);
2825 if (cur->codec <= AST_FORMAT_MAX_AUDIO) {
2826 strncat(m, costr, sizeof(m) - strlen(m));
2827 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2828 strncat(a, costr, sizeof(a));
2830 strncat(m2, costr, sizeof(m2) - strlen(m2));
2831 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2832 strncat(a2, costr, sizeof(a2));
2836 alreadysent |= cur->codec;
2839 /* Now send any other common codecs, and non-codec formats: */
2840 for (x = 1; x <= (videosupport ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
2841 if ((p->jointcapability & x) && !(alreadysent & x)) {
2843 ast_verbose("Answering with capability %d\n", x);
2844 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2846 snprintf(costr, sizeof(costr), " %d", codec);
2847 if (x <= AST_FORMAT_MAX_AUDIO) {
2848 strncat(m, costr, sizeof(m) - strlen(m));
2849 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2850 strncat(a, costr, sizeof(a) - strlen(a));
2852 strncat(m2, costr, sizeof(m2) - strlen(m2));
2853 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2854 strncat(a2, costr, sizeof(a2) - strlen(a2));
2859 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2860 if (p->noncodeccapability & x) {
2862 ast_verbose("Answering with non-codec capability %d\n", x);
2863 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2865 snprintf(costr, sizeof(costr), " %d", codec);
2866 strncat(m, costr, sizeof(m) - strlen(m));
2867 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2868 strncat(a, costr, sizeof(a) - strlen(a));
2869 if (x == AST_RTP_DTMF) {
2870 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2871 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2873 strncat(a, costr, sizeof(a) - strlen(a));
2878 strncat(a, "a=silenceSupp:off - - - -\r\n", sizeof(a) - strlen(a));
2879 if (strlen(m) < sizeof(m) - 2)
2881 if (strlen(m2) < sizeof(m2) - 2)
2883 if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
2884 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
2885 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2886 if ((p->vrtp) && (p->jointcapability & VIDEO_CODEC_MASK)) /* only if video response is appropriate */
2887 len += strlen(m2) + strlen(a2);
2888 snprintf(costr, sizeof(costr), "%d", len);
2889 add_header(resp, "Content-Type", "application/sdp");
2890 add_header(resp, "Content-Length", costr);
2898 if ((p->vrtp) && (p->jointcapability & VIDEO_CODEC_MASK)) { /* only if video response is appropriate */
2905 static void copy_request(struct sip_request *dst,struct sip_request *src)
2909 offset = ((void *)dst) - ((void *)src);
2910 /* First copy stuff */
2911 memcpy(dst, src, sizeof(*dst));
2912 /* Now fix pointer arithmetic */
2913 for (x=0;x<src->headers;x++)
2914 dst->header[x] += offset;
2915 for (x=0;x<src->lines;x++)
2916 dst->line[x] += offset;
2919 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2921 struct sip_request resp;
2923 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2924 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2927 respprep(&resp, p, msg, req);
2928 add_sdp(&resp, p, NULL, NULL);
2929 return send_response(p, &resp, retrans, seqno);
2932 static int determine_firstline_parts( struct sip_request *req ) {
2937 cmd= req->header[0];
2938 while(*cmd && (*cmd < 33)) {
2945 while(*e && (*e > 32)) {
2948 /* Get the command */
2954 while( *e && ( *e < 33 ) ) {
2961 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2962 /* We have a response */
2964 len= strlen( req->rlPart2 );
2965 if( len < 2 ) { return -1; }
2967 while( *e && *e<33 ) {
2972 /* We have a request */
2975 if( !*e ) { return -1; }
2978 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2981 while( isspace( *(--e) ) ) {}
2991 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2993 struct sip_request req;
2994 if (p->canreinvite == REINVITE_UPDATE)
2995 reqprep(&req, p, "UPDATE", 0, 1);
2997 reqprep(&req, p, "INVITE", 0, 1);
2999 add_header(&req, "Allow", ALLOWED_METHODS);
3000 add_sdp(&req, p, rtp, vrtp);
3001 /* Use this as the basis */
3002 copy_request(&p->initreq, &req);
3004 determine_firstline_parts(&p->initreq);
3005 p->lastinvite = p->ocseq;
3007 return send_request(p, &req, 1, p->ocseq);
3010 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
3012 char stripped[256]="";
3014 strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
3015 c = strchr(stripped, '<');
3027 strncpy(p->uri, c, sizeof(p->uri) - 1);
3030 static void build_contact(struct sip_pvt *p)
3032 /* Construct Contact: header */
3033 if (ourport != 5060)
3034 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
3036 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
3039 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
3046 char *l = callerid, *n=NULL;
3048 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
3050 if (p->owner && p->owner->callerid) {
3051 strcpy(cid, p->owner->callerid);
3052 ast_callerid_parse(cid, &n, &l);
3054 ast_shrink_phone_number(l);
3055 if (!l || !ast_isphonenumber(l))
3058 /* if user want's his callerid restricted */
3059 if (p->restrictcid) {
3060 l = CALLERID_UNKNOWN;
3063 if (!n || !strlen(n))
3065 /* Allow user to be overridden */
3066 if (strlen(p->fromuser))
3069 if ((ourport != 5060) && !strlen(p->fromdomain))
3070 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);
3072 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
3074 if (strlen(p->username)) {
3075 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
3076 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
3078 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
3080 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
3081 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
3083 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
3085 strncpy(p->uri, invite, sizeof(p->uri) - 1);
3086 /* If there is a VXML URL append it to the SIP URL */
3089 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
3093 snprintf(to, sizeof(to), "<%s>", invite );
3095 memset(req, 0, sizeof(struct sip_request));
3096 init_req(req, cmd, invite);
3097 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
3099 add_header(req, "Via", p->via);
3100 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
3101 * OTOH, then we won't have anything in p->route anyway */
3102 add_header(req, "From", from);
3103 strncpy(p->exten, l, sizeof(p->exten) - 1);
3105 add_header(req, "To", to);
3106 add_header(req, "Contact", p->our_contact);
3107 add_header(req, "Call-ID", p->callid);
3108 add_header(req, "CSeq", tmp);
3109 add_header(req, "User-Agent", "Asterisk PBX");
3112 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, int init)
3114 struct sip_request req;
3117 /* Bump branch even on initial requests */
3118 p->branch ^= rand();
3119 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
3120 initreqprep(&req, p, cmd, vxml_url);
3122 reqprep(&req, p, cmd, 0, 1);
3125 add_header(&req, authheader, auth);
3127 if (!strcasecmp(cmd, "REFER")) {
3128 if (strlen(p->refer_to))
3129 add_header(&req, "Refer-To", p->refer_to);
3130 if (strlen(p->referred_by))
3131 add_header(&req, "Referred-By", p->referred_by);
3134 if (distinctive_ring)
3136 add_header(&req, "Alert-info",distinctive_ring);
3138 add_header(&req, "Allow", ALLOWED_METHODS);
3140 add_sdp(&req, p, NULL, NULL);
3142 add_header(&req, "Content-Length", "0");
3143 add_blank_header(&req);
3146 if (!p->initreq.headers) {
3147 /* Use this as the basis */
3148 copy_request(&p->initreq, &req);
3150 determine_firstline_parts(&p->initreq);
3152 p->lastinvite = p->ocseq;
3153 return send_request(p, &req, init ? 2 : 1, p->ocseq);
3156 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
3159 char from[256], to[256];
3162 struct sip_request req;
3165 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
3167 c = ditch_braces(from);
3168 if (strncmp(c, "sip:", 4)) {
3169 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3172 if ((a = strchr(c, ';'))) {
3177 reqprep(&req, p, "NOTIFY", 0, 1);
3179 if (p->subscribed == 1) {
3180 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
3182 c = ditch_braces(to);
3183 if (strncmp(c, "sip:", 4)) {
3184 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3187 if ((a = strchr(c, ';'))) {
3192 add_header(&req, "Content-Type", "application/xpidf+xml");
3194 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
3196 else if (state==AST_EXTENSION_INUSE)
3202 sprintf(t, "<?xml version=\"1.0\"?>\n");
3203 t = tmp + strlen(tmp);
3204 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
3205 t = tmp + strlen(tmp);
3206 sprintf(t, "<presence>\n");
3207 t = tmp + strlen(tmp);
3208 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
3209 t = tmp + strlen(tmp);
3210 sprintf(t, "<atom id=\"%s\">\n", p->exten);
3211 t = tmp + strlen(tmp);
3212 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
3213 t = tmp + strlen(tmp);
3214 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
3215 t = tmp + strlen(tmp);
3216 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
3217 t = tmp + strlen(tmp);
3218 sprintf(t, "</address>\n</atom>\n</presence>\n");
3220 add_header(&req, "Event", "dialog");
3221 add_header(&req, "Content-Type", "application/dialog-info+xml");
3224 sprintf(t, "<?xml version=\"1.0\"?>\n");
3225 t = tmp + strlen(tmp);
3226 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);
3227 t = tmp + strlen(tmp);
3228 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
3229 t = tmp + strlen(tmp);
3230 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
3231 t = tmp + strlen(tmp);
3232 sprintf(t, "</dialog>\n</dialog-info>\n");
3234 if (t > tmp + sizeof(tmp))
3235 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
3237 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
3238 add_header(&req, "Content-Length", clen);
3239 add_line(&req, tmp);
3241 return send_request(p, &req, 1, p->ocseq);
3244 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
3246 struct sip_request req;
3250 initreqprep(&req, p, "NOTIFY", NULL);
3251 add_header(&req, "Event", "message-summary");
3252 add_header(&req, "Content-Type", notifymime);
3254 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
3255 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
3256 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
3257 add_header(&req, "Content-Length", clen);
3258 add_line(&req, tmp);
3259 add_line(&req, tmp2);
3261 if (!p->initreq.headers) {
3262 /* Use this as the basis */
3263 copy_request(&p->initreq, &req);
3265 determine_firstline_parts(&p->initreq);
3268 return send_request(p, &req, 1, p->ocseq);
3271 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
3273 static int sip_reregister(void *data)
3275 /* if we are here, we know that we need to reregister. */
3276 struct sip_registry *r=(struct sip_registry *)data;
3277 ast_mutex_lock(®l.lock);
3279 __sip_do_register(r);
3280 ast_mutex_unlock(®l.lock);
3285 static int __sip_do_register(struct sip_registry *r)
3288 res=transmit_register(r, "REGISTER", NULL, NULL);
3292 static int sip_reg_timeout(void *data)
3294 /* if we are here, our registration timed out, so we'll just do it over */
3295 struct sip_registry *r=data;
3298 ast_mutex_lock(®l.lock);
3299 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
3301 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
3302 in the single SIP manager thread. */
3308 r->regstate=REG_STATE_UNREGISTERED;
3310 res=transmit_register(r, "REGISTER", NULL, NULL);
3311 ast_mutex_unlock(®l.lock);
3315 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
3317 struct sip_request req;
3324 struct ast_hostent ahp;
3327 /* exit if we are already in process with this registrar ?*/
3328 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
3329 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
3335 ast_log(LOG_WARNING, "Already have a call??\n");
3340 if (!r->callid_valid) {
3341 build_callid(r->callid, sizeof(r->callid), __ourip);
3342 r->callid_valid = 1;
3344 p=sip_alloc( r->callid, &r->addr, 0);
3346 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
3352 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
3353 strncpy(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret)-1);
3354 if (strlen(r->authuser))
3355 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
3357 strncpy(p->peername, r->username, sizeof(p->peername)-1);
3358 strncpy(p->username, r->username, sizeof(p->username)-1);
3359 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
3362 check which address we should use in our contact header
3363 based on whether the remote host is on the external or
3364 internal network so we can register through nat
3366 if ((hp = ast_gethostbyname(r->hostname, &ahp))) {
3367 if (ast_sip_ouraddrfor((struct in_addr *)hp->h_addr, &p->ourip))
3368 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
3373 /* set up a timeout */
3375 if (r->timeout > -1) {
3376 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
3377 ast_sched_del(sched, r->timeout);
3379 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
3380 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
3383 if (strchr(r->username, '@')) {
3384 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
3385 snprintf(to, sizeof(to), "<sip:%s>", r->username);
3387 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
3388 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
3391 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
3392 strncpy(p->uri, addr, sizeof(p->uri) - 1);
3394 p->branch ^= rand();
3396 memset(&req, 0, sizeof(req));
3397 init_req(&req, cmd, addr);
3399 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
3400 p->ocseq = r->ocseq;
3402 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
3403 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
3404 add_header(&req, "Via", via);
3405 add_header(&req, "From", from);
3406 add_header(&req, "To", to);
3407 add_header(&req, "Call-ID", p->callid);
3408 add_header(&req, "CSeq", tmp);
3409 add_header(&req, "User-Agent", "Asterisk PBX");
3411 add_header(&req, authheader, auth);
3413 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
3414 add_header(&req, "Expires", tmp);
3415 add_header(&req, "Contact", p->our_contact);
3416 add_header(&req, "Event", "registration");
3417 add_header(&req, "Content-Length", "0");
3418 add_blank_header(&req);
3419 copy_request(&p->initreq, &req);
3421 determine_firstline_parts(&p->initreq);
3422 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
3423 return send_request(p, &req, 2, p->ocseq);
3426 static int transmit_message_with_text(struct sip_pvt *p, char *text)
3428 struct sip_request req;
3429 reqprep(&req, p, "MESSAGE", 0, 1);
3430 add_text(&req, text);
3431 return send_request(p, &req, 1, p->ocseq);
3434 static int transmit_refer(struct sip_pvt *p, char *dest)
3436 struct sip_request req;
3441 of = get_header(&p->initreq, "To");
3443 of = get_header(&p->initreq, "From");
3444 strncpy(from, of, sizeof(from) - 1);
3445 of = ditch_braces(from);
3446 strncpy(p->from,of,sizeof(p->from) - 1);
3447 if (strncmp(of, "sip:", 4)) {
3448 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3451 /* Get just the username part */
3452 if ((c = strchr(of, '@'))) {
3457 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
3459 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
3462 /* save in case we get 407 challenge */
3463 strncpy(p->refer_to, referto, sizeof(p->refer_to) - 1);
3464 strncpy(p->referred_by, p->our_contact, sizeof(p->referred_by) - 1);
3466 reqprep(&req, p, "REFER", 0, 1);
3467 add_header(&req, "Refer-To", referto);
3468 if (strlen(p->our_contact))
3469 add_header(&req, "Referred-By", p->our_contact);
3470 add_blank_header(&req);
3471 return send_request(p, &req, 1, p->ocseq);
3474 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
3476 struct sip_request req;
3477 reqprep(&req, p, "INFO", 0, 1);
3478 add_digit(&req, digit);
3479 return send_request(p, &req, 1, p->ocseq);
3482 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable, int newbranch)
3484 struct sip_request resp;
3485 reqprep(&resp, p, msg, seqno, newbranch);
3486 add_header(&resp, "Content-Length", "0");
3487 add_blank_header(&resp);
3488 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3491 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable, int newbranch)
3493 struct sip_request resp;
3494 reqprep(&resp, p, msg, seqno, newbranch);
3498 memset(digest,0,sizeof(digest));
3499 build_reply_digest(p, msg, digest, sizeof(digest));
3500 add_header(&resp, "Proxy-Authorization", digest);
3503 add_header(&resp, "Content-Length", "0");
3504 add_blank_header(&resp);
3505 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3508 static int expire_register(void *data)
3510 struct sip_peer *p = data;
3511 memset(&p->addr, 0, sizeof(p->addr));
3512 ast_db_del("SIP/Registry", p->name);
3514 ast_device_state_changed("SIP/%s", p->name);
3515 if (p->selfdestruct) {
3522 static int sip_poke_peer(struct sip_peer *peer);
3524 static void reg_source_db(struct sip_peer *p)
3530 if (!ast_db_get("SIP/Registry", p->name, data, sizeof(data))) {
3531 c = strchr(data, ':');
3535 if (inet_aton(data, &in)) {