/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 1999 - 2006, Digium, Inc.
 *
 * Mark Spencer <markster@digium.com>
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 */

/*!
 * \file
 * \brief Implementation of Session Initiation Protocol
 *
 * \author Mark Spencer <markster@digium.com>
 *
 * See Also:
 * \arg \ref AstCREDITS
 *
 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
 * Configuration file \link Config_sip sip.conf \endlink
 *
 *
 * \todo SIP over TCP
 * \todo SIP over TLS
 * \todo Better support of forking
 *
 * \ingroup channel_drivers
 *
 */


#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <netdb.h>
#include <signal.h>
#include <sys/signal.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <regex.h>

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "Revision: 16600 ")

#include "asterisk/lock.h"
#include "asterisk/channel.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/manager.h"
#include "asterisk/callerid.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/musiconhold.h"
#include "asterisk/dsp.h"
#include "asterisk/features.h"
#include "asterisk/acl.h"
#include "asterisk/srv.h"
#include "asterisk/astdb.h"
#include "asterisk/causes.h"
#include "asterisk/utils.h"
#include "asterisk/file.h"
#include "asterisk/astobj.h"
#include "asterisk/dnsmgr.h"
#include "asterisk/devicestate.h"
#include "asterisk/linkedlists.h"
#include "asterisk/stringfields.h"
#include "asterisk/monitor.h"

#ifdef OSP_SUPPORT
#include "asterisk/astosp.h"
#endif

#ifndef FALSE
#define FALSE	0
#endif

#ifndef TRUE
#define TRUE 1
#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 VOCAL_DATA_HACK */

#define DEFAULT_DEFAULT_EXPIRY  120
#define DEFAULT_MIN_EXPIRY	60
#define DEFAULT_MAX_EXPIRY	3600
#define DEFAULT_REGISTRATION_TIMEOUT	20
#define DEFAULT_MAX_FORWARDS	"70"

/* guard limit must be larger than guard secs */
/* 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 */
#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 */
#define DEFAULT_EXPIRY 900			/*!< Expire slowly */

static int min_expiry = DEFAULT_MIN_EXPIRY;	/*!< Minimum accepted registration time */
static int max_expiry = DEFAULT_MAX_EXPIRY;	/*!< Maximum accepted registration time */
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
static int expiry = DEFAULT_EXPIRY;

#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif

#define CALLERID_UNKNOWN	"Unknown"

#define DEFAULT_MAXMS		2000		/*!< Qualification: Must be faster than 2 seconds by default */
#define DEFAULT_FREQ_OK		60 * 1000	/*!< Qualification: How often to check for the host to be up */
#define DEFAULT_FREQ_NOTOK	10 * 1000	/*!< Qualification: How often to check, if the host is down... */

#define DEFAULT_RETRANS		1000		/*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
#define MAX_RETRANS		6		/*!< Try only 6 times for retransmissions, a total of 7 transmissions */
#define MAX_AUTHTRIES		3		/*!< Try authentication three times, then fail */

#define SIP_MAX_HEADERS		64			/*!< Max amount of SIP headers to read */
#define SIP_MAX_LINES 		64			/*!< Max amount of lines in SIP attachment (like SDP) */
#define SIP_MAX_PACKET		4096	/*!< Also from RFC 3261 (2543), should sub headers tho */


static const char desc[] = "Session Initiation Protocol (SIP)";
static const char config[] = "sip.conf";
static const char notify_config[] = "sip_notify.conf";
static int usecnt = 0;


#define RTP 	1
#define NO_RTP	0

/* Do _NOT_ make any changes to this enum, or the array following it;
   if you think you are doing the right thing, you are probably
   not doing the right thing. If you think there are changes
   needed, get someone else to review them first _before_
   submitting a patch. If these two lists do not match properly
   bad things will happen.
*/

enum xmittype {
	XMIT_CRITICAL = 2,		/*!< Transmit critical SIP message reliably, with re-transmits.
							If it fails, it's critical and will cause a teardown of the session */
	XMIT_RELIABLE = 1,		/*!< Transmit SIP message reliably, with re-transmits */
	XMIT_UNRELIABLE = 0,		/*!< Transmit SIP message without bothering with re-transmits */
};

enum subscriptiontype { 
	NONE = 0,
	TIMEOUT,
	XPIDF_XML,
	DIALOG_INFO_XML,
	CPIM_PIDF_XML,
	PIDF_XML,
	MWI_NOTIFICATION
};

static const struct cfsubscription_types {
	enum subscriptiontype type;
	const char * const event;
	const char * const mediatype;
	const char * const text;
} subscription_types[] = {
	{ NONE,		   "-",        "unknown",	             "unknown" },
 	/* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
	{ CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
	{ XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
	{ MWI_NOTIFICATION,	"message-summary", "application/simple-message-summary", "mwi" } /* Mailbox notification */
};

enum sipmethod {
	SIP_UNKNOWN,
	SIP_RESPONSE,
	SIP_REGISTER,
	SIP_OPTIONS,
	SIP_NOTIFY,
	SIP_INVITE,
	SIP_ACK,
	SIP_PRACK,
	SIP_BYE,
	SIP_REFER,
	SIP_SUBSCRIBE,
	SIP_MESSAGE,
	SIP_UPDATE,
	SIP_INFO,
	SIP_CANCEL,
	SIP_PUBLISH,
} sip_method_list;

enum sip_auth_type {
	PROXY_AUTH,
	WWW_AUTH,
};

/*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
static const struct  cfsip_methods { 
	enum sipmethod id;
	int need_rtp;		/*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
	char * const text;
} sip_methods[] = {
	{ SIP_UNKNOWN,	 RTP,    "-UNKNOWN-" },
	{ SIP_RESPONSE,	 NO_RTP, "SIP/2.0" },
	{ SIP_REGISTER,	 NO_RTP, "REGISTER" },
 	{ SIP_OPTIONS,	 NO_RTP, "OPTIONS" },
	{ SIP_NOTIFY,	 NO_RTP, "NOTIFY" },
	{ SIP_INVITE,	 RTP,    "INVITE" },
	{ SIP_ACK,	 NO_RTP, "ACK" },
	{ SIP_PRACK,	 NO_RTP, "PRACK" },
	{ SIP_BYE,	 NO_RTP, "BYE" },
	{ SIP_REFER,	 NO_RTP, "REFER" },
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
	{ SIP_MESSAGE,	 NO_RTP, "MESSAGE" },
	{ SIP_UPDATE,	 NO_RTP, "UPDATE" },
	{ SIP_INFO,	 NO_RTP, "INFO" },
	{ SIP_CANCEL,	 NO_RTP, "CANCEL" },
	{ SIP_PUBLISH,	 NO_RTP, "PUBLISH" }
};

/*! \brief Structure for conversion between compressed SIP and "normal" SIP */
static const struct cfalias {
	char * const fullname;
	char * const shortname;
} aliases[] = {
	{ "Content-Type", "c" },
	{ "Content-Encoding", "e" },
	{ "From", "f" },
	{ "Call-ID", "i" },
	{ "Contact", "m" },
	{ "Content-Length", "l" },
	{ "Subject", "s" },
	{ "To", "t" },
	{ "Supported", "k" },
	{ "Refer-To", "r" },
	{ "Referred-By", "b" },
	{ "Allow-Events", "u" },
	{ "Event", "o" },
	{ "Via", "v" },
	{ "Accept-Contact", "a" },
	{ "Reject-Contact", "j" },
	{ "Request-Disposition", "d" },
	{ "Session-Expires", "x" },
};

/*!  Define SIP option tags, used in Require: and Supported: headers 
 	We need to be aware of these properties in the phones to use 
	the replace: header. We should not do that without knowing
	that the other end supports it... 
	This is nothing we can configure, we learn by the dialog
	Supported: header on the REGISTER (peer) or the INVITE
	(other devices)
	We are not using many of these today, but will in the future.
	This is documented in RFC 3261
*/
#define SUPPORTED		1
#define NOT_SUPPORTED		0

#define SIP_OPT_REPLACES	(1 << 0)
#define SIP_OPT_100REL		(1 << 1)
#define SIP_OPT_TIMER		(1 << 2)
#define SIP_OPT_EARLY_SESSION	(1 << 3)
#define SIP_OPT_JOIN		(1 << 4)
#define SIP_OPT_PATH		(1 << 5)
#define SIP_OPT_PREF		(1 << 6)
#define SIP_OPT_PRECONDITION	(1 << 7)
#define SIP_OPT_PRIVACY		(1 << 8)
#define SIP_OPT_SDP_ANAT	(1 << 9)
#define SIP_OPT_SEC_AGREE	(1 << 10)
#define SIP_OPT_EVENTLIST	(1 << 11)
#define SIP_OPT_GRUU		(1 << 12)
#define SIP_OPT_TARGET_DIALOG	(1 << 13)

/*! \brief List of well-known SIP options. If we get this in a require,
   we should check the list and answer accordingly. */
