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>
63 #define IPTOS_MINCOST 0x02
66 /* #define VOCAL_DATA_HACK */
69 #define DEFAULT_DEFAULT_EXPIRY 120
70 #define DEFAULT_MAX_EXPIRY 3600
71 #define EXPIRY_GUARD_SECS 15
73 #define CALLERID_UNKNOWN "Unknown"
75 #define SIP_DTMF_RFC2833 (1 << 0)
76 #define SIP_DTMF_INBAND (1 << 1)
77 #define SIP_DTMF_INFO (1 << 2)
79 static int max_expiry = DEFAULT_MAX_EXPIRY;
80 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
82 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
83 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
84 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
86 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
87 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
90 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
92 static char mydbuser[80];
93 static char mydbpass[80];
94 static char mydbhost[80];
95 static char mydbname[80];
98 static char *desc = "Session Initiation Protocol (SIP)";
99 static char *type = "SIP";
100 static char *tdesc = "Session Initiation Protocol (SIP)";
101 static char *config = "sip.conf";
103 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
104 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
106 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
108 static char context[AST_MAX_EXTENSION] = "default";
110 static char language[MAX_LANGUAGE] = "";
112 static char callerid[AST_MAX_EXTENSION] = "asterisk";
114 static char fromdomain[AST_MAX_EXTENSION] = "";
116 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
118 static int srvlookup = 0;
120 static int pedanticsipchecking = 0;
122 static int autocreatepeer = 0;
124 static int usecnt =0;
125 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
127 /* Protect the interface list (of sip_pvt's) */
128 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
130 /* Protect the monitoring thread, so only one process can kill or start it, and not
131 when it's doing something critical. */
132 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
134 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
136 /* This is the thread for the monitor which checks for input on the channels
137 which are not currently in use. */
138 static pthread_t monitor_thread = AST_PTHREADT_NULL;
140 static int restart_monitor(void);
142 /* Codecs that we support by default: */
143 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
144 static int noncodeccapability = AST_RTP_DTMF;
146 static char ourhost[256];
147 static struct in_addr __ourip;
150 static int sipdebug = 0;
154 static int videosupport = 0;
156 static int globaldtmfmode = SIP_DTMF_RFC2833;
159 static int expiry = 900;
161 static struct sched_context *sched;
162 static struct io_context *io;
163 /* The private structures of the sip channels are linked for
164 selecting outgoing channels */
166 #define SIP_MAX_HEADERS 64
167 #define SIP_MAX_LINES 64
171 #define DEC_OUT_USE 2
172 #define INC_OUT_USE 3
174 static struct sip_codec_pref {
176 struct sip_codec_pref *next;
180 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
181 char *rlPart2; /* The Request URI or Response Status */
183 int headers; /* SIP Headers */
184 char *header[SIP_MAX_HEADERS];
185 int lines; /* SDP Content */
186 char *line[SIP_MAX_LINES];
187 char data[SIP_MAX_PACKET];
193 struct sip_route *next;
197 static struct sip_pvt {
198 ast_mutex_t lock; /* Channel private lock */
199 char callid[80]; /* Global CallID */
200 char randdata[80]; /* Random data */
201 unsigned int ocseq; /* Current outgoing seqno */
202 unsigned int icseq; /* Current incoming seqno */
203 unsigned int callgroup;
204 unsigned int pickupgroup;
205 int lastinvite; /* Last Cseq of invite */
206 int alreadygone; /* Whether or not we've already been destroyed by or peer */
207 int needdestroy; /* if we need to be destroyed */
208 int capability; /* Special capability */
209 int jointcapability; /* Supported capability at both ends */
210 int prefcodec; /* Preferred codec (outbound only) */
211 int noncodeccapability;
212 int outgoing; /* Outgoing or incoming call? */
213 int authtries; /* Times we've tried to authenticate */
214 int insecure; /* Don't check source port/ip */
215 int expiry; /* How long we take to expire */
216 int branch; /* One random number */
217 int canreinvite; /* Do we support reinvite */
218 int ringing; /* Have sent 180 ringing */
219 int progress; /* Have sent 183 message progress */
220 int tag; /* Another random number */
221 int nat; /* Whether to try to support NAT */
222 int sessionid; /* SDP Session ID */
223 int sessionversion; /* SDP Session Version */
224 struct sockaddr_in sa; /* Our peer */
225 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
226 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
227 struct sockaddr_in recv; /* Received as */
228 struct in_addr ourip; /* Our IP */
229 struct ast_channel *owner; /* Who owns us */
230 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
231 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
232 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
233 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
234 struct sip_pvt *refer_call; /* Call we are referring */
235 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
236 char remote_party_id[256];
238 char context[AST_MAX_EXTENSION];
239 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
240 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
241 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
242 char language[MAX_LANGUAGE];
243 char rdnis[256]; /* Referring DNIS */
244 char theirtag[256]; /* Their tag */
247 char uri[256]; /* Original requested URI */
248 char peersecret[256];
249 char peermd5secret[256];
250 char callerid[256]; /* Caller*ID */
251 int restrictcid; /* hide presentation from remote user */
253 char accountcode[20]; /* Account code */
254 char our_contact[256]; /* Our contact header */
255 char realm[256]; /* Authorization realm */
256 char nonce[256]; /* Authorization nonce */
257 char domain[256]; /* Authorization nonce */
258 char lastmsg[256]; /* Last Message sent/received */
259 int amaflags; /* AMA Flags */
260 int pendinginvite; /* Any pending invite */
261 int pendingbye; /* Need to send bye after we ack? */
262 int gotrefer; /* Got a refer? */
263 struct sip_request initreq; /* Initial request */
265 int maxtime; /* Max time for first response */
266 int initid; /* Auto-congest ID if appropriate */
267 int autokillid; /* Auto-kill ID */
276 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
277 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
278 struct ast_rtp *rtp; /* RTP Session */
279 struct ast_rtp *vrtp; /* Video RTP session */
280 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
281 struct sip_pvt *next;
285 struct sip_pkt *next; /* Next packet */
286 int retrans; /* Retransmission number */
287 int seqno; /* Sequence number */
288 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
289 struct sip_pvt *owner; /* Owner call */
290 int retransid; /* Retransmission ID */
291 int packetlen; /* Length of packet */
296 /* Users who can access various contexts */
303 char accountcode[20];
304 char language[MAX_LANGUAGE];
305 unsigned int callgroup;
306 unsigned int pickupgroup;
320 struct sip_user *next;
327 char context[80]; /* JK02: peers need context too to allow parking etc */
333 char mailbox[AST_MAX_EXTENSION];
343 unsigned int callgroup;
344 unsigned int pickupgroup;
346 struct sockaddr_in addr;
350 struct sip_pvt *call; /* Call pointer */
351 int pokeexpire; /* When to expire poke */
352 int lastms; /* How long last response took (in ms), or -1 for no response */
353 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
354 struct timeval ps; /* Ping send time */
356 struct sockaddr_in defaddr;
362 struct sip_peer *next;
365 static ast_mutex_t sip_reload_lock = AST_MUTEX_INITIALIZER;
366 static int sip_reloading = 0;
368 #define REG_STATE_UNREGISTERED 0
369 #define REG_STATE_REGSENT 1
370 #define REG_STATE_AUTHSENT 2
371 #define REG_STATE_REGISTERED 3
372 #define REG_STATE_REJECTED 4
373 #define REG_STATE_TIMEOUT 5
374 #define REG_STATE_NOAUTH 6
376 struct sip_registry {
377 struct sockaddr_in addr; /* Who we connect to for registration purposes */
378 char username[80]; /* Who we are registering as */
379 char authuser[80]; /* Who we *authenticate* as */
381 char secret[80]; /* Password or key name in []'s */
383 char contact[80]; /* Contact extension */
385 int expire; /* Sched ID of expiration */
386 int timeout; /* sched id of sip_reg_timeout */
387 int refresh; /* How often to refresh */
388 struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
390 int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
391 char callid[80]; /* Global CallID for this registry */
392 unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
393 struct sockaddr_in us; /* Who the server thinks we are */
394 struct sip_registry *next;
397 static struct ast_user_list {
398 struct sip_user *users;
400 } userl = { NULL, AST_MUTEX_INITIALIZER };
402 static struct ast_peer_list {
403 struct sip_peer *peers;
405 } peerl = { NULL, AST_MUTEX_INITIALIZER };
407 static struct ast_register_list {
408 struct sip_registry *registrations;
411 } regl = { NULL, AST_MUTEX_INITIALIZER };
414 #define REINVITE_INVITE 1
415 #define REINVITE_UPDATE 2
417 static int __sip_do_register(struct sip_registry *r);
419 static int sipsock = -1;
420 static int globalnat = 0;
421 static int globalcanreinvite = REINVITE_INVITE;
424 static struct sockaddr_in bindaddr;
425 static struct sockaddr_in localnet;
426 static struct sockaddr_in localmask;
427 static struct sockaddr_in externip;
429 static struct ast_frame *sip_read(struct ast_channel *ast);
430 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
431 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
432 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
433 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
434 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
435 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
436 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
437 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
438 static int transmit_message_with_text(struct sip_pvt *p, char *text);
439 static int transmit_refer(struct sip_pvt *p, char *dest);
440 static struct sip_peer *temp_peer(char *name);
441 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
442 // static char *getsipuri(char *header);
443 static void free_old_route(struct sip_route *route);
444 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
445 static int find_user(struct sip_pvt *fup, int event);
446 static void prune_peers(void);
447 static int sip_do_reload(void);
449 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
453 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
455 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
457 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));
462 static void sip_destroy(struct sip_pvt *p);
464 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
467 check to see if them is contained in our localnet/mask,
468 if not, use our externip for us, otherwise use the
469 real internal address in bindaddr
471 if (localnet.sin_addr.s_addr && externip.sin_addr.s_addr &&
472 ((htonl(them->s_addr) & htonl(localnet.sin_addr.s_addr)) != htonl(localnet.sin_addr.s_addr)))
473 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
474 else if (bindaddr.sin_addr.s_addr)
475 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
477 return ast_ouraddrfor(them, us);
481 static int retrans_pkt(void *data)
483 struct sip_pkt *pkt=data;
485 ast_mutex_lock(&pkt->owner->lock);
486 if (pkt->retrans < MAX_RETRANS) {
490 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));
492 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));
494 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
497 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
499 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
500 ast_mutex_unlock(&pkt->owner->lock);
502 ast_mutex_lock(&pkt->owner->lock);
504 if (pkt->owner->owner) {
505 /* XXX Potential deadlocK?? XXX */
506 ast_queue_hangup(pkt->owner->owner, 0);
507 ast_mutex_unlock(&pkt->owner->owner->lock);
509 /* If no owner, destroy now */
510 pkt->owner->needdestroy = 1;
514 ast_mutex_unlock(&pkt->owner->lock);
518 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
521 pkt = malloc(sizeof(struct sip_pkt) + len);
524 memset(pkt, 0, sizeof(struct sip_pkt));
525 memcpy(pkt->data, data, len);
526 pkt->packetlen = len;
527 pkt->next = p->packets;
531 /* Schedule retransmission */
532 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
533 pkt->next = p->packets;
535 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
536 if (!strncasecmp(pkt->data, "INVITE", 6)) {
537 /* Note this is a pending invite */
538 p->pendinginvite = seqno;
543 static int __sip_autodestruct(void *data)
545 struct sip_pvt *p = data;
547 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
549 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
550 ast_queue_hangup(p->owner, 0);
557 static int sip_scheddestroy(struct sip_pvt *p, int ms)
559 if (p->autokillid > -1)
560 ast_sched_del(sched, p->autokillid);
561 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
565 static int sip_cancel_destroy(struct sip_pvt *p)
567 if (p->autokillid > -1)
568 ast_sched_del(sched, p->autokillid);
573 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
575 struct sip_pkt *cur, *prev = NULL;
580 if ((cur->seqno == seqno) && (cur->resp == resp)) {
581 if (!resp && (seqno == p->pendinginvite)) {
582 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
583 p->pendinginvite = 0;
586 /* this is our baby */
588 prev->next = cur->next;
590 p->packets = cur->next;
591 if (cur->retransid > -1)
592 ast_sched_del(sched, cur->retransid);
600 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
604 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
610 if ((cur->seqno == seqno) && (cur->resp == resp)) {
611 /* this is our baby */
612 if (cur->retransid > -1)
613 ast_sched_del(sched, cur->retransid);
620 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");
624 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
629 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));
631 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));
634 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
636 res = __sip_xmit(p, req->data, req->len);
642 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
647 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));
649 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));
652 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
654 res = __sip_xmit(p, req->data, req->len);
658 static char *ditch_braces(char *tmp)
662 if ((n = strchr(tmp, '<')) ) {
664 while(*c && *c != '>') c++;
666 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
675 static int sip_sendtext(struct ast_channel *ast, char *text)
677 struct sip_pvt *p = ast->pvt->pvt;
679 ast_verbose("Sending text %s on %s\n", text, ast->name);
682 if (!text || !strlen(text))
685 ast_verbose("Really sending text %s on %s\n", text, ast->name);
686 transmit_message_with_text(p, text);
692 static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
694 if (mysql && (strlen(peer) < 128)) {
699 name = alloca(strlen(peer) * 2 + 1);
700 uname = alloca(strlen(username) * 2 + 1);
702 mysql_real_escape_string(mysql, name, peer, strlen(peer));
703 mysql_real_escape_string(mysql, uname, username, strlen(username));
704 snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"",
705 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
706 ast_mutex_lock(&mysqllock);
707 if (mysql_real_query(mysql, query, strlen(query)))
708 ast_log(LOG_WARNING, "Unable to update database\n");
710 ast_mutex_unlock(&mysqllock);
714 static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
719 p = malloc(sizeof(struct sip_peer));
720 memset(p, 0, sizeof(struct sip_peer));
721 if (mysql && (!peer || (strlen(peer) < 128))) {
726 time_t regseconds, nowtime;
731 name = alloca(strlen(peer) * 2 + 1);
732 mysql_real_escape_string(mysql, name, peer, strlen(peer));
735 snprintf(query, sizeof(query), "SELECT * FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
737 snprintf(query, sizeof(query), "SELECT * FROM sipfriends WHERE name=\"%s\"", name);
738 ast_mutex_lock(&mysqllock);
739 mysql_query(mysql, query);
740 if ((result = mysql_store_result(mysql))) {
741 if ((rowval = mysql_fetch_row(result))) {
742 numfields = mysql_num_fields(result);
743 fields = mysql_fetch_fields(result);
745 for (x=0;x<numfields;x++) {
747 if (!strcasecmp(fields[x].name, "secret")) {
748 strncpy(p->secret, rowval[x], sizeof(p->secret));
749 } else if (!strcasecmp(fields[x].name, "name")) {
750 strncpy(p->name, rowval[x], sizeof(p->name) - 1);
751 } else if (!strcasecmp(fields[x].name, "context")) {
752 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
753 } else if (!strcasecmp(fields[x].name, "username")) {
754 strncpy(p->username, rowval[x], sizeof(p->username) - 1);
755 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
756 inet_aton(rowval[x], &p->addr.sin_addr);
757 } else if (!strcasecmp(fields[x].name, "port")) {
758 if (sscanf(rowval[x], "%i", &port) != 1)
760 p->addr.sin_port = htons(port);
761 } else if (!strcasecmp(fields[x].name, "regseconds")) {
762 if (sscanf(rowval[x], "%li", ®seconds) != 1)
768 if (nowtime > regseconds)
769 memset(&p->addr, 0, sizeof(p->addr));
771 mysql_free_result(result);
774 ast_mutex_unlock(&mysqllock);
781 p->capability = capability;
783 p->dtmfmode = globaldtmfmode;
791 #endif /* MYSQL_FRIENDS */
793 static int create_addr(struct sip_pvt *r, char *peer)
800 char host[256], *hostn;
802 r->sa.sin_family = AF_INET;
803 ast_mutex_lock(&peerl.lock);
806 if (!strcasecmp(p->name, peer))
812 p = mysql_peer(peer, NULL);
817 r->capability = p->capability;
820 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
821 ast_rtp_setnat(r->rtp, r->nat);
824 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
825 ast_rtp_setnat(r->vrtp, r->nat);
827 strncpy(r->peername, p->username, sizeof(r->peername)-1);
828 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
829 strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
830 strncpy(r->username, p->username, sizeof(r->username)-1);
831 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
832 if (!strlen(r->tohost)) {
833 if (p->addr.sin_addr.s_addr)
834 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
836 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
838 if (strlen(p->fromdomain))
839 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
840 if (strlen(p->fromuser))
841 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
842 r->insecure = p->insecure;
843 r->canreinvite = p->canreinvite;
844 r->maxtime = p->maxms;
845 r->callgroup = p->callgroup;
846 r->pickupgroup = p->pickupgroup;
848 r->dtmfmode = p->dtmfmode;
849 if (r->dtmfmode & SIP_DTMF_RFC2833)
850 r->noncodeccapability |= AST_RTP_DTMF;
852 r->noncodeccapability &= ~AST_RTP_DTMF;
854 strncpy(r->context, p->context,sizeof(r->context)-1);
855 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
856 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
857 if (p->addr.sin_addr.s_addr) {
858 r->sa.sin_addr = p->addr.sin_addr;
859 r->sa.sin_port = p->addr.sin_port;
861 r->sa.sin_addr = p->defaddr.sin_addr;
862 r->sa.sin_port = p->defaddr.sin_port;
864 memcpy(&r->recv, &r->sa, sizeof(r->recv));
871 ast_mutex_unlock(&peerl.lock);
873 if ((port=strchr(peer, ':'))) {
881 portno = DEFAULT_SIP_PORT;
886 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
887 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
893 hp = gethostbyname(hostn);
895 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
896 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
897 r->sa.sin_port = htons(portno);
898 memcpy(&r->recv, &r->sa, sizeof(r->recv));
901 ast_log(LOG_WARNING, "No such host: %s\n", peer);
913 static int auto_congest(void *nothing)
915 struct sip_pvt *p = nothing;
916 ast_mutex_lock(&p->lock);
919 if (!ast_mutex_trylock(&p->owner->lock)) {
920 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
921 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
922 ast_mutex_unlock(&p->owner->lock);
925 ast_mutex_unlock(&p->lock);
929 static void sip_prefs_free(void)
931 struct sip_codec_pref *cur, *next;
941 static void sip_pref_remove(int format)
943 struct sip_codec_pref *cur, *prev=NULL;
946 if (cur->codec == format) {
948 prev->next = cur->next;
959 static int sip_pref_append(int format)
961 struct sip_codec_pref *cur, *tmp;
962 sip_pref_remove(format);
963 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
966 memset(tmp, 0, sizeof(struct sip_codec_pref));
978 static int sip_codec_choose(int formats)
980 struct sip_codec_pref *cur;
981 formats &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
984 if (formats & cur->codec)
988 return ast_best_codec(formats);
991 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
995 char *vxml_url = NULL;
996 char *distinctive_ring = NULL;
997 struct varshead *headp;
998 struct ast_var_t *current;
1001 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1002 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1005 /* Check whether there is vxml_url, distinctive ring variables */
1007 headp=&ast->varshead;
1008 AST_LIST_TRAVERSE(headp,current,entries) {
1009 /* Check whether there is a VXML_URL variable */
1010 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
1012 vxml_url = ast_var_value(current);
1015 /* Check whether there is a ALERT_INFO variable */
1016 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
1018 distinctive_ring = ast_var_value(current);
1025 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1026 res = find_user(p,INC_OUT_USE);
1028 p->restrictcid = ast->restrictcid;
1029 p->jointcapability = p->capability;
1030 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
1032 /* Initialize auto-congest time */
1033 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1039 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1041 struct sip_pvt *cur, *prev = NULL;
1044 ast_log(LOG_DEBUG, "Destroying call '%s'\n", p->callid);
1045 if (p->stateid > -1)
1046 ast_extension_state_del(p->stateid, NULL);
1048 ast_sched_del(sched, p->initid);
1049 if (p->autokillid > -1)
1050 ast_sched_del(sched, p->autokillid);
1053 ast_rtp_destroy(p->rtp);
1056 ast_rtp_destroy(p->vrtp);
1059 free_old_route(p->route);
1063 /* Carefully unlink from registry */
1064 struct sip_registry *reg;
1065 ast_mutex_lock(®l.lock);
1066 reg = regl.registrations;
1068 if ((reg == p->registry) && (p->registry->call == p))
1069 p->registry->call=NULL;
1072 ast_mutex_unlock(®l.lock);
1074 /* Unlink us from the owner if we have one */
1077 ast_mutex_lock(&p->owner->lock);
1078 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1079 p->owner->pvt->pvt = NULL;
1081 ast_mutex_unlock(&p->owner->lock);
1087 prev->next = cur->next;
1096 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1099 ast_sched_del(sched, p->initid);
1100 while((cp = p->packets)) {
1101 p->packets = p->packets->next;
1102 if (cp->retransid > -1)
1103 ast_sched_del(sched, cp->retransid);
1110 static int find_user(struct sip_pvt *fup, int event)
1112 char name[256] = "";
1114 strncpy(name, fup->username, sizeof(name) - 1);
1115 ast_mutex_lock(&userl.lock);
1118 if (!strcasecmp(u->name, name)) {
1124 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1125 ast_mutex_unlock(&userl.lock);
1129 /* incoming and outgoing affects the inUse counter */
1132 if ( u->inUse > 0 ) {
1140 if (u->incominglimit > 0 ) {
1141 if (u->inUse >= u->incominglimit) {
1142 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
1143 ast_mutex_unlock(&userl.lock);
1144 /* inc inUse as well */
1145 if ( event == INC_OUT_USE ) {
1152 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1154 /* we don't use these anymore
1156 if ( u->outUse > 0 ) {
1163 if ( u->outgoinglimit > 0 ) {
1164 if ( u->outUse >= u->outgoinglimit ) {
1165 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1166 ast_mutex_unlock(&userl.lock);
1174 ast_log(LOG_ERROR, "find_user(%s,%d) called with no event!\n",u->name,event);
1176 ast_mutex_unlock(&userl.lock);
1180 static void sip_destroy(struct sip_pvt *p)
1182 ast_mutex_lock(&iflock);
1183 __sip_destroy(p, 1);
1184 ast_mutex_unlock(&iflock);
1187 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
1189 static int hangup_sip2cause(int cause)
1194 return AST_CAUSE_BUSY;
1196 return AST_CAUSE_NORMAL;
1202 static char *hangup_cause2sip(int cause)
1206 case AST_CAUSE_BUSY:
1215 static int sip_hangup(struct ast_channel *ast)
1217 struct sip_pvt *p = ast->pvt->pvt;
1219 int needdestroy = 0;
1221 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1222 if (!ast->pvt->pvt) {
1223 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1226 ast_mutex_lock(&p->lock);
1227 if ( p->outgoing ) {
1228 ast_log(LOG_DEBUG, "find_user(%s) - decrement outUse counter\n", p->username);
1229 find_user(p, DEC_OUT_USE);
1231 ast_log(LOG_DEBUG, "find_user(%s) - decrement inUse counter\n", p->username);
1232 find_user(p, DEC_IN_USE);
1234 /* Determine how to disconnect */
1235 if (p->owner != ast) {
1236 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1237 ast_mutex_unlock(&p->lock);
1240 if (!ast || (ast->_state != AST_STATE_UP))
1245 ast_dsp_free(p->vad);
1248 ast->pvt->pvt = NULL;
1250 ast_mutex_lock(&usecnt_lock);
1252 ast_mutex_unlock(&usecnt_lock);
1253 ast_update_use_count();
1256 /* Start the process if it's not already started */
1257 if (!p->alreadygone && strlen(p->initreq.data)) {
1260 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
1261 /* Actually don't destroy us yet, wait for the 487 on our original
1262 INVITE, but do set an autodestruct just in case. */
1264 sip_scheddestroy(p, 15000);
1265 if ( p->initid != -1 ) {
1266 /* channel still up - reverse dec of inUse counter
1267 only if the channel is not auto-congested */
1268 if ( p->outgoing ) {
1269 find_user(p, INC_OUT_USE);
1272 find_user(p, INC_IN_USE);
1277 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1278 transmit_response_reliable(p, res, &p->initreq);
1280 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
1283 if (!p->pendinginvite) {
1285 transmit_request_with_auth(p, "BYE", 0, 1);
1287 /* Note we will need a BYE when this all settles out
1288 but we can't send one while we have "INVITE" outstanding. */
1293 p->needdestroy = needdestroy;
1294 ast_mutex_unlock(&p->lock);
1298 static int sip_answer(struct ast_channel *ast)
1302 struct sip_pvt *p = ast->pvt->pvt;
1305 if (ast->_state != AST_STATE_UP) {
1309 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1311 fmt=ast_getformatbyname(codec);
1313 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1314 p->jointcapability=fmt;
1315 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1318 ast_setstate(ast, AST_STATE_UP);
1320 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1321 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1326 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1328 struct sip_pvt *p = ast->pvt->pvt;
1330 if (frame->frametype == AST_FRAME_VOICE) {
1331 if (!(frame->subclass & ast->nativeformats)) {
1332 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1333 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1337 ast_mutex_lock(&p->lock);
1339 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1340 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1343 res = ast_rtp_write(p->rtp, frame);
1345 ast_mutex_unlock(&p->lock);
1347 } else if (frame->frametype == AST_FRAME_VIDEO) {
1349 ast_mutex_lock(&p->lock);
1351 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1352 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1355 res = ast_rtp_write(p->vrtp, frame);
1357 ast_mutex_unlock(&p->lock);
1359 } else if (frame->frametype == AST_FRAME_IMAGE) {
1362 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1369 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan, int needlock)
1371 struct sip_pvt *p = newchan->pvt->pvt;
1373 ast_mutex_lock(&p->lock);
1374 if (p->owner != oldchan) {
1375 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1377 ast_mutex_unlock(&p->lock);
1382 ast_mutex_unlock(&p->lock);
1386 static int sip_senddigit(struct ast_channel *ast, char digit)
1388 struct sip_pvt *p = ast->pvt->pvt;
1389 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1390 transmit_info_with_digit(p, digit);
1392 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1393 ast_rtp_senddigit(p->rtp, digit);
1395 /* If in-band DTMF is desired, send that */
1396 if (p->dtmfmode & SIP_DTMF_INBAND)
1401 static int sip_transfer(struct ast_channel *ast, char *dest)
1403 struct sip_pvt *p = ast->pvt->pvt;
1405 res = transmit_refer(p, dest);
1409 static int sip_indicate(struct ast_channel *ast, int condition)
1411 struct sip_pvt *p = ast->pvt->pvt;
1413 case AST_CONTROL_RINGING:
1414 if (ast->_state == AST_STATE_RING) {
1415 if (!p->progress && !p->ringing) {
1416 transmit_response(p, "180 Ringing", &p->initreq);
1420 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1424 case AST_CONTROL_BUSY:
1425 if (ast->_state != AST_STATE_UP) {
1426 transmit_response(p, "486 Busy Here", &p->initreq);
1428 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1432 case AST_CONTROL_CONGESTION:
1433 if (ast->_state != AST_STATE_UP) {
1434 transmit_response(p, "503 Service Unavailable", &p->initreq);
1436 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1440 case AST_CONTROL_PROGRESS:
1441 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1442 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1450 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1458 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1460 struct ast_channel *tmp;
1462 tmp = ast_channel_alloc(1);
1464 /* Select our native format based on codec preference until we receive
1465 something from another device to the contrary. */
1466 if (i->jointcapability)
1467 tmp->nativeformats = sip_codec_choose(i->jointcapability);
1468 else if (i->capability)
1469 tmp->nativeformats = sip_codec_choose(i->capability);
1471 tmp->nativeformats = sip_codec_choose(capability);
1472 fmt = ast_best_codec(tmp->nativeformats);
1474 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1476 if (strchr(i->fromdomain,':'))
1478 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1482 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1485 if (i->dtmfmode & SIP_DTMF_INBAND) {
1486 i->vad = ast_dsp_new();
1487 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1489 tmp->fds[0] = ast_rtp_fd(i->rtp);
1490 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1492 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1493 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1495 ast_setstate(tmp, state);
1496 if (state == AST_STATE_RING)
1498 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1499 tmp->writeformat = fmt;
1500 tmp->pvt->rawwriteformat = fmt;
1501 tmp->readformat = fmt;
1502 tmp->pvt->rawreadformat = fmt;
1504 tmp->pvt->send_text = sip_sendtext;
1505 tmp->pvt->call = sip_call;
1506 tmp->pvt->hangup = sip_hangup;
1507 tmp->pvt->answer = sip_answer;
1508 tmp->pvt->read = sip_read;
1509 tmp->pvt->write = sip_write;
1510 tmp->pvt->write_video = sip_write;
1511 tmp->pvt->indicate = sip_indicate;
1512 tmp->pvt->transfer = sip_transfer;
1513 tmp->pvt->fixup = sip_fixup;
1514 tmp->pvt->send_digit = sip_senddigit;
1516 tmp->pvt->bridge = ast_rtp_bridge;
1518 tmp->callgroup = i->callgroup;
1519 tmp->pickupgroup = i->pickupgroup;
1520 tmp->restrictcid = i->restrictcid;
1521 if (strlen(i->accountcode))
1522 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1524 tmp->amaflags = i->amaflags;
1525 if (strlen(i->language))
1526 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1528 ast_mutex_lock(&usecnt_lock);
1530 ast_mutex_unlock(&usecnt_lock);
1531 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1532 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1533 if (strlen(i->callerid))
1534 tmp->callerid = strdup(i->callerid);
1535 if (strlen(i->rdnis))
1536 tmp->rdnis = strdup(i->rdnis);
1537 if (strlen(i->exten) && strcmp(i->exten, "s"))
1538 tmp->dnid = strdup(i->exten);
1540 if (strlen(i->domain)) {
1541 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1544 if (state != AST_STATE_DOWN) {
1545 if (ast_pbx_start(tmp)) {
1546 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1552 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1556 static struct cfalias {
1560 { "Content-Type", "c" },
1561 { "Content-Encoding", "e" },
1565 { "Content-Length", "l" },
1571 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1572 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1573 char* r = line + nameLen + 1;
1574 while (*r && (*r < 33)) ++r;
1581 static char *get_sdp(struct sip_request *req, char *name) {
1583 int len = strlen(name);
1586 for (x=0; x<req->lines; x++) {
1587 r = get_sdp_by_line(req->line[x], name, len);
1588 if (r[0] != '\0') return r;
1593 static void sdpLineNum_iterator_init(int* iterator) {
1597 static char* get_sdp_iterate(int* iterator,
1598 struct sip_request *req, char *name) {
1599 int len = strlen(name);
1601 while (*iterator < req->lines) {
1602 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1603 if (r[0] != '\0') return r;
1608 static char *__get_header(struct sip_request *req, char *name, int *start)
1611 int len = strlen(name);
1613 for (x=*start;x<req->headers;x++) {
1614 if (!strncasecmp(req->header[x], name, len) &&
1615 (req->header[x][len] == ':')) {
1616 r = req->header[x] + len + 1;
1617 while(*r && (*r < 33))
1624 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1625 if (!strcasecmp(aliases[x].fullname, name))
1626 return __get_header(req, aliases[x].shortname, start);
1628 /* Don't return NULL, so get_header is always a valid pointer */
1632 static char *get_header(struct sip_request *req, char *name)
1635 return __get_header(req, name, &start);
1638 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1640 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1641 struct ast_frame *f;
1642 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1645 f = ast_rtp_read(p->rtp);
1648 f = ast_rtcp_read(p->rtp);
1651 f = ast_rtp_read(p->vrtp);
1654 f = ast_rtcp_read(p->vrtp);
1659 /* Don't send RFC2833 if we're not supposed to */
1660 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1663 /* We already hold the channel lock */
1664 if (f->frametype == AST_FRAME_VOICE) {
1665 if (f->subclass != p->owner->nativeformats) {
1666 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1667 p->owner->nativeformats = f->subclass;
1668 ast_set_read_format(p->owner, p->owner->readformat);
1669 ast_set_write_format(p->owner, p->owner->writeformat);
1671 if (p->dtmfmode & SIP_DTMF_INBAND) {
1672 f = ast_dsp_process(p->owner,p->vad,f,0);
1679 static struct ast_frame *sip_read(struct ast_channel *ast)
1681 struct ast_frame *fr;
1682 struct sip_pvt *p = ast->pvt->pvt;
1683 ast_mutex_lock(&p->lock);
1684 fr = sip_rtp_read(ast, p);
1685 ast_mutex_unlock(&p->lock);
1689 static void build_callid(char *callid, int len, struct in_addr ourip)
1696 res = snprintf(callid, len, "%08x", val);
1700 /* It's not important that we really use our right IP here... */
1701 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1704 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1708 p = malloc(sizeof(struct sip_pvt));
1711 /* Keep track of stuff */
1712 memset(p, 0, sizeof(struct sip_pvt));
1716 p->rtp = ast_rtp_new(sched, io, 1, 0);
1718 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1722 /* Start with 101 instead of 1 */
1725 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1729 ast_rtp_settos(p->rtp, tos);
1731 ast_rtp_settos(p->vrtp, tos);
1732 if (useglobalnat && sin) {
1733 /* Setup NAT structure according to global settings if we have an address */
1735 memcpy(&p->recv, sin, sizeof(p->recv));
1736 ast_rtp_setnat(p->rtp, p->nat);
1738 ast_rtp_setnat(p->vrtp, p->nat);
1740 ast_mutex_init(&p->lock);
1743 memcpy(&p->sa, sin, sizeof(p->sa));
1744 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1745 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1747 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1749 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1750 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1752 build_callid(p->callid, sizeof(p->callid), p->ourip);
1754 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1755 /* Assume reinvite OK and via INVITE */
1756 p->canreinvite = globalcanreinvite;
1757 p->dtmfmode = globaldtmfmode;
1758 p->capability = capability;
1759 if (p->dtmfmode & SIP_DTMF_RFC2833)
1760 p->noncodeccapability |= AST_RTP_DTMF;
1761 strncpy(p->context, context, sizeof(p->context) - 1);
1762 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1764 ast_mutex_lock(&iflock);
1767 ast_mutex_unlock(&iflock);
1769 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1773 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1781 callid = get_header(req, "Call-ID");
1783 if (pedanticsipchecking) {
1784 /* In principle Call-ID's uniquely identify a call, however some vendors
1785 (i.e. Pingtel) send multiple calls with the same Call-ID and different
1786 tags in order to simplify billing. The RFC does state that we have to
1787 compare tags in addition to the call-id, but this generate substantially
1788 more overhead which is totally unnecessary for the vast majority of sane
1789 SIP implementations, and thus Asterisk does not enable this behavior
1790 by default. Short version: You'll need this option to support conferencing
1792 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1794 c = strchr(tmp, ' ');
1797 if (!strcasecmp(cmd, "SIP/2.0")) {
1803 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1805 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1806 tag = strstr(tmp, "tag=");
1809 c = strchr(tag, ';');
1816 if (!strlen(callid)) {
1817 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1820 ast_mutex_lock(&iflock);
1823 if (!strcmp(p->callid, callid) &&
1824 (!pedanticsipchecking || !tag || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1825 /* Found the call */
1826 ast_mutex_lock(&p->lock);
1827 ast_mutex_unlock(&iflock);
1832 ast_mutex_unlock(&iflock);
1833 p = sip_alloc(callid, sin, 1);
1835 ast_mutex_lock(&p->lock);
1839 static int sip_register(char *value, int lineno)
1841 struct sip_registry *reg;
1842 char copy[256] = "";
1843 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1851 strncpy(copy, value, sizeof(copy)-1);
1854 hostname = strrchr(stringp, '@');
1859 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1860 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1864 username = strsep(&stringp, ":");
1866 secret = strsep(&stringp, ":");
1868 authuser = strsep(&stringp, ":");
1871 hostname = strsep(&stringp, "/");
1873 contact = strsep(&stringp, "/");
1874 if (!contact || !strlen(contact))
1877 hostname = strsep(&stringp, ":");
1878 porta = strsep(&stringp, ":");
1880 if (porta && !atoi(porta)) {
1881 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1884 hp = gethostbyname(hostname);
1886 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1889 reg = malloc(sizeof(struct sip_registry));
1891 memset(reg, 0, sizeof(struct sip_registry));
1892 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1894 strncpy(reg->username, username, sizeof(reg->username)-1);
1896 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1898 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1900 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1903 reg->refresh = default_expiry;
1904 reg->addr.sin_family = AF_INET;
1905 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1906 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1907 reg->callid_valid = 0;
1909 ast_mutex_lock(®l.lock);
1910 reg->next = regl.registrations;
1911 regl.registrations = reg;
1912 ast_mutex_unlock(®l.lock);
1914 ast_log(LOG_ERROR, "Out of memory\n");
1920 static void parse(struct sip_request *req)
1922 /* Divide fields by NULL's */
1927 /* First header starts immediately */
1931 /* We've got a new header */
1935 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1937 if (!strlen(req->header[f])) {
1938 /* Line by itself means we're now in content */
1942 if (f >= SIP_MAX_HEADERS - 1) {
1943 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1946 req->header[f] = c + 1;
1947 } else if (*c == '\r') {
1948 /* Ignore but eliminate \r's */
1953 /* Check for last header */
1954 if (strlen(req->header[f]))
1957 /* Now we process any mime content */
1962 /* We've got a new line */
1965 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1967 if (f >= SIP_MAX_LINES - 1) {
1968 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1971 req->line[f] = c + 1;
1972 } else if (*c == '\r') {
1973 /* Ignore and eliminate \r's */
1978 /* Check for last line */
1979 if (strlen(req->line[f]))
1983 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1985 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1988 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1997 int peercapability, peernoncodeccapability;
1998 int vpeercapability=0, vpeernoncodeccapability=0;
1999 struct sockaddr_in sin;
2007 /* Get codec and RTP info from SDP */
2008 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2009 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2012 m = get_sdp(req, "m");
2013 c = get_sdp(req, "c");
2014 if (!strlen(m) || !strlen(c)) {
2015 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2018 if (sscanf(c, "IN IP4 %256s", host) != 1) {
2019 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2022 /* XXX This could block for a long time, and block the main thread! XXX */
2023 hp = gethostbyname(host);
2025 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2028 sdpLineNum_iterator_init(&iterator);
2029 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2030 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
2032 // Scan through the RTP payload types specified in a "m=" line:
2033 ast_rtp_pt_clear(p->rtp);
2035 while(strlen(codecs)) {
2036 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2037 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2041 ast_verbose("Found audio format %s\n", ast_getformatname(codec));
2042 ast_rtp_set_m_type(p->rtp, codec);
2044 /* Skip over any whitespace */
2045 while(*codecs && (*codecs < 33)) codecs++;
2048 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2050 // Scan through the RTP payload types specified in a "m=" line:
2051 ast_rtp_pt_clear(p->vrtp);
2053 while(strlen(codecs)) {
2054 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2055 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2059 ast_verbose("Found video format %s\n", ast_getformatname(codec));
2060 ast_rtp_set_m_type(p->vrtp, codec);
2062 /* Skip over any whitespace */
2063 while(*codecs && (*codecs < 33)) codecs++;
2067 sin.sin_family = AF_INET;
2068 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2069 /* Setup audio port number */
2070 sin.sin_port = htons(portno);
2071 if (p->rtp && sin.sin_port)
2072 ast_rtp_set_peer(p->rtp, &sin);
2073 /* Setup video port number */
2074 sin.sin_port = htons(vportno);
2075 if (p->vrtp && sin.sin_port)
2076 ast_rtp_set_peer(p->vrtp, &sin);
2078 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2080 // Next, scan through each "a=rtpmap:" line, noting each
2081 // specified RTP payload type (with corresponding MIME subtype):
2082 sdpLineNum_iterator_init(&iterator);
2083 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2084 char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
2085 if (!strcasecmp(a, "sendonly")) {
2089 if (!strcasecmp(a, "sendrecv")) {
2092 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2094 ast_verbose("Found description format %s\n", mimeSubtype);
2095 // Note: should really look at the 'freq' and '#chans' params too
2096 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2098 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2101 // Now gather all of the codecs that were asked for:
2102 ast_rtp_get_current_formats(p->rtp,
2103 &peercapability, &peernoncodeccapability);
2105 ast_rtp_get_current_formats(p->vrtp,
2106 &vpeercapability, &vpeernoncodeccapability);
2107 p->jointcapability = p->capability & (peercapability | vpeercapability);
2108 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
2111 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
2112 p->capability, peercapability, vpeercapability, p->jointcapability);
2113 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
2114 noncodeccapability, peernoncodeccapability,
2115 p->noncodeccapability);
2117 if (!p->jointcapability) {
2118 ast_log(LOG_WARNING, "No compatible codecs!\n");
2122 if (!(p->owner->nativeformats & p->jointcapability)) {
2123 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);
2124 p->owner->nativeformats = sip_codec_choose(p->jointcapability);
2125 ast_set_read_format(p->owner, p->owner->readformat);
2126 ast_set_write_format(p->owner, p->owner->writeformat);
2128 if (p->owner->bridge) {
2129 /* Turn on/off music on hold if we are holding/unholding */
2130 if (sin.sin_addr.s_addr && !sendonly) {
2131 ast_moh_stop(p->owner->bridge);
2133 ast_moh_start(p->owner->bridge, NULL);
2141 static int add_header(struct sip_request *req, char *var, char *value)
2143 if (req->len >= sizeof(req->data) - 4) {
2144 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2148 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2151 req->header[req->headers] = req->data + req->len;
2152 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2153 req->len += strlen(req->header[req->headers]);
2154 if (req->headers < SIP_MAX_HEADERS)
2157 ast_log(LOG_WARNING, "Out of header space\n");
2163 static int add_blank_header(struct sip_request *req)
2165 if (req->len >= sizeof(req->data) - 4) {
2166 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2170 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2173 req->header[req->headers] = req->data + req->len;
2174 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2175 req->len += strlen(req->header[req->headers]);
2176 if (req->headers < SIP_MAX_HEADERS)
2179 ast_log(LOG_WARNING, "Out of header space\n");
2185 static int add_line(struct sip_request *req, char *line)
2187 if (req->len >= sizeof(req->data) - 4) {
2188 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2192 /* Add extra empty return */
2193 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2194 req->len += strlen(req->data + req->len);
2196 req->line[req->lines] = req->data + req->len;
2197 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2198 req->len += strlen(req->line[req->lines]);
2199 if (req->lines < SIP_MAX_LINES)
2202 ast_log(LOG_WARNING, "Out of line space\n");
2208 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2211 tmp = get_header(orig, field);
2213 /* Add what we're responding to */
2214 return add_header(req, field, tmp);
2216 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2220 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2226 tmp = __get_header(orig, field, &start);
2228 /* Add what we're responding to */
2229 add_header(req, field, tmp);
2234 return copied ? 0 : -1;
2237 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2244 tmp = __get_header(orig, field, &start);
2246 if (!copied && p->nat) {
2247 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2248 /* SLD: FIXME: Nice try, but the received= should not have a port */
2249 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2250 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
2252 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2253 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2256 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2257 add_header(req, field, new);
2259 /* Add what we're responding to */
2260 add_header(req, field, tmp);
2267 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2273 /* Add Route: header into request per learned route */
2274 static void add_route(struct sip_request *req, struct sip_route *route)
2277 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2283 n = strlen(route->hop);
2284 if ((n+3)>rem) break;
2290 strcpy(p, route->hop); p += n;
2293 route = route->next;
2296 add_header(req, "Route", r);
2299 static void set_destination(struct sip_pvt *p, char *uri)
2301 char *h, *maddr, hostname[256];
2305 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2306 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2309 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2311 /* Find and parse hostname */
2312 h = strchr(uri, '@');
2317 if (strncmp(h, "sip:", 4) == 0)
2319 else if (strncmp(h, "sips:", 5) == 0)
2322 hn = strcspn(h, ":;>");
2324 strncpy(hostname, h, hn); hostname[hn] = '\0';
2327 /* Is "port" present? if not default to 5060 */
2331 port = strtol(h, &h, 10);
2336 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2337 maddr = strstr(h, "maddr=");
2340 hn = strspn(maddr, "0123456789.");
2342 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2345 hp = gethostbyname(hostname);
2347 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2350 p->sa.sin_family = AF_INET;
2351 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2352 p->sa.sin_port = htons(port);
2354 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2357 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2359 /* Initialize a response */
2360 if (req->headers || req->len) {
2361 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2364 req->header[req->headers] = req->data + req->len;
2365 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2366 req->len += strlen(req->header[req->headers]);
2367 if (req->headers < SIP_MAX_HEADERS)
2370 ast_log(LOG_WARNING, "Out of header space\n");
2374 static int init_req(struct sip_request *req, char *resp, char *recip)
2376 /* Initialize a response */
2377 if (req->headers || req->len) {
2378 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2381 req->header[req->headers] = req->data + req->len;
2382 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2383 req->len += strlen(req->header[req->headers]);
2384 if (req->headers < SIP_MAX_HEADERS)
2387 ast_log(LOG_WARNING, "Out of header space\n");
2391 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2393 char newto[256] = "", *ot;
2394 memset(resp, 0, sizeof(*resp));
2395 init_resp(resp, msg, req);
2396 copy_via_headers(p, resp, req, "Via");
2397 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2398 copy_header(resp, req, "From");
2399 ot = get_header(req, "To");
2400 if (!strstr(ot, "tag=")) {
2401 /* Add the proper tag if we don't have it already. If they have specified
2402 their tag, use it. Otherwise, use our own tag */
2403 if (strlen(p->theirtag) && p->outgoing)
2404 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2405 else if (p->tag && !p->outgoing)
2406 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2408 strncpy(newto, ot, sizeof(newto) - 1);
2411 add_header(resp, "To", ot);
2412 copy_header(resp, req, "Call-ID");
2413 copy_header(resp, req, "CSeq");
2414 add_header(resp, "User-Agent", "Asterisk PBX");
2415 add_header(resp, "Allow", ALLOWED_METHODS);
2417 /* For registration responses, we also need expiry and
2421 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2422 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2423 add_header(resp, "Expires", tmp);
2424 add_header(resp, "Contact", contact);
2426 add_header(resp, "Contact", p->our_contact);
2431 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2433 struct sip_request *orig = &p->initreq;
2434 char stripped[80] ="";
2440 memset(req, 0, sizeof(struct sip_request));
2442 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2449 if (strlen(p->uri)) {
2453 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2455 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2457 c = strchr(stripped, '<');
2469 init_req(req, msg, c);
2471 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2473 add_header(req, "Via", p->via);
2475 set_destination(p, p->route->hop);
2476 add_route(req, p->route->next);
2479 ot = get_header(orig, "To");
2480 of = get_header(orig, "From");
2482 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2483 as our original request, including tag (or presumably lack thereof) */
2484 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2485 /* Add the proper tag if we don't have it already. If they have specified
2486 their tag, use it. Otherwise, use our own tag */
2487 if (p->outgoing && strlen(p->theirtag))
2488 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2489 else if (!p->outgoing)
2490 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2492 snprintf(newto, sizeof(newto), "%s", ot);
2497 add_header(req, "From", of);
2498 add_header(req, "To", ot);
2500 add_header(req, "From", ot);
2501 add_header(req, "To", of);
2503 add_header(req, "Contact", p->our_contact);
2504 copy_header(req, orig, "Call-ID");
2505 add_header(req, "CSeq", tmp);
2507 add_header(req, "User-Agent", "Asterisk PBX");
2511 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2513 struct sip_request resp;
2515 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2516 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2519 respprep(&resp, p, msg, req);
2520 add_header(&resp, "Content-Length", "0");
2521 add_blank_header(&resp);
2522 return send_response(p, &resp, reliable, seqno);
2525 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2527 return __transmit_response(p, msg, req, 0);
2529 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2531 return __transmit_response(p, msg, req, 1);
2534 static void append_date(struct sip_request *req)
2541 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2542 add_header(req, "Date", tmpdat);
2545 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2547 struct sip_request resp;
2548 respprep(&resp, p, msg, req);
2550 add_header(&resp, "Content-Length", "0");
2551 add_blank_header(&resp);
2552 return send_response(p, &resp, 0, 0);
2555 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2557 struct sip_request resp;
2558 respprep(&resp, p, msg, req);
2559 add_header(&resp, "Accept", "application/sdp");
2560 add_header(&resp, "Content-Length", "0");
2561 add_blank_header(&resp);
2562 return send_response(p, &resp, 0, 0);
2565 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2567 struct sip_request resp;
2570 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2571 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2574 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2575 respprep(&resp, p, msg, req);
2576 add_header(&resp, "Proxy-Authenticate", tmp);
2577 add_header(&resp, "Content-Length", "0");
2578 add_blank_header(&resp);
2579 return send_response(p, &resp, reliable, seqno);
2582 static int add_text(struct sip_request *req, char *text)
2584 /* XXX Convert \n's to \r\n's XXX */
2585 int len = strlen(text);
2587 snprintf(clen, sizeof(clen), "%d", len);
2588 add_header(req, "Content-Type", "text/plain");
2589 add_header(req, "Content-Length", clen);
2590 add_line(req, text);
2594 static int add_digit(struct sip_request *req, char digit)
2599 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2601 snprintf(clen, sizeof(clen), "%d", len);
2602 add_header(req, "Content-Type", "application/dtmf-relay");
2603 add_header(req, "Content-Length", clen);
2608 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2612 int alreadysent = 0;
2614 struct sockaddr_in sin;
2615 struct sockaddr_in vsin;
2616 struct sip_codec_pref *cur;
2627 struct sockaddr_in dest;
2628 struct sockaddr_in vdest = { 0, };
2629 /* XXX We break with the "recommendation" and send our IP, in order that our
2630 peer doesn't have to gethostbyname() us XXX */
2633 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2636 if (!p->sessionid) {
2637 p->sessionid = getpid();
2638 p->sessionversion = p->sessionid;
2640 p->sessionversion++;
2641 ast_rtp_get_us(p->rtp, &sin);
2643 ast_rtp_get_us(p->vrtp, &vsin);
2645 if (p->redirip.sin_addr.s_addr) {
2646 dest.sin_port = p->redirip.sin_port;
2647 dest.sin_addr = p->redirip.sin_addr;
2649 ast_rtp_get_peer(rtp, &dest);
2651 dest.sin_addr = p->ourip;
2652 dest.sin_port = sin.sin_port;
2655 /* Determine video destination */
2657 if (p->vredirip.sin_addr.s_addr) {
2658 vdest.sin_port = p->vredirip.sin_port;
2659 vdest.sin_addr = p->vredirip.sin_addr;
2661 ast_rtp_get_peer(vrtp, &vdest);
2663 vdest.sin_addr = p->ourip;
2664 vdest.sin_port = vsin.sin_port;
2668 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2669 if (sipdebug && p->vrtp)
2670 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2671 snprintf(v, sizeof(v), "v=0\r\n");
2672 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
2673 snprintf(s, sizeof(s), "s=session\r\n");
2674 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2675 snprintf(t, sizeof(t), "t=0 0\r\n");
2676 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2677 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2678 if (p->jointcapability & p->prefcodec) {
2680 ast_verbose("Answering/Requesting with root capability %d\n", p->prefcodec);
2681 codec = ast_rtp_lookup_code(p->rtp, 1, p->prefcodec);
2683 snprintf(costr, sizeof(costr), " %d", codec);
2684 if (p->prefcodec <= AST_FORMAT_MAX_AUDIO) {
2685 strncat(m, costr, sizeof(m) - strlen(m));
2686 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2687 strncat(a, costr, sizeof(a));
2689 strncat(m2, costr, sizeof(m2) - strlen(m2));
2690 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2691 strncat(a2, costr, sizeof(a2));
2694 alreadysent |= p->prefcodec;
2696 /* Start by sending our preferred codecs */
2699 if (p->jointcapability & cur->codec) {
2701 ast_verbose("Answering/Requesting with preferred capability %d\n", cur->codec);
2702 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2704 snprintf(costr, sizeof(costr), " %d", codec);
2705 if (cur->codec <= AST_FORMAT_MAX_AUDIO) {
2706 strncat(m, costr, sizeof(m) - strlen(m));
2707 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2708 strncat(a, costr, sizeof(a));
2710 strncat(m2, costr, sizeof(m2) - strlen(m2));
2711 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2712 strncat(a2, costr, sizeof(a2));
2716 alreadysent |= cur->codec;
2719 /* Now send any other common codecs, and non-codec formats: */
2720 for (x = 1; x <= (videosupport ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
2721 if ((p->jointcapability & x) && !(alreadysent & x)) {
2723 ast_verbose("Answering with capability %d\n", x);
2724 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2726 snprintf(costr, sizeof(costr), " %d", codec);
2727 if (x <= AST_FORMAT_MAX_AUDIO) {
2728 strncat(m, costr, sizeof(m) - strlen(m));
2729 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2730 strncat(a, costr, sizeof(a) - strlen(a));
2732 strncat(m2, costr, sizeof(m2) - strlen(m2));
2733 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2734 strncat(a2, costr, sizeof(a2) - strlen(a2));
2739 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2740 if (p->noncodeccapability & x) {
2742 ast_verbose("Answering with non-codec capability %d\n", x);
2743 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2745 snprintf(costr, sizeof(costr), " %d", codec);
2746 strncat(m, costr, sizeof(m) - strlen(m));
2747 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2748 strncat(a, costr, sizeof(a) - strlen(a));
2749 if (x == AST_RTP_DTMF) {
2750 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2751 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2753 strncat(a, costr, sizeof(a) - strlen(a));
2758 strncat(a, "a=silenceSupp:off - - - -\r\n", sizeof(a) - strlen(a));
2759 if (strlen(m) < sizeof(m) - 2)
2761 if (strlen(m2) < sizeof(m2) - 2)
2763 if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
2764 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
2765 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2767 len += strlen(m2) + strlen(a2);
2768 snprintf(costr, sizeof(costr), "%d", len);
2769 add_header(resp, "Content-Type", "application/sdp");
2770 add_header(resp, "Content-Length", costr);
2785 static void copy_request(struct sip_request *dst,struct sip_request *src)
2789 offset = ((void *)dst) - ((void *)src);
2790 /* First copy stuff */
2791 memcpy(dst, src, sizeof(*dst));
2792 /* Now fix pointer arithmetic */
2793 for (x=0;x<src->headers;x++)
2794 dst->header[x] += offset;
2795 for (x=0;x<src->lines;x++)
2796 dst->line[x] += offset;
2799 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2801 struct sip_request resp;
2803 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2804 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2807 respprep(&resp, p, msg, req);
2808 add_sdp(&resp, p, NULL, NULL);
2809 return send_response(p, &resp, retrans, seqno);
2812 static int determine_firstline_parts( struct sip_request *req ) {
2817 cmd= req->header[0];
2818 while(*cmd && (*cmd < 33)) {
2825 while(*e && (*e > 32)) {
2828 /* Get the command */
2834 while( *e && ( *e < 33 ) ) {
2841 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2842 /* We have a response */
2844 len= strlen( req->rlPart2 );
2845 if( len < 2 ) { return -1; }
2847 while( *e && *e<33 ) {
2852 /* We have a request */
2855 if( !*e ) { return -1; }
2858 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2861 while( isspace( *(--e) ) ) {}
2871 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2873 struct sip_request req;
2874 if (p->canreinvite == REINVITE_UPDATE)
2875 reqprep(&req, p, "UPDATE", 0);
2878 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2879 reqprep(&req, p, "INVITE", 0);
2881 add_header(&req, "Allow", ALLOWED_METHODS);
2882 add_sdp(&req, p, rtp, vrtp);
2883 /* Use this as the basis */
2884 copy_request(&p->initreq, &req);
2886 determine_firstline_parts(&p->initreq);
2887 p->lastinvite = p->ocseq;
2889 return send_request(p, &req, 1, p->ocseq);
2892 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
2894 char stripped[256]="";
2896 strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
2897 c = strchr(stripped, '<');
2909 strncpy(p->uri, c, sizeof(p->uri) - 1);
2912 static void build_contact(struct sip_pvt *p)
2914 /* Construct Contact: header */
2915 if (ourport != 5060)
2916 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2918 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2921 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2928 char *l = callerid, *n=NULL;
2930 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
2932 if (p->owner && p->owner->callerid) {
2933 strcpy(cid, p->owner->callerid);
2934 ast_callerid_parse(cid, &n, &l);
2936 ast_shrink_phone_number(l);
2937 if (!l || !ast_isphonenumber(l))
2940 /* if user want's his callerid restricted */
2941 if (p->restrictcid) {
2942 l = CALLERID_UNKNOWN;
2945 if (!n || !strlen(n))
2947 /* Allow user to be overridden */
2948 if (strlen(p->fromuser))
2951 if ((ourport != 5060) && !strlen(p->fromdomain))
2952 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);
2954 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2956 if (strlen(p->username)) {
2957 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2958 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2960 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2962 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2963 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2965 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2967 strncpy(p->uri, invite, sizeof(p->uri) - 1);
2968 /* If there is a VXML URL append it to the SIP URL */
2971 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2975 snprintf(to, sizeof(to), "<%s>", invite );
2977 memset(req, 0, sizeof(struct sip_request));
2978 init_req(req, cmd, invite);
2979 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2981 add_header(req, "Via", p->via);
2982 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2983 * OTOH, then we won't have anything in p->route anyway */
2984 add_header(req, "From", from);
2985 strncpy(p->exten, l, sizeof(p->exten) - 1);
2987 add_header(req, "To", to);
2988 add_header(req, "Contact", p->our_contact);
2989 add_header(req, "Call-ID", p->callid);
2990 add_header(req, "CSeq", tmp);
2991 add_header(req, "User-Agent", "Asterisk PBX");
2994 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, int init)
2996 struct sip_request req;
2999 initreqprep(&req, p, cmd, vxml_url);
3001 reqprep(&req, p, cmd, 0);
3004 add_header(&req, authheader, auth);
3006 if (!strcasecmp(cmd, "REFER")) {
3007 if (strlen(p->refer_to))
3008 add_header(&req, "Refer-To", p->refer_to);
3009 if (strlen(p->referred_by))
3010 add_header(&req, "Referred-By", p->referred_by);
3013 if (distinctive_ring)
3015 add_header(&req, "Alert-info",distinctive_ring);
3017 add_header(&req, "Allow", ALLOWED_METHODS);
3019 add_sdp(&req, p, NULL, NULL);
3021 add_header(&req, "Content-Length", "0");
3022 add_blank_header(&req);
3025 if (!p->initreq.headers) {
3026 /* Use this as the basis */
3027 copy_request(&p->initreq, &req);
3029 determine_firstline_parts(&p->initreq);
3031 p->lastinvite = p->ocseq;
3032 return send_request(p, &req, 1, p->ocseq);
3035 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
3038 char from[256], to[256];
3041 struct sip_request req;
3044 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
3046 c = ditch_braces(from);
3047 if (strncmp(c, "sip:", 4)) {
3048 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3051 if ((a = strchr(c, ';'))) {
3056 reqprep(&req, p, "NOTIFY", 0);
3058 if (p->subscribed == 1) {
3059 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
3061 c = ditch_braces(to);
3062 if (strncmp(c, "sip:", 4)) {
3063 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3066 if ((a = strchr(c, ';'))) {
3071 add_header(&req, "Content-Type", "application/xpidf+xml");
3073 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
3075 else if (state==AST_EXTENSION_INUSE)
3081 sprintf(t, "<?xml version=\"1.0\"?>\n");
3082 t = tmp + strlen(tmp);
3083 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
3084 t = tmp + strlen(tmp);
3085 sprintf(t, "<presence>\n");
3086 t = tmp + strlen(tmp);
3087 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
3088 t = tmp + strlen(tmp);
3089 sprintf(t, "<atom id=\"%s\">\n", p->exten);
3090 t = tmp + strlen(tmp);
3091 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
3092 t = tmp + strlen(tmp);
3093 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
3094 t = tmp + strlen(tmp);
3095 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
3096 t = tmp + strlen(tmp);
3097 sprintf(t, "</address>\n</atom>\n</presence>\n");
3099 add_header(&req, "Event", "dialog");
3100 add_header(&req, "Content-Type", "application/dialog-info+xml");
3103 sprintf(t, "<?xml version=\"1.0\"?>\n");
3104 t = tmp + strlen(tmp);
3105 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);
3106 t = tmp + strlen(tmp);
3107 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
3108 t = tmp + strlen(tmp);
3109 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
3110 t = tmp + strlen(tmp);
3111 sprintf(t, "</dialog>\n</dialog-info>\n");
3113 if (t > tmp + sizeof(tmp))
3114 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
3116 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
3117 add_header(&req, "Content-Length", clen);
3118 add_line(&req, tmp);
3120 return send_request(p, &req, 1, p->ocseq);
3123 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
3125 struct sip_request req;
3129 initreqprep(&req, p, "NOTIFY", NULL);
3130 add_header(&req, "Event", "message-summary");
3131 add_header(&req, "Content-Type", notifymime);
3133 snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
3134 snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
3135 snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
3136 add_header(&req, "Content-Length", clen);
3137 add_line(&req, tmp);
3138 add_line(&req, tmp2);
3140 if (!p->initreq.headers) {
3141 /* Use this as the basis */
3142 copy_request(&p->initreq, &req);
3144 determine_firstline_parts(&p->initreq);
3147 return send_request(p, &req, 1, p->ocseq);
3150 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
3152 static int sip_reregister(void *data)
3154 /* if we are here, we know that we need to reregister. */
3155 struct sip_registry *r=(struct sip_registry *)data;
3156 ast_mutex_lock(®l.lock);
3158 __sip_do_register(r);
3159 ast_mutex_unlock(®l.lock);
3164 static int __sip_do_register(struct sip_registry *r)
3167 res=transmit_register(r, "REGISTER", NULL, NULL);
3171 static int sip_reg_timeout(void *data)
3173 /* if we are here, our registration timed out, so we'll just do it over */
3174 struct sip_registry *r=data;
3177 ast_mutex_lock(®l.lock);
3178 ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
3180 /* Unlink us, destroy old call. Locking is not relevent here because all this happens
3181 in the single SIP manager thread. */
3187 r->regstate=REG_STATE_UNREGISTERED;
3189 res=transmit_register(r, "REGISTER", NULL, NULL);
3190 ast_mutex_unlock(®l.lock);
3194 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
3196 struct sip_request req;
3205 /* exit if we are already in process with this registrar ?*/
3206 if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
3207 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
3213 ast_log(LOG_WARNING, "Already have a call??\n");
3218 if (!r->callid_valid) {
3219 build_callid(r->callid, sizeof(r->callid), __ourip);
3220 r->callid_valid = 1;
3222 p=sip_alloc( r->callid, &r->addr, 0);
3224 ast_log(LOG_WARNING, "Unable to allocate registration call\n");
3230 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
3231 strncpy(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret)-1);
3232 if (strlen(r->authuser))
3233 strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
3235 strncpy(p->peername, r->username, sizeof(p->peername)-1);
3236 strncpy(p->username, r->username, sizeof(p->username)-1);
3237 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
3240 check which address we should use in our contact header
3241 based on whether the remote host is on the external or
3242 internal network so we can register through nat
3244 if ((hp = gethostbyname(r->hostname))) {
3245 if (ast_sip_ouraddrfor((struct in_addr *)hp->h_addr, &p->ourip))
3246 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
3251 /* set up a timeout */
3253 if (r->timeout > -1) {
3254 ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
3255 ast_sched_del(sched, r->timeout);
3257 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
3258 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
3261 if (strchr(r->username, '@')) {
3262 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
3263 snprintf(to, sizeof(to), "<sip:%s>", r->username);
3265 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
3266 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
3269 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
3270 strncpy(p->uri, addr, sizeof(p->uri) - 1);
3272 memset(&req, 0, sizeof(req));
3273 init_req(&req, cmd, addr);
3275 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
3276 p->ocseq = r->ocseq;
3278 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
3279 snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
3280 add_header(&req, "Via", via);
3281 add_header(&req, "From", from);
3282 add_header(&req, "To", to);
3283 add_header(&req, "Call-ID", p->callid);
3284 add_header(&req, "CSeq", tmp);
3285 add_header(&req, "User-Agent", "Asterisk PBX");
3287 add_header(&req, authheader, auth);
3289 snprintf(tmp, sizeof(tmp), "%d", default_expiry);
3290 add_header(&req, "Expires", tmp);
3291 add_header(&req, "Contact", p->our_contact);
3292 add_header(&req, "Event", "registration");
3293 add_header(&req, "Content-Length", "0");
3294 add_blank_header(&req);
3295 copy_request(&p->initreq, &req);
3297 determine_firstline_parts(&p->initreq);
3298 r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
3299 return send_request(p, &req, 1, p->ocseq);
3302 static int transmit_message_with_text(struct sip_pvt *p, char *text)
3304 struct sip_request req;
3305 reqprep(&req, p, "MESSAGE", 0);
3306 add_text(&req, text);
3307 return send_request(p, &req, 1, p->ocseq);
3310 static int transmit_refer(struct sip_pvt *p, char *dest)
3312 struct sip_request req;
3317 of = get_header(&p->initreq, "To");
3319 of = get_header(&p->initreq, "From");
3320 strncpy(from, of, sizeof(from) - 1);
3321 of = ditch_braces(from);
3322 strncpy(p->from,of,sizeof(p->from) - 1);
3323 if (strncmp(of, "sip:", 4)) {
3324 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3327 /* Get just the username part */
3328 if ((c = strchr(of, '@'))) {
3333 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
3335 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
3338 /* save in case we get 407 challenge */
3339 strncpy(p->refer_to, referto, sizeof(p->refer_to) - 1);
3340 strncpy(p->referred_by, p->our_contact, sizeof(p->referred_by) - 1);
3342 reqprep(&req, p, "REFER", 0);
3343 add_header(&req, "Refer-To", referto);
3344 if (strlen(p->our_contact))
3345 add_header(&req, "Referred-By", p->our_contact);
3346 add_blank_header(&req);
3347 return send_request(p, &req, 1, p->ocseq);
3350 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
3352 struct sip_request req;
3353 reqprep(&req, p, "INFO", 0);
3354 add_digit(&req, digit);
3355 return send_request(p, &req, 1, p->ocseq);
3358 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
3360 struct sip_request resp;
3361 reqprep(&resp, p, msg, seqno);
3362 add_header(&resp, "Content-Length", "0");
3363 add_blank_header(&resp);
3364 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3367 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
3369 struct sip_request resp;
3370 reqprep(&resp, p, msg, seqno);
3374 memset(digest,0,sizeof(digest));
3375 build_reply_digest(p, msg, digest, sizeof(digest));
3376 add_header(&resp, "Proxy-Authorization", digest);
3379 add_header(&resp, "Content-Length", "0");
3380 add_blank_header(&resp);
3381 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3384 static int expire_register(void *data)
3386 struct sip_peer *p = data;
3387 memset(&p->addr, 0, sizeof(p->addr));
3388 ast_db_del("SIP/Registry", p->name);
3390 ast_device_state_changed("SIP/%s", p->name);
3391 if (p->selfdestruct) {
3398 static int sip_poke_peer(struct sip_peer *peer);
3400 static void reg_source_db(struct sip_peer *p)
3406 if (!ast_db_get("SIP/Registry", p->name, data, sizeof(data))) {
3407 c = strchr(data, ':');
3411 if (inet_aton(data, &in)) {
3420 strncpy(p->username, u, sizeof(p->username));
3422 ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding '%s' at %s@%s:%d for %d\n", p->name,
3423 p->username, inet_ntoa(in), atoi(c), atoi(d));
3426 memset(&p->addr, 0, sizeof(p->addr));
3427 p->addr.sin_family = AF_INET;
3428 p->addr.sin_addr = in;
3429 p->addr.sin_port = htons(atoi(c));
3431 ast_sched_del(sched, p->expire);
3432 p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, (void *)p);
3440 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
3442 char contact[80]= "";
3444 char *expires = get_header(req, "Expires");
3445 int expiry = atoi(expires);
3449 struct sockaddr_in oldsin;
3450 if (!strlen(expires)) {
3451 expires = strstr(get_header(req, "Contact"), "expires=");
3453 if (sscanf(expires + 8, "%d;", &expiry) != 1)
3454 expiry = default_expiry;
3456 /* Nothing has been specified */
3457 expiry = default_expiry;
3460 /* Look for brackets */
3461 strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
3464 if ((n=strchr(c, '<'))) {
3467 /* Lose the part after the > */
3471 if (!strcasecmp(c, "*") || !expiry) {
3472 /* This means remove all registrations and return OK */
3473 memset(&p->addr, 0, sizeof(p->addr));
3475 ast_sched_del(sched, p->expire);
3477 ast_db_del("SIP/Registry", p->name);
3478 if (option_verbose > 2)
3479 ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->name);
3482 /* Make sure it's a SIP URL */
3483 if (strncasecmp(c, "sip:", 4)) {
3484 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
3500 pt = strchr(n, ':');
3506 port = DEFAULT_SIP_PORT;
3507 memcpy(&oldsin, &p->addr, sizeof(oldsin));
3509 /* XXX This could block for a long time XXX */
3510 hp = gethostbyname(n);
3512 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
3515 p->addr.sin_family = AF_INET;
3516 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
3517 p->addr.sin_port = htons(port);
3519 /* Don't trust the contact field. Just use what they came to us
3521 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
3524 strncpy(p->username, c, sizeof(p->username) - 1);
3526 strcpy(p->username, "");
3528 ast_sched_del(sched, p->expire);
3529 if ((expiry < 1) || (expiry > max_expiry))
3530 expiry = max_expiry;