Newer
Older
/*
* Asterisk -- A telephony toolkit for Linux.
*
* Implementation of Session Initiation Protocol
*
* Copyright (C) 1999, Mark Spencer
*
* Mark Spencer <markster@linux-support.net>
*
* This program is free software, distributed under the terms of
* the GNU General Public License
*/
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <asterisk/lock.h>
#include <asterisk/channel.h>
#include <asterisk/channel_pvt.h>
#include <asterisk/config.h>
#include <asterisk/logger.h>
#include <asterisk/module.h>
#include <asterisk/pbx.h>
#include <asterisk/options.h>
#include <asterisk/lock.h>
#include <asterisk/sched.h>
#include <asterisk/io.h>
#include <asterisk/rtp.h>
#include <asterisk/acl.h>
#include <asterisk/callerid.h>
#include <asterisk/cli.h>
#include <asterisk/md5.h>
#include <asterisk/app.h>
#include <asterisk/parking.h>
#include <asterisk/srv.h>
Martin Pycko
committed
#include <asterisk/causes.h>
#include <asterisk/utils.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
#ifdef SIP_MYSQL_FRIENDS
#define MYSQL_FRIENDS
#ifndef DEFAULT_USERAGENT
#define DEFAULT_USERAGENT "Asterisk PBX"
#endif
#define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
#ifndef IPTOS_MINCOST
#define IPTOS_MINCOST 0x02
#endif
#define DEFAULT_DEFAULT_EXPIRY 120
#define DEFAULT_MAX_EXPIRY 3600
/* guard limit must be larger than guard secs */
Mark Spencer
committed
/* guard min must be < 1000, and should be >= 250 */
#define EXPIRY_GUARD_SECS 15 /* How long before expiry do we reregister */
#define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of EXPIRY_GUARD_SECS */
Mark Spencer
committed
#define EXPIRY_GUARD_MIN 500 /* This is the minimum guard time applied. If GUARD_PCT turns out
to be lower than this, it will use this time instead. This is in
milliseconds. */
#define EXPIRY_GUARD_PCT 0.20 /* Percentage of expires timeout to use when below EXPIRY_GUARD_LIMIT */
#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
Martin Pycko
committed
#define CALLERID_UNKNOWN "Unknown"
/* --- Choices for DTMF support in SIP channel */
#define SIP_DTMF_RFC2833 (1 << 0)
#define SIP_DTMF_INBAND (1 << 1)
#define SIP_DTMF_INFO (1 << 2)
static int max_expiry = DEFAULT_MAX_EXPIRY;
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
#define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
#define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
#define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
#define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
#define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
/* MYSQL_FRIENDS: Check if peer exists in database and read some configuration
from databse (not all options supported though) */
#ifdef MYSQL_FRIENDS
static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
static MYSQL *mysql;
static char mydbuser[80];
static char mydbpass[80];
static char mydbhost[80];
static char mydbname[80];
#endif
/* SIP Debug */
#define DEBUG_READ 0 /* Recieved data */
#define DEBUG_SEND 1 /* Transmit data */
static char *desc = "Session Initiation Protocol (SIP)";
static char *type = "SIP";
static char *tdesc = "Session Initiation Protocol (SIP)";
static char *config = "sip.conf";
#define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
#define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
#define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
static char useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
static char context[AST_MAX_EXTENSION] = "default";
static char language[MAX_LANGUAGE] = "";
static char callerid[AST_MAX_EXTENSION] = "asterisk";
Mark Spencer
committed
static char fromdomain[AST_MAX_EXTENSION] = "";
static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
static int srvlookup = 0;
static int pedanticsipchecking = 0;
static int globalrtptimeout = 0;
static int globalrtpholdtimeout = 0;
static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
/* Protect the interface list (of sip_pvt's) */
static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
/* Protect the monitoring thread, so only one process can kill or start it, and not
when it's doing something critical. */
static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
/* This is the thread for the monitor which checks for input on the channels
which are not currently in use. */
static pthread_t monitor_thread = AST_PTHREADT_NULL;
/* Codecs that we support by default: */
static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
static struct sockaddr_in debugaddr;
static int videosupport = 0;
static int globaldtmfmode = SIP_DTMF_RFC2833; /* DTMF mode default */
Mark Spencer
committed
static int recordhistory = 0;
static char globalmusicclass[MAX_LANGUAGE] = ""; /* Global music on hold class */
static char global_realm[AST_MAX_EXTENSION] = "asterisk"; /* Default realm */
static struct sched_context *sched;
static struct io_context *io;
/* The private structures of the sip channels are linked for
selecting outgoing channels */
#define SIP_MAX_HEADERS 64
#define SIP_MAX_LINES 64
#define DEC_IN_USE 0
#define INC_IN_USE 1
#define DEC_OUT_USE 2
#define INC_OUT_USE 3
static struct sip_codec_pref {
int codec;
struct sip_codec_pref *next;
} *prefs;
/* sip_request: The data grabbed from the UDP socket */
char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
char *rlPart2; /* The Request URI or Response Status */
int len;
int headers; /* SIP Headers */
char *header[SIP_MAX_HEADERS];
int lines; /* SDP Content */
char *line[SIP_MAX_LINES];
char data[SIP_MAX_PACKET];
};
struct sip_route {
struct sip_route *next;
char hop[0];
};
Mark Spencer
committed
struct sip_history {
char event[80];
struct sip_history *next;
};
/* sip_pvt: PVT structures are used for each SIP conversation, ie. a call */
ast_mutex_t lock; /* Channel private lock */
char callid[80]; /* Global CallID */
char randdata[80]; /* Random data */
unsigned int ocseq; /* Current outgoing seqno */
unsigned int icseq; /* Current incoming seqno */
unsigned int callgroup; /* Call group */
unsigned int pickupgroup; /* Pickup group */
int lastinvite; /* Last Cseq of invite */
int alreadygone; /* Whether or not we've already been destroyed by or peer */
int needdestroy; /* if we need to be destroyed */
int capability; /* Special capability (codec) */
int jointcapability; /* Supported capability at both ends (codecs ) */
int prefcodec; /* Preferred codec (outbound only) */
int outgoing; /* Outgoing or incoming call? */
int authtries; /* Times we've tried to authenticate */
int insecure; /* Don't check source port/ip */
int expiry; /* How long we take to expire */
int branch; /* One random number */
int canreinvite; /* Do we support reinvite */
int ringing; /* Have sent 180 ringing */
int progress; /* Have sent 183 message progress */
int tag; /* Another random number */
int nat; /* Whether to try to support NAT */
int sessionid; /* SDP Session ID */
int sessionversion; /* SDP Session Version */
struct sockaddr_in sa; /* Our peer */
struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
int redircodecs; /* Redirect codecs */
struct sockaddr_in recv; /* Received as */
struct in_addr ourip; /* Our IP */
struct ast_channel *owner; /* Who owns us */
char exten[AST_MAX_EXTENSION]; /* Extension where to start */
char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
char referred_by[AST_MAX_EXTENSION]; /* Place to store REFERRED-BY extension */
char refer_contact[AST_MAX_EXTENSION]; /* Place to store Contact info from a REFER extension */
struct sip_pvt *refer_call; /* Call we are referring */
struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
int route_persistant; /* Is this the "real" route? */
char from[256]; /* The From: header */
char useragent[256]; /* User agent in SIP request */
char context[AST_MAX_EXTENSION]; /* Context for this call */
char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
Mark Spencer
committed
char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
char language[MAX_LANGUAGE]; /* Default language for this call */
char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
char rdnis[256]; /* Referring DNIS */
char theirtag[256]; /* Their tag */
char username[256];
char peername[256];
char authname[256]; /* Who we use for authentication */
char uri[256]; /* Original requested URI */
char callerid[256]; /* Caller*ID */
Martin Pycko
committed
int restrictcid; /* hide presentation from remote user */
char accountcode[20]; /* Account code */
char our_contact[256]; /* Our contact header */
char realm[256]; /* Authorization realm */
char nonce[256]; /* Authorization nonce */
char opaque[256]; /* Opaque nonsense */
char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
char domain[256]; /* Authorization nonce */
char lastmsg[256]; /* Last Message sent/received */
int amaflags; /* AMA Flags */
int pendinginvite; /* Any pending invite */
int needreinvite; /* Do we need to send another reinvite? */
int pendingbye; /* Need to send bye after we ack? */
int gotrefer; /* Got a refer? */
struct sip_request initreq; /* Initial request */
int maxtime; /* Max time for first response */
int initid; /* Auto-congest ID if appropriate */
int autokillid; /* Auto-kill ID */
time_t lastrtprx; /* Last RTP received */
int rtptimeout; /* RTP timeout time */
int rtpholdtimeout; /* RTP timeout when on hold */
int subscribed;
int stateid;
int dialogver;
struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
struct ast_rtp *rtp; /* RTP Session */
struct ast_rtp *vrtp; /* Video RTP session */
struct sip_pkt *packets; /* Packets scheduled for re-transmission */
Mark Spencer
committed
struct sip_history *history; /* History of this SIP dialog */
struct sip_pvt *next; /* Next call in chain */
#define FLAG_RESPONSE (1 << 0)
#define FLAG_FATAL (1 << 1)
/* sip packet - read in sipsock_read, transmitted in send_request */
struct sip_pkt {
struct sip_pkt *next; /* Next packet */
int retrans; /* Retransmission number */
int seqno; /* Sequence number */
int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
struct sip_pvt *owner; /* Owner call */
int retransid; /* Retransmission ID */
int packetlen; /* Length of packet */
char data[0];
};
/* Structure for SIP user data. User's place calls to us */
struct sip_user {
/* Users who can access various contexts */
char name[80];
char secret[80];
char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
char useragent[256]; /* User agent in SIP request */
unsigned int callgroup;
unsigned int pickupgroup;
int hascallerid;
int amaflags;
int insecure;
int dtmfmode;
int inUse;
int incominglimit;
Martin Pycko
committed
int restrictcid;
struct ast_ha *ha;
struct sip_user *next;
};
/* Structure for SIP peer data, we place calls to peers if registred or fixed IP address (host) */
struct sip_peer {
char name[80];
char secret[80];
char context[80]; /* JK02: peers need context too to allow parking etc */
Mark Spencer
committed
char fromuser[80];
char fromdomain[80];
char language[MAX_LANGUAGE];
char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
char useragent[256]; /* User agent in SIP request */
int lastmsgssent;
time_t lastmsgcheck;
int rtptimeout;
int rtpholdtimeout;
unsigned int callgroup;
unsigned int pickupgroup;
struct sockaddr_in addr;
struct in_addr mask;
/* Qualification */
struct sip_pvt *call; /* Call pointer */
int pokeexpire; /* When to expire poke */
int lastms; /* How long last response took (in ms), or -1 for no response */
int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
struct timeval ps; /* Ping send time */
struct sockaddr_in defaddr;
struct ast_ha *ha;
int delme;
static ast_mutex_t sip_reload_lock = AST_MUTEX_INITIALIZER;
static int sip_reloading = 0;
#define REG_STATE_UNREGISTERED 0
#define REG_STATE_REGSENT 1
#define REG_STATE_AUTHSENT 2
#define REG_STATE_REGISTERED 3
#define REG_STATE_REJECTED 4
#define REG_STATE_TIMEOUT 5
#define REG_STATE_NOAUTH 6
/* sip_registry: Registrations with other SIP proxies */
struct sockaddr_in addr; /* Who we connect to for registration purposes */
char username[80]; /* Who we are registering as */
char authuser[80]; /* Who we *authenticate* as */
char secret[80]; /* Password or key name in []'s */
char contact[80]; /* Contact extension */
int expire; /* Sched ID of expiration */
int timeout; /* sched id of sip_reg_timeout */
int refresh; /* How often to refresh */
struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
int regstate;
int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
char callid[80]; /* Global CallID for this registry */
unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
struct sockaddr_in us; /* Who the server thinks we are */
/*--- The user list: Users and friends ---*/
static struct ast_user_list {
struct sip_user *users;
ast_mutex_t lock;
} userl = { NULL, AST_MUTEX_INITIALIZER };
/*--- The peer list: Peers and Friends ---*/
static struct ast_peer_list {
struct sip_peer *peers;
ast_mutex_t lock;
} peerl = { NULL, AST_MUTEX_INITIALIZER };
/*--- The register list: Other SIP proxys we register with and call ---*/
static struct ast_register_list {
struct sip_registry *registrations;
ast_mutex_t lock;
} regl = { NULL, AST_MUTEX_INITIALIZER };
#define REINVITE_INVITE 1
#define REINVITE_UPDATE 2
static int __sip_do_register(struct sip_registry *r);
static int globalcanreinvite = REINVITE_INVITE;
static struct sockaddr_in externip;
Mark Spencer
committed
static struct ast_ha *localaddr;
static struct ast_frame *sip_read(struct ast_channel *ast);
static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
Mark Spencer
committed
static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
static int transmit_reinvite_with_sdp(struct sip_pvt *p);
static int transmit_info_with_digit(struct sip_pvt *p, char digit);
static int transmit_message_with_text(struct sip_pvt *p, char *text);
static int transmit_refer(struct sip_pvt *p, char *dest);
static struct sip_peer *temp_peer(char *name);
static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
static void free_old_route(struct sip_route *route);
static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
static int update_user_counter(struct sip_pvt *fup, int event);
static int sip_do_reload(void);
static int sip_debug_test_addr(struct sockaddr_in *addr);
static int sip_debug_test_pvt(struct sip_pvt *p);
/*--- __sip_xmit: Transmit SIP message ---*/
static int __sip_xmit(struct sip_pvt *p, char *data, int len)
{
int res;
if (p->nat)
res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
else
res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
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));
static void sip_destroy(struct sip_pvt *p);
/*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
/* Only used for outbound registrations */
static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
{
Mark Spencer
committed
* Using the localaddr structure built up with localnet statements
* apply it to their address to see if we need to substitute our
* externip or can get away with our internal bindaddr
*/
struct sockaddr_in theirs;
theirs.sin_addr = *them;
if (localaddr && externip.sin_addr.s_addr &&
ast_apply_ha(localaddr, &theirs)) {
char t[256];
memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
Mark Spencer
committed
strcpy(t, inet_ntoa(*(struct in_addr *)&them->s_addr));
ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", t);
}
else if (bindaddr.sin_addr.s_addr)
memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
else
return ast_ouraddrfor(them, us);
return 0;
}
Mark Spencer
committed
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
static int append_history(struct sip_pvt *p, char *event, char *data)
{
struct sip_history *hist, *prev;
char *c;
if (!recordhistory)
return 0;
hist = malloc(sizeof(struct sip_history));
if (hist) {
memset(hist, 0, sizeof(struct sip_history));
snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
/* Trim up nicely */
c = hist->event;
while(*c) {
if ((*c == '\r') || (*c == '\n')) {
*c = '\0';
break;
}
c++;
}
/* Enqueue into history */
prev = p->history;
if (prev) {
while(prev->next)
prev = prev->next;
prev->next = hist;
} else {
p->history = hist;
}
}
return 0;
}
/*--- retrans_pkt: Retransmit SIP message if no answer ---*/
struct sip_pkt *pkt=data, *prev, *cur;
ast_mutex_lock(&pkt->owner->lock);
if (pkt->retrans < MAX_RETRANS) {
pkt->retrans++;
if (sip_debug_test_pvt(pkt->owner)) {
if (pkt->owner->nat)
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));
else
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));
Mark Spencer
committed
append_history(pkt->owner, "ReTx", pkt->data);
__sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
res = 1;
ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (pkt->flags & FLAG_FATAL) ? "Critical" : "Non-critical", (pkt->flags & FLAG_RESPONSE) ? "Response" : "Request");
Mark Spencer
committed
append_history(pkt->owner, "MaxRetries", pkt->flags & FLAG_FATAL ? "(Critical)" : "(Non-critical)");
if (pkt->flags & FLAG_FATAL) {
while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
ast_mutex_unlock(&pkt->owner->lock);
usleep(1);
ast_mutex_lock(&pkt->owner->lock);
}
if (pkt->owner->owner) {
Mark Spencer
committed
ast_queue_hangup(pkt->owner->owner);
ast_mutex_unlock(&pkt->owner->owner->lock);
} else {
/* If no owner, destroy now */
pkt->owner->needdestroy = 1;
}
/* In any case, go ahead and remove the packet */
prev = NULL;
cur = pkt->owner->packets;
while(cur) {
if (cur == pkt)
break;
prev = cur;
cur = cur->next;
}
if (cur) {
if (prev)
prev->next = cur->next;
else
pkt->owner->packets = cur->next;
ast_mutex_unlock(&pkt->owner->lock);
free(cur);
pkt = NULL;
} else
ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
ast_mutex_unlock(&pkt->owner->lock);
/*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
{
struct sip_pkt *pkt;
pkt = malloc(sizeof(struct sip_pkt) + len);
if (!pkt)
return -1;
memset(pkt, 0, sizeof(struct sip_pkt));
memcpy(pkt->data, data, len);
pkt->packetlen = len;
pkt->next = p->packets;
pkt->owner = p;
pkt->seqno = seqno;
pkt->flags = resp;
if (fatal)
pkt->flags |= FLAG_FATAL;
pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
pkt->next = p->packets;
p->packets = pkt;
__sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
if (!strncasecmp(pkt->data, "INVITE", 6)) {
/* Note this is a pending invite */
p->pendinginvite = seqno;
}
/*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
static int __sip_autodestruct(void *data)
{
struct sip_pvt *p = data;
p->autokillid = -1;
ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
Mark Spencer
committed
append_history(p, "AutoDestroy", "");
if (p->owner) {
ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
Mark Spencer
committed
ast_queue_hangup(p->owner);
} else {
sip_destroy(p);
}
return 0;
}
/*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
static int sip_scheddestroy(struct sip_pvt *p, int ms)
{
Mark Spencer
committed
char tmp[80];
if (sip_debug_test_pvt(p))
ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
Mark Spencer
committed
if (recordhistory) {
snprintf(tmp, sizeof(tmp), "%d ms", ms);
append_history(p, "SchedDestroy", tmp);
}
if (p->autokillid > -1)
ast_sched_del(sched, p->autokillid);
p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
return 0;
}
/*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
static int sip_cancel_destroy(struct sip_pvt *p)
{
if (p->autokillid > -1)
ast_sched_del(sched, p->autokillid);
Mark Spencer
committed
append_history(p, "CancelDestroy", "");
/*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
{
struct sip_pkt *cur, *prev = NULL;
int res = -1;
int resetinvite = 0;
if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
if (!resp && (seqno == p->pendinginvite)) {
ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
p->pendinginvite = 0;
resetinvite = 1;
}
/* this is our baby */
if (prev)
prev->next = cur->next;
else
p->packets = cur->next;
if (cur->retransid > -1)
ast_sched_del(sched, cur->retransid);
free(cur);
res = 0;
break;
}
prev = cur;
cur = cur->next;
}
ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
/*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
{
struct sip_pkt *cur;
int res = -1;
cur = p->packets;
while(cur) {
if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
/* this is our baby */
if (cur->retransid > -1)
ast_sched_del(sched, cur->retransid);
cur->retransid = -1;
res = 0;
break;
}
cur = cur->next;
}
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");
/*--- send_response: Transmit response on SIP request---*/
static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
if (sip_debug_test_pvt(p)) {
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));
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));
Mark Spencer
committed
if (reliable) {
append_history(p, "TxRespRel", req->data);
res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
Mark Spencer
committed
} else {
append_history(p, "TxResp", req->data);
Mark Spencer
committed
}
if (res > 0)
res = 0;
return res;
}
/*--- send_request: Send SIP Request to the other part of the dialogue ---*/
static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
if (sip_debug_test_pvt(p)) {
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));
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));
Mark Spencer
committed
if (reliable) {
append_history(p, "TxReqRel", req->data);
res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
Mark Spencer
committed
} else {
append_history(p, "TxReq", req->data);
Mark Spencer
committed
}
/*--- ditch_braces: Pick out text in braces from character string ---*/
static char *ditch_braces(char *tmp)
{
char *c = tmp;
char *n;
if ((n = strchr(tmp, '<')) ) {
c = n + 1;
while(*c && *c != '>') c++;
if (*c != '>') {
ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
} else {
*c = '\0';
}
return n+1;
}
return c;
}
/*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
/* Called from PBX core text message functions */
static int sip_sendtext(struct ast_channel *ast, char *text)
if (sip_debug_test_pvt(p))
ast_verbose("Sending text %s on %s\n", text, ast->name);
if (!p)
return -1;
if (!text || ast_strlen_zero(text))
if (sip_debug_test_pvt(p))
ast_verbose("Really sending text %s on %s\n", text, ast->name);
transmit_message_with_text(p, text);
return 0;
/*--- mysql_update_peer: Update peer from database ---*/
/* This function adds registration state to database */
static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
{
if (mysql && (strlen(peer) < 128)) {
char query[512];
char *name;
char *uname;
time_t nowtime;
name = alloca(strlen(peer) * 2 + 1);
uname = alloca(strlen(username) * 2 + 1);
time(&nowtime);
mysql_real_escape_string(mysql, name, peer, strlen(peer));
mysql_real_escape_string(mysql, uname, username, strlen(username));
snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"",
inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
ast_mutex_lock(&mysqllock);
if (mysql_real_query(mysql, query, strlen(query)))
ast_log(LOG_WARNING, "Unable to update database\n");
ast_mutex_unlock(&mysqllock);
}
}
/*--- mysql_peer: Get peer from database ---*/
static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
{
struct sip_peer *p;
int success = 0;
p = malloc(sizeof(struct sip_peer));
memset(p, 0, sizeof(struct sip_peer));
if (mysql && (!peer || (strlen(peer) < 128))) {
char query[512];
char *name = NULL;
int numfields, x;
int port;
time_t regseconds, nowtime;
MYSQL_RES *result;
MYSQL_FIELD *fields;
MYSQL_ROW rowval;
if (peer) {
name = alloca(strlen(peer) * 2 + 1);
mysql_real_escape_string(mysql, name, peer, strlen(peer));
}
if (sin)
snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE name=\"%s\"", name);
ast_mutex_lock(&mysqllock);
mysql_query(mysql, query);
if ((result = mysql_store_result(mysql))) {
if ((rowval = mysql_fetch_row(result))) {
numfields = mysql_num_fields(result);
fields = mysql_fetch_fields(result);
success = 1;
for (x=0;x<numfields;x++) {
if (rowval[x]) {
if (!strcasecmp(fields[x].name, "secret")) {
strncpy(p->secret, rowval[x], sizeof(p->secret));
} else if (!strcasecmp(fields[x].name, "name")) {
strncpy(p->name, rowval[x], sizeof(p->name) - 1);
} else if (!strcasecmp(fields[x].name, "context")) {
strncpy(p->context, rowval[x], sizeof(p->context) - 1);
} else if (!strcasecmp(fields[x].name, "username")) {
strncpy(p->username, rowval[x], sizeof(p->username) - 1);
} else if (!strcasecmp(fields[x].name, "ipaddr")) {
inet_aton(rowval[x], &p->addr.sin_addr);
} else if (!strcasecmp(fields[x].name, "port")) {
if (sscanf(rowval[x], "%i", &port) != 1)
port = 0;
p->addr.sin_port = htons(port);
} else if (!strcasecmp(fields[x].name, "regseconds")) {
if (sscanf(rowval[x], "%li", ®seconds) != 1)
regseconds = 0;
}
}
}
time(&nowtime);
memset(&p->addr, 0, sizeof(p->addr));
}
mysql_free_result(result);
result = NULL;
}
ast_mutex_unlock(&mysqllock);
}
if (!success) {
free(p);
p = NULL;
} else {
p->dynamic = 1;
p->capability = capability;
p->nat = globalnat;
p->dtmfmode = globaldtmfmode;
p->insecure = 1;
p->expire = -1;
p->temponly = 1;
}
return p;
}
#endif /* MYSQL_FRIENDS */
/*--- update_peer: Update peer data in database (if used) ---*/
static void update_peer(struct sip_peer *p, int expiry)
{
#ifdef MYSQL_FRIENDS
if (p->temponly)
mysql_update_peer(p->name, &p->addr, p->username, expiry);
#endif
return;
}
/*--- find_peer: Locate peer by name or ip address */
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
static struct sip_peer *find_peer(char *peer, struct sockaddr_in *sin)
{
struct sip_peer *p = NULL;
p = peerl.peers;
if (peer) {
/* Find by peer name */
while(p) {
if (!strcasecmp(p->name, peer)) {
break;
}
p = p->next;
}
}
else {
/* Find by sin */
while(p) {
if (!inaddrcmp(&p->addr, sin) ||
(p->insecure &&
(p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))) {
break;
}
p = p->next;
}
}
#ifdef MYSQL_FRIENDS
if (!p) {
p = mysql_peer(peer, sin);