static const struct cfsip_options {
	int id;			/*!< Bitmap ID */
	int supported;		/*!< Supported by Asterisk ? */
	char * const text;	/*!< Text id, as in standard */
} sip_options[] = {
	/* Replaces: header for transfer */
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replaces" },	
	/* RFC3262: PRACK 100% reliability */
	{ SIP_OPT_100REL,	NOT_SUPPORTED,	"100rel" },	
	/* SIP Session Timers */
	{ SIP_OPT_TIMER,	NOT_SUPPORTED,	"timer" },
	/* RFC3959: SIP Early session support */
	{ SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,	"early-session" },
	/* SIP Join header support */
	{ SIP_OPT_JOIN,		NOT_SUPPORTED,	"join" },
	/* RFC3327: Path support */
	{ SIP_OPT_PATH,		NOT_SUPPORTED,	"path" },
	/* RFC3840: Callee preferences */
	{ SIP_OPT_PREF,		NOT_SUPPORTED,	"pref" },
	/* RFC3312: Precondition support */
	{ SIP_OPT_PRECONDITION,	NOT_SUPPORTED,	"precondition" },
	/* RFC3323: Privacy with proxies*/
	{ SIP_OPT_PRIVACY,	NOT_SUPPORTED,	"privacy" },
	/* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
	{ SIP_OPT_SDP_ANAT,	NOT_SUPPORTED,	"sdp-anat" },
	/* RFC3329: Security agreement mechanism */
	{ SIP_OPT_SEC_AGREE,	NOT_SUPPORTED,	"sec_agree" },
	/* SIMPLE events:  draft-ietf-simple-event-list-07.txt */
	{ SIP_OPT_EVENTLIST,	NOT_SUPPORTED,	"eventlist" },
	/* GRUU: Globally Routable User Agent URI's */
	{ SIP_OPT_GRUU,		NOT_SUPPORTED,	"gruu" },
	/* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
	{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,	"target-dialog" },
};


/*! \brief SIP Methods we support */
#define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"

/*! \brief SIP Extensions we support */
#define SUPPORTED_EXTENSIONS "replaces" 


/* Default values, set and reset in reload_config before reading configuration */
/* These are default values in the source. There are other recommended values in the
   sip.conf.sample for new installations. These may differ to keep backwards compatibility,
   yet encouraging new behaviour on new installations 
 */
#define DEFAULT_SIP_PORT	5060	/*!< From RFC 3261 (former 2543) */
#define DEFAULT_CONTEXT		"default"
#define DEFAULT_MUSICCLASS	"default"
#define DEFAULT_VMEXTEN 	"asterisk"
#define DEFAULT_CALLERID 	"asterisk"
#define DEFAULT_NOTIFYMIME 	"application/simple-message-summary"
#define DEFAULT_MWITIME 	10
#define DEFAULT_ALLOWGUEST	TRUE
#define DEFAULT_SRVLOOKUP	FALSE		/*!< Recommended setting is ON */
#define DEFAULT_COMPACTHEADERS	FALSE
#define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
#define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
#define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
#define DEFAULT_ALLOW_EXT_DOM	TRUE
#define DEFAULT_REALM		"asterisk"
#define DEFAULT_NOTIFYRINGING	TRUE
#define DEFAULT_PEDANTIC	FALSE
#define DEFAULT_AUTOCREATEPEER	FALSE
#define DEFAULT_QUALIFY		FALSE
#define DEFAULT_T1MIN		100		/*!< 100 MS for minimal roundtrip time */
#define DEFAULT_MAX_CALL_BITRATE (384)		/*!< Max bitrate for video */
#ifndef DEFAULT_USERAGENT
#define DEFAULT_USERAGENT "Asterisk PBX"	/*!< Default Useragent: header unless re-defined in sip.conf */
#endif


/* Default setttings are used as a channel setting and as a default when
   configuring devices */
static char default_context[AST_MAX_CONTEXT];
static char default_subscribecontext[AST_MAX_CONTEXT];
static char default_language[MAX_LANGUAGE];
static char default_callerid[AST_MAX_EXTENSION];
static char default_fromdomain[AST_MAX_EXTENSION];
static char default_notifymime[AST_MAX_EXTENSION];
static int default_qualify;		/*!< Default Qualify= setting */
static char default_vmexten[AST_MAX_EXTENSION];
static char default_musicclass[MAX_MUSICCLASS];		/*!< Global music on hold class */
static int default_maxcallbitrate;	/*!< Maximum bitrate for call */
static struct ast_codec_pref default_prefs;		/*!< Default codec prefs */

/* Global settings only apply to the channel */
static int global_rtautoclear;
static int global_notifyringing;	/*!< Send notifications on ringing */
static int srvlookup;			/*!< SRV Lookup on or off. Default is off, RFC behavior is on */
static int pedanticsipchecking;		/*!< Extra checking ?  Default off */
static int autocreatepeer;		/*!< Auto creation of peers at registration? Default off. */
static int global_relaxdtmf;			/*!< Relax DTMF */
static int global_rtptimeout;		/*!< Time out call if no RTP */
static int global_rtpholdtimeout;
static int global_rtpkeepalive;		/*!< Send RTP keepalives */
static int global_reg_timeout;	
static int global_regattempts_max;	/*!< Registration attempts before giving up */
static int global_allowguest;		/*!< allow unauthenticated users/peers to connect? */
static int global_allowsubscribe;	/*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
					    the global setting is in globals_flags[1] */
static int global_mwitime;		/*!< Time between MWI checks for peers */
static int global_tos_sip;		/*!< IP type of service for SIP packets */
static int global_tos_audio;		/*!< IP type of service for audio RTP packets */
static int global_tos_video;		/*!< IP type of service for video RTP packets */
static int compactheaders;		/*!< send compact sip headers */
static int recordhistory;		/*!< Record SIP history. Off by default */
static int dumphistory;			/*!< Dump history to verbose before destroying SIP dialog */
static char global_realm[MAXHOSTNAMELEN]; 		/*!< Default realm */
static char global_regcontext[AST_MAX_CONTEXT];		/*!< Context for auto-extensions */
static char global_useragent[AST_MAX_EXTENSION];	/*!< Useragent for the SIP channel */
static int allow_external_domains;	/*!< Accept calls to external SIP domains? */
static int global_callevents;		/*!< Whether we send manager events or not */
static int global_t1min;		/*!< T1 roundtrip time minimum */

/*! \brief Codecs that we support by default: */
static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
static int noncodeccapability = AST_RTP_DTMF;

/* Object counters */
static int suserobjs = 0;		/*!< Static users */
static int ruserobjs = 0;		/*!< Realtime users */
static int speerobjs = 0;		/*!< Statis peers */
static int rpeerobjs = 0;		/*!< Realtime peers */
static int apeerobjs = 0;		/*!< Autocreated peer objects */
static int regobjs = 0;			/*!< Registry objects */

static struct ast_flags global_flags[2] = {{0}};	/*!< global SIP_ flags */

AST_MUTEX_DEFINE_STATIC(usecnt_lock);

AST_MUTEX_DEFINE_STATIC(rand_lock);			/*!< Lock for thread-safe random generator */

/*! \brief Protect the SIP dialog list (of sip_pvt's) */
AST_MUTEX_DEFINE_STATIC(iflock);

/*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
   when it's doing something critical. */
AST_MUTEX_DEFINE_STATIC(netlock);

AST_MUTEX_DEFINE_STATIC(monlock);

AST_MUTEX_DEFINE_STATIC(sip_reload_lock);

/*! \brief 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;

static int sip_reloading = FALSE;			/*!< Flag for avoiding multiple reloads at the same time */
static enum channelreloadreason sip_reloadreason;	/*!< Reason for last reload/load of configuration */

static struct sched_context *sched;	/*!< The scheduling context */
static struct io_context *io;		/*!< The IO context */

#define DEC_CALL_LIMIT	0
#define INC_CALL_LIMIT	1


/*! \brief sip_request: The data grabbed from the UDP socket */
struct sip_request {
	char *rlPart1; 		/*!< SIP Method Name or "SIP/2.0" protocol version */
	char *rlPart2; 		/*!< The Request URI or Response Status */
	int len;		/*!< Length */
	int headers;		/*!< # of SIP Headers */
	int method;		/*!< Method of this request */
	char *header[SIP_MAX_HEADERS];
	int lines;		/*!< SDP Content */
	char *line[SIP_MAX_LINES];
	char data[SIP_MAX_PACKET];
	int debug;		/*!< Debug flag for this packet */
	unsigned int flags;	/*!< SIP_PKT Flags for this packet */
};

/*! \brief structure used in transfers */
struct sip_dual {
	struct ast_channel *chan1;
	struct ast_channel *chan2;
	struct sip_request req;
};

struct sip_pkt;

/*! \brief Parameters to the transmit_invite function */
struct sip_invite_param {
	const char *distinctive_ring;	/*!< Distinctive ring header */
	const char *osptoken;		/*!< OSP token for this call */
	int addsipheaders;	/*!< Add extra SIP headers */
	const char *uri_options;	/*!< URI options to add to the URI */
	const char *vxml_url;		/*!< VXML url for Cisco phones */
	char *auth;		/*!< Authentication */
	char *authheader;	/*!< Auth header */
	enum sip_auth_type auth_type;	/*!< Authentication type */
};

/*! \brief Structure to save routing information for a SIP session */
struct sip_route {
	struct sip_route *next;
	char hop[0];
};

/*! \brief Modes for SIP domain handling in the PBX */
enum domain_mode {
	SIP_DOMAIN_AUTO,	/*!< This domain is auto-configured */
	SIP_DOMAIN_CONFIG,	/*!< This domain is from configuration */
};

struct domain {
	char domain[MAXHOSTNAMELEN];		/*!< SIP domain we are responsible for */
	char context[AST_MAX_EXTENSION];	/*!< Incoming context for this domain */
	enum domain_mode mode;			/*!< How did we find this domain? */
	AST_LIST_ENTRY(domain) list;		/*!< List mechanics */
};

static AST_LIST_HEAD_STATIC(domain_list, domain);	/*!< The SIP domain list */


/*! \brief sip_history: Structure for saving transactions within a SIP dialog */
struct sip_history {
	AST_LIST_ENTRY(sip_history) list;
	char event[0];	/* actually more, depending on needs */
};

AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */

/*! \brief sip_auth: Creadentials for authentication to other SIP services */
struct sip_auth {
	char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
	char username[256];		/*!< Username */
	char secret[256];		/*!< Secret */
	char md5secret[256];		/*!< MD5Secret */
	struct sip_auth *next;		/*!< Next auth structure in list */
};

/*--- Various flags for the flags field in the pvt structure 
 Peer only flags should be set in PAGE2 below
*/
#define SIP_ALREADYGONE		(1 << 0)	/*!< Whether or not we've already been destroyed by our peer */
#define SIP_NEEDDESTROY		(1 << 1)	/*!< if we need to be destroyed */
#define SIP_NOVIDEO		(1 << 2)	/*!< Didn't get video in invite, don't offer */
#define SIP_RINGING		(1 << 3)	/*!< Have sent 180 ringing */
#define SIP_PROGRESS_SENT	(1 << 4)	/*!< Have sent 183 message progress */
#define SIP_NEEDREINVITE	(1 << 5)	/*!< Do we need to send another reinvite? */
#define SIP_PENDINGBYE		(1 << 6)	/*!< Need to send bye after we ack? */
#define SIP_GOTREFER		(1 << 7)	/*!< Got a refer? */
#define SIP_PROMISCREDIR	(1 << 8)	/*!< Promiscuous redirection */
#define SIP_TRUSTRPID		(1 << 9)	/*!< Trust RPID headers? */
#define SIP_USEREQPHONE		(1 << 10)	/*!< Add user=phone to numeric URI. Default off */
#define SIP_REALTIME		(1 << 11)	/*!< Flag for realtime users */
#define SIP_USECLIENTCODE	(1 << 12)	/*!< Trust X-ClientCode info message */
#define SIP_OUTGOING		(1 << 13)	/*!< Is this an outgoing call? */
#define SIP_FREEBIT		(1 << 14)	/*!< Free for session-related use */
#define SIP_FREEBIT3		(1 << 15)	/*!< Free for session-related use */
#define SIP_DTMF		(3 << 16)	/*!< DTMF Support: four settings, uses two bits */
#define SIP_DTMF_RFC2833	(0 << 16)	/*!< DTMF Support: RTP DTMF - "rfc2833" */
#define SIP_DTMF_INBAND		(1 << 16)	/*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
#define SIP_DTMF_INFO		(2 << 16)	/*!< DTMF Support: SIP Info messages - "info" */
#define SIP_DTMF_AUTO		(3 << 16)	/*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
/* NAT settings */
#define SIP_NAT			(3 << 18)	/*!< four settings, uses two bits */
#define SIP_NAT_NEVER		(0 << 18)	/*!< No nat support */
#define SIP_NAT_RFC3581		(1 << 18)
#define SIP_NAT_ROUTE		(2 << 18)
#define SIP_NAT_ALWAYS		(3 << 18)
/* re-INVITE related settings */
#define SIP_REINVITE		(3 << 20)	/*!< two bits used */
#define SIP_CAN_REINVITE	(1 << 20)	/*!< allow peers to be reinvited to send media directly p2p */
#define SIP_REINVITE_UPDATE	(2 << 20)	/*!< use UPDATE (RFC3311) when reinviting this peer */
/* "insecure" settings */
#define SIP_INSECURE_PORT	(1 << 22)	/*!< don't require matching port for incoming requests */
#define SIP_INSECURE_INVITE	(1 << 23)	/*!< don't require authentication for incoming INVITEs */
/* Sending PROGRESS in-band settings */
#define SIP_PROG_INBAND		(3 << 24)	/*!< three settings, uses two bits */
#define SIP_PROG_INBAND_NEVER	(0 << 24)
#define SIP_PROG_INBAND_NO	(1 << 24)
#define SIP_PROG_INBAND_YES	(2 << 24)
/* Open Settlement Protocol authentication */
#define SIP_OSPAUTH		(3 << 26)	/*!< four settings, uses two bits */
#define SIP_OSPAUTH_NO		(0 << 26)
#define SIP_OSPAUTH_GATEWAY	(1 << 26)
#define SIP_OSPAUTH_PROXY	(2 << 26)
#define SIP_OSPAUTH_EXCLUSIVE	(3 << 26)
/* Call states */
#define SIP_CALL_ONHOLD		(1 << 28)	 
#define SIP_CALL_LIMIT		(1 << 29)
/* Remote Party-ID Support */
#define SIP_SENDRPID		(1 << 30)
/* Did this connection increment the counter of in-use calls? */
#define SIP_INC_COUNT		(1 << 31)

#define SIP_FLAGS_TO_COPY \
	(SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
	 SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
	 SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)

/* a new page of flags for peers */
#define SIP_PAGE2_RTCACHEFRIENDS	(1 << 0)
#define SIP_PAGE2_RTUPDATE		(1 << 1)
#define SIP_PAGE2_RTAUTOCLEAR		(1 << 2)
#define SIP_PAGE2_IGNOREREGEXPIRE	(1 << 3)
#define SIP_PAGE2_RT_FROMCONTACT 	(1 << 4)
#define SIP_PAGE2_DEBUG			(3 << 5)
#define SIP_PAGE2_DEBUG_CONFIG 		(1 << 5)
#define SIP_PAGE2_DEBUG_CONSOLE 	(1 << 6)
#define SIP_PAGE2_DYNAMIC		(1 << 7)	/*!< Dynamic Peers register with Asterisk */
#define SIP_PAGE2_SELFDESTRUCT		(1 << 8)	/*!< Automatic peers need to destruct themselves */
#define SIP_PAGE2_VIDEOSUPPORT		(1 << 9)
#define SIP_PAGE2_ALLOWSUBSCRIBE	(1 << 10)	/*!< Allow subscriptions from this peer? */
#define SIP_PAGE2_ALLOWOVERLAP		(1 << 11)	/*!< Allow overlap dialing ? */
#define SIP_PAGE2_SUBSCRIBEMWIONLY	(1 << 12)	/*!< Only issue MWI notification if subscribed to */


#define SIP_PAGE2_FLAGS_TO_COPY \
	(SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT)

/* SIP packet flags */
#define SIP_PKT_DEBUG		(1 << 0)	/*!< Debug this packet */
#define SIP_PKT_WITH_TOTAG	(1 << 1)	/*!< This packet has a to-tag */

#define sipdebug		ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
#define sipdebug_config		ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
#define sipdebug_console	ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)

/*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe  */
static struct sip_pvt {
	ast_mutex_t lock;			/*!< Dialog private lock */
	int method;				/*!< SIP method that opened this dialog */
	AST_DECLARE_STRING_FIELDS(
		AST_STRING_FIELD(callid);	/*!< Global CallID */
		AST_STRING_FIELD(randdata);	/*!< Random data */
		AST_STRING_FIELD(accountcode);	/*!< Account code */
		AST_STRING_FIELD(realm);	/*!< Authorization realm */
		AST_STRING_FIELD(nonce);	/*!< Authorization nonce */
		AST_STRING_FIELD(opaque);	/*!< Opaque nonsense */
		AST_STRING_FIELD(qop);		/*!< Quality of Protection, since SIP wasn't complicated enough yet. */
		AST_STRING_FIELD(domain);	/*!< Authorization domain */
		AST_STRING_FIELD(refer_to);	/*!< Place to store REFER-TO extension */
		AST_STRING_FIELD(referred_by);	/*!< Place to store REFERRED-BY extension */
		AST_STRING_FIELD(refer_contact);/*!< Place to store Contact info from a REFER extension */
		AST_STRING_FIELD(from);		/*!< The From: header */
		AST_STRING_FIELD(useragent);	/*!< User agent in SIP request */
		AST_STRING_FIELD(exten);	/*!< Extension where to start */
		AST_STRING_FIELD(context);	/*!< Context for this call */
		AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
		AST_STRING_FIELD(fromdomain);	/*!< Domain to show in the from field */
		AST_STRING_FIELD(fromuser);	/*!< User to show in the user field */
		AST_STRING_FIELD(fromname);	/*!< Name to show in the user field */
		AST_STRING_FIELD(tohost);	/*!< Host we should put in the "to" field */
		AST_STRING_FIELD(language);	/*!< Default language for this call */
		AST_STRING_FIELD(musicclass);	/*!< Music on Hold class */
		AST_STRING_FIELD(rdnis);	/*!< Referring DNIS */
		AST_STRING_FIELD(theirtag);	/*!< Their tag */
		AST_STRING_FIELD(username);	/*!< [user] name */
		AST_STRING_FIELD(peername);	/*!< [peer] name, not set if [user] */
		AST_STRING_FIELD(authname);	/*!< Who we use for authentication */
		AST_STRING_FIELD(uri);		/*!< Original requested URI */
		AST_STRING_FIELD(okcontacturi);	/*!< URI from the 200 OK on INVITE */
		AST_STRING_FIELD(peersecret);	/*!< Password */
		AST_STRING_FIELD(peermd5secret);
		AST_STRING_FIELD(cid_num);	/*!< Caller*ID */
		AST_STRING_FIELD(cid_name);	/*!< Caller*ID */
		AST_STRING_FIELD(via);		/*!< Via: header */
		AST_STRING_FIELD(fullcontact);	/*!< The Contact: that the UA registers with us */
		AST_STRING_FIELD(our_contact);	/*!< Our contact header */
		AST_STRING_FIELD(rpid);		/*!< Our RPID header */
		AST_STRING_FIELD(rpid_from);	/*!< Our RPID From header */
	);
	struct ast_codec_pref prefs;		/*!< codec prefs */
	unsigned int ocseq;			/*!< Current outgoing seqno */
	unsigned int icseq;			/*!< Current incoming seqno */
	ast_group_t callgroup;			/*!< Call group */
	ast_group_t pickupgroup;		/*!< Pickup group */
	int lastinvite;				/*!< Last Cseq of invite */
	struct ast_flags flags[2];		/*!< SIP_ flags */
	int timer_t1;				/*!< SIP timer T1, ms rtt */
	unsigned int sipoptions;		/*!< Supported SIP sipoptions on the other end */
	int capability;				/*!< Special capability (codec) */
	int jointcapability;			/*!< Supported capability at both ends (codecs ) */
	int peercapability;			/*!< Supported peer capability */
	int prefcodec;				/*!< Preferred codec (outbound only) */
	int noncodeccapability;
	int maxcallbitrate;			/*!< Maximum Call Bitrate for Video Calls */	
	int callingpres;			/*!< Calling presentation */
	int authtries;				/*!< Times we've tried to authenticate */
	int expiry;				/*!< How long we take to expire */
	int branch;				/*!< One random number */
	char tag[11];				/*!< Another random number */
	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 */
	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? */
	struct sip_auth *peerauth;		/*!< Realm authentication */
	int noncecount;				/*!< Nonce-count */
	char lastmsg[256];			/*!< Last Message sent/received */
	int amaflags;				/*!< AMA Flags */
	int pendinginvite;			/*!< Any pending invite */
#ifdef OSP_SUPPORT
	int osphandle;				/*!< OSP Handle for call */
	time_t ospstart;			/*!< OSP Start time */
	unsigned int osptimelimit;		/*!< OSP call duration limit */
#endif
	struct sip_request initreq;		/*!< Initial request that opened the SIP dialog */
	
	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 */
	time_t lastrtptx;			/*!< Last RTP sent */
	int rtptimeout;				/*!< RTP timeout time */
	int rtpholdtimeout;			/*!< RTP timeout when on hold */
	int rtpkeepalive;			/*!< Send RTP packets for keepalive */
	enum subscriptiontype subscribed;	/*!< Is this dialog a subscription?  */
	int stateid;
	int laststate;				/*!< Last known extension state */
	int dialogver;
	
	struct ast_dsp *vad;			/*!< Voice Activation Detection dsp */
	
	struct sip_peer *relatedpeer;		/*!< If this dialog is related to a peer, which one 
							Used in peerpoke, mwi subscriptions */
	struct sip_registry *registry;		/*!< If this is a REGISTER dialog, 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 */
	struct sip_history_head *history;	/*!< History of this SIP dialog */
	struct ast_variable *chanvars;		/*!< Channel variables to set for call */
	struct sip_pvt *next;			/*!< Next dialog in chain */
	struct sip_invite_param *options;	/*!< Options for INVITE */
} *iflist = NULL;

#define FLAG_RESPONSE (1 << 0)
#define FLAG_FATAL (1 << 1)

/*! \brief sip packet - read in sipsock_read(), transmitted in send_request() */
struct sip_pkt {
	struct sip_pkt *next;			/*!< Next packet */
	int retrans;				/*!< Retransmission number */
	int method;				/*!< SIP method for this packet */
	int seqno;				/*!< Sequence number */
	unsigned int flags;			/*!< non-zero if this is a response packet (e.g. 200 OK) */
	struct sip_pvt *owner;			/*!< Owner AST call */
	int retransid;				/*!< Retransmission ID */
	int timer_a;				/*!< SIP timer A, retransmission timer */
	int timer_t1;				/*!< SIP Timer T1, estimated RTT or 500 ms */
	int packetlen;				/*!< Length of packet */
	char data[0];
};	

/*! \brief Structure for SIP user data. User's place calls to us */
struct sip_user {
	/* Users who can access various contexts */
	ASTOBJ_COMPONENTS(struct sip_user);
	char secret[80];		/*!< Password */
	char md5secret[80];		/*!< Password in md5 */
	char context[AST_MAX_CONTEXT];	/*!< Default context for incoming calls */
	char subscribecontext[AST_MAX_CONTEXT];	/* Default context for subscriptions */
	char cid_num[80];		/*!< Caller ID num */
	char cid_name[80];		/*!< Caller ID name */
	char accountcode[AST_MAX_ACCOUNT_CODE];	/* Account code */
	char language[MAX_LANGUAGE];	/*!< Default language for this user */
	char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
	char useragent[256];		/*!< User agent in SIP request */
	struct ast_codec_pref prefs;	/*!< codec prefs */
	ast_group_t callgroup;		/*!< Call group */
	ast_group_t pickupgroup;	/*!< Pickup Group */
	unsigned int sipoptions;	/*!< Supported SIP options */
	struct ast_flags flags[2];	/*!< SIP_ flags */
	int amaflags;			/*!< AMA flags for billing */
	int callingpres;		/*!< Calling id presentation */
	int capability;			/*!< Codec capability */
	int inUse;			/*!< Number of calls in use */
	int call_limit;			/*!< Limit of concurrent calls */
	struct ast_ha *ha;		/*!< ACL setting */
	struct ast_variable *chanvars;	/*!< Variables to set for channel created by user */
	int maxcallbitrate;		/*!< Maximum Bitrate for a video call */
};

/*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
struct sip_peer {
	ASTOBJ_COMPONENTS(struct sip_peer);	/*!< name, refcount, objflags,  object pointers */
					/*!< peer->name is the unique name of this object */
	char secret[80];		/*!< Password */
	char md5secret[80];		/*!< Password in MD5 */
	struct sip_auth *auth;		/*!< Realm authentication list */
	char context[AST_MAX_CONTEXT];	/*!< Default context for incoming calls */
	char subscribecontext[AST_MAX_CONTEXT];	/*!< Default context for subscriptions */
	char username[80];		/*!< Temporary username until registration */ 
	char accountcode[AST_MAX_ACCOUNT_CODE];	/*!< Account code */
	int amaflags;			/*!< AMA Flags (for billing) */
	char tohost[MAXHOSTNAMELEN];	/*!< If not dynamic, IP address */
	char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
	char fromuser[80];		/*!< From: user when calling this peer */
	char fromdomain[MAXHOSTNAMELEN];	/*!< From: domain when calling this peer */
	char fullcontact[256];		/*!< Contact registered with us (not in sip.conf) */
	char cid_num[80];		/*!< Caller ID num */
	char cid_name[80];		/*!< Caller ID name */
	int callingpres;		/*!< Calling id presentation */
	int inUse;			/*!< Number of calls in use */
	int call_limit;			/*!< Limit of concurrent calls */
	char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
	char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
	char language[MAX_LANGUAGE];	/*!<  Default language for prompts */
	char musicclass[MAX_MUSICCLASS];/*!<  Music on Hold class */
	char useragent[256];		/*!<  User agent in SIP request (saved from registration) */
	struct ast_codec_pref prefs;	/*!<  codec prefs */
	int lastmsgssent;
	time_t	lastmsgcheck;		/*!<  Last time we checked for MWI */
	unsigned int sipoptions;	/*!<  Supported SIP options */
	struct ast_flags flags[2];	/*!<  SIP_ flags */
	int expire;			/*!<  When to expire this peer registration */
	int capability;			/*!<  Codec capability */
	int rtptimeout;			/*!<  RTP timeout */
	int rtpholdtimeout;		/*!<  RTP Hold Timeout */
	int rtpkeepalive;		/*!<  Send RTP packets for keepalive */
	ast_group_t callgroup;		/*!<  Call group */
	ast_group_t pickupgroup;	/*!<  Pickup group */
	struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
	struct sockaddr_in addr;	/*!<  IP address of peer */
	int maxcallbitrate;		/*!< Maximum Bitrate for a video call */
	
	/* Qualification */
	struct sip_pvt *call;		/*!<  Call pointer */
	int pokeexpire;			/*!<  When to expire poke (qualify= checking) */
	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;	/*!<  Default IP address, used until registration */
	struct ast_ha *ha;		/*!<  Access control list */
	struct ast_variable *chanvars;	/*!<  Variables to set for channel created by user */
	struct sip_pvt *mwipvt;		/*!<  Subscription for MWI */
	int lastmsg;
};


