2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Session Initiation Protocol
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
18 #include <asterisk/lock.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <asterisk/lock.h>
27 #include <asterisk/sched.h>
28 #include <asterisk/io.h>
29 #include <asterisk/rtp.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/md5.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <asterisk/parking.h>
38 #include <asterisk/acl.h>
39 #include <asterisk/srv.h>
40 #include <asterisk/astdb.h>
41 #include <asterisk/causes.h>
42 #include <sys/socket.h>
43 #include <sys/ioctl.h>
50 #include <arpa/inet.h>
51 #include <sys/signal.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
56 #include <mysql/mysql.h>
60 #define IPTOS_MINCOST 0x02
63 /* #define VOCAL_DATA_HACK */
66 #define DEFAULT_DEFAULT_EXPIRY 120
67 #define DEFAULT_MAX_EXPIRY 3600
68 #define EXPIRY_GUARD_SECS 15
70 #define CALLERID_UNKNOWN "Unknown"
72 #define SIP_DTMF_RFC2833 (1 << 0)
73 #define SIP_DTMF_INBAND (1 << 1)
74 #define SIP_DTMF_INFO (1 << 2)
76 static int max_expiry = DEFAULT_MAX_EXPIRY;
77 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
79 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
80 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
81 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
83 #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
84 #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
87 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
89 static char mydbuser[80];
90 static char mydbpass[80];
91 static char mydbhost[80];
92 static char mydbname[80];
95 static char *desc = "Session Initiation Protocol (SIP)";
96 static char *type = "SIP";
97 static char *tdesc = "Session Initiation Protocol (SIP)";
98 static char *config = "sip.conf";
100 #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
101 #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
103 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
105 static char context[AST_MAX_EXTENSION] = "default";
107 static char language[MAX_LANGUAGE] = "";
109 static char callerid[AST_MAX_EXTENSION] = "asterisk";
111 static char fromdomain[AST_MAX_EXTENSION] = "";
113 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
115 static int srvlookup = 0;
117 static int pedanticsipchecking = 0;
119 static int autocreatepeer = 0;
121 static int usecnt =0;
122 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
124 /* Protect the interface list (of sip_pvt's) */
125 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
127 /* Protect the monitoring thread, so only one process can kill or start it, and not
128 when it's doing something critical. */
129 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
131 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
133 /* This is the thread for the monitor which checks for input on the channels
134 which are not currently in use. */
135 static pthread_t monitor_thread = 0;
137 static int restart_monitor(void);
139 /* Codecs that we support by default: */
140 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
141 static int noncodeccapability = AST_RTP_DTMF;
143 static char ourhost[256];
144 static struct in_addr __ourip;
147 static int sipdebug = 0;
151 static int videosupport = 0;
153 static int globaldtmfmode = SIP_DTMF_RFC2833;
156 static int expiry = 900;
158 static struct sched_context *sched;
159 static struct io_context *io;
160 /* The private structures of the sip channels are linked for
161 selecting outgoing channels */
163 #define SIP_MAX_HEADERS 64
164 #define SIP_MAX_LINES 64
168 #define DEC_OUT_USE 2
169 #define INC_OUT_USE 3
171 static struct sip_codec_pref {
173 struct sip_codec_pref *next;
177 char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
178 char *rlPart2; /* The Request URI or Response Status */
180 int headers; /* SIP Headers */
181 char *header[SIP_MAX_HEADERS];
182 int lines; /* SDP Content */
183 char *line[SIP_MAX_LINES];
184 char data[SIP_MAX_PACKET];
190 struct sip_route *next;
194 static struct sip_pvt {
195 ast_mutex_t lock; /* Channel private lock */
196 char callid[80]; /* Global CallID */
197 char randdata[80]; /* Random data */
198 unsigned int ocseq; /* Current outgoing seqno */
199 unsigned int icseq; /* Current incoming seqno */
200 unsigned int callgroup;
201 unsigned int pickupgroup;
202 int lastinvite; /* Last Cseq of invite */
203 int alreadygone; /* Whether or not we've already been destroyed by or peer */
204 int needdestroy; /* if we need to be destroyed */
205 int capability; /* Special capability */
206 int jointcapability; /* Supported capability at both ends */
207 int noncodeccapability;
208 int outgoing; /* Outgoing or incoming call? */
209 int authtries; /* Times we've tried to authenticate */
210 int insecure; /* Don't check source port/ip */
211 int expiry; /* How long we take to expire */
212 int branch; /* One random number */
213 int canreinvite; /* Do we support reinvite */
214 int ringing; /* Have sent 180 ringing */
215 int progress; /* Have sent 183 message progress */
216 int tag; /* Another random number */
217 int nat; /* Whether to try to support NAT */
218 int sessionid; /* SDP Session ID */
219 int sessionversion; /* SDP Session Version */
220 struct sockaddr_in sa; /* Our peer */
221 struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
222 struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
223 struct sockaddr_in recv; /* Received as */
224 struct in_addr ourip; /* Our IP */
225 struct ast_channel *owner; /* Who owns us */
226 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
227 char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
228 char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
229 char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
230 struct sip_pvt *refer_call; /* Call we are referring */
231 struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
232 char remote_party_id[256];
234 char context[AST_MAX_EXTENSION];
235 char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
236 char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
237 char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
238 char language[MAX_LANGUAGE];
239 char rdnis[256]; /* Referring DNIS */
240 char theirtag[256]; /* Their tag */
243 char uri[256]; /* Original requested URI */
244 char peersecret[256];
245 char peermd5secret[256];
246 char callerid[256]; /* Caller*ID */
247 int restrictcid; /* hide presentation from remote user */
249 char accountcode[20]; /* Account code */
250 char our_contact[256]; /* Our contact header */
251 char realm[256]; /* Authorization realm */
252 char nonce[256]; /* Authorization nonce */
253 char domain[256]; /* Authorization nonce */
254 char lastmsg[256]; /* Last Message sent/received */
255 int amaflags; /* AMA Flags */
256 int pendinginvite; /* Any pending invite */
257 int pendingbye; /* Need to send bye after we ack? */
258 int gotrefer; /* Got a refer? */
259 struct sip_request initreq; /* Initial request */
261 int maxtime; /* Max time for first response */
262 int initid; /* Auto-congest ID if appropriate */
263 int autokillid; /* Auto-kill ID */
272 struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
273 struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
274 struct ast_rtp *rtp; /* RTP Session */
275 struct ast_rtp *vrtp; /* Video RTP session */
276 struct sip_pkt *packets; /* Packets scheduled for re-transmission */
277 struct sip_pvt *next;
281 struct sip_pkt *next; /* Next packet */
282 int retrans; /* Retransmission number */
283 int seqno; /* Sequence number */
284 int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
285 struct sip_pvt *owner; /* Owner call */
286 int retransid; /* Retransmission ID */
287 int packetlen; /* Length of packet */
292 /* Users who can access various contexts */
299 char accountcode[20];
300 char language[MAX_LANGUAGE];
301 unsigned int callgroup;
302 unsigned int pickupgroup;
316 struct sip_user *next;
323 char context[80]; /* JK02: peers need context too to allow parking etc */
329 char mailbox[AST_MAX_EXTENSION];
339 unsigned int callgroup;
340 unsigned int pickupgroup;
342 struct sockaddr_in addr;
346 struct sip_pvt *call; /* Call pointer */
347 int pokeexpire; /* When to expire poke */
348 int lastms; /* How long last response took (in ms), or -1 for no response */
349 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
350 struct timeval ps; /* Ping send time */
352 struct sockaddr_in defaddr;
358 struct sip_peer *next;
361 static struct ast_user_list {
362 struct sip_user *users;
364 } userl = { NULL, AST_MUTEX_INITIALIZER };
366 static struct ast_peer_list {
367 struct sip_peer *peers;
369 } peerl = { NULL, AST_MUTEX_INITIALIZER };
371 ast_mutex_t sip_reload_lock = AST_MUTEX_INITIALIZER;
373 #define REG_STATE_UNREGISTERED 0
374 #define REG_STATE_REGSENT 1
375 #define REG_STATE_AUTHSENT 2
376 #define REG_STATE_REGISTERED 3
377 #define REG_STATE_REJECTED 4
378 #define REG_STATE_TIMEOUT 5
379 #define REG_STATE_NOAUTH 6
381 struct sip_registry {
382 ast_mutex_t lock; /* Channel private lock */
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 #define REINVITE_INVITE 1
404 #define REINVITE_UPDATE 2
406 static int sip_do_register(struct sip_registry *r);
407 static struct sip_registry *registrations;
409 static int sipsock = -1;
410 static int globalnat = 0;
411 static int globalcanreinvite = REINVITE_INVITE;
414 static struct sockaddr_in bindaddr;
415 static struct sockaddr_in localnet;
416 static struct sockaddr_in localmask;
417 static struct sockaddr_in externip;
419 static struct ast_frame *sip_read(struct ast_channel *ast);
420 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
421 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
422 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
423 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
424 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
425 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
426 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
427 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
428 static int transmit_message_with_text(struct sip_pvt *p, char *text);
429 static int transmit_refer(struct sip_pvt *p, char *dest);
430 static struct sip_peer *temp_peer(char *name);
431 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
432 // static char *getsipuri(char *header);
433 static void free_old_route(struct sip_route *route);
434 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
435 static int find_user(struct sip_pvt *fup, int event);
436 static void prune_peers(void);
438 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
442 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
444 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
446 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));
451 static void sip_destroy(struct sip_pvt *p);
453 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
456 check to see if them is contained in our localnet/mask,
457 if not, use our externip for us, otherwise use the
458 real internal address in bindaddr
460 if (localnet.sin_addr.s_addr && externip.sin_addr.s_addr &&
461 ((htonl(them->s_addr) & htonl(localnet.sin_addr.s_addr)) != htonl(localnet.sin_addr.s_addr)))
462 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
463 else if (bindaddr.sin_addr.s_addr)
464 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
466 return ast_ouraddrfor(them, us);
470 static int retrans_pkt(void *data)
472 struct sip_pkt *pkt=data;
474 ast_mutex_lock(&pkt->owner->lock);
475 if (pkt->retrans < MAX_RETRANS) {
479 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));
481 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));
483 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
486 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
488 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
489 ast_mutex_unlock(&pkt->owner->lock);
491 ast_mutex_lock(&pkt->owner->lock);
493 if (pkt->owner->owner) {
494 /* XXX Potential deadlocK?? XXX */
495 ast_queue_hangup(pkt->owner->owner, 0);
496 ast_mutex_unlock(&pkt->owner->owner->lock);
498 /* If no owner, destroy now */
499 pkt->owner->needdestroy = 1;
503 ast_mutex_unlock(&pkt->owner->lock);
507 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
510 pkt = malloc(sizeof(struct sip_pkt) + len);
513 memset(pkt, 0, sizeof(struct sip_pkt));
514 memcpy(pkt->data, data, len);
515 pkt->packetlen = len;
516 pkt->next = p->packets;
520 /* Schedule retransmission */
521 pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
522 pkt->next = p->packets;
524 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
525 if (!strncasecmp(pkt->data, "INVITE", 6)) {
526 /* Note this is a pending invite */
527 p->pendinginvite = seqno;
532 static int __sip_autodestruct(void *data)
534 struct sip_pvt *p = data;
536 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
538 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
539 ast_queue_hangup(p->owner, 0);
546 static int sip_scheddestroy(struct sip_pvt *p, int ms)
548 if (p->autokillid > -1)
549 ast_sched_del(sched, p->autokillid);
550 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
554 static int sip_cancel_destroy(struct sip_pvt *p)
556 if (p->autokillid > -1)
557 ast_sched_del(sched, p->autokillid);
562 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
564 struct sip_pkt *cur, *prev = NULL;
569 if ((cur->seqno == seqno) && (cur->resp == resp)) {
570 if (!resp && (seqno == p->pendinginvite)) {
571 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
572 p->pendinginvite = 0;
575 /* this is our baby */
577 prev->next = cur->next;
579 p->packets = cur->next;
580 if (cur->retransid > -1)
581 ast_sched_del(sched, cur->retransid);
589 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
593 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
599 if ((cur->seqno == seqno) && (cur->resp == resp)) {
600 /* this is our baby */
601 if (cur->retransid > -1)
602 ast_sched_del(sched, cur->retransid);
609 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");
613 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
618 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));
620 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));
623 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
625 res = __sip_xmit(p, req->data, req->len);
631 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
636 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));
638 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));
641 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
643 res = __sip_xmit(p, req->data, req->len);
647 static char *ditch_braces(char *tmp)
651 if ((n = strchr(tmp, '<')) ) {
653 while(*c && *c != '>') c++;
655 ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
664 static int sip_sendtext(struct ast_channel *ast, char *text)
666 struct sip_pvt *p = ast->pvt->pvt;
668 ast_verbose("Sending text %s on %s\n", text, ast->name);
671 if (!text || !strlen(text))
674 ast_verbose("Really sending text %s on %s\n", text, ast->name);
675 transmit_message_with_text(p, text);
681 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
683 if (mysql && (strlen(peer) < 128)) {
687 name = alloca(strlen(peer) * 2 + 1);
689 mysql_real_escape_string(mysql, name, peer, strlen(peer));
690 snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
691 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
692 ast_mutex_lock(&mysqllock);
693 if (mysql_real_query(mysql, query, strlen(query)))
694 ast_log(LOG_WARNING, "Unable to update database\n");
696 ast_mutex_unlock(&mysqllock);
700 static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
705 p = malloc(sizeof(struct sip_peer));
706 memset(p, 0, sizeof(struct sip_peer));
707 if (mysql && (!peer || (strlen(peer) < 128))) {
712 time_t regseconds, nowtime;
717 name = alloca(strlen(peer) * 2 + 1);
718 mysql_real_escape_string(mysql, name, peer, strlen(peer));
721 snprintf(query, sizeof(query), "SELECT * FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
723 snprintf(query, sizeof(query), "SELECT * FROM sipfriends WHERE name=\"%s\"", name);
724 ast_mutex_lock(&mysqllock);
725 mysql_query(mysql, query);
726 if ((result = mysql_store_result(mysql))) {
727 if ((rowval = mysql_fetch_row(result))) {
728 numfields = mysql_num_fields(result);
729 fields = mysql_fetch_fields(result);
731 for (x=0;x<numfields;x++) {
733 if (!strcasecmp(fields[x].name, "secret")) {
734 strncpy(p->secret, rowval[x], sizeof(p->secret));
735 } else if (!strcasecmp(fields[x].name, "name")) {
736 strncpy(p->name, rowval[x], sizeof(p->name) - 1);
737 } else if (!strcasecmp(fields[x].name, "context")) {
738 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
739 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
740 inet_aton(rowval[x], &p->addr.sin_addr);
741 } else if (!strcasecmp(fields[x].name, "port")) {
742 if (sscanf(rowval[x], "%i", &port) != 1)
744 p->addr.sin_port = htons(port);
745 } else if (!strcasecmp(fields[x].name, "regseconds")) {
746 if (sscanf(rowval[x], "%li", ®seconds) != 1)
752 if ((nowtime - regseconds) > default_expiry)
753 memset(&p->addr, 0, sizeof(p->addr));
756 ast_mutex_unlock(&mysqllock);
763 p->capability = capability;
765 p->dtmfmode = globaldtmfmode;
773 #endif /* MYSQL_FRIENDS */
775 static int create_addr(struct sip_pvt *r, char *peer)
782 char host[256], *hostn;
784 r->sa.sin_family = AF_INET;
785 ast_mutex_lock(&peerl.lock);
788 if (!strcasecmp(p->name, peer))
794 p = mysql_peer(peer, NULL);
799 r->capability = p->capability;
802 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
803 ast_rtp_setnat(r->rtp, r->nat);
806 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
807 ast_rtp_setnat(r->vrtp, r->nat);
809 strncpy(r->peername, p->username, sizeof(r->peername)-1);
810 strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
811 strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
812 strncpy(r->username, p->username, sizeof(r->username)-1);
813 strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
814 if (!strlen(r->tohost)) {
815 if (p->addr.sin_addr.s_addr)
816 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
818 snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
820 if (strlen(p->fromdomain))
821 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
822 if (strlen(p->fromuser))
823 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
824 r->insecure = p->insecure;
825 r->canreinvite = p->canreinvite;
826 r->maxtime = p->maxms;
827 r->callgroup = p->callgroup;
828 r->pickupgroup = p->pickupgroup;
830 r->dtmfmode = p->dtmfmode;
831 if (r->dtmfmode & SIP_DTMF_RFC2833)
832 r->noncodeccapability |= AST_RTP_DTMF;
834 r->noncodeccapability &= ~AST_RTP_DTMF;
836 strncpy(r->context, p->context,sizeof(r->context)-1);
837 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
838 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
839 if (p->addr.sin_addr.s_addr) {
840 r->sa.sin_addr = p->addr.sin_addr;
841 r->sa.sin_port = p->addr.sin_port;
843 r->sa.sin_addr = p->defaddr.sin_addr;
844 r->sa.sin_port = p->defaddr.sin_port;
846 memcpy(&r->recv, &r->sa, sizeof(r->recv));
850 ast_mutex_unlock(&peerl.lock);
852 if ((port=strchr(peer, ':'))) {
860 portno = DEFAULT_SIP_PORT;
865 snprintf(service, sizeof(service), "_sip._udp.%s", peer);
866 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
872 hp = gethostbyname(hostn);
874 strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
875 memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
876 r->sa.sin_port = htons(portno);
877 memcpy(&r->recv, &r->sa, sizeof(r->recv));
880 ast_log(LOG_WARNING, "No such host: %s\n", peer);
892 static int auto_congest(void *nothing)
894 struct sip_pvt *p = nothing;
895 ast_mutex_lock(&p->lock);
898 if (!ast_mutex_trylock(&p->owner->lock)) {
899 ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
900 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
901 ast_mutex_unlock(&p->owner->lock);
904 ast_mutex_unlock(&p->lock);
908 static void sip_prefs_free(void)
910 struct sip_codec_pref *cur, *next;
920 static void sip_pref_remove(int format)
922 struct sip_codec_pref *cur, *prev=NULL;
925 if (cur->codec == format) {
927 prev->next = cur->next;
938 static int sip_pref_append(int format)
940 struct sip_codec_pref *cur, *tmp;
941 sip_pref_remove(format);
942 tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
945 memset(tmp, 0, sizeof(struct sip_codec_pref));
957 static int sip_codec_choose(int formats)
959 struct sip_codec_pref *cur;
960 formats &= (AST_FORMAT_MAX_AUDIO - 1);
963 if (formats & cur->codec)
967 return ast_best_codec(formats);
970 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
974 char *vxml_url = NULL;
975 char *distinctive_ring = NULL;
976 struct varshead *headp;
977 struct ast_var_t *current;
980 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
981 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
984 /* Check whether there is vxml_url, distinctive ring variables */
986 headp=&ast->varshead;
987 AST_LIST_TRAVERSE(headp,current,entries) {
988 /* Check whether there is a VXML_URL variable */
989 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
991 vxml_url = ast_var_value(current);
994 /* Check whether there is a ALERT_INFO variable */
995 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
997 distinctive_ring = ast_var_value(current);
1004 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1005 res = find_user(p,INC_OUT_USE);
1007 p->restrictcid = ast->restrictcid;
1008 p->jointcapability = p->capability;
1009 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
1011 /* Initialize auto-congest time */
1012 p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1018 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1020 struct sip_pvt *cur, *prev = NULL;
1023 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
1024 if (p->stateid > -1)
1025 ast_extension_state_del(p->stateid, NULL);
1027 ast_sched_del(sched, p->initid);
1028 if (p->autokillid > -1)
1029 ast_sched_del(sched, p->autokillid);
1032 ast_rtp_destroy(p->rtp);
1035 ast_rtp_destroy(p->vrtp);
1038 free_old_route(p->route);
1042 /* Carefully unlink from registry */
1043 struct sip_registry *reg;
1044 reg = registrations;
1046 if ((reg == p->registry) && (p->registry->call == p))
1047 p->registry->call=NULL;
1051 /* Unlink us from the owner if we have one */
1054 ast_mutex_lock(&p->owner->lock);
1055 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1056 p->owner->pvt->pvt = NULL;
1058 ast_mutex_unlock(&p->owner->lock);
1064 prev->next = cur->next;
1073 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1076 ast_sched_del(sched, p->initid);
1077 while((cp = p->packets)) {
1078 p->packets = p->packets->next;
1079 if (cp->retransid > -1)
1080 ast_sched_del(sched, cp->retransid);
1087 static int find_user(struct sip_pvt *fup, int event)
1089 char name[256] = "";
1091 strncpy(name, fup->username, sizeof(name) - 1);
1092 ast_mutex_lock(&userl.lock);
1095 if (!strcasecmp(u->name, name)) {
1101 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1102 ast_mutex_unlock(&userl.lock);
1106 /* incoming and outgoing affects the inUse counter */
1109 if ( u->inUse > 0 ) {
1117 if (u->incominglimit > 0 ) {
1118 if (u->inUse >= u->incominglimit) {
1119 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
1120 ast_mutex_unlock(&userl.lock);
1121 /* inc inUse as well */
1122 if ( event == INC_OUT_USE ) {
1129 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1131 /* we don't use these anymore
1133 if ( u->outUse > 0 ) {
1140 if ( u->outgoinglimit > 0 ) {
1141 if ( u->outUse >= u->outgoinglimit ) {
1142 ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1143 ast_mutex_unlock(&userl.lock);
1151 ast_log(LOG_ERROR, "find_user(%s,%d) called with no event!\n",u->name,event);
1153 ast_mutex_unlock(&userl.lock);
1157 static void sip_destroy(struct sip_pvt *p)
1159 ast_mutex_lock(&iflock);
1160 __sip_destroy(p, 1);
1161 ast_mutex_unlock(&iflock);
1164 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
1166 static int hangup_sip2cause(int cause)
1171 return AST_CAUSE_BUSY;
1173 return AST_CAUSE_NORMAL;
1179 static char *hangup_cause2sip(int cause)
1183 case AST_CAUSE_BUSY:
1192 static int sip_hangup(struct ast_channel *ast)
1194 struct sip_pvt *p = ast->pvt->pvt;
1196 int needdestroy = 0;
1198 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1199 if (!ast->pvt->pvt) {
1200 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1203 ast_mutex_lock(&p->lock);
1204 if ( p->outgoing ) {
1205 ast_log(LOG_DEBUG, "find_user(%s) - decrement outUse counter\n", p->username);
1206 find_user(p, DEC_OUT_USE);
1208 ast_log(LOG_DEBUG, "find_user(%s) - decrement inUse counter\n", p->username);
1209 find_user(p, DEC_IN_USE);
1211 /* Determine how to disconnect */
1212 if (p->owner != ast) {
1213 ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
1214 ast_mutex_unlock(&p->lock);
1217 if (!ast || (ast->_state != AST_STATE_UP))
1222 ast_dsp_free(p->vad);
1225 ast->pvt->pvt = NULL;
1227 ast_mutex_lock(&usecnt_lock);
1229 ast_mutex_unlock(&usecnt_lock);
1230 ast_update_use_count();
1233 /* Start the process if it's not already started */
1234 if (!p->alreadygone && strlen(p->initreq.data)) {
1237 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
1238 /* Actually don't destroy us yet, wait for the 487 on our original
1239 INVITE, but do set an autodestruct just in case. */
1241 sip_scheddestroy(p, 15000);
1242 if ( p->initid != -1 ) {
1243 /* channel still up - reverse dec of inUse counter
1244 only if the channel is not auto-congested */
1245 if ( p->outgoing ) {
1246 find_user(p, INC_OUT_USE);
1249 find_user(p, INC_IN_USE);
1254 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1255 transmit_response_reliable(p, res, &p->initreq);
1257 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
1260 if (!p->pendinginvite) {
1262 transmit_request_with_auth(p, "BYE", 0, 1);
1264 /* Note we will need a BYE when this all settles out
1265 but we can't send one while we have "INVITE" outstanding. */
1270 p->needdestroy = needdestroy;
1271 ast_mutex_unlock(&p->lock);
1275 static int sip_answer(struct ast_channel *ast)
1279 struct sip_pvt *p = ast->pvt->pvt;
1282 if (ast->_state != AST_STATE_UP) {
1286 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1288 fmt=ast_getformatbyname(codec);
1290 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1291 p->jointcapability=fmt;
1292 } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1295 ast_setstate(ast, AST_STATE_UP);
1297 ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1298 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1303 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1305 struct sip_pvt *p = ast->pvt->pvt;
1307 if (frame->frametype == AST_FRAME_VOICE) {
1308 if (!(frame->subclass & ast->nativeformats)) {
1309 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1310 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1314 ast_mutex_lock(&p->lock);
1316 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1317 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1320 res = ast_rtp_write(p->rtp, frame);
1322 ast_mutex_unlock(&p->lock);
1324 } else if (frame->frametype == AST_FRAME_VIDEO) {
1326 ast_mutex_lock(&p->lock);
1328 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1329 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1332 res = ast_rtp_write(p->vrtp, frame);
1334 ast_mutex_unlock(&p->lock);
1336 } else if (frame->frametype == AST_FRAME_IMAGE) {
1339 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1346 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1348 struct sip_pvt *p = newchan->pvt->pvt;
1349 ast_mutex_lock(&p->lock);
1350 if (p->owner != oldchan) {
1351 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1352 ast_mutex_unlock(&p->lock);
1356 ast_mutex_unlock(&p->lock);
1360 static int sip_senddigit(struct ast_channel *ast, char digit)
1362 struct sip_pvt *p = ast->pvt->pvt;
1363 if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1364 transmit_info_with_digit(p, digit);
1366 if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1367 ast_rtp_senddigit(p->rtp, digit);
1369 /* If in-band DTMF is desired, send that */
1370 if (p->dtmfmode & SIP_DTMF_INBAND)
1375 static int sip_transfer(struct ast_channel *ast, char *dest)
1377 struct sip_pvt *p = ast->pvt->pvt;
1379 res = transmit_refer(p, dest);
1383 static int sip_indicate(struct ast_channel *ast, int condition)
1385 struct sip_pvt *p = ast->pvt->pvt;
1387 case AST_CONTROL_RINGING:
1388 if (ast->_state == AST_STATE_RING) {
1389 if (!p->progress && !p->ringing) {
1390 transmit_response(p, "180 Ringing", &p->initreq);
1394 /* Oops, we've sent progress tones. Let Asterisk do it instead */
1398 case AST_CONTROL_BUSY:
1399 if (ast->_state != AST_STATE_UP) {
1400 transmit_response(p, "486 Busy Here", &p->initreq);
1402 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1406 case AST_CONTROL_CONGESTION:
1407 if (ast->_state != AST_STATE_UP) {
1408 transmit_response(p, "503 Service Unavailable", &p->initreq);
1410 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1414 case AST_CONTROL_PROGRESS:
1415 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1416 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1424 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1432 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1434 struct ast_channel *tmp;
1436 tmp = ast_channel_alloc(1);
1438 /* Select our native format based on codec preference until we receive
1439 something from another device to the contrary. */
1440 if (i->jointcapability)
1441 tmp->nativeformats = sip_codec_choose(i->jointcapability);
1442 else if (i->capability)
1443 tmp->nativeformats = sip_codec_choose(i->capability);
1445 tmp->nativeformats = sip_codec_choose(capability);
1446 fmt = ast_best_codec(tmp->nativeformats);
1448 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1450 if (strchr(i->fromdomain,':'))
1452 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1456 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1459 if (i->dtmfmode & SIP_DTMF_INBAND) {
1460 i->vad = ast_dsp_new();
1461 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1463 tmp->fds[0] = ast_rtp_fd(i->rtp);
1464 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1466 tmp->fds[2] = ast_rtp_fd(i->vrtp);
1467 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1469 ast_setstate(tmp, state);
1470 if (state == AST_STATE_RING)
1472 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1473 tmp->writeformat = fmt;
1474 tmp->pvt->rawwriteformat = fmt;
1475 tmp->readformat = fmt;
1476 tmp->pvt->rawreadformat = fmt;
1478 tmp->pvt->send_text = sip_sendtext;
1479 tmp->pvt->call = sip_call;
1480 tmp->pvt->hangup = sip_hangup;
1481 tmp->pvt->answer = sip_answer;
1482 tmp->pvt->read = sip_read;
1483 tmp->pvt->write = sip_write;
1484 tmp->pvt->write_video = sip_write;
1485 tmp->pvt->indicate = sip_indicate;
1486 tmp->pvt->transfer = sip_transfer;
1487 tmp->pvt->fixup = sip_fixup;
1488 tmp->pvt->send_digit = sip_senddigit;
1490 tmp->pvt->bridge = ast_rtp_bridge;
1492 tmp->callgroup = i->callgroup;
1493 tmp->pickupgroup = i->pickupgroup;
1494 tmp->restrictcid = i->restrictcid;
1495 if (strlen(i->accountcode))
1496 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1498 tmp->amaflags = i->amaflags;
1499 if (strlen(i->language))
1500 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1502 ast_mutex_lock(&usecnt_lock);
1504 ast_mutex_unlock(&usecnt_lock);
1505 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1506 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1507 if (strlen(i->callerid))
1508 tmp->callerid = strdup(i->callerid);
1509 if (strlen(i->rdnis))
1510 tmp->rdnis = strdup(i->rdnis);
1512 if (strlen(i->domain)) {
1513 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1516 if (state != AST_STATE_DOWN) {
1517 if (ast_pbx_start(tmp)) {
1518 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1524 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1528 static struct cfalias {
1532 { "Content-Type", "c" },
1533 { "Content-Encoding", "e" },
1537 { "Content-Length", "l" },
1543 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1544 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1545 char* r = line + nameLen + 1;
1546 while (*r && (*r < 33)) ++r;
1553 static char *get_sdp(struct sip_request *req, char *name) {
1555 int len = strlen(name);
1558 for (x=0; x<req->lines; x++) {
1559 r = get_sdp_by_line(req->line[x], name, len);
1560 if (r[0] != '\0') return r;
1565 static void sdpLineNum_iterator_init(int* iterator) {
1569 static char* get_sdp_iterate(int* iterator,
1570 struct sip_request *req, char *name) {
1571 int len = strlen(name);
1573 while (*iterator < req->lines) {
1574 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1575 if (r[0] != '\0') return r;
1580 static char *__get_header(struct sip_request *req, char *name, int *start)
1583 int len = strlen(name);
1585 for (x=*start;x<req->headers;x++) {
1586 if (!strncasecmp(req->header[x], name, len) &&
1587 (req->header[x][len] == ':')) {
1588 r = req->header[x] + len + 1;
1589 while(*r && (*r < 33))
1596 for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
1597 if (!strcasecmp(aliases[x].fullname, name))
1598 return __get_header(req, aliases[x].shortname, start);
1600 /* Don't return NULL, so get_header is always a valid pointer */
1604 static char *get_header(struct sip_request *req, char *name)
1607 return __get_header(req, name, &start);
1610 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1612 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
1613 struct ast_frame *f;
1614 static struct ast_frame null_frame = { AST_FRAME_NULL, };
1617 f = ast_rtp_read(p->rtp);
1620 f = ast_rtcp_read(p->rtp);
1623 f = ast_rtp_read(p->vrtp);
1626 f = ast_rtcp_read(p->vrtp);
1631 /* Don't send RFC2833 if we're not supposed to */
1632 if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1635 /* We already hold the channel lock */
1636 if (f->frametype == AST_FRAME_VOICE) {
1637 if (f->subclass != p->owner->nativeformats) {
1638 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1639 p->owner->nativeformats = f->subclass;
1640 ast_set_read_format(p->owner, p->owner->readformat);
1641 ast_set_write_format(p->owner, p->owner->writeformat);
1643 if (p->dtmfmode & SIP_DTMF_INBAND) {
1644 f = ast_dsp_process(p->owner,p->vad,f,0);
1651 static struct ast_frame *sip_read(struct ast_channel *ast)
1653 struct ast_frame *fr;
1654 struct sip_pvt *p = ast->pvt->pvt;
1655 ast_mutex_lock(&p->lock);
1656 fr = sip_rtp_read(ast, p);
1657 ast_mutex_unlock(&p->lock);
1661 static void build_callid(char *callid, int len, struct in_addr ourip)
1668 res = snprintf(callid, len, "%08x", val);
1672 /* It's not important that we really use our right IP here... */
1673 snprintf(callid, len, "@%s", inet_ntoa(ourip));
1676 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1680 p = malloc(sizeof(struct sip_pvt));
1683 /* Keep track of stuff */
1684 memset(p, 0, sizeof(struct sip_pvt));
1688 p->rtp = ast_rtp_new(sched, io, 1, 0);
1690 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1694 /* Start with 101 instead of 1 */
1697 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1701 ast_rtp_settos(p->rtp, tos);
1703 ast_rtp_settos(p->vrtp, tos);
1704 if (useglobalnat && sin) {
1705 /* Setup NAT structure according to global settings if we have an address */
1707 memcpy(&p->recv, sin, sizeof(p->recv));
1708 ast_rtp_setnat(p->rtp, p->nat);
1710 ast_rtp_setnat(p->vrtp, p->nat);
1712 ast_mutex_init(&p->lock);
1715 memcpy(&p->sa, sin, sizeof(p->sa));
1716 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1717 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1719 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1721 /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
1722 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1724 build_callid(p->callid, sizeof(p->callid), p->ourip);
1726 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1727 /* Assume reinvite OK and via INVITE */
1728 p->canreinvite = globalcanreinvite;
1729 p->dtmfmode = globaldtmfmode;
1730 p->capability = capability;
1731 if (p->dtmfmode & SIP_DTMF_RFC2833)
1732 p->noncodeccapability |= AST_RTP_DTMF;
1733 strncpy(p->context, context, sizeof(p->context) - 1);
1734 strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1736 ast_mutex_lock(&iflock);
1739 ast_mutex_unlock(&iflock);
1741 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1745 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1753 callid = get_header(req, "Call-ID");
1755 if (pedanticsipchecking) {
1756 /* In principle Call-ID's uniquely identify a call, however some vendors
1757 (i.e. Pingtel) send multiple calls with the same Call-ID and different
1758 tags in order to simplify billing. The RFC does state that we have to
1759 compare tags in addition to the call-id, but this generate substantially
1760 more overhead which is totally unnecessary for the vast majority of sane
1761 SIP implementations, and thus Asterisk does not enable this behavior
1762 by default. Short version: You'll need this option to support conferencing
1764 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1766 c = strchr(tmp, ' ');
1769 if (!strcasecmp(cmd, "SIP/2.0")) {
1775 strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1777 strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1778 tag = strstr(tmp, "tag=");
1781 c = strchr(tag, ';');
1788 if (!strlen(callid)) {
1789 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1792 ast_mutex_lock(&iflock);
1795 if (!strcmp(p->callid, callid) &&
1796 (!pedanticsipchecking || !tag || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1797 /* Found the call */
1798 ast_mutex_lock(&p->lock);
1799 ast_mutex_unlock(&iflock);
1804 ast_mutex_unlock(&iflock);
1805 p = sip_alloc(callid, sin, 1);
1807 ast_mutex_lock(&p->lock);
1811 static int sip_register(char *value, int lineno)
1813 struct sip_registry *reg;
1814 char copy[256] = "";
1815 char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1823 strncpy(copy, value, sizeof(copy)-1);
1826 hostname = strrchr(stringp, '@');
1831 if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1832 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1836 username = strsep(&stringp, ":");
1838 secret = strsep(&stringp, ":");
1840 authuser = strsep(&stringp, ":");
1843 hostname = strsep(&stringp, "/");
1845 contact = strsep(&stringp, "/");
1846 if (!contact || !strlen(contact))
1849 hostname = strsep(&stringp, ":");
1850 porta = strsep(&stringp, ":");
1852 if (porta && !atoi(porta)) {
1853 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1856 hp = gethostbyname(hostname);
1858 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1861 reg = malloc(sizeof(struct sip_registry));
1863 memset(reg, 0, sizeof(struct sip_registry));
1864 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1866 strncpy(reg->username, username, sizeof(reg->username)-1);
1868 strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1870 strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1872 strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1875 reg->refresh = default_expiry;
1876 reg->addr.sin_family = AF_INET;
1877 memcpy(®->addr.sin_addr, hp->h_addr, sizeof(®->addr.sin_addr));
1878 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1879 reg->next = registrations;
1880 reg->callid_valid = 0;
1882 registrations = reg;
1884 ast_log(LOG_ERROR, "Out of memory\n");
1890 static void parse(struct sip_request *req)
1892 /* Divide fields by NULL's */
1897 /* First header starts immediately */
1901 /* We've got a new header */
1905 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1907 if (!strlen(req->header[f])) {
1908 /* Line by itself means we're now in content */
1912 if (f >= SIP_MAX_HEADERS - 1) {
1913 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1916 req->header[f] = c + 1;
1917 } else if (*c == '\r') {
1918 /* Ignore but eliminate \r's */
1923 /* Check for last header */
1924 if (strlen(req->header[f]))
1927 /* Now we process any mime content */
1932 /* We've got a new line */
1935 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1937 if (f >= SIP_MAX_LINES - 1) {
1938 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1941 req->line[f] = c + 1;
1942 } else if (*c == '\r') {
1943 /* Ignore and eliminate \r's */
1948 /* Check for last line */
1949 if (strlen(req->line[f]))
1953 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1955 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1958 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1967 int peercapability, peernoncodeccapability;
1968 int vpeercapability=0, vpeernoncodeccapability=0;
1969 struct sockaddr_in sin;
1977 /* Get codec and RTP info from SDP */
1978 if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1979 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1982 m = get_sdp(req, "m");
1983 c = get_sdp(req, "c");
1984 if (!strlen(m) || !strlen(c)) {
1985 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1988 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1989 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1992 /* XXX This could block for a long time, and block the main thread! XXX */
1993 hp = gethostbyname(host);
1995 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1998 sdpLineNum_iterator_init(&iterator);
1999 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2000 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
2002 // Scan through the RTP payload types specified in a "m=" line:
2003 ast_rtp_pt_clear(p->rtp);
2005 while(strlen(codecs)) {
2006 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2007 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2011 ast_verbose("Found audio format %s\n", ast_getformatname(codec));
2012 ast_rtp_set_m_type(p->rtp, codec);
2014 /* Skip over any whitespace */
2015 while(*codecs && (*codecs < 33)) codecs++;
2018 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2020 // Scan through the RTP payload types specified in a "m=" line:
2021 ast_rtp_pt_clear(p->vrtp);
2023 while(strlen(codecs)) {
2024 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2025 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2029 ast_verbose("Found video format %s\n", ast_getformatname(codec));
2030 ast_rtp_set_m_type(p->vrtp, codec);
2032 /* Skip over any whitespace */
2033 while(*codecs && (*codecs < 33)) codecs++;
2037 sin.sin_family = AF_INET;
2038 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2039 /* Setup audio port number */
2040 sin.sin_port = htons(portno);
2041 if (p->rtp && sin.sin_port)
2042 ast_rtp_set_peer(p->rtp, &sin);
2043 /* Setup video port number */
2044 sin.sin_port = htons(vportno);
2045 if (p->vrtp && sin.sin_port)
2046 ast_rtp_set_peer(p->vrtp, &sin);
2048 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2050 // Next, scan through each "a=rtpmap:" line, noting each
2051 // specified RTP payload type (with corresponding MIME subtype):
2052 sdpLineNum_iterator_init(&iterator);
2053 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2054 char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
2055 if (!strcasecmp(a, "sendonly")) {
2059 if (!strcasecmp(a, "sendrecv")) {
2062 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2064 ast_verbose("Found description format %s\n", mimeSubtype);
2065 // Note: should really look at the 'freq' and '#chans' params too
2066 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2068 ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2071 // Now gather all of the codecs that were asked for:
2072 ast_rtp_get_current_formats(p->rtp,
2073 &peercapability, &peernoncodeccapability);
2075 ast_rtp_get_current_formats(p->vrtp,
2076 &vpeercapability, &vpeernoncodeccapability);
2077 p->jointcapability = p->capability & (peercapability | vpeercapability);
2078 p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
2081 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
2082 p->capability, peercapability, vpeercapability, p->jointcapability);
2083 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
2084 noncodeccapability, peernoncodeccapability,
2085 p->noncodeccapability);
2087 if (!p->jointcapability) {
2088 ast_log(LOG_WARNING, "No compatible codecs!\n");
2092 if (!(p->owner->nativeformats & p->jointcapability)) {
2093 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);
2094 p->owner->nativeformats = sip_codec_choose(p->jointcapability);
2095 ast_set_read_format(p->owner, p->owner->readformat);
2096 ast_set_write_format(p->owner, p->owner->writeformat);
2098 if (p->owner->bridge) {
2099 /* Turn on/off music on hold if we are holding/unholding */
2100 if (sin.sin_addr.s_addr && !sendonly) {
2101 ast_moh_stop(p->owner->bridge);
2103 ast_moh_start(p->owner->bridge, NULL);
2111 static int add_header(struct sip_request *req, char *var, char *value)
2113 if (req->len >= sizeof(req->data) - 4) {
2114 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2118 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2121 req->header[req->headers] = req->data + req->len;
2122 snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2123 req->len += strlen(req->header[req->headers]);
2124 if (req->headers < SIP_MAX_HEADERS)
2127 ast_log(LOG_WARNING, "Out of header space\n");
2133 static int add_blank_header(struct sip_request *req)
2135 if (req->len >= sizeof(req->data) - 4) {
2136 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2140 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2143 req->header[req->headers] = req->data + req->len;
2144 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2145 req->len += strlen(req->header[req->headers]);
2146 if (req->headers < SIP_MAX_HEADERS)
2149 ast_log(LOG_WARNING, "Out of header space\n");
2155 static int add_line(struct sip_request *req, char *line)
2157 if (req->len >= sizeof(req->data) - 4) {
2158 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2162 /* Add extra empty return */
2163 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2164 req->len += strlen(req->data + req->len);
2166 req->line[req->lines] = req->data + req->len;
2167 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2168 req->len += strlen(req->line[req->lines]);
2169 if (req->lines < SIP_MAX_LINES)
2172 ast_log(LOG_WARNING, "Out of line space\n");
2178 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2181 tmp = get_header(orig, field);
2183 /* Add what we're responding to */
2184 return add_header(req, field, tmp);
2186 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2190 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2196 tmp = __get_header(orig, field, &start);
2198 /* Add what we're responding to */
2199 add_header(req, field, tmp);
2204 return copied ? 0 : -1;
2207 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2214 tmp = __get_header(orig, field, &start);
2216 if (!copied && p->nat) {
2217 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2218 /* SLD: FIXME: Nice try, but the received= should not have a port */
2219 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2220 /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
2222 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2223 snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2226 snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2227 add_header(req, field, new);
2229 /* Add what we're responding to */
2230 add_header(req, field, tmp);
2237 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2243 /* Add Route: header into request per learned route */
2244 static void add_route(struct sip_request *req, struct sip_route *route)
2247 int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2253 n = strlen(route->hop);
2254 if ((n+3)>rem) break;
2260 strcpy(p, route->hop); p += n;
2263 route = route->next;
2266 add_header(req, "Route", r);
2269 static void set_destination(struct sip_pvt *p, char *uri)
2271 char *h, *maddr, hostname[256];
2275 /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2276 /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2279 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2281 /* Find and parse hostname */
2282 h = strchr(uri, '@');
2287 if (strncmp(h, "sip:", 4) == 0)
2289 else if (strncmp(h, "sips:", 5) == 0)
2292 hn = strcspn(h, ":;>");
2294 strncpy(hostname, h, hn); hostname[hn] = '\0';
2297 /* Is "port" present? if not default to 5060 */
2301 port = strtol(h, &h, 10);
2306 /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2307 maddr = strstr(h, "maddr=");
2310 hn = strspn(maddr, "0123456789.");
2312 strncpy(hostname, maddr, hn); hostname[hn] = '\0';
2315 hp = gethostbyname(hostname);
2317 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2320 p->sa.sin_family = AF_INET;
2321 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2322 p->sa.sin_port = htons(port);
2324 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2327 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2329 /* Initialize a response */
2330 if (req->headers || req->len) {
2331 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2334 req->header[req->headers] = req->data + req->len;
2335 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2336 req->len += strlen(req->header[req->headers]);
2337 if (req->headers < SIP_MAX_HEADERS)
2340 ast_log(LOG_WARNING, "Out of header space\n");
2344 static int init_req(struct sip_request *req, char *resp, char *recip)
2346 /* Initialize a response */
2347 if (req->headers || req->len) {
2348 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2351 req->header[req->headers] = req->data + req->len;
2352 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2353 req->len += strlen(req->header[req->headers]);
2354 if (req->headers < SIP_MAX_HEADERS)
2357 ast_log(LOG_WARNING, "Out of header space\n");
2361 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2363 char newto[256] = "", *ot;
2364 memset(resp, 0, sizeof(*resp));
2365 init_resp(resp, msg, req);
2366 copy_via_headers(p, resp, req, "Via");
2367 if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2368 copy_header(resp, req, "From");
2369 ot = get_header(req, "To");
2370 if (!strstr(ot, "tag=")) {
2371 /* Add the proper tag if we don't have it already. If they have specified
2372 their tag, use it. Otherwise, use our own tag */
2373 if (strlen(p->theirtag) && p->outgoing)
2374 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2375 else if (p->tag && !p->outgoing)
2376 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2378 strncpy(newto, ot, sizeof(newto) - 1);
2381 add_header(resp, "To", ot);
2382 copy_header(resp, req, "Call-ID");
2383 copy_header(resp, req, "CSeq");
2384 add_header(resp, "User-Agent", "Asterisk PBX");
2385 add_header(resp, "Allow", ALLOWED_METHODS);
2387 /* For registration responses, we also need expiry and
2391 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2392 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2393 add_header(resp, "Expires", tmp);
2394 add_header(resp, "Contact", contact);
2396 add_header(resp, "Contact", p->our_contact);
2401 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2403 struct sip_request *orig = &p->initreq;
2404 char stripped[80] ="";
2410 memset(req, 0, sizeof(struct sip_request));
2412 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2419 if (strlen(p->uri)) {
2423 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2425 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2427 c = strchr(stripped, '<');
2439 init_req(req, msg, c);
2441 snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2443 add_header(req, "Via", p->via);
2445 set_destination(p, p->route->hop);
2446 add_route(req, p->route->next);
2449 ot = get_header(orig, "To");
2450 of = get_header(orig, "From");
2452 /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2453 as our original request, including tag (or presumably lack thereof) */
2454 if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2455 /* Add the proper tag if we don't have it already. If they have specified
2456 their tag, use it. Otherwise, use our own tag */
2457 if (p->outgoing && strlen(p->theirtag))
2458 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2459 else if (!p->outgoing)
2460 snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2462 snprintf(newto, sizeof(newto), "%s", ot);
2467 add_header(req, "From", of);
2468 add_header(req, "To", ot);
2470 add_header(req, "From", ot);
2471 add_header(req, "To", of);
2473 add_header(req, "Contact", p->our_contact);
2474 copy_header(req, orig, "Call-ID");
2475 add_header(req, "CSeq", tmp);
2477 add_header(req, "User-Agent", "Asterisk PBX");
2481 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2483 struct sip_request resp;
2485 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2486 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2489 respprep(&resp, p, msg, req);
2490 add_header(&resp, "Content-Length", "0");
2491 add_blank_header(&resp);
2492 return send_response(p, &resp, reliable, seqno);
2495 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
2497 return __transmit_response(p, msg, req, 0);
2499 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2501 return __transmit_response(p, msg, req, 1);
2504 static void append_date(struct sip_request *req)
2511 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2512 add_header(req, "Date", tmpdat);
2515 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2517 struct sip_request resp;
2518 respprep(&resp, p, msg, req);
2520 add_header(&resp, "Content-Length", "0");
2521 add_blank_header(&resp);
2522 return send_response(p, &resp, 0, 0);
2525 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2527 struct sip_request resp;
2528 respprep(&resp, p, msg, req);
2529 add_header(&resp, "Accept", "application/sdp");
2530 add_header(&resp, "Content-Length", "0");
2531 add_blank_header(&resp);
2532 return send_response(p, &resp, 0, 0);
2535 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2537 struct sip_request resp;
2540 if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2541 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2544 snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2545 respprep(&resp, p, msg, req);
2546 add_header(&resp, "Proxy-Authenticate", tmp);
2547 add_header(&resp, "Content-Length", "0");
2548 add_blank_header(&resp);
2549 return send_response(p, &resp, reliable, seqno);
2552 static int add_text(struct sip_request *req, char *text)
2554 /* XXX Convert \n's to \r\n's XXX */
2555 int len = strlen(text);
2557 snprintf(clen, sizeof(clen), "%d", len);
2558 add_header(req, "Content-Type", "text/plain");
2559 add_header(req, "Content-Length", clen);
2560 add_line(req, text);
2564 static int add_digit(struct sip_request *req, char digit)
2569 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2571 snprintf(clen, sizeof(clen), "%d", len);
2572 add_header(req, "Content-Type", "application/dtmf-relay");
2573 add_header(req, "Content-Length", clen);
2578 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2582 int alreadysent = 0;
2584 struct sockaddr_in sin;
2585 struct sockaddr_in vsin;
2586 struct sip_codec_pref *cur;
2597 struct sockaddr_in dest;
2598 struct sockaddr_in vdest;
2599 /* XXX We break with the "recommendation" and send our IP, in order that our
2600 peer doesn't have to gethostbyname() us XXX */
2603 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2606 if (!p->sessionid) {
2607 p->sessionid = getpid();
2608 p->sessionversion = p->sessionid;
2610 p->sessionversion++;
2611 ast_rtp_get_us(p->rtp, &sin);
2613 ast_rtp_get_us(p->vrtp, &vsin);
2615 if (p->redirip.sin_addr.s_addr) {
2616 dest.sin_port = p->redirip.sin_port;
2617 dest.sin_addr = p->redirip.sin_addr;
2619 ast_rtp_get_peer(rtp, &dest);
2621 dest.sin_addr = p->ourip;
2622 dest.sin_port = sin.sin_port;
2625 /* Determine video destination */
2627 if (p->vredirip.sin_addr.s_addr) {
2628 vdest.sin_port = p->vredirip.sin_port;
2629 vdest.sin_addr = p->vredirip.sin_addr;
2631 ast_rtp_get_peer(vrtp, &vdest);
2633 vdest.sin_addr = p->ourip;
2634 vdest.sin_port = vsin.sin_port;
2638 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
2639 if (sipdebug && p->vrtp)
2640 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
2641 snprintf(v, sizeof(v), "v=0\r\n");
2642 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
2643 snprintf(s, sizeof(s), "s=session\r\n");
2644 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2645 snprintf(t, sizeof(t), "t=0 0\r\n");
2646 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2647 snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2648 /* Start by sending our preferred codecs */
2651 if (p->jointcapability & cur->codec) {
2653 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2654 codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2656 snprintf(costr, sizeof(costr), " %d", codec);
2657 if (cur->codec < AST_FORMAT_MAX_AUDIO) {
2658 strncat(m, costr, sizeof(m) - strlen(m));
2659 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2660 strncat(a, costr, sizeof(a));
2662 strncat(m2, costr, sizeof(m2) - strlen(m2));
2663 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2664 strncat(a2, costr, sizeof(a2));
2668 alreadysent |= cur->codec;
2671 /* Now send any other common codecs, and non-codec formats: */
2672 for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2673 if ((p->jointcapability & x) && !(alreadysent & x)) {
2675 ast_verbose("Answering with capability %d\n", x);
2676 codec = ast_rtp_lookup_code(p->rtp, 1, x);
2678 snprintf(costr, sizeof(costr), " %d", codec);
2679 if (x < AST_FORMAT_MAX_AUDIO) {
2680 strncat(m, costr, sizeof(m) - strlen(m));
2681 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2682 strncat(a, costr, sizeof(a) - strlen(a));
2684 strncat(m2, costr, sizeof(m2) - strlen(m2));
2685 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2686 strncat(a2, costr, sizeof(a2) - strlen(a2));
2691 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2692 if (p->noncodeccapability & x) {
2694 ast_verbose("Answering with non-codec capability %d\n", x);
2695 codec = ast_rtp_lookup_code(p->rtp, 0, x);
2697 snprintf(costr, sizeof(costr), " %d", codec);
2698 strncat(m, costr, sizeof(m) - strlen(m));
2699 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2700 strncat(a, costr, sizeof(a) - strlen(a));
2701 if (x == AST_RTP_DTMF) {
2702 /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
2703 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2705 strncat(a, costr, sizeof(a) - strlen(a));
2710 if (strlen(m) < sizeof(m) - 2)
2712 if (strlen(m2) < sizeof(m2) - 2)
2714 if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
2715 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
2716 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2718 len += strlen(m2) + strlen(a2);
2719 snprintf(costr, sizeof(costr), "%d", len);
2720 add_header(resp, "Content-Type", "application/sdp");
2721 add_header(resp, "Content-Length", costr);
2736 static void copy_request(struct sip_request *dst,struct sip_request *src)
2740 offset = ((void *)dst) - ((void *)src);
2741 /* First copy stuff */
2742 memcpy(dst, src, sizeof(*dst));
2743 /* Now fix pointer arithmetic */
2744 for (x=0;x<src->headers;x++)
2745 dst->header[x] += offset;
2746 for (x=0;x<src->lines;x++)
2747 dst->line[x] += offset;
2750 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2752 struct sip_request resp;
2754 if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2755 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2758 respprep(&resp, p, msg, req);
2759 add_sdp(&resp, p, NULL, NULL);
2760 return send_response(p, &resp, retrans, seqno);
2763 static int determine_firstline_parts( struct sip_request *req ) {
2768 cmd= req->header[0];
2769 while(*cmd && (*cmd < 33)) {
2776 while(*e && (*e > 32)) {
2779 /* Get the command */
2785 while( *e && ( *e < 33 ) ) {
2792 if ( !strcasecmp(cmd, "SIP/2.0") ) {
2793 /* We have a response */
2795 len= strlen( req->rlPart2 );
2796 if( len < 2 ) { return -1; }
2798 while( *e && *e<33 ) {
2803 /* We have a request */
2806 if( !*e ) { return -1; }
2809 if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2812 while( isspace( *(--e) ) ) {}
2822 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2824 struct sip_request req;
2825 if (p->canreinvite == REINVITE_UPDATE)
2826 reqprep(&req, p, "UPDATE", 0);
2829 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2830 reqprep(&req, p, "INVITE", 0);
2832 add_header(&req, "Allow", ALLOWED_METHODS);
2833 add_sdp(&req, p, rtp, vrtp);
2834 /* Use this as the basis */
2835 copy_request(&p->initreq, &req);
2837 determine_firstline_parts(&p->initreq);
2838 p->lastinvite = p->ocseq;
2840 return send_request(p, &req, 1, p->ocseq);
2843 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
2845 char stripped[256]="";
2847 strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
2848 c = strchr(stripped, '<');
2860 strncpy(p->uri, c, sizeof(p->uri) - 1);
2863 static void build_contact(struct sip_pvt *p)
2865 /* Construct Contact: header */
2866 if (ourport != 5060)
2867 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2869 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2872 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2879 char *l = callerid, *n=NULL;
2881 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
2883 if (p->owner && p->owner->callerid) {
2884 strcpy(cid, p->owner->callerid);
2885 ast_callerid_parse(cid, &n, &l);
2887 ast_shrink_phone_number(l);
2888 if (!l || !ast_isphonenumber(l))
2891 /* if user want's his callerid restricted */
2893 l = CALLERID_UNKNOWN;
2894 if (!n || !strlen(n))
2896 /* Allow user to be overridden */
2897 if (strlen(p->fromuser))
2900 if ((ourport != 5060) && !strlen(p->fromdomain))
2901 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);
2903 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2905 if (strlen(p->username)) {
2906 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2907 snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2909 snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2911 } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2912 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2914 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2916 strncpy(p->uri, invite, sizeof(p->uri) - 1);
2917 /* If there is a VXML URL append it to the SIP URL */
2920 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2924 snprintf(to, sizeof(to), "<%s>", invite );
2926 memset(req, 0, sizeof(struct sip_request));
2927 init_req(req, cmd, invite);
2928 snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2930 add_header(req, "Via", p->via);
2931 /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
2932 * OTOH, then we won't have anything in p->route anyway */
2933 add_header(req, "From", from);
2934 strncpy(p->exten, l, sizeof(p->exten) - 1);
2936 add_header(req, "To", to);
2937 add_header(req, "Contact", p->our_contact);
2938 add_header(req, "Call-ID", p->callid);
2939 add_header(req, "CSeq", tmp);
2940 add_header(req, "User-Agent", "Asterisk PBX");
2943 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, int init)
2945 struct sip_request req;
2948 initreqprep(&req, p, cmd, vxml_url);
2950 reqprep(&req, p, cmd, 0);
2953 add_header(&req, authheader, auth);
2955 if (!strcasecmp(cmd, "REFER")) {
2956 if (strlen(p->refer_to))
2957 add_header(&req, "Refer-To", p->refer_to);
2958 if (strlen(p->referred_by))
2959 add_header(&req, "Referred-By", p->referred_by);
2962 if (distinctive_ring)
2964 add_header(&req, "Alert-info",distinctive_ring);
2966 add_header(&req, "Allow", ALLOWED_METHODS);
2968 add_sdp(&req, p, NULL, NULL);
2970 add_header(&req, "Content-Length", "0");
2971 add_blank_header(&req);
2974 if (!p->initreq.headers) {
2975 /* Use this as the basis */
2976 copy_request(&p->initreq, &req);
2978 determine_firstline_parts(&p->initreq);
2980 p->lastinvite = p->ocseq;
2981 return send_request(p, &req, 1, p->ocseq);
2984 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2987 char from[256], to[256];
2990 struct sip_request req;
2993 strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2995 c = ditch_braces(from);
2996 if (strncmp(c, "sip:", 4)) {
2997 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3000 if ((a = strchr(c, ';'))) {
3005 reqprep(&req, p, "NOTIFY", 0);
3007 if (p->subscribed == 1) {
3008 strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
3010 c = ditch_braces(to);
3011 if (strncmp(c, "sip:", 4)) {
3012 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
3015 if ((a = strchr(c, ';'))) {
3020 add_header(&req, "Content-Type", "application/xpidf+xml");
3022 if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
3024 else if (state==AST_EXTENSION_INUSE)
3030 sprintf(t, "<?xml version=\"1.0\"?>\n");
3031 t = tmp + strlen(tmp);
3032 sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
3033 t = tmp + strlen(tmp);
3034 sprintf(t, "<presence>\n");
3035 t = tmp + strlen(tmp);
3036 sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
3037 t = tmp + strlen(tmp);
3038 sprintf(t, "<atom id=\"%s\">\n", p->exten);
3039 t = tmp + strlen(tmp);
3040 sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
3041 t = tmp + strlen(tmp);
3042 sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
3043 t = tmp + strlen(tmp);
3044 sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
3045 t = tmp + strlen(tmp);
3046 sprintf(t, "</address>\n</atom>\n</presence>\n");
3048 add_header(&req, "Event", "dialog");
3049 add_header(&req, "Content-Type", "application/dialog-info+xml");
3052 sprintf(t, "<?xml version=\"1.0\"?>\n");
3053 t = tmp + strlen(tmp);
3054 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);
3055 t = tmp + strlen(tmp);
3056 sprintf(t, "<dialog id=\"%s\">\n", p->exten);
3057 t = tmp + strlen(tmp);
3058 sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
3059 t = tmp + strlen(tmp);
3060 sprintf(t, "</dialog>\n</dialog-info>\n");
3062 if (t > tmp + sizeof(tmp))
3063 ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
3065 snprintf(clen, sizeof(clen), "%d", strlen(tmp));
3066 add_header(&req, "Content-Length", clen);
3067 add_line(&req, tmp);
3069 return send_request(p, &req, 1, p->ocseq);