/* States for outbound registrations (with register= lines in sip.conf */
#define REG_STATE_UNREGISTERED		0	/*!< We are not registred */
#define REG_STATE_REGSENT		1	/*!< Registration request sent */
#define REG_STATE_AUTHSENT		2	/*!< We have tried to authenticate */
#define REG_STATE_REGISTERED		3	/*!< Registred and done */
#define REG_STATE_REJECTED		4	/*!< Registration rejected */
#define REG_STATE_TIMEOUT		5	/*!< Registration timed out */
#define REG_STATE_NOAUTH		6	/*!< We have no accepted credentials */
#define REG_STATE_FAILED		7	/*!< Registration failed after several tries */


/*! \brief Registrations with other SIP proxies */
struct sip_registry {
	ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
	AST_DECLARE_STRING_FIELDS(
		AST_STRING_FIELD(callid);	/*!< Global Call-ID */
		AST_STRING_FIELD(realm);	/*!< Authorization realm */
		AST_STRING_FIELD(nonce);	/*!< Authorization nonce */
		AST_STRING_FIELD(opaque);	/*!< Opaque nonsense */
		AST_STRING_FIELD(qop);		/*!< Quality of Protection, since SIP wasn't complicated enough yet. */
		AST_STRING_FIELD(domain);	/*!< Authorization domain */
		AST_STRING_FIELD(username);	/*!< Who we are registering as */
		AST_STRING_FIELD(authuser);	/*!< Who we *authenticate* as */
		AST_STRING_FIELD(hostname);	/*!< Domain or host we register to */
		AST_STRING_FIELD(secret);	/*!< Password in clear text */	
		AST_STRING_FIELD(md5secret);	/*!< Password in md5 */
		AST_STRING_FIELD(contact);	/*!< Contact extension */
		AST_STRING_FIELD(random);
	);
	int portno;			/*!<  Optional port override */
	int expire;			/*!< Sched ID of expiration */
	int regattempts;		/*!< Number of attempts (since the last success) */
	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 dialog" in progress */
	int regstate;			/*!< Registration state (see above) */
	int callid_valid;		/*!< 0 means we haven't chosen callid for this registry yet. */
	unsigned int ocseq;		/*!< Sequence number we got to for REGISTERs for this registry */
	struct sockaddr_in us;		/*!< Who the server thinks we are */
	int noncecount;			/*!< Nonce-count */
	char lastmsg[256];		/*!< Last Message sent/received */
};

/* --- Linked lists of various objects --------*/

/*! \brief  The user list: Users and friends */
static struct ast_user_list {
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
} userl;

/*! \brief  The peer list: Peers and Friends */
static struct ast_peer_list {
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
} peerl;

/*! \brief  The register list: Other SIP proxys we register with and place calls to */
static struct ast_register_list {
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
	int recheck;
} regl;

/*! \todo Move the sip_auth list to AST_LIST */
static struct sip_auth *authl = NULL;		/*!< Authentication list for realm authentication */


/* --- Sockets and networking --------------*/
static int sipsock  = -1;			/*!< Main socket for SIP network communication */
static struct sockaddr_in bindaddr = { 0, };	/*!< The address we bind to */
static struct sockaddr_in externip;		/*!< External IP address if we are behind NAT */
static char externhost[MAXHOSTNAMELEN];		/*!< External host name (possibly with dynamic DNS and DHCP */
static time_t externexpire = 0;			/*!< Expiration counter for re-resolving external host name in dynamic DNS */
static int externrefresh = 10;
static struct ast_ha *localaddr;		/*!< List of local networks, on the same side of NAT as this Asterisk */
static struct in_addr __ourip;
static struct sockaddr_in outboundproxyip;
static int ourport;
static struct sockaddr_in debugaddr;

struct ast_config *notify_types;		/*!< The list of manual NOTIFY types we know how to send */



/*---------------------------- Forward declarations of functions in chan_sip.c */
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, enum xmittype reliable);
static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, 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_info_with_vidupdate(struct sip_pvt *p);
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
static int transmit_refer(struct sip_pvt *p, const char *dest);
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
static struct sip_peer *temp_peer(const char *name);
static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
static void free_old_route(struct sip_route *route);
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
static int update_call_counter(struct sip_pvt *fup, int event);
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
static int sip_do_reload(enum channelreloadreason reason);
static int expire_register(void *data);
static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
static int sip_devicestate(void *data);
static int sip_sendtext(struct ast_channel *ast, const char *text);
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
static int sip_hangup(struct ast_channel *ast);
static int sip_answer(struct ast_channel *ast);
static struct ast_frame *sip_read(struct ast_channel *ast);
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
static int sip_indicate(struct ast_channel *ast, int condition);
static int sip_transfer(struct ast_channel *ast, const char *dest);
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
static int sip_senddigit(struct ast_channel *ast, char digit);
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);	/* Add realm authentication in list */
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);	/* Find authentication for a specific realm */
static int check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
		const char *secret, const char *md5secret, int sipmethod,
		char *uri, enum xmittype reliable, int ignore);
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
static int determine_firstline_parts(struct sip_request *req);
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to LOG_DEBUG at end of dialog, before destroying data */
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
static int transmit_state_notify(struct sip_pvt *p, int state, int full);
static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
static int find_sip_method(char *msg);
static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported);
static void sip_destroy(struct sip_pvt *p);
static void sip_destroy_peer(struct sip_peer *peer);
static void sip_destroy_user(struct sip_user *user);
static void parse_request(struct sip_request *req);
static char *get_header(struct sip_request *req, const char *name);
static void copy_request(struct sip_request *dst,struct sip_request *src);
static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
static int sip_poke_peer(struct sip_peer *peer);
static int __sip_do_register(struct sip_registry *r);
static int restart_monitor(void);
static void set_peer_defaults(struct sip_peer *peer);
static struct sip_peer *temp_peer(const char *name);
static int sip_send_mwi_to_peer(struct sip_peer *peer);
static int sip_scheddestroy(struct sip_pvt *p, int ms);


/*----- RTP interface functions */
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan);
static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan);
static int sip_get_codec(struct ast_channel *chan);

/*! \brief Definition of this channel for PBX channel registration */
static const struct ast_channel_tech sip_tech = {
	.type = "SIP",
	.description = "Session Initiation Protocol (SIP)",
	.capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
	.properties = AST_CHAN_TP_WANTSJITTER,
	.requester = sip_request_call,
	.devicestate = sip_devicestate,
	.call = sip_call,
	.hangup = sip_hangup,
	.answer = sip_answer,
	.read = sip_read,
	.write = sip_write,
	.write_video = sip_write,
	.indicate = sip_indicate,
	.transfer = sip_transfer,
	.fixup = sip_fixup,
	.send_digit = sip_senddigit,
	.bridge = ast_rtp_bridge,
	.send_text = sip_sendtext,
};

/*! \brief Interface structure with callbacks used to connect to RTP module */
static struct ast_rtp_protocol sip_rtp = {
	type: "SIP",
	get_rtp_info: sip_get_rtp_peer,
	get_vrtp_info: sip_get_vrtp_peer,
	set_rtp_peer: sip_set_rtp_peer,
	get_codec: sip_get_codec,
};


/*!
  \brief Thread-safe random number generator
  \return a random number

  This function uses a mutex lock to guarantee that no
  two threads will receive the same random number.
 */
static force_inline int thread_safe_rand(void)
{
	int val;

	ast_mutex_lock(&rand_lock);
	val = rand();
	ast_mutex_unlock(&rand_lock);
	
	return val;
}

/*! \brief Find SIP method from header
 * Strictly speaking, SIP methods are case SENSITIVE, but we don't check 
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
static int find_sip_method(char *msg)
{
	int i, res = 0;
	
	if (ast_strlen_zero(msg))
		return 0;

	for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
		if (!strcasecmp(sip_methods[i].text, msg)) 
			res = sip_methods[i].id;
	}
	return res;
}

/*! \brief Parse supported header in incoming packet */
static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
{
	char *next = NULL;
	char *sep = NULL;
	char *temp = ast_strdupa(supported);
	int i;
	unsigned int profile = 0;

	if (ast_strlen_zero(supported) )
		return 0;

	if (option_debug > 2 && sipdebug)
		ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);

	next = temp;
	while (next) {
		char res=0;
		if ( (sep = strchr(next, ',')) != NULL) {
			*sep = '\0';
			sep++;
		}
		while (*next == ' ')	/* Skip spaces */
			next++;
		if (option_debug > 2 && sipdebug)
			ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
		for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
			if (!strcasecmp(next, sip_options[i].text)) {
				profile |= sip_options[i].id;
				res = 1;
				if (option_debug > 2 && sipdebug)
					ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
			}
		}
		if (!res) 
			if (option_debug > 2 && sipdebug)
				ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
		next = sep;
	}
	if (pvt) {
		pvt->sipoptions = profile;
		if (option_debug)
			ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
	}
	return profile;
}

/*! \brief See if we pass debug IP filter */
static inline int sip_debug_test_addr(struct sockaddr_in *addr) 
{
	if (!sipdebug)
		return 0;
	if (debugaddr.sin_addr.s_addr) {
		if (((ntohs(debugaddr.sin_port) != 0)
			&& (debugaddr.sin_port != addr->sin_port))
			|| (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
			return 0;
	}
	return 1;
}

/*! \brief Test PVT for debugging output */
static inline int sip_debug_test_pvt(struct sip_pvt *p) 
{
	if (!sipdebug)
		return 0;
	return sip_debug_test_addr(ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) ? &p->recv : &p->sa);
}


/*! \brief Transmit SIP message */
static int __sip_xmit(struct sip_pvt *p, char *data, int len)
{
	int res;
	char iabuf[INET_ADDRSTRLEN];

	if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
		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));

	if (res != len) {
		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), res, strerror(errno));
	}
	return res;
}


/*! \brief Build a Via header for a request */
static void build_via(struct sip_pvt *p)
{
	char iabuf[INET_ADDRSTRLEN];
	/* Work around buggy UNIDEN UIP200 firmware */
	const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";

	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
	ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
			 ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch, rport);
}

/*! \brief 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)
{
	/*
	 * 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)) {
		if (externexpire && (time(NULL) >= externexpire)) {
			struct ast_hostent ahp;
			struct hostent *hp;

			time(&externexpire);
			externexpire += externrefresh;
			if ((hp = ast_gethostbyname(externhost, &ahp))) {
				memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
			} else
				ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
		}
		memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
		if (option_debug) {
			char iabuf[INET_ADDRSTRLEN];
			ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
		
			ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
		}
	} else if (bindaddr.sin_addr.s_addr)
		memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
	else
		return ast_ouraddrfor(them, us);
	return 0;
}

/*! \brief Append to SIP dialog history 
	\return Always returns 0 */
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)

static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
	__attribute__ ((format (printf, 2, 3)));

/*! \brief Append to SIP dialog history with arg list  */
static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
{
	char buf[80], *c = buf; /* max history length */
	struct sip_history *hist;
	int l;

	vsnprintf(buf, sizeof(buf), fmt, ap);
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
	l = strlen(buf) + 1;
	if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
		return;
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
		free(hist);
		return;
	}
	memcpy(hist->event, buf, l);
	AST_LIST_INSERT_TAIL(p->history, hist, list);
}

/*! \brief Append to SIP dialog history with arg list  */
static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
{
	va_list ap;

	if (!recordhistory || !p)
		return 0;
	va_start(ap, fmt);
	append_history_va(p, fmt, ap);
	va_end(ap);

	return 0;
}

/*! \brief Retransmit SIP message if no answer */
static int retrans_pkt(void *data)
{
	struct sip_pkt *pkt=data, *prev, *cur = NULL;
	char iabuf[INET_ADDRSTRLEN];
	int reschedule = DEFAULT_RETRANS;

	/* Lock channel */
	ast_mutex_lock(&pkt->owner->lock);

	if (pkt->retrans < MAX_RETRANS) {
		pkt->retrans++;
 		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
			if (sipdebug && option_debug > 3)
 				ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
		} else {
 			int siptimer_a;

 			if (sipdebug && option_debug > 3)
 				ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
 			if (!pkt->timer_a)
 				pkt->timer_a = 2 ;
 			else
 				pkt->timer_a = 2 * pkt->timer_a;
 
 			/* For non-invites, a maximum of 4 secs */
 			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
 			if (pkt->method != SIP_INVITE && siptimer_a > 4000)
 				siptimer_a = 4000;
 		
 			/* Reschedule re-transmit */
			reschedule = siptimer_a;
 			if (option_debug > 3)
 				ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
 		} 

		if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
			if (ast_test_flag(&pkt->owner->flags[0], SIP_NAT_ROUTE))
				ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
			else
				ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
		}

		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
		__sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
		ast_mutex_unlock(&pkt->owner->lock);
		return  reschedule;
	} 
	/* Too many retries */
	if (pkt->owner && pkt->method != SIP_OPTIONS) {
		if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug)	/* Tell us if it's critical or if we're debugging */
			ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
	} else {
		if ((pkt->method == SIP_OPTIONS) && sipdebug)
			ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
	}
	append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
 		
	pkt->retransid = -1;

	if (ast_test_flag(pkt, 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) {
			ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
			ast_queue_hangup(pkt->owner->owner);
			ast_mutex_unlock(&pkt->owner->owner->lock);
		} else {
			/* If no channel owner, destroy now */
			ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);	
		}
	}
	/* 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");
	if (pkt)
		ast_mutex_unlock(&pkt->owner->lock);
	return 0;
}

/*! \brief Transmit packet with retransmits 
	\return 0 on success, -1 on failure to allocate packet 
*/
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
{
	struct sip_pkt *pkt;
	int siptimer_a = DEFAULT_RETRANS;

	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
		return -1;
	memcpy(pkt->data, data, len);
	pkt->method = sipmethod;
	pkt->packetlen = len;
	pkt->next = p->packets;
	pkt->owner = p;
	pkt->seqno = seqno;
	pkt->flags = resp;
	pkt->data[len] = '\0';
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
	if (fatal)
		ast_set_flag(pkt, FLAG_FATAL);

	if (pkt->timer_t1)
		siptimer_a = pkt->timer_t1 * 2;

	/* Schedule retransmission */
	pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
	if (option_debug > 3 && sipdebug)
		ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id  #%d\n", pkt->retransid);
	pkt->next = p->packets;
	p->packets = pkt;

	__sip_xmit(pkt->owner, pkt->data, pkt->packetlen);	/* Send packet */
	if (sipmethod == SIP_INVITE) {
		/* Note this is a pending invite */
		p->pendinginvite = seqno;
	}
	return 0;
}

/*! \brief Kill a SIP dialog (called by scheduler) */
static int __sip_autodestruct(void *data)
{
	struct sip_pvt *p = data;

	/* If this is a subscription, tell the phone that we got a timeout */
	if (p->subscribed) {
		p->subscribed = TIMEOUT;
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1);	/* Send last notification */
		p->subscribed = NONE;
		append_history(p, "Subscribestatus", "timeout");
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
	}

	/* Reset schedule ID */
	p->autokillid = -1;

	if (option_debug)
		ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
	append_history(p, "AutoDestroy", "");
	if (p->owner) {
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
		ast_queue_hangup(p->owner);
	} else {
		sip_destroy(p);
	}
	return 0;
}

/*! \brief Schedule destruction of SIP call */
static int sip_scheddestroy(struct sip_pvt *p, int ms)
{
	if (sip_debug_test_pvt(p))
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
	if (recordhistory)
		append_history(p, "SchedDestroy", "%d ms", ms);

	if (p->autokillid > -1)
		ast_sched_del(sched, p->autokillid);
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
	return 0;
}

/*! \brief Cancel destruction of SIP dialog */
static int sip_cancel_destroy(struct sip_pvt *p)
{
	if (p->autokillid > -1)
		ast_sched_del(sched, p->autokillid);
	append_history(p, "CancelDestroy", "");
	p->autokillid = -1;
	return 0;
}

/*! \brief Acknowledges receipt of a packet and stops retransmission */
static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
{
	struct sip_pkt *cur, *prev = NULL;
	int res = -1;

	/* Just in case... */
	char *msg;

	msg = sip_methods[sipmethod].text;

	ast_mutex_lock(&p->lock);
	cur = p->packets;
	while(cur) {
		if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
			((ast_test_flag(cur, FLAG_RESPONSE)) || 
			 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
			if (!resp && (seqno == p->pendinginvite)) {
				ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
				p->pendinginvite = 0;
			}
			/* this is our baby */
			if (prev)
				prev->next = cur->next;
			else
				p->packets = cur->next;
			if (cur->retransid > -1) {
				if (sipdebug && option_debug > 3)
					ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
				ast_sched_del(sched, cur->retransid);
			}
			free(cur);
			res = 0;
			break;
		}
		prev = cur;
		cur = cur->next;
	}
	ast_mutex_unlock(&p->lock);
	if (option_debug)
		ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
	return res;
}

/*! \brief Pretend to ack all packets */
static int __sip_pretend_ack(struct sip_pvt *p)
{
	struct sip_pkt *cur=NULL;

	while(p->packets) {
		if (cur == p->packets) {
			ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
			return -1;
		}
		cur = p->packets;
		if (cur->method)
			__sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
		else {	/* Unknown packet type */
			char *c;
			char method[128];

			ast_copy_string(method, p->packets->data, sizeof(method));
			c = ast_skip_blanks(method); /* XXX what ? */
			*c = '\0';
			__sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
		}
	}
	return 0;
}

/*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
{
	struct sip_pkt *cur;
	int res = -1;
	char *msg = sip_methods[sipmethod].text;

	cur = p->packets;
	while(cur) {
		if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
			((ast_test_flag(cur, FLAG_RESPONSE)) || 
			 (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
			/* this is our baby */
			if (cur->retransid > -1) {
				if (option_debug > 3 && sipdebug)
					ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
				ast_sched_del(sched, cur->retransid);
			}
			cur->retransid = -1;
			res = 0;
			break;
		}
		cur = cur->next;
	}
	if (option_debug)
		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");
	return res;
}


/*! \brief Copy SIP request, parse it */
static void parse_copy(struct sip_request *dst, struct sip_request *src)
{
	memset(dst, 0, sizeof(*dst));
	memcpy(dst->data, src->data, sizeof(dst->data));
	dst->len = src->len;
	parse_request(dst);
}

/*! \brief Transmit response on SIP request*/
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
{
	int res;

	if (sip_debug_test_pvt(p)) {
		char iabuf[INET_ADDRSTRLEN];
		if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
			ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
		else
			ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
	}
	if (recordhistory) {
		struct sip_request tmp;
		parse_copy(&tmp, req);
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
	}
	res = (reliable) ?
		__sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
		__sip_xmit(p, req->data, req->len);
	if (res > 0)
		return 0;
	return res;
}

/*! \brief Send SIP Request to the other part of the dialogue */
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
{
	int res;

	if (sip_debug_test_pvt(p)) {
		char iabuf[INET_ADDRSTRLEN];
		if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
			ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
		else
			ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
	}
	if (recordhistory) {
		struct sip_request tmp;
		parse_copy(&tmp, req);
		append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
	}
	res = (reliable) ?
		__sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
		__sip_xmit(p, req->data, req->len);
	return res;
}

/*! \brief Pick out text in brackets from character string
	\return pointer to terminated stripped string
	\param tmp input string that will be modified */
static char *get_in_brackets(char *tmp)
{
	char *parse;
	char *first_quote;
	char *first_bracket;
	char *second_bracket;
	char last_char;

	parse = tmp;
	while (1) {
		first_quote = strchr(parse, '"');
		first_bracket = strchr(parse, '<');
		if (first_quote && first_bracket && (first_quote < first_bracket)) {
			last_char = '\0';
			for (parse = first_quote + 1; *parse; parse++) {
				if ((*parse == '"') && (last_char != '\\'))
					break;
				last_char = *parse;
			}
			if (!*parse) {
				ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
				return tmp;
			}
			parse++;
			continue;
		}
		if (first_bracket) {
			second_bracket = strchr(first_bracket + 1, '>');
			if (second_bracket) {
				*second_bracket = '\0';
				return first_bracket + 1;
			} else {
				ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
				return tmp;
			}
		}
		return tmp;
	}
}

/*! \brief Send SIP MESSAGE text within a call
	Called from PBX core sendtext() application */
static int sip_sendtext(struct ast_channel *ast, const char *text)
{
	struct sip_pvt *p = ast->tech_pvt;
	int debug = sip_debug_test_pvt(p);

	if (debug)
		ast_verbose("Sending text %s on %s\n", text, ast->name);
	if (!p)
		return -1;
	if (ast_strlen_zero(text))
		return 0;
	if (debug)
		ast_verbose("Really sending text %s on %s\n", text, ast->name);
	transmit_message_with_text(p, text);
	return 0;	
}

/*! \brief Update peer object in realtime storage */
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
{
	char port[10];
	char ipaddr[20];
	char regseconds[20];
	time_t nowtime;
	
	time(&nowtime);
	nowtime += expirey;
	snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);	/* Expiration time */
	ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
	snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
	
	if (fullcontact)
		ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL);
	else
		ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
}

/*! \brief Automatically add peer extension to dial plan */
static void register_peer_exten(struct sip_peer *peer, int onoff)
{
	char multi[256];
	char *stringp, *ext;
	if (!ast_strlen_zero(global_regcontext)) {

		ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
		stringp = multi;
		while((ext = strsep(&stringp, "&"))) {
			if (onoff)
				ast_add_extension(global_regcontext, 1, ext, 1, NULL, NULL, "Noop",
						  ast_strdup(peer->name), free, "SIP");
			else
				ast_context_remove_extension(global_regcontext, ext, 1, NULL);
		}
	}
}

/*! \brief Destroy peer object from memory */
static void sip_destroy_peer(struct sip_peer *peer)
{
	if (option_debug > 2)
		ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);

	/* Delete it, it needs to disappear */
	if (peer->call)
		sip_destroy(peer->call);

	if (peer->mwipvt) {	/* We have an active subscription, delete it */
		sip_destroy(peer->mwipvt);
	}

	if (peer->chanvars) {
		ast_variables_destroy(peer->chanvars);
		peer->chanvars = NULL;
	}
	if (peer->expire > -1)
		ast_sched_del(sched, peer->expire);
	if (peer->pokeexpire > -1)
		ast_sched_del(sched, peer->pokeexpire);
	register_peer_exten(peer, FALSE);
	ast_free_ha(peer->ha);
	if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
		apeerobjs--;
	else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
		rpeerobjs--;
	else
		speerobjs--;
	clear_realm_authentication(peer->auth);
	peer->auth = (struct sip_auth *) NULL;
	if (peer->dnsmgr)
		ast_dnsmgr_release(peer->dnsmgr);
	free(peer);
}

/*! \brief Update peer data in database (if used) */
static void update_peer(struct sip_peer *p, int expiry)
{
	int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
	if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
	    (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
		realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
	}
}


/*! \brief  realtime_peer: Get peer from realtime storage
 * Checks the "sippeers" realtime family from extconfig.conf 
 * \todo Consider adding check of port address when matching here to follow the same
 * 	algorithm as for static peers. Will we break anything by adding that?
*/
static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
{
	struct sip_peer *peer = NULL;
	struct ast_variable *var;
	struct ast_variable *tmp;
	char *newpeername = (char *) peername;
	char iabuf[80];

	/* First check on peer name */
	if (newpeername) 
		var = ast_load_realtime("sippeers", "name", peername, NULL);
	else if (sin) {	/* Then check on IP address for dynamic peers */
		ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
		var = ast_load_realtime("sippeers", "host", iabuf, NULL);	/* First check for fixed IP hosts */
		if (!var)
			var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);	/* Then check for registred hosts */
	
	} else
		return NULL;

	if (!var)
		return NULL;

	for (tmp = var; tmp; tmp = tmp->next) {
		/* If this is type=user, then skip this object. */
		if (!strcasecmp(tmp->name, "type") &&
		    !strcasecmp(tmp->value, "user")) {
			ast_variables_destroy(var);
			return NULL;
		} else if (!newpeername && !strcasecmp(tmp->name, "name")) {
			newpeername = tmp->value;
		}
	}
	
	if (!newpeername) {	/* Did not find peer in realtime */
		ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
		ast_variables_destroy(var);
		return (struct sip_peer *) NULL;
	}

	/* Peer found in realtime, now build it in memory */
	peer = build_peer(newpeername, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
	if (!peer) {
		ast_variables_destroy(var);
		return (struct sip_peer *) NULL;
	}

	if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
		/* Cache peer */
		ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
		if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
			if (peer->expire > -1) {
				ast_sched_del(sched, peer->expire);
			}
			peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
		}
		ASTOBJ_CONTAINER_LINK(&peerl,peer);
	} else {
		ast_set_flag(&peer->flags[0], SIP_REALTIME);
	}
	ast_variables_destroy(var);

	return peer;
}

/*! \brief Support routine for find_peer */
static int sip_addrcmp(char *name, struct sockaddr_in *sin)
{
	/* We know name is the first field, so we can cast */
	struct sip_peer *p = (struct sip_peer *) name;
	return 	!(!inaddrcmp(&p->addr, sin) || 
					(ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
					(p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
}

/*! \brief Locate peer by name or ip address 
 *	This is used on incoming SIP message to find matching peer on ip
	or outgoing message to find matching peer on name */
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
{
	struct sip_peer *p = NULL;

	if (peer)
		p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
	else
		p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);

	if (!p && realtime) {
		p = realtime_peer(peer, sin);
	}
	return p;
}

/*! \brief Remove user object from in-memory storage */
static void sip_destroy_user(struct sip_user *user)
{
	if (option_debug > 2)
		ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
	ast_free_ha(user->ha);
	if (user->chanvars) {
		ast_variables_destroy(user->chanvars);
		user->chanvars = NULL;
	}
	if (ast_test_flag(&user->flags[0], SIP_REALTIME))
		ruserobjs--;
	else
		suserobjs--;
	free(user);
}

/*! \brief Load user from realtime storage
 * Loads user from "sipusers" category in realtime (extconfig.conf)
 * Users are matched on From: user name (the domain in skipped) */
static struct sip_user *realtime_user(const char *username)
{
	struct ast_variable *var;
	struct ast_variable *tmp;
	struct sip_user *user = NULL;

	var = ast_load_realtime("sipusers", "name", username, NULL);

	if (!var)
		return NULL;

	for (tmp = var; tmp; tmp = tmp->next) {
		if (!strcasecmp(tmp->name, "type") &&
			!strcasecmp(tmp->value, "peer")) {
			ast_variables_destroy(var);
			return NULL;
		}
	}

	user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
	
	if (!user) {	/* No user found */
		ast_variables_destroy(var);
		return NULL;
	}

	if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
		ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
		suserobjs++;
		ASTOBJ_CONTAINER_LINK(&userl,user);
	} else {
		/* Move counter from s to r... */
		suserobjs--;
		ruserobjs++;
		ast_set_flag(&user->flags[0], SIP_REALTIME);
	}
	ast_variables_destroy(var);
	return user;
}

/*! \brief Locate user by name 
 * Locates user by name (From: sip uri user name part) first
 * from in-memory list (static configuration) then from 
 * realtime storage (defined in extconfig.conf) */
static struct sip_user *find_user(const char *name, int realtime)
{
	struct sip_user *u = NULL;
	u = ASTOBJ_CONTAINER_FIND(&userl,name);
	if (!u && realtime) {
		u = realtime_user(name);
	}
	return u;
}

/*! \brief Create address structure from peer reference */
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
{
	if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
	    (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
		if (peer->addr.sin_addr.s_addr) {
			r->sa.sin_family = peer->addr.sin_family;
			r->sa.sin_addr = peer->addr.sin_addr;
			r->sa.sin_port = peer->addr.sin_port;
		} else {
			r->sa.sin_family = peer->defaddr.sin_family;
			r->sa.sin_addr = peer->defaddr.sin_addr;
			r->sa.sin_port = peer->defaddr.sin_port;
		}
		memcpy(&r->recv, &r->sa, sizeof(r->recv));
	} else {
		return -1;
	}

	ast_copy_flags(&r->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&r->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
	r->capability = peer->capability;
	if (!ast_test_flag(&r->flags[1], SIP_PAGE2_VIDEOSUPPORT) && r->vrtp) {
		ast_rtp_destroy(r->vrtp);
		r->vrtp = NULL;
	}
	r->prefs = peer->prefs;
	if (r->rtp) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE));
		ast_rtp_setnat(r->rtp, (ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE));
	}
	if (r->vrtp) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE));
		ast_rtp_setnat(r->vrtp, (ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE));
	}
	ast_string_field_set(r, peername, peer->username);
	ast_string_field_set(r, authname, peer->username);
	ast_string_field_set(r, username, peer->username);
	ast_string_field_set(r, peersecret, peer->secret);
	ast_string_field_set(r, peermd5secret, peer->md5secret);
	ast_string_field_set(r, tohost, peer->tohost);
	ast_string_field_set(r, fullcontact, peer->fullcontact);
	if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
		char *tmpcall;
		char *c;
		tmpcall = ast_strdupa(r->callid);
		if (tmpcall) {
			c = strchr(tmpcall, '@');
			if (c) {
				*c = '\0';
				ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
			}
		}
	}
	if (ast_strlen_zero(r->tohost)) {
		char iabuf[INET_ADDRSTRLEN];

		ast_inet_ntoa(iabuf, sizeof(iabuf),  peer->addr.sin_addr.s_addr ? peer->addr.sin_addr : peer->defaddr.sin_addr);

		ast_string_field_set(r, tohost, iabuf);
	}
	if (!ast_strlen_zero(peer->fromdomain))
		ast_string_field_set(r, fromdomain, peer->fromdomain);
	if (!ast_strlen_zero(peer->fromuser))
		ast_string_field_set(r, fromuser, peer->fromuser);
	r->maxtime = peer->maxms;
	r->callgroup = peer->callgroup;
	r->pickupgroup = peer->pickupgroup;
	/* Set timer T1 to RTT for this peer (if known by qualify=) */
	/* Minimum is settable or default to 100 ms */
	if (peer->maxms && peer->lastms)
		r->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
	if ((ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
	    (ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
		r->noncodeccapability |= AST_RTP_DTMF;
	else
		r->noncodeccapability &= ~AST_RTP_DTMF;
	ast_string_field_set(r, context, peer->context);
	r->rtptimeout = peer->rtptimeout;
	r->rtpholdtimeout = peer->rtpholdtimeout;
	r->rtpkeepalive = peer->rtpkeepalive;
	if (peer->call_limit)
		ast_set_flag(&r->flags[0], SIP_CALL_LIMIT);
	r->maxcallbitrate = peer->maxcallbitrate;
	
	return 0;
}

/*! \brief create address structure from peer name
 *      Or, if peer not found, find it in the global DNS 
 *      returns TRUE (-1) on failure, FALSE on success */
static int create_addr(struct sip_pvt *dialog, const char *opeer)
{
	struct hostent *hp;
	struct ast_hostent ahp;
	struct sip_peer *p;
	int found=0;
	char *port;
	int portno;
	char host[MAXHOSTNAMELEN], *hostn;
	char peer[256];

	ast_copy_string(peer, opeer, sizeof(peer));
	port = strchr(peer, ':');
	if (port) {
		*port = '\0';
		port++;
	}
	dialog->sa.sin_family = AF_INET;
	dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
	p = find_peer(peer, NULL, 1);

	if (p) {
		found++;
		if (create_addr_from_peer(dialog, p))
			ASTOBJ_UNREF(p, sip_destroy_peer);
	}
	if (!p) {
		if (found)
			return -1;

		hostn = peer;
		if (port)
			portno = atoi(port);
		else
			portno = DEFAULT_SIP_PORT;
		if (srvlookup) {
			char service[MAXHOSTNAMELEN];
			int tportno;
			int ret;
			snprintf(service, sizeof(service), "_sip._udp.%s", peer);
			ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
			if (ret > 0) {
				hostn = host;
				portno = tportno;
			}
		}
		hp = ast_gethostbyname(hostn, &ahp);
		if (hp) {
			ast_string_field_set(dialog, tohost, peer);
			memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
			dialog->sa.sin_port = htons(portno);
			memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
			return 0;
		} else {
			ast_log(LOG_WARNING, "No such host: %s\n", peer);
			return -1;
		}
	} else {
		ASTOBJ_UNREF(p, sip_destroy_peer);
		return 0;
	}
}

/*! \brief Scheduled congestion on a call */
static int auto_congest(void *nothing)
{
	struct sip_pvt *p = nothing;

	ast_mutex_lock(&p->lock);
	p->initid = -1;
	if (p->owner) {
		if (!ast_mutex_trylock(&p->owner->lock)) {
			ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
			ast_mutex_unlock(&p->owner->lock);
		}
	}
	ast_mutex_unlock(&p->lock);
	return 0;
}




/*! \brief Initiate SIP call from PBX 
 *      used from the dial() application      */
static int sip_call(struct ast_channel *ast, char *dest, int timeout)
{
	int res;
	struct sip_pvt *p;
#ifdef OSP_SUPPORT
	const char *osphandle = NULL;
#endif	
	struct varshead *headp;
	struct ast_var_t *current;
	
	p = ast->tech_pvt;
	if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
		ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
		return -1;
	}

	/* Check whether there is vxml_url, distinctive ring variables */
	headp=&ast->varshead;
	AST_LIST_TRAVERSE(headp,current,entries) {
		/* Check whether there is a VXML_URL variable */
		if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
			p->options->vxml_url = ast_var_value(current);
		} else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
			p->options->uri_options = ast_var_value(current);
		} else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
			/* Check whether there is a ALERT_INFO variable */
			p->options->distinctive_ring = ast_var_value(current);
		} else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
			/* Check whether there is a variable with a name starting with SIPADDHEADER */
			p->options->addsipheaders = 1;
		}

		
#ifdef OSP_SUPPORT
		else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
			p->options->osptoken = ast_var_value(current);
		} else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
			osphandle = ast_var_value(current);
		}
#endif
	}
	
	res = 0;
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
#ifdef OSP_SUPPORT
	if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
		/* Force Disable OSP support */
		if (option_debug)
			ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
		p->options->osptoken = NULL;
		osphandle = NULL;
		p->osphandle = -1;
	}
#endif
	ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
	res = update_call_counter(p, INC_CALL_LIMIT);
	if ( res != -1 ) {
		p->callingpres = ast->cid.cid_pres;
		p->jointcapability = p->capability;
		transmit_invite(p, SIP_INVITE, 1, 2);
		if (p->maxtime) {
			/* Initialize auto-congest time */
			p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
		}
	}
	return res;
}

/*! \brief Destroy registry object
	Objects created with the register= statement in static configuration */
static void sip_registry_destroy(struct sip_registry *reg)
{
	/* Really delete */
	if (option_debug > 2)
		ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);

	if (reg->call) {
		/* Clear registry before destroying to ensure
		   we don't get reentered trying to grab the registry lock */
		reg->call->registry = NULL;
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
		sip_destroy(reg->call);
	}
	if (reg->expire > -1)
		ast_sched_del(sched, reg->expire);
	if (reg->timeout > -1)
		ast_sched_del(sched, reg->timeout);
	ast_string_field_free_all(reg);
	regobjs--;
	free(reg);
	
}

/*! \brief Execute destrucion of SIP dialog structure, release memory */
static void __sip_destroy(struct sip_pvt *p, int lockowner)
{
	struct sip_pvt *cur, *prev = NULL;
	struct sip_pkt *cp;

	if (sip_debug_test_pvt(p) || option_debug > 2)
		ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);

	/* Remove link from peer to subscription of MWI */
	if (p->relatedpeer && p->relatedpeer->mwipvt)
		p->relatedpeer->mwipvt = (struct sip_pvt *) NULL;

	if (dumphistory)
		sip_dump_history(p);

	if (p->options)
		free(p->options);

	if (p->stateid > -1)
		ast_extension_state_del(p->stateid, NULL);
	if (p->initid > -1)
		ast_sched_del(sched, p->initid);
	if (p->autokillid > -1)
		ast_sched_del(sched, p->autokillid);

	if (p->rtp) {
		ast_rtp_destroy(p->rtp);
	}
	if (p->vrtp) {
		ast_rtp_destroy(p->vrtp);
	}
	if (p->route) {
		free_old_route(p->route);
		p->route = NULL;
	}
	if (p->registry) {
		if (p->registry->call == p)
			p->registry->call = NULL;
		ASTOBJ_UNREF(p->registry, sip_registry_destroy);
	}

	/* Unlink us from the owner if we have one */
	if (p->owner) {
		if (lockowner)
			ast_mutex_lock(&p->owner->lock);
		if (option_debug)
			ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
		p->owner->tech_pvt = NULL;
		if (lockowner)
			ast_mutex_unlock(&p->owner->lock);
	}
	/* Clear history */
	if (p->history) {
		while(!AST_LIST_EMPTY(p->history)) {
			struct sip_history *hist = AST_LIST_FIRST(p->history);
			AST_LIST_REMOVE_HEAD(p->history, list);
			free(hist);
		}
		free(p->history);
		p->history = NULL;
	}

	cur = iflist;
	while(cur) {
		if (cur == p) {
			if (prev)
				prev->next = cur->next;
			else
				iflist = cur->next;
			break;
		}
		prev = cur;
		cur = cur->next;
	}
	if (!cur) {
		ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
		return;
	} 
	if (p->initid > -1)
		ast_sched_del(sched, p->initid);

	/* remove all current packets in this dialog */
	while((cp = p->packets)) {
		p->packets = p->packets->next;
		if (cp->retransid > -1) {
			ast_sched_del(sched, cp->retransid);
		}
		free(cp);
	}
	if (p->chanvars) {
		ast_variables_destroy(p->chanvars);
		p->chanvars = NULL;
	}
	ast_mutex_destroy(&p->lock);

	ast_string_field_free_all(p);

	free(p);
}

/*! \brief  update_call_counter: Handle call_limit for SIP users 
 * Setting a call-limit will cause calls above the limit not to be accepted.
 *
 * Remember that for a type=friend, there's one limit for the user and
 * another for the peer, not a combined call limit.
 * This will cause unexpected behaviour in subscriptions, since a "friend"
 * is *two* devices in Asterisk, not one.
 *
 * Thought: For realtime, we should propably update storage with inuse counter... 
 *
 * \return 0 if call is ok (no call limit, below treshold)
 *	-1 on rejection of call
 *		
 */
static int update_call_counter(struct sip_pvt *fup, int event)
{
	char name[256];
	int *inuse, *call_limit;
	int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
	struct sip_user *u = NULL;
	struct sip_peer *p = NULL;

	if (option_debug > 2)
		ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
	/* Test if we need to check call limits, in order to avoid 
	   realtime lookups if we do not need it */
	if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
		return 0;

	ast_copy_string(name, fup->username, sizeof(name));

	/* Check the list of users */
	if (!outgoing)	/* Only check users for incoming calls */
		u = find_user(name, 1);

	if (u) {
		inuse = &u->inUse;
		call_limit = &u->call_limit;
		p = NULL;
	} else {
		/* Try to find peer */
		if (!p)
			p = find_peer(fup->peername, NULL, 1);
		if (p) {
			inuse = &p->inUse;
			call_limit = &p->call_limit;
			ast_copy_string(name, fup->peername, sizeof(name));
		} else {
			if (option_debug > 1)
				ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
			return 0;
		}
	}
	switch(event) {
		/* incoming and outgoing affects the inUse counter */
		case DEC_CALL_LIMIT:
			if ( *inuse > 0 ) {
				if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
					(*inuse)--;
			} else {
				*inuse = 0;
			}
			if (option_debug > 1 || sipdebug) {
				ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
			}
			break;
		case INC_CALL_LIMIT:
			if (*call_limit > 0 ) {
				if (*inuse >= *call_limit) {
					ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
					if (u)
						ASTOBJ_UNREF(u, sip_destroy_user);
					else
						ASTOBJ_UNREF(p, sip_destroy_peer);
					return -1; 
				}
			}
			(*inuse)++;
			ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
			if (option_debug > 1 || sipdebug) {
				ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
			}
			break;
		default:
			ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
	}
	if (u)
		ASTOBJ_UNREF(u, sip_destroy_user);
	else
		ASTOBJ_UNREF(p, sip_destroy_peer);
	return 0;
}

/*! \brief Destroy SIP call structure */
static void sip_destroy(struct sip_pvt *p)
{
	ast_mutex_lock(&iflock);
	if (option_debug > 2)
		ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
	__sip_destroy(p, 1);
	ast_mutex_unlock(&iflock);
}

/*! \brief Convert SIP hangup causes to Asterisk hangup causes */
static int hangup_sip2cause(int cause)
{
	/* Possible values taken from causes.h */

	switch(cause) {
		case 401:	/* Unauthorized */
			return AST_CAUSE_CALL_REJECTED;
		case 403:	/* Not found */
			return AST_CAUSE_CALL_REJECTED;
		case 404:	/* Not found */
			return AST_CAUSE_UNALLOCATED;
		case 405:	/* Method not allowed */
			return AST_CAUSE_INTERWORKING;
		case 407:	/* Proxy authentication required */
			return AST_CAUSE_CALL_REJECTED;
		case 408:	/* No reaction */
			return AST_CAUSE_NO_USER_RESPONSE;
		case 409:	/* Conflict */
			return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
		case 410:	/* Gone */
			return AST_CAUSE_UNALLOCATED;
		case 411:	/* Length required */
			return AST_CAUSE_INTERWORKING;
		case 413:	/* Request entity too large */
			return AST_CAUSE_INTERWORKING;
		case 414:	/* Request URI too large */
			return AST_CAUSE_INTERWORKING;
		case 415:	/* Unsupported media type */
			return AST_CAUSE_INTERWORKING;
		case 420:	/* Bad extension */
			return AST_CAUSE_NO_ROUTE_DESTINATION;
		case 480:	/* No answer */
			return AST_CAUSE_FAILURE;
		case 481:	/* No answer */
			return AST_CAUSE_INTERWORKING;
		case 482:	/* Loop detected */
			return AST_CAUSE_INTERWORKING;
		case 483:	/* Too many hops */
			return AST_CAUSE_NO_ANSWER;
		case 484:	/* Address incomplete */
			return AST_CAUSE_INVALID_NUMBER_FORMAT;
		case 485:	/* Ambigous */
			return AST_CAUSE_UNALLOCATED;
		case 486:	/* Busy everywhere */
			return AST_CAUSE_BUSY;
		case 487:	/* Request terminated */
			return AST_CAUSE_INTERWORKING;
		case 488:	/* No codecs approved */
			return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
		case 491:	/* Request pending */
			return AST_CAUSE_INTERWORKING;
		case 493:	/* Undecipherable */
			return AST_CAUSE_INTERWORKING;
		case 500:	/* Server internal failure */
			return AST_CAUSE_FAILURE;
		case 501:	/* Call rejected */
			return AST_CAUSE_FACILITY_REJECTED;
		case 502:	
			return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
		case 503:	/* Service unavailable */
			return AST_CAUSE_CONGESTION;
		case 504:	/* Gateway timeout */
			return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
		case 505:	/* SIP version not supported */
			return AST_CAUSE_INTERWORKING;
		case 600:	/* Busy everywhere */
			return AST_CAUSE_USER_BUSY;
		case 603:	/* Decline */
			return AST_CAUSE_CALL_REJECTED;
		case 604:	/* Does not exist anywhere */
			return AST_CAUSE_UNALLOCATED;
		case 606:	/* Not acceptable */
			return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
		default:
			return AST_CAUSE_NORMAL;
	}
	/* Never reached */
	return 0;
}

/*! \brief Convert Asterisk hangup causes to SIP codes 
\verbatim
 Possible values from causes.h
        AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
        AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED

	In addition to these, a lot of PRI codes is defined in causes.h 
	...should we take care of them too ?
	
	Quote RFC 3398

   ISUP Cause value                        SIP response
   ----------------                        ------------
   1  unallocated number                   404 Not Found
   2  no route to network                  404 Not found
   3  no route to destination              404 Not found
   16 normal call clearing                 --- (*)
   17 user busy                            486 Busy here
   18 no user responding                   408 Request Timeout
   19 no answer from the user              480 Temporarily unavailable
   20 subscriber absent                    480 Temporarily unavailable
   21 call rejected                        403 Forbidden (+)
   22 number changed (w/o diagnostic)      410 Gone
   22 number changed (w/ diagnostic)       301 Moved Permanently
   23 redirection to new destination       410 Gone
   26 non-selected user clearing           404 Not Found (=)
   27 destination out of order             502 Bad Gateway
   28 address incomplete                   484 Address incomplete
   29 facility rejected                    501 Not implemented
   31 normal unspecified                   480 Temporarily unavailable
\endverbatim
*/
static char *hangup_cause2sip(int cause)
{
	switch(cause)
	{
		case AST_CAUSE_UNALLOCATED:		/* 1 */
		case AST_CAUSE_NO_ROUTE_DESTINATION:	/* 3 IAX2: Can't find extension in context */
		case AST_CAUSE_NO_ROUTE_TRANSIT_NET:	/* 2 */
			return "404 Not Found";
		case AST_CAUSE_CONGESTION:		/* 34 */
		case AST_CAUSE_SWITCH_CONGESTION:	/* 42 */
			return "503 Service Unavailable";
		case AST_CAUSE_NO_USER_RESPONSE:	/* 18 */
			return "408 Request Timeout";
		case AST_CAUSE_NO_ANSWER:		/* 19 */
			return "480 Temporarily unavailable";
		case AST_CAUSE_CALL_REJECTED:		/* 21 */
			return "403 Forbidden";
		case AST_CAUSE_NUMBER_CHANGED:		/* 22 */
			return "410 Gone";
		case AST_CAUSE_NORMAL_UNSPECIFIED:	/* 31 */
			return "480 Temporarily unavailable";
		case AST_CAUSE_INVALID_NUMBER_FORMAT:
			return "484 Address incomplete";
		case AST_CAUSE_USER_BUSY:
			return "486 Busy here";
		case AST_CAUSE_FAILURE:
			return "500 Server internal failure";
		case AST_CAUSE_FACILITY_REJECTED:	/* 29 */
			return "501 Not Implemented";
		case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
			return "503 Service Unavailable";
		/* Used in chan_iax2 */
		case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
			return "502 Bad Gateway";
		case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:	/* Can't find codec to connect to host */
			return "488 Not Acceptable Here";
			
		case AST_CAUSE_NOTDEFINED:
		default:
			ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
			return NULL;
	}

	/* Never reached */
	return 0;
}


/*! \brief  sip_hangup: Hangup SIP call
 * Part of PBX interface, called from ast_hangup */
static int sip_hangup(struct ast_channel *ast)
{
	struct sip_pvt *p = ast->tech_pvt;
	int needcancel = FALSE;
	struct ast_flags locflags = {0};

	if (!p) {
		ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
		return 0;
	}
	if (option_debug && sipdebug)
		ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);

	ast_mutex_lock(&p->lock);
#ifdef OSP_SUPPORT
	if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
		ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
	}
#endif	
	if (option_debug && sipdebug)
		ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
	update_call_counter(p, DEC_CALL_LIMIT);
	/* Determine how to disconnect */
	if (p->owner != ast) {
		ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
		ast_mutex_unlock(&p->lock);
		return 0;
	}
	/* If the call is not UP, we need to send CANCEL instead of BYE */
	if (ast->_state != AST_STATE_UP)
		needcancel = TRUE;

	/* Disconnect */
	p = ast->tech_pvt;
	if (p->vad)
		ast_dsp_free(p->vad);

	p->owner = NULL;
	ast->tech_pvt = NULL;

	ast_mutex_lock(&usecnt_lock);
	usecnt--;
	ast_mutex_unlock(&usecnt_lock);
	ast_update_use_count();

	ast_set_flag(&locflags, SIP_NEEDDESTROY);	

	/* Start the process if it's not already started */
	if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
		if (needcancel) {	/* Outgoing call, not up */
			if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
				/* stop retransmitting an INVITE that has not received a response */
				__sip_pretend_ack(p);

				/* Send a new request: CANCEL */
				transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, 0);
				/* Actually don't destroy us yet, wait for the 487 on our original 
				   INVITE, but do set an autodestruct just in case we never get it. */
				ast_clear_flag(&locflags, SIP_NEEDDESTROY);

				sip_scheddestroy(p, 32000);
				if ( p->initid != -1 ) {
					/* channel still up - reverse dec of inUse counter
					   only if the channel is not auto-congested */
					update_call_counter(p, INC_CALL_LIMIT);
				}
			} else {	/* Incoming call, not up */
				char *res;
				if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
					transmit_response_reliable(p, res, &p->initreq);
				} else 
					transmit_response_reliable(p, "603 Declined", &p->initreq);
			}
		} else {	/* Call is in UP state, send BYE */
			if (!p->pendinginvite) {
				/* Send a hangup */
				transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
			} else {
				/* Note we will need a BYE when this all settles out
				   but we can't send one while we have "INVITE" outstanding. */
				ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
				ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);	
			}
		}
	}
	ast_copy_flags(&p->flags[0], &locflags, SIP_NEEDDESTROY);	
	ast_mutex_unlock(&p->lock);
	return 0;
}

/*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
static void try_suggested_sip_codec(struct sip_pvt *p)
{
	int fmt;
	const char *codec;

	codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
	if (!codec) 
		return;

	fmt = ast_getformatbyname(codec);
	if (fmt) {
		ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n", codec);
		if (p->jointcapability & fmt) {
			p->jointcapability &= fmt;
			p->capability &= fmt;
		} else
			ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
	} else
		ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
	return;	
}

/*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
 * Part of PBX interface */
static int sip_answer(struct ast_channel *ast)
{
	int res = 0;
	struct sip_pvt *p = ast->tech_pvt;

	ast_mutex_lock(&p->lock);
	if (ast->_state != AST_STATE_UP) {
#ifdef OSP_SUPPORT	
		time(&p->ospstart);
#endif
		try_suggested_sip_codec(p);	

		ast_setstate(ast, AST_STATE_UP);
		if (option_debug)
			ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
		res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_RELIABLE);
	}
	ast_mutex_unlock(&p->lock);
	return res;
}

/*! \brief Send frame to media channel (rtp) */
static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res = 0;

	switch (frame->frametype) {
	case AST_FRAME_VOICE:
		if (!(frame->subclass & ast->nativeformats)) {
			ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
				frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
			return 0;
		}
		if (p) {
			ast_mutex_lock(&p->lock);
			if (p->rtp) {
				/* If channel is not up, activate early media session */
				if ((ast->_state != AST_STATE_UP) &&
				    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
				    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
					transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
					ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);	
				}
				time(&p->lastrtptx);
				res =  ast_rtp_write(p->rtp, frame);
			}
			ast_mutex_unlock(&p->lock);
		}
		break;
	case AST_FRAME_VIDEO:
		if (p) {
			ast_mutex_lock(&p->lock);
			if (p->vrtp) {
				/* Activate video early media */
				if ((ast->_state != AST_STATE_UP) &&
				    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
				    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
					transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
					ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);	
				}
				time(&p->lastrtptx);
				res =  ast_rtp_write(p->vrtp, frame);
			}
			ast_mutex_unlock(&p->lock);
		}
		break;
	case AST_FRAME_IMAGE:
		return 0;
		break;
	default: 
		ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
		return 0;
	}

	return res;
}

/*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
        Basically update any ->owner links */
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
{
	struct sip_pvt *p = newchan->tech_pvt;
	ast_mutex_lock(&p->lock);
	if (p->owner != oldchan) {
		ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
		ast_mutex_unlock(&p->lock);
		return -1;
	}
	p->owner = newchan;
	ast_mutex_unlock(&p->lock);
	return 0;
}

/*! \brief Send DTMF character on SIP channel
	within one call, we're able to transmit in many methods simultaneously */
static int sip_senddigit(struct ast_channel *ast, char digit)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res = 0;

	ast_mutex_lock(&p->lock);
	switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
	case SIP_DTMF_INFO:
		transmit_info_with_digit(p, digit);
		break;
	case SIP_DTMF_RFC2833:
		if (p->rtp)
			ast_rtp_senddigit(p->rtp, digit);
		break;
	case SIP_DTMF_INBAND:
		res = -1;
		break;
	}
	ast_mutex_unlock(&p->lock);
	return res;
}

/*! \brief Transfer SIP call */
static int sip_transfer(struct ast_channel *ast, const char *dest)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res;

	ast_mutex_lock(&p->lock);
	if (ast->_state == AST_STATE_RING)
		res = sip_sipredirect(p, dest);
	else
		res = transmit_refer(p, dest);
	ast_mutex_unlock(&p->lock);
	return res;
}

/*! \brief Play indication to user 
 * With SIP a lot of indications is sent as messages, letting the device play
   the indication - busy signal, congestion etc 
   \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
*/
static int sip_indicate(struct ast_channel *ast, int condition)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res = 0;

	ast_mutex_lock(&p->lock);
	switch(condition) {
	case AST_CONTROL_RINGING:
		if (ast->_state == AST_STATE_RING) {
			if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
			    (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {				
				/* Send 180 ringing if out-of-band seems reasonable */
				transmit_response(p, "180 Ringing", &p->initreq);
				ast_set_flag(&p->flags[0], SIP_RINGING);
				if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
					break;
			} else {
				/* Well, if it's not reasonable, just send in-band */
			}
		}
		res = -1;
		break;
	case AST_CONTROL_BUSY:
		if (ast->_state != AST_STATE_UP) {
			transmit_response(p, "486 Busy Here", &p->initreq);
			ast_set_flag(&p->flags[0], SIP_ALREADYGONE);	
			ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
			break;
		}
		res = -1;
		break;
	case AST_CONTROL_CONGESTION:
		if (ast->_state != AST_STATE_UP) {
			transmit_response(p, "503 Service Unavailable", &p->initreq);
			ast_set_flag(&p->flags[0], SIP_ALREADYGONE);	
			ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
			break;
		}
		res = -1;
		break;
	case AST_CONTROL_PROCEEDING:
		if ((ast->_state != AST_STATE_UP) &&
		    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
		    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
			transmit_response(p, "100 Trying", &p->initreq);
			break;
		}
		res = -1;
		break;
	case AST_CONTROL_PROGRESS:
		if ((ast->_state != AST_STATE_UP) &&
		    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
		    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
			transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
			ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);	
			break;
		}
		res = -1;
		break;
	case AST_CONTROL_HOLD:	/* The other part of the bridge are put on hold */
		if (sipdebug)
			ast_log(LOG_DEBUG, "Bridged channel now on hold - %s\n", p->callid);
		res = -1;
		break;
	case AST_CONTROL_UNHOLD:	/* The other part of the bridge are back from hold */
		if (sipdebug)
			ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
		res = -1;
		break;
	case AST_CONTROL_VIDUPDATE:	/* Request a video frame update */
		if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
			transmit_info_with_vidupdate(p);
			/* ast_rtcp_send_h261fur(p->vrtp); */
			res = 0;
		} else
			res = -1;
		break;
	case -1:
		res = -1;
		break;
	default:
		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
		res = -1;
		break;
	}
	ast_mutex_unlock(&p->lock);
	return res;
}



/*! \brief Initiate a call in the SIP channel
	called from sip_request_call (calls from the pbx ) */
static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
{
	struct ast_channel *tmp;
	struct ast_variable *v = NULL;
	int fmt;
	int what;
#ifdef OSP_SUPPORT
	char iabuf[INET_ADDRSTRLEN];
	char peer[MAXHOSTNAMELEN];
#endif	
	
	ast_mutex_unlock(&i->lock);
	/* Don't hold a sip pvt lock while we allocate a channel */
	tmp = ast_channel_alloc(1);
	ast_mutex_lock(&i->lock);
	if (!tmp) {
		ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
		return NULL;
	}
	tmp->tech = &sip_tech;
	/* Select our native format based on codec preference until we receive
	   something from another device to the contrary. */
	if (i->jointcapability)
		what = i->jointcapability;
	else if (i->capability)
		what = i->capability;
	else
		what = global_capability;
	tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
	fmt = ast_best_codec(tmp->nativeformats);

	if (title)
		ast_string_field_build(tmp, name, "SIP/%s-%04x", title, thread_safe_rand() & 0xffff);
	else if (strchr(i->fromdomain,':'))
		ast_string_field_build(tmp, name, "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
	else
		ast_string_field_build(tmp, name, "SIP/%s-%08x", i->fromdomain, (int)(long)(i));

	if (ast_test_flag(&i->flags[0], SIP_DTMF) ==  SIP_DTMF_INBAND) {
		i->vad = ast_dsp_new();
		ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
		if (global_relaxdtmf)
			ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
	}
	if (i->rtp) {
		tmp->fds[0] = ast_rtp_fd(i->rtp);
		tmp->fds[1] = ast_rtcp_fd(i->rtp);
	}
	if (i->vrtp) {
		tmp->fds[2] = ast_rtp_fd(i->vrtp);
		tmp->fds[3] = ast_rtcp_fd(i->vrtp);
	}
	if (state == AST_STATE_RING)
		tmp->rings = 1;
	tmp->adsicpe = AST_ADSI_UNAVAILABLE;
	tmp->writeformat = fmt;
	tmp->rawwriteformat = fmt;
	tmp->readformat = fmt;
	tmp->rawreadformat = fmt;
	tmp->tech_pvt = i;

	tmp->callgroup = i->callgroup;
	tmp->pickupgroup = i->pickupgroup;
	tmp->cid.cid_pres = i->callingpres;
	if (!ast_strlen_zero(i->accountcode))
		ast_string_field_set(tmp, accountcode, i->accountcode);
	if (i->amaflags)
		tmp->amaflags = i->amaflags;
	if (!ast_strlen_zero(i->language))
		ast_string_field_set(tmp, language, i->language);
	if (!ast_strlen_zero(i->musicclass))
		ast_string_field_set(tmp, musicclass, i->musicclass);
	i->owner = tmp;
	ast_mutex_lock(&usecnt_lock);
	usecnt++;
	ast_mutex_unlock(&usecnt_lock);
	ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
	ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
	if (!ast_strlen_zero(i->cid_num)) 
		tmp->cid.cid_num = ast_strdup(i->cid_num);
	if (!ast_strlen_zero(i->cid_name))
		tmp->cid.cid_name = ast_strdup(i->cid_name);
	if (!ast_strlen_zero(i->rdnis))
		tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
	if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
		tmp->cid.cid_dnid = ast_strdup(i->exten);
	tmp->priority = 1;
	if (!ast_strlen_zero(i->uri)) {
		pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
	}
	if (!ast_strlen_zero(i->domain)) {
		pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
	}
	if (!ast_strlen_zero(i->useragent)) {
		pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
	}
	if (!ast_strlen_zero(i->callid)) {
		pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
	}
#ifdef OSP_SUPPORT
	snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
	pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
#endif
	ast_setstate(tmp, state);
	if (state != AST_STATE_DOWN) {
		if (ast_pbx_start(tmp)) {
			ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
			tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
			ast_hangup(tmp);
			tmp = NULL;
		}
	}
	/* Set channel variables for this call from configuration */
	for (v = i->chanvars ; v ; v = v->next)
		pbx_builtin_setvar_helper(tmp,v->name,v->value);
				
	return tmp;
}

/*! \brief Reads one line of SIP message body */
static char* get_sdp_by_line(char* line, char *name, int nameLen)
{
	if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
		return ast_skip_blanks(line + nameLen + 1);
	}
	return "";
}

/*! \brief Gets all kind of SIP message bodies, including SDP,
   but the name wrongly applies _only_ sdp */
static char *get_sdp(struct sip_request *req, char *name) 
{
	int x;
	int len = strlen(name);
	char *r;

	for (x = 0; x < req->lines; x++) {
		r = get_sdp_by_line(req->line[x], name, len);
		if (r[0] != '\0')
			return r;
	}
	return "";
}


static void sdpLineNum_iterator_init(int* iterator) 
{
	*iterator = 0;
}

static char* get_sdp_iterate(int* iterator,
			     struct sip_request *req, char *name)
{
	int len = strlen(name);
	char *r;

	while (*iterator < req->lines) {
		r = get_sdp_by_line(req->line[(*iterator)++], name, len);
		if (r[0] != '\0')
			return r;
	}
	return "";
}

static char *find_alias(const char *name, char *_default)
{
	int x;
	for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
		if (!strcasecmp(aliases[x].fullname, name))
			return aliases[x].shortname;
	return _default;
}

static char *__get_header(struct sip_request *req, const char *name, int *start)
{
	int pass;

	/*
	 * Technically you can place arbitrary whitespace both before and after the ':' in
	 * a header, although RFC3261 clearly says you shouldn't before, and place just
	 * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
	 * a good idea to say you can do it, and if you can do it, why in the hell would.
	 * you say you shouldn't.
	 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
	 * and we always allow spaces after that for compatibility.
	 */
	for (pass = 0; name && pass < 2;pass++) {
		int x, len = strlen(name);
		for (x=*start; x<req->headers; x++) {
			if (!strncasecmp(req->header[x], name, len)) {
				char *r = req->header[x] + len;	/* skip name */
				if (pedanticsipchecking)
					r = ast_skip_blanks(r);

				if (*r == ':') {
					*start = x+1;
					return ast_skip_blanks(r+1);
				}
			}
		}
		if (pass == 0) /* Try aliases */
			name = find_alias(name, NULL);
	}

	/* Don't return NULL, so get_header is always a valid pointer */
	return "";
}

/*! \brief Get header from SIP request */
static char *get_header(struct sip_request *req, const char *name)
{
	int start = 0;
	return __get_header(req, name, &start);
}

/*! \brief Read RTP from network */
static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
{
	/* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
	struct ast_frame *f;
	
	if (!p->rtp) {
		/* We have no RTP allocated for this channel */
		return &ast_null_frame;
	}

	switch(ast->fdno) {
	case 0:
		f = ast_rtp_read(p->rtp);	/* RTP Audio */
		break;
	case 1:
		f = ast_rtcp_read(p->rtp);	/* RTCP Control Channel */
		break;
	case 2:
		f = ast_rtp_read(p->vrtp);	/* RTP Video */
		break;
	case 3:
		f = ast_rtcp_read(p->vrtp);	/* RTCP Control Channel for video */
		break;
	default:
		f = &ast_null_frame;
	}
	/* Don't forward RFC2833 if we're not supposed to */
	if (f && (f->frametype == AST_FRAME_DTMF) &&
	    (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
		return &ast_null_frame;

	if (p->owner) {
		/* We already hold the channel lock */
		if (f->frametype == AST_FRAME_VOICE) {
			if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
				if (option_debug)
					ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
				p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
				ast_set_read_format(p->owner, p->owner->readformat);
				ast_set_write_format(p->owner, p->owner->writeformat);
			}
			if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
				f = ast_dsp_process(p->owner, p->vad, f);
				if (option_debug && f && (f->frametype == AST_FRAME_DTMF)) 
					ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
			}
		}
	}
	return f;
}

/*! \brief Read SIP RTP from channel */
static struct ast_frame *sip_read(struct ast_channel *ast)
{
	struct ast_frame *fr;
	struct sip_pvt *p = ast->tech_pvt;

	ast_mutex_lock(&p->lock);
	fr = sip_rtp_read(ast, p);
	time(&p->lastrtprx);
	ast_mutex_unlock(&p->lock);
	return fr;
}


/*! \brief Generate 32 byte random string for callid's etc */
static char *generate_random_string(char *buf, size_t size)
{
	int val[4];
	int x;

	for (x=0; x<4; x++)
		val[x] = thread_safe_rand();
	snprintf(buf, size, "%08x%08x%08x%08x", val[0], val[1], val[2], val[3]);

	return buf;
}

/*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
static void build_callid_pvt(struct sip_pvt *pvt)
{
	char iabuf[INET_ADDRSTRLEN];
	char buf[33];

	const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(iabuf, sizeof(iabuf), pvt->ourip));
	
	ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);

}

/*! \brief Build SIP Call-ID value for a REGISTER transaction */
static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
{
	char iabuf[INET_ADDRSTRLEN];
	char buf[33];

	const char *host = S_OR(fromdomain, ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));

	ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
}

/*! \brief Make our SIP dialog tag */
static void make_our_tag(char *tagbuf, size_t len)
{
	snprintf(tagbuf, len, "as%08x", thread_safe_rand());
}

/*! \brief Allocate SIP_PVT structure and set defaults */
static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
				 int useglobal_nat, const int intended_method)
{
	struct sip_pvt *p;

	if (!(p = ast_calloc(1, sizeof(*p))))
		return NULL;

	if (ast_string_field_init(p, 512)) {
		free(p);
		return NULL;
	}

	ast_mutex_init(&p->lock);

	p->method = intended_method;
	p->initid = -1;
	p->autokillid = -1;
	p->subscribed = NONE;
	p->stateid = -1;
	p->prefs = default_prefs;		/* Set default codecs for this call */

	if (intended_method != SIP_OPTIONS)	/* Peerpoke has it's own system */
		p->timer_t1 = 500;	/* Default SIP retransmission timer T1 (RFC 3261) */
#ifdef OSP_SUPPORT
	p->osphandle = -1;
	p->osptimelimit = 0;
#endif	
	if (sin) {
		memcpy(&p->sa, sin, sizeof(p->sa));
		if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
			memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
	} else {
		memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
	}
	
	ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);

	p->branch = thread_safe_rand();	
	make_our_tag(p->tag, sizeof(p->tag));
	/* Start with 101 instead of 1 */
	p->ocseq = 101;

	if (sip_methods[intended_method].need_rtp) {
		p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
			p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
		if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
			ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
				ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
			ast_mutex_destroy(&p->lock);
			if (p->chanvars) {
				ast_variables_destroy(p->chanvars);
				p->chanvars = NULL;
			}
			free(p);
			return NULL;
		}
		ast_rtp_settos(p->rtp, global_tos_audio);
		if (p->vrtp)
			ast_rtp_settos(p->vrtp, global_tos_video);
		p->rtptimeout = global_rtptimeout;
		p->rtpholdtimeout = global_rtpholdtimeout;
		p->rtpkeepalive = global_rtpkeepalive;
		p->maxcallbitrate = default_maxcallbitrate;
	}

	if (useglobal_nat && sin) {
		/* Setup NAT structure according to global settings if we have an address */
		ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
		memcpy(&p->recv, sin, sizeof(p->recv));
		if (p->rtp)
			ast_rtp_setnat(p->rtp, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
		if (p->vrtp)
			ast_rtp_setnat(p->vrtp, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
	}

	if (p->method != SIP_REGISTER)
		ast_string_field_set(p, fromdomain, default_fromdomain);
	build_via(p);
	if (!callid)
		build_callid_pvt(p);
	else
		ast_string_field_set(p, callid, callid);
	/* Assign default music on hold class */
	ast_string_field_set(p, musicclass, default_musicclass);
	p->capability = global_capability;
	if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
	    (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
		p->noncodeccapability |= AST_RTP_DTMF;
	ast_string_field_set(p, context, default_context);

	/* Add to active dialog list */
	ast_mutex_lock(&iflock);
	p->next = iflist;
	iflist = p;
	ast_mutex_unlock(&iflock);
	if (option_debug)
		ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
	return p;
}

/*! \brief Connect incoming SIP message to current dialog or create new dialog structure
	Called by handle_request, sipsock_read */
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
{
	struct sip_pvt *p;
	char *callid;
	char *tag = "";
	char totag[128];
	char fromtag[128];

	callid = get_header(req, "Call-ID");

	if (pedanticsipchecking) {
		/* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
		   we need more to identify a branch - so we have to check branch, from
		   and to tags to identify a call leg.
		   For Asterisk to behave correctly, you need to turn on pedanticsipchecking
		   in sip.conf
		   */
		if (gettag(req, "To", totag, sizeof(totag)))
			ast_set_flag(req, SIP_PKT_WITH_TOTAG);	/* Used in handle_request/response */
		gettag(req, "From", fromtag, sizeof(fromtag));

		if (req->method == SIP_RESPONSE)
			tag = totag;
		else
			tag = fromtag;
			

		if (option_debug > 4 )
			ast_log(LOG_DEBUG, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
	}

	ast_mutex_lock(&iflock);
	p = iflist;
	while(p) {	/* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
		int found = FALSE;
		if (req->method == SIP_REGISTER)
			found = (!strcmp(p->callid, callid));
		else 
			found = (!strcmp(p->callid, callid) && 
			(!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;

		if (option_debug > 4)
			ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);

		/* If we get a new request within an existing to-tag - check the to tag as well */
		if (pedanticsipchecking && found  && req->method != SIP_RESPONSE) {	/* SIP Request */
			if (p->tag[0] == '\0' && totag[0]) {
				/* We have no to tag, but they have. Wrong dialog */
				found = FALSE;
			} else if (totag[0]) {			/* Both have tags, compare them */
				if (strcmp(totag, p->tag)) {
					found = FALSE;		/* This is not our packet */
				}
			}
			if (!found && option_debug > 4)
				ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
		}


		if (found) {
			/* Found the call */
			ast_mutex_lock(&p->lock);
			ast_mutex_unlock(&iflock);
			return p;
		}
		p = p->next;
	}
	ast_mutex_unlock(&iflock);
	p = sip_alloc(callid, sin, 1, intended_method);
	if (p)
		ast_mutex_lock(&p->lock);
	return p;
}

/*! \brief Parse register=> line in sip.conf and add to registry */
static int sip_register(char *value, int lineno)
{
	struct sip_registry *reg;
	char copy[256];
	char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
	char *porta=NULL;
	char *contact=NULL;
	char *stringp=NULL;
	
	if (!value)
		return -1;
	ast_copy_string(copy, value, sizeof(copy));
	stringp=copy;
	username = stringp;
	hostname = strrchr(stringp, '@');
	if (hostname) {
		*hostname = '\0';
		hostname++;
	}
	if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
		ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
		return -1;
	}
	stringp = username;
	username = strsep(&stringp, ":");
	if (username) {
		secret = strsep(&stringp, ":");
		if (secret) 
			authuser = strsep(&stringp, ":");
	}
	stringp = hostname;
	hostname = strsep(&stringp, "/");
	if (hostname) 
		contact = strsep(&stringp, "/");
	if (ast_strlen_zero(contact))
		contact = "s";
	stringp=hostname;
	hostname = strsep(&stringp, ":");
	porta = strsep(&stringp, ":");
	
	if (porta && !atoi(porta)) {
		ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
		return -1;
	}
	if (!(reg = ast_calloc(1, sizeof(*reg)))) {
		ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
		return -1;
	}

	if (ast_string_field_init(reg, 256)) {
		ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
		free(reg);
		return -1;
	}

	regobjs++;
	ASTOBJ_INIT(reg);
	ast_string_field_set(reg, contact, contact);
	if (username)
		ast_string_field_set(reg, username, username);
	if (hostname)
		ast_string_field_set(reg, hostname, hostname);
	if (authuser)
		ast_string_field_set(reg, authuser, authuser);
	if (secret)
		ast_string_field_set(reg, secret, secret);
	reg->expire = -1;
	reg->timeout =  -1;
	reg->refresh = default_expiry;
	reg->portno = porta ? atoi(porta) : 0;
	reg->callid_valid = FALSE;
	reg->ocseq = 101;
	ASTOBJ_CONTAINER_LINK(&regl, reg);	/* Add the new registry entry to the list */
	ASTOBJ_UNREF(reg,sip_registry_destroy);
	return 0;
}

/*! \brief  Parse multiline SIP headers into one header
	This is enabled if pedanticsipchecking is enabled */
static int lws2sws(char *msgbuf, int len) 
{ 
	int h = 0, t = 0; 
	int lws = 0; 

	for (; h < len;) { 
		/* Eliminate all CRs */ 
		if (msgbuf[h] == '\r') { 
			h++; 
			continue; 
		} 
		/* Check for end-of-line */ 
		if (msgbuf[h] == '\n') { 
			/* Check for end-of-message */ 
			if (h + 1 == len) 
				break; 
			/* Check for a continuation line */ 
			if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
				/* Merge continuation line */ 
				h++; 
				continue; 
			} 
			/* Propagate LF and start new line */ 
			msgbuf[t++] = msgbuf[h++]; 
			lws = 0;
			continue; 
		} 
		if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
			if (lws) { 
				h++; 
				continue; 
			} 
			msgbuf[t++] = msgbuf[h++]; 
			lws = 1; 
			continue; 
		} 
		msgbuf[t++] = msgbuf[h++]; 
		if (lws) 
			lws = 0; 
	} 
	msgbuf[t] = '\0'; 
	return t; 
}

/*! \brief Parse a SIP message */
static void parse_request(struct sip_request *req)
{
	/* Divide fields by NULL's */
	char *c;
	int f = 0;

	c = req->data;

	/* First header starts immediately */
	req->header[f] = c;
	while(*c) {
		if (*c == '\n') {
			/* We've got a new header */
			*c = 0;

			if (sipdebug && option_debug > 3)
				ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
			if (ast_strlen_zero(req->header[f])) {
				/* Line by itself means we're now in content */
				c++;
				break;
			}
			if (f >= SIP_MAX_HEADERS - 1) {
				ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
			} else
				f++;
			req->header[f] = c + 1;
		} else if (*c == '\r') {
			/* Ignore but eliminate \r's */
			*c = 0;
		}
		c++;
	}
	/* Check for last header */
	if (!ast_strlen_zero(req->header[f])) {
		if (sipdebug && option_debug > 3)
			ast_log(LOG_DEBUG, "Header %d: %s (%d)\n", f, req->header[f], (int) strlen(req->header[f]));
		f++;
	}
	req->headers = f;
	/* Now we process any mime content */
	f = 0;
	req->line[f] = c;
	while(*c) {
		if (*c == '\n') {
			/* We've got a new line */
			*c = 0;
			if (sipdebug && option_debug > 3)
				ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
			if (f >= SIP_MAX_LINES - 1) {
				ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
			} else
				f++;
			req->line[f] = c + 1;
		} else if (*c == '\r') {
			/* Ignore and eliminate \r's */
			*c = 0;
		}
		c++;
	}
	/* Check for last line */
	if (!ast_strlen_zero(req->line[f])) 
		f++;
	req->lines = f;
	if (*c) 
		ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
	/* Split up the first line parts */
	determine_firstline_parts(req);
}

/*! \brief Process SIP SDP and activate RTP channels*/
static int process_sdp(struct sip_pvt *p, struct sip_request *req)
{
	char *m;
	char *c;
	char *a;
	char host[258];
	char iabuf[INET_ADDRSTRLEN];
	int len = -1;
	int portno = -1;
	int vportno = -1;
	int peercapability, peernoncodeccapability;
	int vpeercapability=0, vpeernoncodeccapability=0;
	struct sockaddr_in sin;
	char *codecs;
	struct hostent *hp;
	struct ast_hostent ahp;
	int codec;
	int destiterator = 0;
	int iterator;
	int sendonly = 0;
	int x,y;
	int debug=sip_debug_test_pvt(p);
	struct ast_channel *bridgepeer = NULL;

	if (!p->rtp) {
		ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
		return -1;
	}

	/* Update our last rtprx when we receive an SDP, too */
	time(&p->lastrtprx);
	time(&p->lastrtptx);

	/* Get codec and RTP info from SDP */
	if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
		ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
		return -1;
	}
	m = get_sdp(req, "m");
	sdpLineNum_iterator_init(&destiterator);
	c = get_sdp_iterate(&destiterator, req, "c");
	if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
		ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
		return -1;
	}
	if (sscanf(c, "IN IP4 %256s", host) != 1) {
		ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
		return -1;
	}
	/* XXX This could block for a long time, and block the main thread! XXX */
	hp = ast_gethostbyname(host, &ahp);
	if (!hp) {
		ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
		return -1;
	}
	sdpLineNum_iterator_init(&iterator);
	ast_set_flag(&p->flags[0], SIP_NOVIDEO);	
	while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
		int found = 0;
		if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2) ||
		    (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
			found = 1;
			portno = x;
			/* Scan through the RTP payload types specified in a "m=" line: */
			ast_rtp_pt_clear(p->rtp);
			codecs = m + len;
			while(!ast_strlen_zero(codecs)) {
				if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
					ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
					return -1;
				}
				if (debug)
					ast_verbose("Found RTP audio format %d\n", codec);
				ast_rtp_set_m_type(p->rtp, codec);
				codecs = ast_skip_blanks(codecs + len);
			}
		}
		if (p->vrtp)
			ast_rtp_pt_clear(p->vrtp);  /* Must be cleared in case no m=video line exists */

		if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
			found = 1;
			ast_clear_flag(&p->flags[0], SIP_NOVIDEO);	
			vportno = x;
			/* Scan through the RTP payload types specified in a "m=" line: */
			codecs = m + len;
			while(!ast_strlen_zero(codecs)) {
				if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
					ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
					return -1;
				}
				if (debug)
					ast_verbose("Found RTP video format %d\n", codec);
				ast_rtp_set_m_type(p->vrtp, codec);
				codecs = ast_skip_blanks(codecs + len);
			}
		}
		if (!found )
			ast_log(LOG_WARNING, "Unknown SDP media type in offer: %s\n", m);
	}
	if (portno == -1 && vportno == -1) {
		/* No acceptable offer found in SDP */
		return -2;
	}
	/* Check for Media-description-level-address for audio */
	if (pedanticsipchecking) {
		c = get_sdp_iterate(&destiterator, req, "c");
		if (!ast_strlen_zero(c)) {
			if (sscanf(c, "IN IP4 %256s", host) != 1) {
				ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
			} else {
				/* XXX This could block for a long time, and block the main thread! XXX */
				hp = ast_gethostbyname(host, &ahp);
				if (!hp) {
					ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
				}
			}
		}
	}
	/* RTP addresses and ports for audio and video */
	sin.sin_family = AF_INET;
	memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));

	/* Setup audio port number */
	sin.sin_port = htons(portno);
	if (p->rtp && sin.sin_port) {
		ast_rtp_set_peer(p->rtp, &sin);
		if (debug) {
			ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
		}
	}
	/* Check for Media-description-level-address for video */
	if (pedanticsipchecking) {
		c = get_sdp_iterate(&destiterator, req, "c");
		if (!ast_strlen_zero(c)) {
			if (sscanf(c, "IN IP4 %256s", host) != 1) {
				ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
			} else {
				/* XXX This could block for a long time, and block the main thread! XXX */
				hp = ast_gethostbyname(host, &ahp);
				if (!hp) {
					ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
				}
			}
		}
	}
	/* Setup video port number */
	sin.sin_port = htons(vportno);
	if (p->vrtp && sin.sin_port) {
		ast_rtp_set_peer(p->vrtp, &sin);
		if (debug) {
			ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
		}
	}

	/* Next, scan through each "a=rtpmap:" line, noting each
	 * specified RTP payload type (with corresponding MIME subtype):
	 */
	sdpLineNum_iterator_init(&iterator);
	while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
		char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
		if (!strcasecmp(a, "sendonly")) {
			sendonly=1;
			continue;
		}
		if (!strcasecmp(a, "sendrecv")) {
		  	sendonly=0;
		}
		if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
		if (debug)
			ast_verbose("Found description format %s\n", mimeSubtype);
		/* Note: should really look at the 'freq' and '#chans' params too */
		ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
		if (p->vrtp)
			ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
	}

	/* Now gather all of the codecs that were asked for: */
	ast_rtp_get_current_formats(p->rtp,
				&peercapability, &peernoncodeccapability);
	if (p->vrtp)
		ast_rtp_get_current_formats(p->vrtp,
				&vpeercapability, &vpeernoncodeccapability);
	p->jointcapability = p->capability & (peercapability | vpeercapabilit