/*
 * 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
 * \todo VIA branch tag transaction checking
 * \todo Transaction support
 *
 * \ingroup channel_drivers
 *
 * \par Overview of the handling of SIP sessions
 * The SIP channel handles several types of SIP sessions, or dialogs,
 * not all of them being "telephone calls".
 * - Incoming calls that will be sent to the PBX core
 * - Outgoing calls, generated by the PBX
 * - SIP subscriptions and notifications of states and voicemail messages
 * - SIP registrations, both inbound and outbound
 * - SIP peer management (peerpoke, OPTIONS)
 * - SIP text messages
 *
 * In the SIP channel, there's a list of active SIP dialogs, which includes
 * all of these when they are active. "sip show channels" in the CLI will
 * show most of these, excluding subscriptions which are shown by
 * "sip show subscriptions"
 *
 * \par incoming packets
 * Incoming packets are received in the monitoring thread, then handled by
 * sipsock_read(). This function parses the packet and matches an existing
 * dialog or starts a new SIP dialog.
 * 
 * sipsock_read sends the packet to handle_request(), that parses a bit more.
 * if it's a response to an outbound request, it's sent to handle_response().
 * If it is a request, handle_request sends it to one of a list of functions
 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
 * sipsock_read locks the ast_channel if it exists (an active call) and
 * unlocks it after we have processed the SIP message.
 *
 * A new INVITE is sent to handle_request_invite(), that will end up
 * starting a new channel in the PBX, the new channel after that executing
 * in a separate channel thread. This is an incoming "call".
 * When the call is answered, either by a bridged channel or the PBX itself
 * the sip_answer() function is called.
 *
 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
 * in rtp.c 
 * 
 * \par Outbound calls
 * Outbound calls are set up by the PBX through the sip_request_call()
 * function. After that, they are activated by sip_call().
 * 
 * \par Hanging up
 * The PBX issues a hangup on both incoming and outgoing calls through
 * the sip_hangup() function
 *
 * \par Deprecated stuff
 * This is deprecated and will be removed after the 1.4 release
 * - the SIPUSERAGENT dialplan variable
 * - the ALERT_INFO dialplan variable
 */


#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision: 49212 $")

#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/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/sched.h"
#include "asterisk/io.h"
#include "asterisk/rtp.h"
#include "asterisk/udptl.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/srv.h"
#include "asterisk/astdb.h"
#include "asterisk/causes.h"
#include "asterisk/utils.h"
#include "asterisk/file.h"
#include "asterisk/astobj.h"
#include "asterisk/devicestate.h"
#include "asterisk/linkedlists.h"
#include "asterisk/stringfields.h"
#include "asterisk/monitor.h"
#include "asterisk/localtime.h"
#include "asterisk/abstract_jb.h"
#include "asterisk/compiler.h"
#include "asterisk/threadstorage.h"
#include "asterisk/translate.h"

#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 SIP_TRANS_TIMEOUT            32000            /*!< SIP request timeout (rfc 3261) 64*T1 
                                                      \todo Use known T1 for timeout (peerpoke)
                                                      */
#define DEFAULT_TRANS_TIMEOUT        -1               /* Use default SIP transaction timeout */
#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 */

#define INITIAL_CSEQ                 101              /*!< our initial sip sequence number */

/*! \brief Global jitterbuffer configuration - by default, jb is disabled */
static struct ast_jb_conf default_jbconf =
{
        .flags = 0,
	.max_size = -1,
	.resync_threshold = -1,
	.impl = ""
};
static struct ast_jb_conf global_jbconf;

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

/*! \brief Authorization scheme for call transfers 
\note Not a bitfield flag, since there are plans for other modes,
	like "only allow transfers for authenticated devices" */
enum transfermodes {
	TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
	TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
};


enum sip_result {
	AST_SUCCESS = 0,
	AST_FAILURE = -1,
};

/*! \brief States for the INVITE transaction, not the dialog 
	\note this is for the INVITE that sets up the dialog
*/
enum invitestates {
	INV_NONE = 0,	        /*!< No state at all, maybe not an INVITE dialog */
	INV_CALLING = 1,	/*!< Invite sent, no answer */
	INV_PROCEEDING = 2,	/*!< We got/sent 1xx message */
	INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
	INV_COMPLETED = 4,	/*!< Got final response with error. Wait for ACK, then CONFIRMED */
	INV_CONFIRMED = 5,	/*!< Confirmed response - we've got an ack (Incoming calls only) */
	INV_TERMINATED = 6,	/*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
			    	     The only way out of this is a BYE from one side */
	INV_CANCELLED = 7,	/*!< Transaction cancelled by client or server in non-terminated state */
};

/* 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 parse_register_result {
	PARSE_REGISTER_FAILED,
	PARSE_REGISTER_UPDATE,
	PARSE_REGISTER_QUERY,
};

enum subscriptiontype { 
	NONE = 0,
	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" },
 	/* RFC 4235: SIP Dialog event package */
	{ 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" } /* RFC 3842: Mailbox notification */
};

/*! \brief SIP Request methods known by Asterisk */
enum sipmethod {
	SIP_UNKNOWN,		/* Unknown response */
	SIP_RESPONSE,		/* Not request, response to outbound request */
	SIP_REGISTER,
	SIP_OPTIONS,
	SIP_NOTIFY,
	SIP_INVITE,
	SIP_ACK,
	SIP_PRACK,		/* Not supported at all */
	SIP_BYE,
	SIP_REFER,
	SIP_SUBSCRIBE,
	SIP_MESSAGE,
	SIP_UPDATE,		/* We can send UPDATE; but not accept it */
	SIP_INFO,
	SIP_CANCEL,
	SIP_PUBLISH,		/* Not supported at all */
	SIP_PING,		/* Not supported at all, no standard but still implemented out there */
};

/*! \brief Authentication types - proxy or www authentication 
	\note Endpoints, like Asterisk, should always use WWW authentication to
	allow multiple authentications in the same call - to the proxy and
	to the end point.
*/
enum sip_auth_type {
	PROXY_AUTH,
	WWW_AUTH,
};

/*! \brief Authentication result from check_auth* functions */
enum check_auth_result {
	AUTH_SUCCESSFUL = 0,
	AUTH_CHALLENGE_SENT = 1,
	AUTH_SECRET_FAILED = -1,
	AUTH_USERNAME_MISMATCH = -2,
	AUTH_NOT_FOUND = -3,
	AUTH_FAKE_AUTH = -4,
	AUTH_UNKNOWN_DOMAIN = -5,
};

/*! \brief States for outbound registrations (with register= lines in sip.conf */
enum sipregistrystate {
	REG_STATE_UNREGISTERED = 0,	/*!< We are not registred */
	REG_STATE_REGSENT,	/*!< Registration request sent */
	REG_STATE_AUTHSENT,	/*!< We have tried to authenticate */
	REG_STATE_REGISTERED,	/*!< Registred and done */
	REG_STATE_REJECTED,	/*!< Registration rejected */
	REG_STATE_TIMEOUT,	/*!< Registration timed out */
	REG_STATE_NOAUTH,	/*!< We have no accepted credentials */
	REG_STATE_FAILED,	/*!< Registration failed after several tries */
};

#define CAN_NOT_CREATE_DIALOG	0
#define CAN_CREATE_DIALOG	1
#define CAN_CREATE_DIALOG_UNSUPPORTED_METHOD	2

/*! 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;
	int can_create;
} sip_methods[] = {
	{ SIP_UNKNOWN,	 RTP,    "-UNKNOWN-", 	CAN_CREATE_DIALOG },
	{ SIP_RESPONSE,	 NO_RTP, "SIP/2.0",	CAN_NOT_CREATE_DIALOG },
	{ SIP_REGISTER,	 NO_RTP, "REGISTER", 	CAN_CREATE_DIALOG },
 	{ SIP_OPTIONS,	 NO_RTP, "OPTIONS", 	CAN_CREATE_DIALOG },
	{ SIP_NOTIFY,	 NO_RTP, "NOTIFY", 	CAN_CREATE_DIALOG },
	{ SIP_INVITE,	 RTP,    "INVITE", 	CAN_CREATE_DIALOG },
	{ SIP_ACK,	 NO_RTP, "ACK", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_PRACK,	 NO_RTP, "PRACK", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_BYE,	 NO_RTP, "BYE", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_REFER,	 NO_RTP, "REFER", 	CAN_CREATE_DIALOG },
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", 	CAN_CREATE_DIALOG },
	{ SIP_MESSAGE,	 NO_RTP, "MESSAGE", 	CAN_CREATE_DIALOG },
	{ SIP_UPDATE,	 NO_RTP, "UPDATE", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_INFO,	 NO_RTP, "INFO", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_CANCEL,	 NO_RTP, "CANCEL", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_PUBLISH,	 NO_RTP, "PUBLISH", 	CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
	{ SIP_PING,	 NO_RTP, "PING", 	CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
};

/*!  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)
#define SIP_OPT_NOREFERSUB	(1 << 14)
#define SIP_OPT_HISTINFO	(1 << 15)
#define SIP_OPT_RESPRIORITY	(1 << 16)

/*! \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[] = {	/* XXX used in 3 places */
	/* RFC3891: Replaces: header for transfer */
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replaces" },	
	/* One version of Polycom firmware has the wrong label */
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replace" },	
	/* RFC3262: PRACK 100% reliability */
	{ SIP_OPT_100REL,	NOT_SUPPORTED,	"100rel" },	
	/* RFC4028: SIP Session Timers */
	{ SIP_OPT_TIMER,	NOT_SUPPORTED,	"timer" },
	/* RFC3959: SIP Early session support */
	{ SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,	"early-session" },
	/* RFC3911: 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:  RFC4662 */
	{ SIP_OPT_EVENTLIST,	NOT_SUPPORTED,	"eventlist" },
	/* GRUU: Globally Routable User Agent URI's */
	{ SIP_OPT_GRUU,		NOT_SUPPORTED,	"gruu" },
	/* RFC4538: Target-dialog */
	{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,	"tdialog" },
	/* Disable the REFER subscription, RFC 4488 */
	{ SIP_OPT_NOREFERSUB,	NOT_SUPPORTED,	"norefersub" },
	/* ietf-sip-history-info-06.txt */
	{ SIP_OPT_HISTINFO,	NOT_SUPPORTED,	"histinfo" },
	/* ietf-sip-resource-priority-10.txt */
	{ SIP_OPT_RESPRIORITY,	NOT_SUPPORTED,	"resource-priority" },
};


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

/*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
#define STANDARD_SIP_PORT	5060
/* Note: in many SIP headers, absence of a port number implies port 5060,
 * and this is why we cannot change the above constant.
 * There is a limited number of places in asterisk where we could,
 * in principle, use a different "default" port number, but
 * we do not support this feature at the moment.
 */

/* 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_CONTEXT		"default"
#define DEFAULT_MOHINTERPRET    "default"
#define DEFAULT_MOHSUGGEST      ""
#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_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
static char default_mohsuggest[MAX_MUSICCLASS];	   /*!< Global setting for moh class to suggest when putting 
                                                    *   a bridged channel on hold */
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_limitonpeers;		/*!< Match call limit on peers only */
static int global_rtautoclear;
static int global_notifyringing;	/*!< Send notifications on ringing */
static int global_notifyhold;		/*!< Send notifications on hold */
static int global_alwaysauthreject;	/*!< Send 401 Unauthorized for all failing requests */
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 unsigned int global_tos_sip;		/*!< IP type of service for SIP packets */
static unsigned int global_tos_audio;		/*!< IP type of service for audio RTP packets */
static unsigned 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 */
static int global_autoframing;          /*!< Turn autoframing on or off. */
static enum transfermodes global_allowtransfer;	/*!< SIP Refer restriction scheme */

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

/*! \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 */
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */

#define DEC_CALL_LIMIT	0
#define INC_CALL_LIMIT	1
#define DEC_CALL_RINGING 2
#define INC_CALL_RINGING 3

/*! \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 */
	int lines;              /*!< Body Content */
	unsigned int flags;     /*!< SIP_PKT Flags for this packet */
	char *header[SIP_MAX_HEADERS];
	char *line[SIP_MAX_LINES];
	char data[SIP_MAX_PACKET];
	unsigned int sdp_start; /*!< the line number where the SDP begins */
	unsigned int sdp_end;   /*!< the line number where the SDP ends */
};

/*
 * A sip packet is stored into the data[] buffer, with the header followed
 * by an empty line and the body of the message.
 * On outgoing packets, data is accumulated in data[] with len reflecting
 * the next available byte, headers and lines count the number of lines
 * in both parts. There are no '\0' in data[0..len-1].
 *
 * On received packet, the input read from the socket is copied into data[],
 * len is set and the string is NUL-terminated. Then a parser fills up
 * the other fields -header[] and line[] to point to the lines of the
 * message, rlPart1 and rlPart2 parse the first lnie as below:
 *
 * Requests have in the first line	METHOD URI SIP/2.0
 *	rlPart1 = method; rlPart2 = uri;
 * Responses have in the first line	SIP/2.0 code description
 *	rlPart1 = SIP/2.0; rlPart2 = code + description;
 *
 */

/*! \brief structure used in transfers */
struct sip_dual {
	struct ast_channel *chan1;	/*!< First channel involved */
	struct ast_channel *chan2;	/*!< Second channel involved */
	struct sip_request req;		/*!< Request that caused the transfer (REFER) */
	int seqno;			/*!< Sequence number */
};

struct sip_pkt;

/*! \brief Parameters to the transmit_invite function */
struct sip_invite_param {
	const char *distinctive_ring;	/*!< Distinctive ring header */
	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 */
	const char *replaces;		/*!< Replaces header for call transfers */
	int transfer;			/*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
};

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

/*! \brief Domain data structure. 
	\note In the future, we will connect this to a configuration tree specific
	for this domain
*/
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: Credentials 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 */
#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 by the monitor thread */
#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)	/*!< Direction of the last transaction in this dialog */
#define SIP_FREE_BIT		(1 << 14)	/*!< ---- */
#define SIP_DEFER_BYE_ON_TRANSFER	(1 << 15)	/*!< Do not hangup at first ast_hangup */
#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)	/*!< NAT RFC3581 */
#define SIP_NAT_ROUTE		(2 << 18)	/*!< NAT Only ROUTE */
#define SIP_NAT_ALWAYS		(3 << 18)	/*!< NAT Both ROUTE and RFC3581 */
/* re-INVITE related settings */
#define SIP_REINVITE		(7 << 20)	/*!< three bits used */
#define SIP_CAN_REINVITE	(1 << 20)	/*!< allow peers to be reinvited to send media directly p2p */
#define SIP_CAN_REINVITE_NAT	(2 << 20)	/*!< allow media reinvite when new peer is behind NAT */
#define SIP_REINVITE_UPDATE	(4 << 20)	/*!< use UPDATE (RFC3311) when reinviting this peer */
/* "insecure" settings */
#define SIP_INSECURE_PORT	(1 << 23)	/*!< don't require matching port for incoming requests */
#define SIP_INSECURE_INVITE	(1 << 24)	/*!< don't require authentication for incoming INVITEs */
/* Sending PROGRESS in-band settings */
#define SIP_PROG_INBAND		(3 << 25)	/*!< three settings, uses two bits */
#define SIP_PROG_INBAND_NEVER	(0 << 25)
#define SIP_PROG_INBAND_NO	(1 << 25)
#define SIP_PROG_INBAND_YES	(2 << 25)
#define SIP_NO_HISTORY		(1 << 27)	/*!< Suppress recording request/response history */
#define SIP_CALL_LIMIT		(1 << 28)	/*!< Call limit enforced for this call */
#define SIP_SENDRPID		(1 << 29)	/*!< Remote Party-ID Support */
#define SIP_INC_COUNT		(1 << 30)	/*!< Did this connection increment the counter of in-use calls? */
#define SIP_G726_NONSTANDARD	(1 << 31)	/*!< Use non-standard packing for G726-32 data */

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

/*--- a new page of flags (for flags[1] */
/* realtime flags */
#define SIP_PAGE2_RTCACHEFRIENDS	(1 << 0)
#define SIP_PAGE2_RTUPDATE		(1 << 1)
#define SIP_PAGE2_RTAUTOCLEAR		(1 << 2)
#define SIP_PAGE2_RT_FROMCONTACT 	(1 << 4)
#define SIP_PAGE2_RTSAVE_SYSNAME 	(1 << 5)
/* Space for addition of other realtime flags in the future */
#define SIP_PAGE2_IGNOREREGEXPIRE	(1 << 10)
#define SIP_PAGE2_DEBUG			(3 << 11)
#define SIP_PAGE2_DEBUG_CONFIG 		(1 << 11)
#define SIP_PAGE2_DEBUG_CONSOLE 	(1 << 12)
#define SIP_PAGE2_DYNAMIC		(1 << 13)	/*!< Dynamic Peers register with Asterisk */
#define SIP_PAGE2_SELFDESTRUCT		(1 << 14)	/*!< Automatic peers need to destruct themselves */
#define SIP_PAGE2_VIDEOSUPPORT		(1 << 15)
#define SIP_PAGE2_ALLOWSUBSCRIBE	(1 << 16)	/*!< Allow subscriptions from this peer? */
#define SIP_PAGE2_ALLOWOVERLAP		(1 << 17)	/*!< Allow overlap dialing ? */
#define SIP_PAGE2_SUBSCRIBEMWIONLY	(1 << 18)	/*!< Only issue MWI notification if subscribed to */
#define SIP_PAGE2_INC_RINGING		(1 << 19)	/*!< Did this connection increment the counter of in-use calls? */
#define SIP_PAGE2_T38SUPPORT		(7 << 20)	/*!< T38 Fax Passthrough Support */
#define SIP_PAGE2_T38SUPPORT_UDPTL	(1 << 20)	/*!< 20: T38 Fax Passthrough Support */
#define SIP_PAGE2_T38SUPPORT_RTP	(2 << 20)	/*!< 21: T38 Fax Passthrough Support (not implemented) */
#define SIP_PAGE2_T38SUPPORT_TCP	(4 << 20)	/*!< 22: T38 Fax Passthrough Support (not implemented) */
#define SIP_PAGE2_CALL_ONHOLD		(3 << 23)	/*!< Call states */
#define SIP_PAGE2_CALL_ONHOLD_ONEDIR	(1 << 23)	/*!< 23: One directional hold */
#define SIP_PAGE2_CALL_ONHOLD_INACTIVE	(1 << 24)	/*!< 24: Inactive  */
#define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)	/*!< 25: ???? */
#define SIP_PAGE2_BUGGY_MWI		(1 << 26)	/*!< 26: Buggy CISCO MWI fix */

#define SIP_PAGE2_FLAGS_TO_COPY \
	(SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
	SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI)

/* 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 SIP_PKT_IGNORE 		(1 << 2)	/*!< This is a re-transmit, ignore it */
#define SIP_PKT_IGNORE_RESP	(1 << 3)	/*!< Resp ignore - ??? */
#define SIP_PKT_IGNORE_REQ	(1 << 4)	/*!< Req ignore - ??? */

/* T.38 set of flags */
#define T38FAX_FILL_BIT_REMOVAL		(1 << 0)	/*!< Default: 0 (unset)*/
#define T38FAX_TRANSCODING_MMR			(1 << 1)	/*!< Default: 0 (unset)*/
#define T38FAX_TRANSCODING_JBIG		(1 << 2)	/*!< Default: 0 (unset)*/
/* Rate management */
#define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF	(0 << 3)
#define T38FAX_RATE_MANAGEMENT_LOCAL_TCF	(1 << 3)	/*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
/* UDP Error correction */
#define T38FAX_UDP_EC_NONE			(0 << 4)	/*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
#define T38FAX_UDP_EC_FEC			(1 << 4)	/*!< Set for t38UDPFEC */
#define T38FAX_UDP_EC_REDUNDANCY		(2 << 4)	/*!< Set for t38UDPRedundancy */
/* T38 Spec version */
#define T38FAX_VERSION				(3 << 6)	/*!< two bits, 2 values so far, up to 4 values max */
#define T38FAX_VERSION_0			(0 << 6)	/*!< Version 0 */
#define T38FAX_VERSION_1			(1 << 6)	/*!< Version 1 */
/* Maximum Fax Rate */
#define T38FAX_RATE_2400			(1 << 8)	/*!< 2400 bps t38FaxRate */
#define T38FAX_RATE_4800			(1 << 9)	/*!< 4800 bps t38FaxRate */
#define T38FAX_RATE_7200			(1 << 10)	/*!< 7200 bps t38FaxRate */
#define T38FAX_RATE_9600			(1 << 11)	/*!< 9600 bps t38FaxRate */
#define T38FAX_RATE_12000			(1 << 12)	/*!< 12000 bps t38FaxRate */
#define T38FAX_RATE_14400			(1 << 13)	/*!< 14400 bps t38FaxRate */

/*!< This is default: NO MMR and JBIG trancoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;

#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 T38 States for a call */
enum t38state {
        T38_DISABLED = 0,                /*!< Not enabled */
        T38_LOCAL_DIRECT,                /*!< Offered from local */
        T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
        T38_PEER_DIRECT,                 /*!< Offered from peer */
        T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
        T38_ENABLED                      /*!< Negotiated (enabled) */
};

/*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
struct t38properties {
	struct ast_flags t38support;	/*!< Flag for udptl, rtp or tcp support for this session */
	int capability;			/*!< Our T38 capability */
	int peercapability;		/*!< Peers T38 capability */
	int jointcapability;		/*!< Supported T38 capability at both ends */
	enum t38state state;		/*!< T.38 state */
};

/*! \brief Parameters to know status of transfer */
enum referstatus {
        REFER_IDLE,                    /*!< No REFER is in progress */
        REFER_SENT,                    /*!< Sent REFER to transferee */
        REFER_RECEIVED,                /*!< Received REFER from transferer */
        REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING */
        REFER_ACCEPTED,                /*!< Accepted by transferee */
        REFER_RINGING,                 /*!< Target Ringing */
        REFER_200OK,                   /*!< Answered by transfer target */
        REFER_FAILED,                  /*!< REFER declined - go on */
        REFER_NOAUTH                   /*!< We had no auth for REFER */
};

static const struct c_referstatusstring {
	enum referstatus status;
	char *text;
} referstatusstrings[] = {
	{ REFER_IDLE,		"<none>" },
	{ REFER_SENT,		"Request sent" },
	{ REFER_RECEIVED,	"Request received" },
	{ REFER_ACCEPTED,	"Accepted" },
	{ REFER_RINGING,	"Target ringing" },
	{ REFER_200OK,		"Done" },
	{ REFER_FAILED,		"Failed" },
	{ REFER_NOAUTH,		"Failed - auth failure" }
} ;

/*! \brief Structure to handle SIP transfers. Dynamically allocated when needed  */
/* OEJ: Should be moved to string fields */
struct sip_refer {
	char refer_to[AST_MAX_EXTENSION];		/*!< Place to store REFER-TO extension */
	char refer_to_domain[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO domain */
	char refer_to_urioption[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO uri options */
	char refer_to_context[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO context */
	char referred_by[AST_MAX_EXTENSION];		/*!< Place to store REFERRED-BY extension */
	char referred_by_name[AST_MAX_EXTENSION];	/*!< Place to store REFERRED-BY extension */
	char refer_contact[AST_MAX_EXTENSION];		/*!< Place to store Contact info from a REFER extension */
	char replaces_callid[BUFSIZ];			/*!< Replace info: callid */
	char replaces_callid_totag[BUFSIZ/2];		/*!< Replace info: to-tag */
	char replaces_callid_fromtag[BUFSIZ/2];		/*!< Replace info: from-tag */
	struct sip_pvt *refer_call;			/*!< Call we are referring */
	int attendedtransfer;				/*!< Attended or blind transfer? */
	int localtransfer;				/*!< Transfer to local domain? */
	enum referstatus status;			/*!< REFER status */
};

/*! \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 */
	enum invitestates invitestate;		/*!< The state of the INVITE transaction only */
	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(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(subscribeuri); /*!< 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(mohinterpret);	/*!< MOH class to use when put on hold */
		AST_STRING_FIELD(mohsuggest);	/*!< MOH class to suggest when putting a peer on hold */
		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 number */
		AST_STRING_FIELD(cid_name);	/*!< Caller*ID name */
		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 */
	);
	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 options on the other end */
	struct ast_codec_pref prefs;		/*!< codec prefs */
	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;			/*!< DTMF RFC2833 telephony-event */
	int redircodecs;			/*!< Redirect codecs */
	int maxcallbitrate;			/*!< Maximum Call Bitrate for Video Calls */	
	struct t38properties t38;		/*!< T38 settings */
	struct sockaddr_in udptlredirip;	/*!< Where our T.38 UDPTL should be going if not to us */
	struct ast_udptl *udptl;		/*!< T.38 UDPTL session */
	int callingpres;			/*!< Calling presentation */
	int authtries;				/*!< Times we've tried to authenticate */
	int expiry;				/*!< How long we take to expire */
	long branch;				/*!< The branch identifier of this session */
	char tag[11];				/*!< Our tag for this session */
	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 */
	time_t lastrtprx;			/*!< Last RTP received */
	time_t lastrtptx;			/*!< Last RTP sent */
	int rtptimeout;				/*!< RTP timeout time */
	struct sockaddr_in recv;		/*!< Received as */
	struct in_addr ourip;			/*!< Our IP */
	struct ast_channel *owner;		/*!< Who owns us (if we have an owner) */
	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 ? (seqno of this) */
	struct sip_request initreq;		/*!< Request that opened the latest transaction
						     within this SIP dialog */
	
	int maxtime;				/*!< Max time for first response */
	int initid;				/*!< Auto-congest ID if appropriate (scheduler) */
	int autokillid;				/*!< Auto-kill ID (scheduler) */
	enum transfermodes allowtransfer;	/*!< REFER: restriction scheme */
	struct sip_refer *refer;		/*!< REFER: SIP transfer data structure */
	enum subscriptiontype subscribed;	/*!< SUBSCRIBE: Is this dialog a subscription?  */
	int stateid;				/*!< SUBSCRIBE: ID for devicestate subscriptions */
	int laststate;				/*!< SUBSCRIBE: Last known extension state */
	int dialogver;				/*!< SUBSCRIBE: Version for subscription dialog-info */
	
	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 inbound call */
	struct sip_pvt *next;			/*!< Next dialog in chain */
	struct sip_invite_param *options;	/*!< Options for INVITE */
	int autoframing;
} *iflist = NULL;

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

/*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
struct sip_pkt {
	struct sip_pkt *next;			/*!< Next packet in linked list */
	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 mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
	char mohsuggest[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 */
	enum transfermodes allowtransfer;	/*! SIP Refer restriction scheme */
	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 */
	int autoframing;
};

/*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
/* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
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 inRinging;			/*!< Number of calls ringing */
	int onHold;                     /*!< Peer has someone on hold */
	int call_limit;			/*!< Limit of concurrent calls */
	enum transfermodes allowtransfer;	/*! SIP Refer restriction scheme */
	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 mohinterpret[MAX_MUSICCLASS];/*!<  Music on Hold class */
	char mohsuggest[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 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;
	int autoframing;
};



/*! \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 */
	enum sipregistrystate regstate;	/*!< Registration state (see above) */
	time_t regtime;		/*!< Last succesful registration time */
	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;

static void temp_pvt_cleanup(void *);

/*! \brief A per-thread temporary pvt structure */
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);

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

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

/*---------------------------- Forward declarations of functions in chan_sip.c */
/*! \note This is added to help splitting up chan_sip.c into several files
	in coming releases */

/*--- PBX interface functions */
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, const void *data, size_t datalen);
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_begin(struct ast_channel *ast, char digit);
static int sip_senddigit_end(struct ast_channel *ast, char digit);

/*--- Transmitting responses and requests */
static int sipsock_read(int *id, int fd, short events, void *ignore);
static int __sip_xmit(struct sip_pvt *p, char *data, int len);
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
static int retrans_pkt(void *data);
static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
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 seqno, enum xmittype reliable, int newbranch);
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
static int transmit_reinvite_with_sdp(struct sip_pvt *p);
static int transmit_info_with_digit(struct sip_pvt *p, const 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 transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
static void copy_request(struct sip_request *dst, const struct sip_request *src);
static void receive_message(struct sip_pvt *p, struct sip_request *req);
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
static int sip_send_mwi_to_peer(struct sip_peer *peer);
static int does_peer_need_mwi(struct sip_peer *peer);

/*--- Dialog management */
static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
				 int useglobal_nat, const int intended_method);
static int __sip_autodestruct(void *data);
static void sip_scheddestroy(struct sip_pvt *p, int ms);
static void sip_cancel_destroy(struct sip_pvt *p);
static void sip_destroy(struct sip_pvt *p);
static void __sip_destroy(struct sip_pvt *p, int lockowner);
static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
static void __sip_pretend_ack(struct sip_pvt *p);
static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
static int auto_congest(void *nothing);
static int update_call_counter(struct sip_pvt *fup, int event);
static int hangup_sip2cause(int cause);
static const char *hangup_cause2sip(int cause);
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
static void free_old_route(struct sip_route *route);
static void list_route(struct sip_route *route);
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
					      struct sip_request *req, char *uri);
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
static void check_pendings(struct sip_pvt *p);
static void *sip_park_thread(void *stuff);
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
static int sip_sipredirect(struct sip_pvt *p, const char *dest);

/*--- Codec handling / SDP */
static void try_suggested_sip_codec(struct sip_pvt *p);
static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
static const char *get_sdp(struct sip_request *req, const char *name);
static int find_sdp(struct sip_request *req);
static int process_sdp(struct sip_pvt *p, struct sip_request *req);
static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
			     char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
			     int debug, int *min_packet_size);
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
				char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
				int debug);
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);

/*--- Authentication stuff */
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
static enum check_auth_result 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 enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
					      int sipmethod, char *uri, enum xmittype reliable,
					      struct sockaddr_in *sin, struct sip_peer **authpeer);
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);

/*--- Domain handling */
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
static void clear_sip_domains(void);

/*--- SIP realm authentication */
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);

/*--- Misc functions */
static int sip_do_reload(enum channelreloadreason reason);
static int reload_config(enum channelreloadreason reason);
static int expire_register(void *data);
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
static void *do_monitor(void *data);
static int restart_monitor(void);
static int sip_send_mwi_to_peer(struct sip_peer *peer);
static void sip_destroy(struct sip_pvt *p);
static int sip_addrcmp(char *name, struct sockaddr_in *sin);	/* Support for peer matching */
static int sip_refer_allocate(struct sip_pvt *p);
static void ast_quiet_chan(struct ast_channel *chan);
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);

/*--- Device monitoring and Device/extension state handling */
static int cb_extensionstate(char *context, char* exten, int state, void *data);
static int sip_devicestate(void *data);
static int sip_poke_noanswer(void *data);
static int sip_poke_peer(struct sip_peer *peer);
static void sip_poke_all_peers(void);
static void sip_peer_hold(struct sip_pvt *p, int hold);

/*--- Applications, functions, CLI and manager command helpers */
static const char *sip_nat_mode(const struct sip_pvt *p);
static int sip_show_inuse(int fd, int argc, char *argv[]);
static char *transfermode2str(enum transfermodes mode) attribute_const;
static char *nat2str(int nat) attribute_const;
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
static int sip_show_users(int fd, int argc, char *argv[]);
static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
static int manager_sip_show_peers( struct mansession *s, struct message *m );
static int sip_show_peers(int fd, int argc, char *argv[]);
static int sip_show_objects(int fd, int argc, char *argv[]);
static void  print_group(int fd, ast_group_t group, int crlf);
static const char *dtmfmode2str(int mode) attribute_const;
static const char *insecure2str(int port, int invite) attribute_const;
static void cleanup_stale_contexts(char *new, char *old);
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
static const char *domain_mode_to_text(const enum domain_mode mode);
static int sip_show_domains(int fd, int argc, char *argv[]);
static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
static int manager_sip_show_peer( struct mansession *s, struct message *m);
static int sip_show_peer(int fd, int argc, char *argv[]);
static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
static int sip_show_user(int fd, int argc, char *argv[]);
static int sip_show_registry(int fd, int argc, char *argv[]);
static int sip_show_settings(int fd, int argc, char *argv[]);
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
static int sip_show_channels(int fd, int argc, char *argv[]);
static int sip_show_subscriptions(int fd, int argc, char *argv[]);
static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
static char *complete_sipch(const char *line, const char *word, int pos, int state);
static char *complete_sip_peer(const char *word, int state, int flags2);
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
static char *complete_sip_user(const char *word, int state, int flags2);
static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
static int sip_show_channel(int fd, int argc, char *argv[]);
static int sip_show_history(int fd, int argc, char *argv[]);
static int sip_do_debug_ip(int fd, int argc, char *argv[]);
static int sip_do_debug_peer(int fd, int argc, char *argv[]);
static int sip_do_debug(int fd, int argc, char *argv[]);
static int sip_no_debug(int fd, int argc, char *argv[]);
static int sip_notify(int fd, int argc, char *argv[]);
static int sip_do_history(int fd, int argc, char *argv[]);
static int sip_no_history(int fd, int argc, char *argv[]);
static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
static int sip_dtmfmode(struct ast_channel *chan, void *data);
static int sip_addheader(struct ast_channel *chan, void *data);
static int sip_do_reload(enum channelreloadreason reason);
static int sip_reload(int fd, int argc, char *argv[]);

/*--- Debugging 
	Functions for enabling debug per IP or fully, or enabling history logging for
	a SIP dialog
*/
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to LOG_DEBUG at end of dialog, before destroying data */
static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
static inline int sip_debug_test_pvt(struct sip_pvt *p);
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
static void sip_dump_history(struct sip_pvt *dialog);

/*--- Device object handling */
static struct sip_peer *temp_peer(const char *name);
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
static int update_call_counter(struct sip_pvt *fup, int event);
static void sip_destroy_peer(struct sip_peer *peer);
static void sip_destroy_user(struct sip_user *user);
static int sip_poke_peer(struct sip_peer *peer);
static void set_peer_defaults(struct sip_peer *peer);
static struct sip_peer *temp_peer(const char *name);
static void register_peer_exten(struct sip_peer *peer, int onoff);
static void sip_destroy_peer(struct sip_peer *peer);
static void sip_destroy_user(struct sip_user *user);
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
static struct sip_user *find_user(const char *name, int realtime);
static int sip_poke_peer_s(void *data);
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
static int expire_register(void *data);
static void reg_source_db(struct sip_peer *peer);
static void destroy_association(struct sip_peer *peer);
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);

/* Realtime device support */
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
static struct sip_user *realtime_user(const char *username);
static void update_peer(struct sip_peer *p, int expiry);
static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
static int sip_prune_realtime(int fd, int argc, char *argv[]);

/*--- Internal UA client handling (outbound registrations) */
static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
static void sip_registry_destroy(struct sip_registry *reg);
static int sip_register(char *value, int lineno);
static char *regstate2str(enum sipregistrystate regstate) attribute_const;
static int sip_reregister(void *data);
static int __sip_do_register(struct sip_registry *r);
static int sip_reg_timeout(void *data);
static void sip_send_all_registers(void);

/*--- Parsing SIP requests and responses */
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
static int determine_firstline_parts(struct sip_request *req);
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
static int find_sip_method(const char *msg);
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
static void parse_request(struct sip_request *req);
static const char *get_header(const struct sip_request *req, const char *name);
static char *referstatus2str(enum referstatus rstatus) attribute_pure;
static int method_match(enum sipmethod id, const char *name);
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
static char *get_in_brackets(char *tmp);
static const char *find_alias(const char *name, const char *_default);
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
static int lws2sws(char *msgbuf, int len);
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
static int set_address_from_contact(struct sip_pvt *pvt);
static void check_via(struct sip_pvt *p, struct sip_request *req);
static char *get_calleridname(const char *input, char *output, size_t outputsize);
static int get_rpid_num(const char *input, char *output, int maxlen);
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
static int get_msg_text(char *buf, int len, struct sip_request *req);
static void free_old_route(struct sip_route *route);
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);

/*--- Constructing requests and responses */
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
static int init_resp(struct sip_request *resp, const char *msg);
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
static void build_via(struct sip_pvt *p);
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
static int create_addr(struct sip_pvt *dialog, const char *opeer);
static char *generate_random_string(char *buf, size_t size);
static void build_callid_pvt(struct sip_pvt *pvt);
static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
static void make_our_tag(char *tagbuf, size_t len);
static int add_header(struct sip_request *req, const char *var, const char *value);
static int add_header_contentLength(struct sip_request *req, int len);
static int add_line(struct sip_request *req, const char *line);
static int add_text(struct sip_request *req, const char *text);
static int add_digit(struct sip_request *req, char digit);
static int add_vidupdate(struct sip_request *req);
static void add_route(struct sip_request *req, struct sip_route *route);
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
static void set_destination(struct sip_pvt *p, char *uri);
static void append_date(struct sip_request *req);
static void build_contact(struct sip_pvt *p);
static void build_rpid(struct sip_pvt *p);

/*------Request handling functions */
static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e);
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock);
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);

/*------Response handling functions */
static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);
static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno);

/*----- 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 enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
static int sip_get_codec(struct ast_channel *chan);
static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);

/*------ T38 Support --------- */
static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p);
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);

/*! \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 | AST_CHAN_TP_CREATESJITTER,
	.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_begin = sip_senddigit_begin,
	.send_digit_end = sip_senddigit_end,
	.bridge = ast_rtp_bridge,
	.send_text = sip_sendtext,
};

/**--- some list management macros. **/
 
#define UNLINK(element, head, prev) do {	\
	if (prev)				\
		(prev)->next = (element)->next;	\
	else					\
		(head) = (element)->next;	\
	} while (0)

/*! \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 Interface structure with callbacks used to connect to UDPTL module*/
static struct ast_udptl_protocol sip_udptl = {
	type: "SIP",
	get_udptl_info: sip_get_udptl_peer,
	set_udptl_peer: sip_set_udptl_peer,
};

/*! \brief Convert transfer status to string */
static char *referstatus2str(enum referstatus rstatus)
{
	int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
	int x;

	for (x = 0; x < i; x++) {
		if (referstatusstrings[x].status ==  rstatus)
			return (char *) referstatusstrings[x].text;
	}
	return "";
}

/*! \brief Initialize the initital request packet in the pvt structure.
 	This packet is used for creating replies and future requests in
	a dialog */
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
{
	if (p->initreq.headers && option_debug) {
		ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
	}
	/* Use this as the basis */
	copy_request(&p->initreq, req);
	parse_request(&p->initreq);
	if (ast_test_flag(req, SIP_PKT_DEBUG))
		ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
}

static void sip_alreadygone(struct sip_pvt *dialog)
{
	if (option_debug > 2)
		ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
	ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
}


/*! \brief returns true if 'name' (with optional trailing whitespace)
 * matches the sip method 'id'.
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
 * a case-insensitive comparison to be more tolerant.
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
 */
static int method_match(enum sipmethod id, const char *name)
{
	int len = strlen(sip_methods[id].text);
	int l_name = name ? strlen(name) : 0;
	/* true if the string is long enough, and ends with whitespace, and matches */
	return (l_name >= len && name[len] < 33 &&
		!strncasecmp(sip_methods[id].text, name, len));
}

/*! \brief  find_sip_method: Find SIP method from header */
static int find_sip_method(const 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 (method_match(i, 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, const char *supported)
{
	char *next, *sep;
	char *temp;
	unsigned int profile = 0;
	int i, found;

	if (ast_strlen_zero(supported) )
		return 0;
	temp = ast_strdupa(supported);

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

	for (next = temp; next; next = sep) {
		found = FALSE;
		if ( (sep = strchr(next, ',')) != NULL)
			*sep++ = '\0';
		next = ast_skip_blanks(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])); i++) {
			if (!strcasecmp(next, sip_options[i].text)) {
				profile |= sip_options[i].id;
				found = TRUE;
				if (option_debug > 2 && sipdebug)
					ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
				break;
			}
		}
		if (!found && option_debug > 2 && sipdebug) {
			if (!strncasecmp(next, "x-", 2))
				ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
			else
				ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
		}
	}

	if (pvt)
		pvt->sipoptions = profile;
	return profile;
}

/*! \brief See if we pass debug IP filter */
static inline int sip_debug_test_addr(const 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 The real destination address for a write */
static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
{
	return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
}

/*! \brief Display SIP nat mode */
static const char *sip_nat_mode(const struct sip_pvt *p)
{
	return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
}

/*! \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(sip_real_dst(p));
}

/*! \brief Transmit SIP message */
static int __sip_xmit(struct sip_pvt *p, char *data, int len)
{
	int res;
	const struct sockaddr_in *dst = sip_real_dst(p);
	res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, 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(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
	return res;
}


/*! \brief Build a Via header for a request */
static void build_via(struct sip_pvt *p)
{
	/* 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(p->ourip), ourport, p->branch, rport);
}

/*! \brief NAT fix - decide which IP address to use for ASterisk server?
 *
 * Using the localaddr structure built up with localnet statements in sip.conf
 * apply it to their address to see if we need to substitute our
 * externip or can get away with our internal bindaddr
 */
static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
{
	struct sockaddr_in theirs, ours;

	/* Get our local information */
	ast_ouraddrfor(them, us);
	theirs.sin_addr = *them;
	ours.sin_addr = *us;

	if (localaddr && externip.sin_addr.s_addr &&
	    ast_apply_ha(localaddr, &theirs) &&
	    !ast_apply_ha(localaddr, &ours)) {
		if (externexpire && time(NULL) >= externexpire) {
			struct ast_hostent ahp;
			struct hostent *hp;

			externexpire = time(NULL) + 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);
		}
		*us = externip.sin_addr;
		if (option_debug) {
			ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", 
				ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
		}
	} else if (bindaddr.sin_addr.s_addr)
		*us = bindaddr.sin_addr;
	return AST_SUCCESS;
}

/*! \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 void 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 void append_history_full(struct sip_pvt *p, const char *fmt, ...)
{
	va_list ap;

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

	return;
}

/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
static int retrans_pkt(void *data)
{
	struct sip_pkt *pkt = data, *prev, *cur = NULL;
	int reschedule = DEFAULT_RETRANS;

	/* Lock channel PVT */
	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 (sip_debug_test_pvt(pkt->owner)) {
			const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
			ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
				pkt->retrans, sip_nat_mode(pkt->owner),
				ast_inet_ntoa(dst->sin_addr),
				ntohs(dst->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_channel_trylock(pkt->owner->owner)) {
			ast_mutex_unlock(&pkt->owner->lock);	/* SIP_PVT, not channel */
			usleep(1);
			ast_mutex_lock(&pkt->owner->lock);
		}
		if (pkt->owner->owner) {
			sip_alreadygone(pkt->owner);
			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_channel_unlock(pkt->owner->owner);
		} else {
			/* If no channel owner, destroy now */

			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
			if (pkt->method != SIP_OPTIONS)
				ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);	
		}
	}
	/* In any case, go ahead and remove the packet */
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
		if (cur == pkt)
			break;
	}
	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 enum sip_result __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 AST_FAILURE;
	memcpy(pkt->data, data, len);
	pkt->method = sipmethod;
	pkt->packetlen = len;
	pkt->next = p->packets;
	pkt->owner = p;
	pkt->seqno = seqno;
	if (resp)
		ast_set_flag(pkt, FLAG_RESPONSE);
	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 AST_SUCCESS;
}

/*! \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) {
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* 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 */
	}

	/* If we're destroying a subscription, dereference peer object too */
	if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
		ASTOBJ_UNREF(p->relatedpeer,sip_destroy_peer);

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

	if (option_debug)
		ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
	append_history(p, "AutoDestroy", "%s", p->callid);
	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 if (p->refer) {
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	} else
		sip_destroy(p);
	return 0;
}

/*! \brief Schedule destruction of SIP dialog */
static void sip_scheddestroy(struct sip_pvt *p, int ms)
{
	if (ms < 0) {
		if (p->timer_t1 == 0)
			p->timer_t1 = 500;	/* Set timer T1 if not set (RFC 3261) */
		ms = p->timer_t1 * 64;
	}
	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 (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
		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);
}

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

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

	/* Just in case... */
	char *msg;
	int res = FALSE;

	msg = sip_methods[sipmethod].text;

	ast_mutex_lock(&p->lock);
	for (cur = p->packets; cur; prev = cur, cur = cur->next) {
		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)) {
				if (option_debug)
					ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
				p->pendinginvite = 0;
			}
			/* this is our baby */
			res = TRUE;
			UNLINK(cur, p->packets, prev);
			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);
				cur->retransid = -1;
			}
			free(cur);
			break;
		}
	}
	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");
}

/*! \brief Pretend to ack all packets
 * maybe the lock on p is not strictly necessary but there might be a race */
static void __sip_pretend_ack(struct sip_pvt *p)
{
	struct sip_pkt *cur = NULL;

	while (p->packets) {
		int method;
		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;
		}
		cur = p->packets;
		method = (cur->method) ? cur->method : find_sip_method(cur->data);
		__sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
	}
}

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

	for (cur = p->packets; cur; cur = cur->next) {
		if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
			(ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
			/* 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, sip_methods[sipmethod].text);
				ast_sched_del(sched, cur->retransid);
				cur->retransid = -1;
			}
			res = 0;
			break;
		}
	}
	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, const 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 add a blank line if no body */
static void add_blank(struct sip_request *req)
{
	if (!req->lines) {
		/* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
		snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
		req->len += strlen(req->data + req->len);
	}
}

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

	add_blank(req);
	if (sip_debug_test_pvt(p)) {
		const struct sockaddr_in *dst = sip_real_dst(p);

		ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
			reliable ? "Reliably " : "", sip_nat_mode(p),
			ast_inet_ntoa(dst->sin_addr),
			ntohs(dst->sin_port), req->data);
	}
	if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
		struct sip_request tmp;
		parse_copy(&tmp, req);
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), 
			(tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
	}
	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;

	add_blank(req);
	if (sip_debug_test_pvt(p)) {
		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(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(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
	}
	if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
		struct sip_request tmp;
		parse_copy(&tmp, req);
		append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
	}
	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 Locate closing quote in a string, skipping escaped quotes.
 * optionally with a limit on the search.
 * start must be past the first quote.
 */
static const char *find_closing_quote(const char *start, const char *lim)
{
        char last_char = '\0';
        const char *s;
        for (s = start; *s && s != lim; last_char = *s++) {
                if (*s == '"' && last_char != '\\')
                        break;
        }
        return s;
}

/*! \brief Pick out text in brackets from character string
	\return pointer to terminated stripped string
	\param tmp input string that will be modified
	Examples:

	"foo" <bar>	valid input, returns bar
	foo		returns the whole string
	< "foo ... >	returns the string between brackets
	< "foo...	bogus (missing closing bracket), returns the whole string
			XXX maybe should still skip the opening bracket
 */
static char *get_in_brackets(char *tmp)
{
	const char *parse = tmp;
	char *first_bracket;

	/*
	 * Skip any quoted text until we find the part in brackets.
         * On any error give up and return the full string.
         */
        while ( (first_bracket = strchr(parse, '<')) ) {
                char *first_quote = strchr(parse, '"');

		if (!first_quote || first_quote > first_bracket)
			break; /* no need to look at quoted part */
		/* the bracket is within quotes, so ignore it */
		parse = find_closing_quote(first_quote + 1, NULL);
		if (!*parse) { /* not found, return full string ? */
			/* XXX or be robust and return in-bracket part ? */
			ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
			break;
		}
		parse++;
	}
	if (first_bracket) {
		char *second_bracket = strchr(first_bracket + 1, '>');
		if (second_bracket) {
			*second_bracket = '\0';
			tmp = first_bracket + 1;
		} else {
			ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", 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 
	If the Asterisk system name is set in asterisk.conf, we will use
	that name and store that in the "regserver" field in the sippeers
	table to facilitate multi-server setups.
*/
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[INET_ADDRSTRLEN];
	char regseconds[20];

	char *sysname = ast_config_AST_SYSTEM_NAME;
	char *syslabel = NULL;

	time_t nowtime = time(NULL) + expirey;
	const char *fc = fullcontact ? "fullcontact" : NULL;
	
	snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);	/* Expiration time */
	ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
	snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
	
	if (ast_strlen_zero(sysname))	/* No system name, disable this */
		sysname = NULL;
	else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
		syslabel = "regserver";

	if (fc)
		ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
			"port", port, "regseconds", regseconds,
			"username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
	else
		ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
			"port", port, "regseconds", regseconds,
			"username", username, syslabel, sysname, NULL); /* note syslabel _can_ be 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, *context;

	/* XXX note that global_regcontext is both a global 'enable' flag and
	 * the name of the global regexten context, if not specified
	 * individually.
	 */
	if (ast_strlen_zero(global_regcontext))
		return;

	ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
	stringp = multi;
	while ((ext = strsep(&stringp, "&"))) {
		if ((context = strchr(ext, '@'))) {
			*context++ = '\0';	/* split ext@context */
			if (!ast_context_find(context)) {
				ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
				continue;
			}
		} else {
			context = global_regcontext;
		}
		if (onoff)
			ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
				 ast_strdup(peer->name), ast_free, "SIP");
		else
			ast_context_remove_extension(context, 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 = NULL;
	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 *newpeername, struct sockaddr_in *sin)
{
	struct sip_peer *peer;
	struct ast_variable *var = NULL;
	struct ast_variable *tmp;
	char ipaddr[INET_ADDRSTRLEN];

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

	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", ipaddr);
		ast_variables_destroy(var);
		return NULL;
	}

	/* Peer found in realtime, now build it in memory */
	peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
	if (!peer) {
		ast_variables_destroy(var);
		return 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 = ASTOBJ_CONTAINER_FIND(&userl, name);
	if (!u && realtime)
		u = realtime_user(name);
	return u;
}

/*! \brief Set nat mode on the various data sockets */
static void do_setnat(struct sip_pvt *p, int natflags)
{
	const char *mode = natflags ? "On" : "Off";

	if (p->rtp) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
		ast_rtp_setnat(p->rtp, natflags);
	}
	if (p->vrtp) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
		ast_rtp_setnat(p->vrtp, natflags);
	}
	if (p->udptl) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
		ast_udptl_setnat(p->udptl, natflags);
	}
}

/*! \brief Create address structure from peer reference.
 *  return -1 on error, 0 on success.
 */
static int create_addr_from_peer(struct sip_pvt *dialog, 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)))) {
		dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
		dialog->recv = dialog->sa;
	} else 
		return -1;

	ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
	dialog->capability = peer->capability;
	if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
		ast_rtp_destroy(dialog->vrtp);
		dialog->vrtp = NULL;
	}
	dialog->prefs = peer->prefs;
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
		dialog->t38.capability = global_t38_capability;
		if (dialog->udptl) {
			if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
				dialog->t38.capability |= T38FAX_UDP_EC_FEC;
			else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
				dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
			else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
				dialog->t38.capability |= T38FAX_UDP_EC_NONE;
			dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
			if (option_debug > 1)
				ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
		}
		dialog->t38.jointcapability = dialog->t38.capability;
	} else if (dialog->udptl) {
		ast_udptl_destroy(dialog->udptl);
		dialog->udptl = NULL;
	}
	do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );

	if (dialog->rtp) {
		ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
		ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
		ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
		ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
		ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
		/* Set Frame packetization */
		ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
		dialog->autoframing = peer->autoframing;
	}
	if (dialog->vrtp) {
		ast_rtp_setdtmf(dialog->vrtp, 0);
		ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
		ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
		ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
		ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
	}

	ast_string_field_set(dialog, peername, peer->username);
	ast_string_field_set(dialog, authname, peer->username);
	ast_string_field_set(dialog, username, peer->username);
	ast_string_field_set(dialog, peersecret, peer->secret);
	ast_string_field_set(dialog, peermd5secret, peer->md5secret);
	ast_string_field_set(dialog, tohost, peer->tohost);
	ast_string_field_set(dialog, fullcontact, peer->fullcontact);
	if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
		char *tmpcall;
		char *c;
		tmpcall = ast_strdupa(dialog->callid);
		c = strchr(tmpcall, '@');
		if (c) {
			*c = '\0';
			ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
		}
	}
	if (ast_strlen_zero(dialog->tohost))
		ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
	if (!ast_strlen_zero(peer->fromdomain))
		ast_string_field_set(dialog, fromdomain, peer->fromdomain);
	if (!ast_strlen_zero(peer->fromuser))
		ast_string_field_set(dialog, fromuser, peer->fromuser);
	dialog->maxtime = peer->maxms;
	dialog->callgroup = peer->callgroup;
	dialog->pickupgroup = peer->pickupgroup;
	dialog->allowtransfer = peer->allowtransfer;
	/* 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)
		dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
	if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
	    (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
		dialog->noncodeccapability |= AST_RTP_DTMF;
	else
		dialog->noncodeccapability &= ~AST_RTP_DTMF;
	ast_string_field_set(dialog, context, peer->context);
	dialog->rtptimeout = peer->rtptimeout;
	if (peer->call_limit)
		ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
	dialog->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;
	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';
	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) {
		int res = create_addr_from_peer(dialog, p);
		ASTOBJ_UNREF(p, sip_destroy_peer);
		return res;
	}
	hostn = peer;
	portno = port ? atoi(port) : STANDARD_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_log(LOG_WARNING, "No such host: %s\n", peer);
		return -1;
	}
	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);
	dialog->recv = dialog->sa;
	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) {
		/* XXX fails on possible deadlock */
		if (!ast_channel_trylock(p->owner)) {
			ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
			append_history(p, "Cong", "Auto-congesting (timer)");
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
			ast_channel_unlock(p->owner);
		}
	}
	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;
	struct varshead *headp;
	struct ast_var_t *current;
	const char *referer = NULL;   /* SIP refererer */	

	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;
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
			/* This is a transfered call */
			p->options->transfer = 1;
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
			/* This is the referer */
			referer = ast_var_value(current);
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
			/* We're replacing a call. */
			p->options->replaces = ast_var_value(current);
		} else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
			p->t38.state = T38_LOCAL_DIRECT;
			if (option_debug)
				ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
		}

	}
	
	res = 0;
	ast_set_flag(&p->flags[0], SIP_OUTGOING);

	if (p->options->transfer) {
		char buf[BUFSIZ/2];

		if (referer) {
			if (sipdebug && option_debug > 2)
				ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
			snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
		} else 
			snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
		ast_string_field_set(p, cid_name, buf);
	} 
	if (option_debug)
		ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);

	res = update_call_counter(p, INC_CALL_RINGING);
	if ( res != -1 ) {
		p->callingpres = ast->cid.cid_pres;
		p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);

		/* If there are no audio formats left to offer, punt */
		if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
			ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
			res = -1;
		} else {
			p->t38.jointcapability = p->t38.capability;
			if (option_debug > 1)
				ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
			transmit_invite(p, SIP_INVITE, 1, 2);
			p->invitestate = INV_CALLING;

			/* Initialize auto-congest time */
			p->initid = ast_sched_add(sched, p->maxtime ? (p->maxtime * 4) : SIP_TRANS_TIMEOUT, 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_pools(reg);
	regobjs--;
	free(reg);
	
}

/*! \brief Execute destruction 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 = 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->udptl)
		ast_udptl_destroy(p->udptl);
	if (p->refer)
		free(p->refer);
	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_channel_lock(p->owner);
		if (option_debug)
			ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
		p->owner->tech_pvt = NULL;
		if (lockowner)
			ast_channel_unlock(p->owner);
	}
	/* Clear history */
	if (p->history) {
		struct sip_history *hist;
		while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
			free(hist);
		free(p->history);
		p->history = NULL;
	}

	for (prev = NULL, cur = iflist; cur; prev = cur, cur = cur->next) {
		if (cur == p) {
			UNLINK(cur, iflist, prev);
			break;
		}
	}
	if (!cur) {
		ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
		return;
	} 

	/* 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_pools(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 = NULL, *call_limit = NULL, *inringing = NULL;
	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 only for incoming calls */
	if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1)))  {
		inuse = &u->inUse;
		call_limit = &u->call_limit;
		inringing = NULL;
	} else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1) ) ) { /* Try to find peer */
		inuse = &p->inUse;
		call_limit = &p->call_limit;
		inringing = &p->inRinging;
		ast_copy_string(name, fup->peername, sizeof(name));
	} 
	if (!p && !u) {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "%s is not a local device, 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 (inringing) {
			if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
				if (*inringing > 0)
					(*inringing)--;
				else
					ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", fup->peername);
				ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
			}
		}
		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_RINGING:
	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; 
			}
		}
		if (inringing && (event == INC_CALL_RINGING)) {
			if (!ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
				(*inringing)++;
				ast_set_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
			}
		}
		/* Continue */
		(*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;

	case DEC_CALL_RINGING:
		if (inringing) {
			if (ast_test_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING)) {
				if (*inringing > 0)
					(*inringing)--;
				else
					ast_log(LOG_WARNING, "Inringing for peer '%s' < 0?\n", p->name);
				ast_clear_flag(&fup->flags[1], SIP_PAGE2_INC_RINGING);
			}
		}
		break;

	default:
		ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
	}
	if (p) {
		ast_device_state_changed("SIP/%s", p->name);
		ASTOBJ_UNREF(p, sip_destroy_peer);
	} else /* u must be set */
		ASTOBJ_UNREF(u, sip_destroy_user);
	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_NO_ANSWER;
		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 const 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:
			if (option_debug)
				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;
	int needdestroy = 0;
	struct ast_channel *oldowner = ast;

	if (!p) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
		return 0;
	}

	if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
		if (option_debug >3)
			ast_log(LOG_DEBUG, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
		if (p->autokillid > -1)
			sip_cancel_destroy(p);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Really hang up next time */
		ast_clear_flag(&p->flags[0], SIP_NEEDDESTROY);
		p->owner->tech_pvt = NULL;
		p->owner = NULL;  /* Owner will be gone after we return, so take it away */
		return 0;
	}
	if (option_debug) {
		if (ast_test_flag(ast, AST_FLAG_ZOMBIE) && p->refer && option_debug)
         		ast_log(LOG_DEBUG, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
		else  {
			if (option_debug)
				ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
		}
	}
	if (option_debug && ast_test_flag(ast, AST_FLAG_ZOMBIE)) 
		ast_log(LOG_DEBUG, "Hanging up zombie call. Be scared.\n");

	ast_mutex_lock(&p->lock);
	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_RING || ast->_state == AST_STATE_RINGING || p->invitestate < INV_COMPLETED) {
		needcancel = TRUE;
		if (option_debug > 3)
			ast_log(LOG_DEBUG, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
	}

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

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

	ast_atomic_fetchadd_int(&usecnt, -1);
	ast_update_use_count();

	/* Do not destroy this pvt until we have timeout or
	   get an answer to the BYE or INVITE/CANCEL 
	   If we get no answer during retransmit period, drop the call anyway.
	   (Sorry, mother-in-law, you can't deny a hangup by sending
	   603 declined to BYE...)
	*/
	if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE))
		needdestroy = 1;	/* Set destroy flag at end of this function */
	else if (p->invitestate != INV_CALLING)
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

	/* 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);

				/* if we can't send right now, mark it pending */
				if (p->invitestate == INV_CALLING) {
					/* We can't send anything in CALLING state */
					ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
					/* Do we need a timer here if we don't hear from them at all? */
				} else {
					/* Send a new request: CANCEL */
					transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
					/* 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. */
					needdestroy = 0;
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				}
				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 */
				const 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) {
				char *audioqos = "";
				char *videoqos = "";
				if (p->rtp)
					audioqos = ast_rtp_get_quality(p->rtp);
				if (p->vrtp)
					videoqos = ast_rtp_get_quality(p->vrtp);
				/* Send a hangup */
				transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);

				/* Get RTCP quality before end of call */
				if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
					if (p->rtp)
						append_history(p, "RTCPaudio", "Quality:%s", audioqos);
					if (p->vrtp)
						append_history(p, "RTCPvideo", "Quality:%s", videoqos);
				}
				if (p->rtp && oldowner)
					pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
				if (p->vrtp && oldowner)
					pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
			} 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);	
				sip_cancel_destroy(p);
			}
		}
	}
	if (needdestroy)
		ast_set_flag(&p->flags[0], 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) {
		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);
		if (p->t38.state == T38_PEER_DIRECT) {
			p->t38.state = T38_ENABLED;
			if (option_debug > 1)
				ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
			res = transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
		} else 
			res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
	}
	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)) {
			char s1[512], s2[512], s3[512];
			ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
				frame->subclass, 
				ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
				ast->nativeformats & AST_FORMAT_AUDIO_MASK,
				ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
				ast->readformat,
				ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
				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);	
				}
				p->lastrtptx = time(NULL);
				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);	
				}
				p->lastrtptx = time(NULL);
				res = ast_rtp_write(p->vrtp, frame);
			}
			ast_mutex_unlock(&p->lock);
		}
		break;
	case AST_FRAME_IMAGE:
		return 0;
		break;
	case AST_FRAME_MODEM:
		if (p) {
			ast_mutex_lock(&p->lock);
			/* UDPTL requires two-way communication, so early media is not needed here.
				we simply forget the frames if we get modem frames before the bridge is up.
				Fax will re-transmit.
			*/
			if (p->udptl && ast->_state != AST_STATE_UP) 
				res = ast_udptl_write(p->udptl, frame);
			ast_mutex_unlock(&p->lock);
		}
		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)
{
	int ret = -1;
	struct sip_pvt *p;

	if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE) && option_debug)
		ast_log(LOG_DEBUG, "New channel is zombie\n");
	if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE) && option_debug)
		ast_log(LOG_DEBUG, "Old channel is zombie\n");

	if (!newchan || !newchan->tech_pvt) {
		if (!newchan)
			ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
		else
			ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
		return -1;
	}
	p = newchan->tech_pvt;

	if (!p) {
		ast_log(LOG_WARNING, "No pvt after masquerade. Strange things may happen\n");
		return -1;
	}

	ast_mutex_lock(&p->lock);
	append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
	append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
	if (p->owner != oldchan)
		ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
	else {
		p->owner = newchan;
		ret = 0;
	}
	if (option_debug > 2)
		ast_log(LOG_DEBUG, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);

	ast_mutex_unlock(&p->lock);
	return ret;
}

static int sip_senddigit_begin(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_INBAND:
		res = -1; /* Tell Asterisk to generate inband indications */
		break;
	case SIP_DTMF_RFC2833:
		if (p->rtp)
			ast_rtp_senddigit_begin(p->rtp, digit);
		break;
	default:
		break;
	}
	ast_mutex_unlock(&p->lock);

	return res;
}

/*! \brief Send DTMF character on SIP channel
	within one call, we're able to transmit in many methods simultaneously */
static int sip_senddigit_end(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_end(p->rtp, digit);
		break;
	case SIP_DTMF_INBAND:
		res = -1; /* Tell Asterisk to stop inband indications */
		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;

	if (dest == NULL)	/* functions below do not take a NULL */
		dest = "";
	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, const void *data, size_t datalen)
{
	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) {
			p->invitestate = INV_EARLY_MEDIA;
			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);
			p->invitestate = INV_TERMINATED;
			sip_alreadygone(p);
			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);
			p->invitestate = INV_TERMINATED;
			sip_alreadygone(p);
			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);
			p->invitestate = INV_PROCEEDING;  
			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)) {
			p->invitestate = INV_EARLY_MEDIA;
			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:
		ast_moh_start(ast, data, p->mohinterpret);
		break;
	case AST_CONTROL_UNHOLD:
		ast_moh_stop(ast);
		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); */
		} 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 ) for outbound channels
	and from handle_request_invite for inbound channels
	
*/
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;
	int needvideo = 0;
	{
		const char *my_name;    /* pick a good name */

		if (title)
			my_name = title;
		else if ( (my_name = strchr(i->fromdomain,':')) )
			my_name++;      /* skip ':' */
		else
			my_name = i->fromdomain;

		ast_mutex_unlock(&i->lock);
		/* Don't hold a sip pvt lock while we allocate a channel */
		tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "SIP/%s-%08x", my_name, (int)(long) i);

	}
	ast_mutex_lock(&i->lock);
	if (!tmp) {
		ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\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)	 	/* The joint capabilities of us and peer */
		what = i->jointcapability;
	else if (i->capability)		/* Our configured capability for this peer */
		what = i->capability;
	else
		what = global_capability;	/* Global codec support */

	/* Set the native formats for audio  and merge in video */
	tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
	if (option_debug > 2) {
		char buf[BUFSIZ];
		ast_log(LOG_DEBUG, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, tmp->nativeformats));
		ast_log(LOG_DEBUG, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->jointcapability));
		ast_log(LOG_DEBUG, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->capability));
		ast_log(LOG_DEBUG, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, BUFSIZ, ast_codec_choose(&i->prefs, what, 1)));
		if (i->prefcodec)
			ast_log(LOG_DEBUG, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, BUFSIZ, i->prefcodec));
	}

	/* XXX Why are we choosing a codec from the native formats?? */
	fmt = ast_best_codec(tmp->nativeformats);

	/* If we have a prefcodec setting, we have an inbound channel that set a 
	   preferred format for this call. Otherwise, we check the jointcapability
	   We also check for vrtp. If it's not there, we are not allowed do any video anyway.
	 */
	if (i->vrtp) {
		if (i->prefcodec)
			needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;	/* Outbound call */
 		else
			needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;	/* Inbound call */
	}

	if (option_debug > 2) {
		if (needvideo) 
			ast_log(LOG_DEBUG, "This channel can handle video! HOLLYWOOD next!\n");
		else
			ast_log(LOG_DEBUG, "This channel will not be able to handle video.\n");
	}



	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 (needvideo && i->vrtp) {
		tmp->fds[2] = ast_rtp_fd(i->vrtp);
		tmp->fds[3] = ast_rtcp_fd(i->vrtp);
	}
	if (i->udptl) {
		tmp->fds[5] = ast_udptl_fd(i->udptl);
	}
	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);
	i->owner = tmp;
	ast_atomic_fetchadd_int(&usecnt, 1);
	ast_update_use_count();
	ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
	ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));

	/* Don't use ast_set_callerid() here because it will
	 * generate an unnecessary NewCallerID event  */
	tmp->cid.cid_num = ast_strdup(i->cid_num);
	tmp->cid.cid_ani = ast_strdup(i->cid_num);
	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);
	if (i->rtp)
		ast_jb_configure(tmp, &global_jbconf);
	if (state != AST_STATE_DOWN && 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);

	if (!ast_test_flag(&i->flags[0], SIP_NO_HISTORY))
		append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);

	return tmp;
}

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

	return "";
}

/*! \brief Lookup 'name' in the SDP starting
 * at the 'start' line. Returns the matching line, and 'start'
 * is updated with the next line number.
 */
static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
{
	int len = strlen(name);

	while (*start < req->sdp_end) {
		const char *r = get_body_by_line(req->line[(*start)++], name, len);
		if (r[0] != '\0')
			return r;
	}

	return "";
}

/*! \brief Get a line from an SDP message body */
static const char *get_sdp(struct sip_request *req, const char *name) 
{
	int dummy = 0;

	return get_sdp_iterate(&dummy, req, name);
}

/*! \brief Get a specific line from the message body */
static char *get_body(struct sip_request *req, char *name) 
{
	int x;
	int len = strlen(name);
	char *r;

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

	return "";
}

/*! \brief Find compressed SIP alias */
static const char *find_alias(const char *name, const char *_default)
{
	/*! \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" },
		{ "Identity",            "y" },
		{ "Identity-Info",       "n" },
	};
	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 const char *__get_header(const 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 const char *get_header(const 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, int *faxdetect)
{
	/* 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;
	case 5:
		f = ast_udptl_read(p->udptl);	/* UDPTL for T.38 */
		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 (f && f->frametype == AST_FRAME_DTMF) {
					if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && f->subclass == 'f') {
						if (option_debug)
							ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
						*faxdetect = 1;
					} else if (option_debug) {
						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;
	int faxdetected = FALSE;

	ast_mutex_lock(&p->lock);
	fr = sip_rtp_read(ast, p, &faxdetected);
	p->lastrtprx = time(NULL);

	/* If we are NOT bridged to another channel, and we have detected fax tone we issue T38 re-invite to a peer */
	/* If we are bridged then it is the responsibility of the SIP device to issue T38 re-invite if it detects CNG or fax preamble */
	if (faxdetected && ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_UDPTL) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
		if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
			if (!p->pendinginvite) {
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "Sending reinvite on SIP (%s) for T.38 negotiation.\n",ast->name);
				p->t38.state = T38_LOCAL_REINVITE;
				transmit_reinvite_with_t38_sdp(p);
				if (option_debug > 1)
					ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, ast->name);
			}
		} else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
			if (option_debug > 2)
				ast_log(LOG_DEBUG, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
			ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
		}
	}

	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)
{
	long val[4];
	int x;

	for (x=0; x<4; x++)
		val[x] = ast_random();
	snprintf(buf, size, "%08lx%08lx%08lx%08lx", 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 buf[33];

	const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(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 buf[33];

	const char *host = S_OR(fromdomain, ast_inet_ntoa(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%08lx", ast_random());
}

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

	if (sin) {
		p->sa = *sin;
		if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
			p->ourip = __ourip;
	} else
		p->ourip = __ourip;

	/* Copy global flags to this PVT at setup. */
	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);

	ast_set2_flag(&p->flags[0], !recordhistory, SIP_NO_HISTORY);

	p->branch = ast_random();	
	make_our_tag(p->tag, sizeof(p->tag));
	p->ocseq = INITIAL_CSEQ;

	if (sip_methods[intended_method].need_rtp) {
		p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
		/* If the global videosupport flag is on, we always create a RTP interface for video */
		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 (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
			p->udptl = ast_udptl_new_with_bindaddr(sched, io, 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_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
		ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
		ast_rtp_settos(p->rtp, global_tos_audio);
		ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
		ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
		ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
		if (p->vrtp) {
			ast_rtp_settos(p->vrtp, global_tos_video);
			ast_rtp_setdtmf(p->vrtp, 0);
			ast_rtp_setdtmfcompensate(p->vrtp, 0);
			ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
			ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
			ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
		}
		if (p->udptl)
			ast_udptl_settos(p->udptl, global_tos_audio);
		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);
		p->recv = *sin;
		do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & 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, mohinterpret, default_mohinterpret);
	ast_string_field_set(p, mohsuggest, default_mohsuggest);
	p->capability = global_capability;
	p->allowtransfer = global_allowtransfer;
	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;
	if (p->udptl) {
		p->t38.capability = global_t38_capability;
		if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY)
			p->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
		else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_FEC)
			p->t38.capability |= T38FAX_UDP_EC_FEC;
		else if (ast_udptl_get_error_correction_scheme(p->udptl) == UDPTL_ERROR_CORRECTION_NONE)
			p->t38.capability |= T38FAX_UDP_EC_NONE;
		p->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
		p->t38.jointcapability = p->t38.capability;
	}
	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 = NULL;
	char *tag = "";	/* note, tag is never NULL */
	char totag[128];
	char fromtag[128];
	const char *callid = get_header(req, "Call-ID");
	const char *from = get_header(req, "From");
	const char *to = get_header(req, "To");
	const char *cseq = get_header(req, "Cseq");

	/* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
	/* get_header always returns non-NULL so we must use ast_strlen_zero() */
	if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
			ast_strlen_zero(from) || ast_strlen_zero(cseq))
		return NULL;	/* Invalid packet */

	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));

		tag = (req->method == SIP_RESPONSE) ? totag : 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);
	for (p = iflist; p; p = p->next) {
		/* 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;
		}
	}
	ast_mutex_unlock(&iflock);

	/* See if the method is capable of creating a dialog */
	if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
		if (intended_method == SIP_REFER) {
			/* We do support REFER, but not outside of a dialog yet */
			transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
		} else if (intended_method == SIP_NOTIFY) {
			/* We do not support out-of-dialog NOTIFY either,
		   	like voicemail notification, so cancel that early */
			transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
		} else {
			/* Ok, time to create a new SIP dialog object, a pvt */
			if ((p = sip_alloc(callid, sin, 1, intended_method)))  {
				/* Ok, we've created a dialog, let's go and process it */
				ast_mutex_lock(&p->lock);
			} else {
				/* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
					getting a dialog from sip_alloc. 
	
					Without a dialog we can't retransmit and handle ACKs and all that, but at least
					send an error message.
	
					Sorry, we apologize for the inconvienience
				*/
				transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
				if (option_debug > 3)
					ast_log(LOG_DEBUG, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
			}
		}
		return p;
	} else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
		/* A method we do not support, let's take it on the volley */
		transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
	} else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
		/* This is a request outside of a dialog that we don't know about 
			...never reply to an ACK!
		*/
		transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
	}
	/* We do not respond to responses for dialogs that we don't know about, we just drop
	   the session quickly */

	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;
	int portnum = 0;
	char username[256] = "";
	char *hostname=NULL, *secret=NULL, *authuser=NULL;
	char *porta=NULL;
	char *contact=NULL;

	if (!value)
		return -1;
	ast_copy_string(username, value, sizeof(username));
	/* First split around the last '@' then parse the two components. */
	hostname = strrchr(username, '@'); /* allow @ in the first part */
	if (hostname)
		*hostname++ = '\0';
	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;
	}
	/* split user[:secret[:authuser]] */
	secret = strchr(username, ':');
	if (secret) {
		*secret++ = '\0';
		authuser = strchr(secret, ':');
		if (authuser)
			*authuser++ = '\0';
	}
	/* split host[:port][/contact] */
	contact = strchr(hostname, '/');
	if (contact)
		*contact++ = '\0';
	if (ast_strlen_zero(contact))
		contact = "s";
	porta = strchr(hostname, ':');
	if (porta) {
		*porta++ = '\0';
		portnum = atoi(porta);
		if (portnum == 0) {
			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 = portnum;
	reg->callid_valid = FALSE;
	reg->ocseq = INITIAL_CSEQ;
	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 
	\note this function is used both on incoming and outgoing packets
*/
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 Determine whether a SIP message contains an SDP in its body
  \param req the SIP request to process
  \return 1 if SDP found, 0 if not found

  Also updates req->sdp_start and req->sdp_end to indicate where the SDP
  lives in the message body.
*/
static int find_sdp(struct sip_request *req)
{
	const char *content_type;
	const char *search;
	char *boundary;
	unsigned int x;

	content_type = get_header(req, "Content-Type");

	/* if the body contains only SDP, this is easy */
	if (!strcasecmp(content_type, "application/sdp")) {
		req->sdp_start = 0;
		req->sdp_end = req->lines;
		return 1;
	}

	/* if it's not multipart/mixed, there cannot be an SDP */
	if (strncasecmp(content_type, "multipart/mixed", 15))
		return 0;

	/* if there is no boundary marker, it's invalid */
	if (!(search = strcasestr(content_type, ";boundary=")))
		return 0;

	search += 10;

	if (ast_strlen_zero(search))
		return 0;

	/* make a duplicate of the string, with two extra characters
	   at the beginning */
	boundary = ast_strdupa(search - 2);
	boundary[0] = boundary[1] = '-';

	/* search for the boundary marker, but stop when there are not enough
	   lines left for it, the Content-Type header and at least one line of
	   body */
	for (x = 0; x < (req->lines - 2); x++) {
		if (!strncasecmp(req->line[x], boundary, strlen(boundary)) &&
		    !strcasecmp(req->line[x + 1], "Content-Type: application/sdp")) {
			x += 2;
			req->sdp_start = x;

			/* search for the end of the body part */
			for ( ; x < req->lines; x++) {
				if (!strncasecmp(req->line[x], boundary, strlen(boundary)))
					break;
			}
			req->sdp_end = x;
			return 1;
		}
	}

	return 0;
}

/*! \brief Process SIP SDP offer, select formats and activate RTP channels
	If offer is rejected, we will not change any properties of the call
 	Return 0 on success, a negative value on errors.
	Must be called after find_sdp().
*/
static int process_sdp(struct sip_pvt *p, struct sip_request *req)
{
	const char *m;		/* SDP media offer */
	const char *c;
	const char *a;
	char host[258];
	int len = -1;
	int portno = -1;		/*!< RTP Audio port number */
	int vportno = -1;		/*!< RTP Video port number */
	int udptlportno = -1;
	int peert38capability = 0;
	char s[256];
	int old = 0;

	/* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */	
	int peercapability = 0, peernoncodeccapability = 0;
	int vpeercapability = 0, vpeernoncodeccapability = 0;
	struct sockaddr_in sin;		/*!< media socket address */
	struct sockaddr_in vsin;	/*!< Video socket address */

	const char *codecs;
	struct hostent *hp;		/*!< RTP Audio host IP */
	struct hostent *vhp = NULL;	/*!< RTP video host IP */
	struct ast_hostent audiohp;
	struct ast_hostent videohp;
	int codec;
	int destiterator = 0;
	int iterator;
	int sendonly = 0;
	int numberofports;
	struct ast_channel *bridgepeer = NULL;
	struct ast_rtp *newaudiortp, *newvideortp;	/* Buffers for codec handling */
	int newjointcapability;				/* Negotiated capability */
	int newpeercapability;
	int newnoncodeccapability;
	int numberofmediastreams = 0;
	int debug = sip_debug_test_pvt(p);
		
	int found_rtpmap_codecs[32];
	int last_rtpmap_codec=0;

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

	/* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
	newaudiortp = alloca(ast_rtp_alloc_size());
	memset(newaudiortp, 0, ast_rtp_alloc_size());
	ast_rtp_new_init(newaudiortp);
	ast_rtp_pt_clear(newaudiortp);

	newvideortp = alloca(ast_rtp_alloc_size());
	memset(newvideortp, 0, ast_rtp_alloc_size());
	ast_rtp_new_init(newvideortp);
	ast_rtp_pt_clear(newvideortp);

	/* Update our last rtprx when we receive an SDP, too */
	p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */


	/* Try to find first media stream */
	m = get_sdp(req, "m");
	destiterator = req->sdp_start;
	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;
	}

	/* Check for IPv4 address (not IPv6 yet) */
	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, &audiohp);
	if (!hp) {
		ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
		return -1;
	}
	vhp = hp;	/* Copy to video address as default too */
	
	iterator = req->sdp_start;
	ast_set_flag(&p->flags[0], SIP_NOVIDEO);	


	/* Find media streams in this SDP offer */
	while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
		int x;
		int audio = FALSE;

		numberofports = 1;
		if ((sscanf(m, "audio %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
		    (sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
			audio = TRUE;
			numberofmediastreams++;
			/* Found audio stream in this media definition */
			portno = x;
			/* Scan through the RTP payload types specified in a "m=" line: */
			for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
				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(newaudiortp, codec);
			}
		} else if ((sscanf(m, "video %d/%d RTP/AVP %n", &x, &numberofports, &len) == 2) ||
		    (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
			/* If it is not audio - is it video ? */
			ast_clear_flag(&p->flags[0], SIP_NOVIDEO);	
			numberofmediastreams++;
			vportno = x;
			/* Scan through the RTP payload types specified in a "m=" line: */
			for (codecs = m + len; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
				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(newvideortp, codec);
			}
		} else if (p->udptl && ( (sscanf(m, "image %d udptl t38%n", &x, &len) == 1) || 
		 (sscanf(m, "image %d UDPTL t38%n", &x, &len) == 1) )) {
			if (debug)
				ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
			udptlportno = x;
			numberofmediastreams++;
			
			if (p->owner && p->lastinvite) {
				p->t38.state = T38_PEER_REINVITE; /* T38 Offered in re-invite from remote party */
				if (option_debug > 1)
					ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>" );
			} else {
				p->t38.state = T38_PEER_DIRECT; /* T38 Offered directly from peer in first invite */
				if (option_debug > 1)
					ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
			}
		} else 
			ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
		if (numberofports > 1)
			ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
		

		/* Check for Media-description-level-address for audio */
		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 */
				if (audio) {
					if ( !(hp = ast_gethostbyname(host, &audiohp)))
						ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
				} else if (!(vhp = ast_gethostbyname(host, &videohp)))
					ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
			}

		}
	}
	if (portno == -1 && vportno == -1 && udptlportno == -1)
		/* No acceptable offer found in SDP  - we have no ports */
		/* Do not change RTP or VRTP if this is a re-invite */
		return -2;

	if (numberofmediastreams > 2)
		/* We have too many fax, audio and/or video media streams, fail this offer */
		return -3;

	/* RTP addresses and ports for audio and video */
	sin.sin_family = AF_INET;
	vsin.sin_family = AF_INET;
	memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
	if (vhp)
		memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));

	/* Setup UDPTL port number */
	if (p->udptl) {
		if (udptlportno > 0) {
			sin.sin_port = htons(udptlportno);
			ast_udptl_set_peer(p->udptl, &sin);
			if (debug)
				ast_log(LOG_DEBUG,"Peer T.38 UDPTL is at port %s:%d\n",ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
		} else {
			ast_udptl_stop(p->udptl);
			if (debug)
				ast_log(LOG_DEBUG, "Peer doesn't provide T.38 UDPTL\n");
		}
	}

		
	if (p->rtp) {
		if (portno > 0) {
			sin.sin_port = htons(portno);
			ast_rtp_set_peer(p->rtp, &sin);
			if (debug)
				ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
		} else {
			if (udptlportno > 0) {
				if (debug)
					ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
			} else {
				ast_rtp_stop(p->rtp);
				if (debug)
					ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
			}
		}
	}
	/* Setup video port number */
	if (vportno != -1)
		vsin.sin_port = htons(vportno);

	/* Next, scan through each "a=rtpmap:" line, noting each
	 * specified RTP payload type (with corresponding MIME subtype):
	 */
	/* XXX This needs to be done per media stream, since it's media stream specific */
	iterator = req->sdp_start;
	while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
		char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
		if (option_debug > 1) {
			int breakout = FALSE;
		
			/* If we're debugging, check for unsupported sdp options */
			if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
				if (debug)
					ast_verbose("Got unsupported a:rtcp in SDP offer \n");
				breakout = TRUE;
			} else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
				/* Format parameters:  Not supported */
				/* Note: This is used for codec parameters, like bitrate for
					G722 and video formats for H263 and H264 
					See RFC2327 for an example */
				if (debug)
					ast_verbose("Got unsupported a:fmtp in SDP offer \n");
				breakout = TRUE;
			} else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
				/* Video stuff:  Not supported */
				if (debug)
					ast_verbose("Got unsupported a:framerate in SDP offer \n");
				breakout = TRUE;
			} else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
				/* Video stuff:  Not supported */
				if (debug)
					ast_verbose("Got unsupported a:maxprate in SDP offer \n");
				breakout = TRUE;
			} else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
				/* SRTP stuff, not yet supported */
				if (debug)
					ast_verbose("Got unsupported a:crypto in SDP offer \n");
				breakout = TRUE;
			}
			if (breakout)	/* We have a match, skip to next header */
				continue;
		}
		if (!strcasecmp(a, "sendonly")) {
			sendonly = 1;
			continue;
		} else if (!strcasecmp(a, "inactive")) {
			sendonly = 2;
			continue;
		}  else if (!strcasecmp(a, "sendrecv")) {
			sendonly = 0;
			continue;
		} else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
			char *tmp = strrchr(a, ':');
			long int framing = 0;
			if (tmp) {
				tmp++;
				framing = strtol(tmp, NULL, 10);
				if (framing == LONG_MIN || framing == LONG_MAX) {
					framing = 0;
					if (option_debug)
						ast_log(LOG_DEBUG, "Can't read framing from SDP: %s\n", a);
				}
			}
			if (framing && last_rtpmap_codec) {
				if (p->autoframing) {
					struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
					int codec_n;
					int format = 0;
					for (codec_n = 0; codec_n < last_rtpmap_codec; codec_n++) {
						format = ast_rtp_codec_getformat(found_rtpmap_codecs[codec_n]);
						if (!format)	/* non-codec or not found */
							continue;
						if (option_debug)
							ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
						ast_codec_pref_setsize(pref, format, framing);
					}
					ast_rtp_codec_setpref(p->rtp, pref);
				}
			}
			memset(&found_rtpmap_codecs, 0, sizeof(found_rtpmap_codecs));
			last_rtpmap_codec = 0;
			continue;
		} else if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) == 2) {
			/* We have a rtpmap to handle */
			if (debug)
				ast_verbose("Found description format %s for ID %d\n", mimeSubtype, codec);
			found_rtpmap_codecs[last_rtpmap_codec] = codec;
			last_rtpmap_codec++;

			/* Note: should really look at the 'freq' and '#chans' params too */
			ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
					ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0);
			if (p->vrtp)
				ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0);
		}
	}
	
	if (udptlportno != -1) {
		int found = 0, x;
		
		old = 0;
		
		/* Scan trough the a= lines for T38 attributes and set apropriate fileds */
		iterator = req->sdp_start;
		while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
			if ((sscanf(a, "T38FaxMaxBuffer:%d", &x) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "MaxBufferSize:%d\n",x);
			} else if ((sscanf(a, "T38MaxBitRate:%d", &x) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG,"T38MaxBitRate: %d\n",x);
				switch (x) {
				case 14400:
					peert38capability |= T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
					break;
				case 12000:
					peert38capability |= T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
					break;
				case 9600:
					peert38capability |= T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
					break;
				case 7200:
					peert38capability |= T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400;
					break;
				case 4800:
					peert38capability |= T38FAX_RATE_4800 | T38FAX_RATE_2400;
					break;
				case 2400:
					peert38capability |= T38FAX_RATE_2400;
					break;
				}
			} else if ((sscanf(a, "T38FaxVersion:%d", &x) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "FaxVersion: %d\n",x);
				if (x == 0)
					peert38capability |= T38FAX_VERSION_0;
				else if (x == 1)
					peert38capability |= T38FAX_VERSION_1;
			} else if ((sscanf(a, "T38FaxMaxDatagram:%d", &x) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "FaxMaxDatagram: %d\n",x);
				ast_udptl_set_far_max_datagram(p->udptl, x);
				ast_udptl_set_local_max_datagram(p->udptl, x);
			} else if ((sscanf(a, "T38FaxFillBitRemoval:%d", &x) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "FillBitRemoval: %d\n",x);
				if (x == 1)
					peert38capability |= T38FAX_FILL_BIT_REMOVAL;
			} else if ((sscanf(a, "T38FaxTranscodingMMR:%d", &x) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "Transcoding MMR: %d\n",x);
				if (x == 1)
					peert38capability |= T38FAX_TRANSCODING_MMR;
			}
			if ((sscanf(a, "T38FaxTranscodingJBIG:%d", &x) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "Transcoding JBIG: %d\n",x);
				if (x == 1)
					peert38capability |= T38FAX_TRANSCODING_JBIG;
			} else if ((sscanf(a, "T38FaxRateManagement:%s", s) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "RateMangement: %s\n", s);
				if (!strcasecmp(s, "localTCF"))
					peert38capability |= T38FAX_RATE_MANAGEMENT_LOCAL_TCF;
				else if (!strcasecmp(s, "transferredTCF"))
					peert38capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
			} else if ((sscanf(a, "T38FaxUdpEC:%s", s) == 1)) {
				found = 1;
				if (option_debug > 2)
					ast_log(LOG_DEBUG, "UDP EC: %s\n", s);
				if (!strcasecmp(s, "t38UDPRedundancy")) {
					peert38capability |= T38FAX_UDP_EC_REDUNDANCY;
					ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
				} else if (!strcasecmp(s, "t38UDPFEC")) {
					peert38capability |= T38FAX_UDP_EC_FEC;
					ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
				} else {
					peert38capability |= T38FAX_UDP_EC_NONE;
					ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
				}
			}
		}
		if (found) { /* Some cisco equipment returns nothing beside c= and m= lines in 200 OK T38 SDP */
			p->t38.peercapability = peert38capability;
			p->t38.jointcapability = (peert38capability & 255); /* Put everything beside supported speeds settings */
			peert38capability &= (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400);
			p->t38.jointcapability |= (peert38capability & p->t38.capability); /* Put the lower of our's and peer's speed */
		}
		if (debug)
			ast_log(LOG_DEBUG, "Our T38 capability = (%d), peer T38 capability (%d), joint T38 capability (%d)\n",
				p->t38.capability,
				p->t38.peercapability,
				p->t38.jointcapability);
	} else {
		p->t38.state = T38_DISABLED;
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
	}

	/* Now gather all of the codecs that we are asked for: */
	ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
	ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);

	newjointcapability = p->capability & (peercapability | vpeercapability);
	newpeercapability = (peercapability | vpeercapability);
	newnoncodeccapability = noncodeccapability & peernoncodeccapability;
		
		
	if (debug) {
		/* shame on whoever coded this.... */
		char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ], s4[BUFSIZ];

		ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
			    ast_getformatname_multiple(s1, BUFSIZ, p->capability),
			    ast_getformatname_multiple(s2, BUFSIZ, newpeercapability),
			    ast_getformatname_multiple(s3, BUFSIZ, vpeercapability),
			    ast_getformatname_multiple(s4, BUFSIZ, newjointcapability));

		ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
			    ast_rtp_lookup_mime_multiple(s1, BUFSIZ, noncodeccapability, 0, 0),
			    ast_rtp_lookup_mime_multiple(s2, BUFSIZ, peernoncodeccapability, 0, 0),
			    ast_rtp_lookup_mime_multiple(s3, BUFSIZ, newnoncodeccapability, 0, 0));
	}
	if (!newjointcapability) {
		/* If T.38 was not negotiated either, totally bail out... */
		if (!p->t38.jointcapability) {
			ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
			/* Do NOT Change current setting */
			return -1;
		} else {
			if (option_debug > 2)
				ast_log(LOG_DEBUG, "Have T.38 but no audio codecs, accepting offer anyway\n");
			return 0;
		}
	}

	/* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
		they are acceptable */
	p->jointcapability = newjointcapability;	/* Our joint codec profile for this call */
	p->peercapability = newpeercapability;		/* The other sides capability in latest offer */
	p->noncodeccapability = newnoncodeccapability;	/* DTMF capabilities */

	ast_rtp_pt_copy(p->rtp, newaudiortp);
	if (p->vrtp)
		ast_rtp_pt_copy(p->vrtp, newvideortp);

	if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
		ast_clear_flag(&p->flags[0], SIP_DTMF);
		if (newnoncodeccapability & AST_RTP_DTMF) {
			/* XXX Would it be reasonable to drop the DSP at this point? XXX */
			ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
		} else {
			ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
		}
	}

	/* Setup audio port number */
	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(sin.sin_addr), ntohs(sin.sin_port));
	}

	/* Setup video port number */
	if (p->vrtp && vsin.sin_port) {
		ast_rtp_set_peer(p->vrtp, &vsin);
		if (debug) 
			ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
	}

	/* Ok, we're going with this offer */
	if (option_debug > 1) {
		char buf[BUFSIZ];
		ast_log(LOG_DEBUG, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, BUFSIZ, p->jointcapability));
	}

	if (!p->owner) 	/* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
		return 0;

	if (option_debug > 3)
		ast_log(LOG_DEBUG, "We have an owner, now see if we need to change this call\n");

	if (!(p->owner->nativeformats & p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
		if (debug) {
			char s1[BUFSIZ], s2[BUFSIZ];
			ast_log(LOG_DEBUG, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
				ast_getformatname_multiple(s1, BUFSIZ, p->jointcapability),
				ast_getformatname_multiple(s2, BUFSIZ, p->owner->nativeformats));
		}
		p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability);
		ast_set_read_format(p->owner, p->owner->readformat);
		ast_set_write_format(p->owner, p->owner->writeformat);
	}
	
	/* Turn on/off music on hold if we are holding/unholding */
	if ((bridgepeer = ast_bridged_channel(p->owner))) {
		if (sin.sin_addr.s_addr && !sendonly) {
			ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
			/* Activate a re-invite */
			ast_queue_frame(p->owner, &ast_null_frame);
		} else if (!sin.sin_addr.s_addr || sendonly) {
			ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
					       S_OR(p->mohsuggest, NULL),
					       !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
			if (sendonly)
				ast_rtp_stop(p->rtp);
			/* RTCP needs to go ahead, even if we're on hold!!! */
			/* Activate a re-invite */
			ast_queue_frame(p->owner, &ast_null_frame);
		}
	}

	/* Manager Hold and Unhold events must be generated, if necessary */
	if (sin.sin_addr.s_addr && !sendonly) {
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
			append_history(p, "Unhold", "%s", req->data);
			if (global_callevents)
				manager_event(EVENT_FLAG_CALL, "Unhold",
					"Channel: %s\r\n"
					"Uniqueid: %s\r\n",
					p->owner->name, 
					p->owner->uniqueid);
			if (global_notifyhold)
				sip_peer_hold(p, 0);
		} 
		ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);	/* Clear both flags */
	} else if (!sin.sin_addr.s_addr || sendonly ) {
		/* No address for RTP, we're on hold */
		append_history(p, "Hold", "%s", req->data);

		if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
			manager_event(EVENT_FLAG_CALL, "Hold",
				"Channel: %s\r\n"
				"Uniqueid: %s\r\n",
				p->owner->name, 
				p->owner->uniqueid);
		}
		if (sendonly == 1)	/* One directional hold (sendonly/recvonly) */
			ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
		else if (sendonly == 2)	/* Inactive stream */
			ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
		if (global_notifyhold)
			sip_peer_hold(p, 1);
	}
	
	return 0;
}


/*! \brief Add header to SIP message */
static int add_header(struct sip_request *req, const char *var, const char *value)
{
	int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */

	if (req->headers == SIP_MAX_HEADERS) {
		ast_log(LOG_WARNING, "Out of SIP header space\n");
		return -1;
	}

	if (req->lines) {
		ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
		return -1;
	}

	if (maxlen <= 0) {
		ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
		return -1;
	}

	req->header[req->headers] = req->data + req->len;

	if (compactheaders)
		var = find_alias(var, var);

	snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
	req->len += strlen(req->header[req->headers]);
	req->headers++;
	if (req->headers < SIP_MAX_HEADERS)
		req->headers++;
	else
		ast_log(LOG_WARNING, "Out of SIP header space... Will generate broken SIP message\n");

	return 0;	
}

/*! \brief Add 'Content-Length' header to SIP message */
static int add_header_contentLength(struct sip_request *req, int len)
{
	char clen[10];

	snprintf(clen, sizeof(clen), "%d", len);
	return add_header(req, "Content-Length", clen);
}

/*! \brief Add content (not header) to SIP message */
static int add_line(struct sip_request *req, const char *line)
{
	if (req->lines == SIP_MAX_LINES)  {
		ast_log(LOG_WARNING, "Out of SIP line space\n");
		return -1;
	}
	if (!req->lines) {
		/* Add extra empty return */
		snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
		req->len += strlen(req->data + req->len);
	}
	if (req->len >= sizeof(req->data) - 4) {
		ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
		return -1;
	}
	req->line[req->lines] = req->data + req->len;
	snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
	req->len += strlen(req->line[req->lines]);
	req->lines++;
	return 0;	
}

/*! \brief Copy one header field from one request to another */
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
{
	const char *tmp = get_header(orig, field);

	if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
		return add_header(req, field, tmp);
	ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
	return -1;
}

/*! \brief Copy all headers from one request to another */
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
{
	int start = 0;
	int copied = 0;
	for (;;) {
		const char *tmp = __get_header(orig, field, &start);

		if (ast_strlen_zero(tmp))
			break;
		/* Add what we're responding to */
		add_header(req, field, tmp);
		copied++;
	}
	return copied ? 0 : -1;
}

/*! \brief Copy SIP VIA Headers from the request to the response
\note	If the client indicates that it wishes to know the port we received from,
	it adds ;rport without an argument to the topmost via header. We need to
	add the port number (from our point of view) to that parameter.
	We always add ;received=<ip address> to the topmost via header.
	Received: RFC 3261, rport RFC 3581 */
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
{
	int copied = 0;
	int start = 0;

	for (;;) {
		char new[256];
		const char *oh = __get_header(orig, field, &start);

		if (ast_strlen_zero(oh))
			break;

		if (!copied) {	/* Only check for empty rport in topmost via header */
			char *rport;

			/* Find ;rport;  (empty request) */
			rport = strstr(oh, ";rport");
			if (rport && *(rport+6) == '=') 
				rport = NULL;		/* We already have a parameter to rport */

			/* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
			if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
				/* We need to add received port - rport */
				char tmp[256], *end;

				ast_copy_string(tmp, oh, sizeof(tmp));

				rport = strstr(tmp, ";rport");

				if (rport) {
					end = strchr(rport + 1, ';');
					if (end)
						memmove(rport, end, strlen(end) + 1);
					else
						*rport = '\0';
				}

				/* Add rport to first VIA header if requested */
				snprintf(new, sizeof(new), "%s;received=%s;rport=%d",
					tmp, ast_inet_ntoa(p->recv.sin_addr),
					ntohs(p->recv.sin_port));
			} else {
				/* We should *always* add a received to the topmost via */
				snprintf(new, sizeof(new), "%s;received=%s",
					oh, ast_inet_ntoa(p->recv.sin_addr));
			}
			oh = new;	/* the header to copy */
		}  /* else add the following via headers untouched */
		add_header(req, field, oh);
		copied++;
	}
	if (!copied) {
		ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
		return -1;
	}
	return 0;
}

/*! \brief Add route header into request per learned route */
static void add_route(struct sip_request *req, struct sip_route *route)
{
	char r[BUFSIZ*2], *p;
	int n, rem = sizeof(r);

	if (!route)
		return;

	p = r;
	for (;route ; route = route->next) {
		n = strlen(route->hop);
		if (rem < n+3) /* we need room for ",<route>" */
			break;
		if (p != r) {	/* add a separator after fist route */
			*p++ = ',';
			--rem;
		}
		*p++ = '<';
		ast_copy_string(p, route->hop, rem); /* cannot fail */
		p += n;
		*p++ = '>';
		rem -= (n+2);
	}
	*p = '\0';
	add_header(req, "Route", r);
}

/*! \brief Set destination from SIP URI */
static void set_destination(struct sip_pvt *p, char *uri)
{
	char *h, *maddr, hostname[256];
	int port, hn;
	struct hostent *hp;
	struct ast_hostent ahp;
	int debug=sip_debug_test_pvt(p);

	/* Parse uri to h (host) and port - uri is already just the part inside the <> */
	/* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */

	if (debug)
		ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);

	/* Find and parse hostname */
	h = strchr(uri, '@');
	if (h)
		++h;
	else {
		h = uri;
		if (strncmp(h, "sip:", 4) == 0)
			h += 4;
		else if (strncmp(h, "sips:", 5) == 0)
			h += 5;
	}
	hn = strcspn(h, ":;>") + 1;
	if (hn > sizeof(hostname)) 
		hn = sizeof(hostname);
	ast_copy_string(hostname, h, hn);
	/* XXX bug here if string has been trimmed to sizeof(hostname) */
	h += hn - 1;

	/* Is "port" present? if not default to STANDARD_SIP_PORT */
	if (*h == ':') {
		/* Parse port */
		++h;
		port = strtol(h, &h, 10);
	}
	else
		port = STANDARD_SIP_PORT;

	/* Got the hostname:port - but maybe there's a "maddr=" to override address? */
	maddr = strstr(h, "maddr=");
	if (maddr) {
		maddr += 6;
		hn = strspn(maddr, "0123456789.") + 1;
		if (hn > sizeof(hostname))
			hn = sizeof(hostname);
		ast_copy_string(hostname, maddr, hn);
	}
	
	hp = ast_gethostbyname(hostname, &ahp);
	if (hp == NULL)  {
		ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
		return;
	}
	p->sa.sin_family = AF_INET;
	memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
	p->sa.sin_port = htons(port);
	if (debug)
		ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
}

/*! \brief Initialize SIP response, based on SIP request */
static int init_resp(struct sip_request *resp, const char *msg)
{
	/* Initialize a response */
	memset(resp, 0, sizeof(*resp));
	resp->method = SIP_RESPONSE;
	resp->header[0] = resp->data;
	snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
	resp->len = strlen(resp->header[0]);
	resp->headers++;
	return 0;
}

/*! \brief Initialize SIP request */
static int init_req(struct sip_request *req, int sipmethod, const char *recip)
{
	/* Initialize a request */
	memset(req, 0, sizeof(*req));
        req->method = sipmethod;
	req->header[0] = req->data;
	snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
	req->len = strlen(req->header[0]);
	req->headers++;
	return 0;
}


/*! \brief Prepare SIP response packet */
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
{
	char newto[256];
	const char *ot;

	init_resp(resp, msg);
	copy_via_headers(p, resp, req, "Via");
	if (msg[0] == '2')
		copy_all_header(resp, req, "Record-Route");
	copy_header(resp, req, "From");
	ot = get_header(req, "To");
	if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
		/* Add the proper tag if we don't have it already.  If they have specified
		   their tag, use it.  Otherwise, use our own tag */
		if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
			snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
		else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
			snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
		else
			ast_copy_string(newto, ot, sizeof(newto));
		ot = newto;
	}
	add_header(resp, "To", ot);
	copy_header(resp, req, "Call-ID");
	copy_header(resp, req, "CSeq");
	add_header(resp, "User-Agent", global_useragent);
	add_header(resp, "Allow", ALLOWED_METHODS);
	add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
	if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
		/* For registration responses, we also need expiry and
		   contact info */
		char tmp[256];

		snprintf(tmp, sizeof(tmp), "%d", p->expiry);
		add_header(resp, "Expires", tmp);
		if (p->expiry) {	/* Only add contact if we have an expiry time */
			char contact[256];
			snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
			add_header(resp, "Contact", contact);	/* Not when we unregister */
		}
	} else if (msg[0] != '4' && p->our_contact[0]) {
		add_header(resp, "Contact", p->our_contact);
	}
	return 0;
}

/*! \brief Initialize a SIP request message (not the initial one in a dialog) */
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
{
	struct sip_request *orig = &p->initreq;
	char stripped[80];
	char tmp[80];
	char newto[256];
	const char *c;
	const char *ot, *of;
	int is_strict = FALSE;		/*!< Strict routing flag */

	memset(req, 0, sizeof(struct sip_request));
	
	snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
	
	if (!seqno) {
		p->ocseq++;
		seqno = p->ocseq;
	}
	
	if (newbranch) {
		p->branch ^= ast_random();
		build_via(p);
	}

	/* Check for strict or loose router */
	if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop,";lr") == NULL) {
		is_strict = TRUE;
		if (sipdebug)
			ast_log(LOG_DEBUG, "Strict routing enforced for session %s\n", p->callid);
	}

	if (sipmethod == SIP_CANCEL)
		c = p->initreq.rlPart2;	/* Use original URI */
	else if (sipmethod == SIP_ACK) {
		/* Use URI from Contact: in 200 OK (if INVITE) 
		(we only have the contacturi on INVITEs) */
		if (!ast_strlen_zero(p->okcontacturi))
			c = is_strict ? p->route->hop : p->okcontacturi;
 		else
 			c = p->initreq.rlPart2;
	} else if (!ast_strlen_zero(p->okcontacturi)) 
		c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
	else if (!ast_strlen_zero(p->uri)) 
		c = p->uri;
	else {
		char *n;
		/* We have no URI, use To: or From:  header as URI (depending on direction) */
		ast_copy_string(stripped, get_header(orig, (ast_test_flag(&p->flags[0], SIP_OUTGOING)) ? "To" : "From"),
				sizeof(stripped));
		n = get_in_brackets(stripped);
		c = strsep(&n, ";");	/* trim ; and beyond */
	}	
	init_req(req, sipmethod, c);

	snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);

	add_header(req, "Via", p->via);
	if (p->route) {
		set_destination(p, p->route->hop);
		add_route(req, is_strict ? p->route->next : p->route);
	}

	ot = get_header(orig, "To");
	of = get_header(orig, "From");

	/* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
	   as our original request, including tag (or presumably lack thereof) */
	if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
		/* Add the proper tag if we don't have it already.  If they have specified
		   their tag, use it.  Otherwise, use our own tag */
		if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_strlen_zero(p->theirtag))
			snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
		else if (!ast_test_flag(&p->flags[0], SIP_OUTGOING))
			snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
		else
			snprintf(newto, sizeof(newto), "%s", ot);
		ot = newto;
	}

	if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
		add_header(req, "From", of);
		add_header(req, "To", ot);
	} else {
		add_header(req, "From", ot);
		add_header(req, "To", of);
	}
	/* Do not add Contact for MESSAGE, BYE and Cancel requests */
	if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
		add_header(req, "Contact", p->our_contact);

	copy_header(req, orig, "Call-ID");
	add_header(req, "CSeq", tmp);

	add_header(req, "User-Agent", global_useragent);
	add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);

	if (!ast_strlen_zero(p->rpid))
		add_header(req, "Remote-Party-ID", p->rpid);

	return 0;
}

/*! \brief Base transmit response function */
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
{
	struct sip_request resp;
	int seqno = 0;

	if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
		ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
		return -1;
	}
	respprep(&resp, p, msg, req);
	add_header_contentLength(&resp, 0);
	/* If we are cancelling an incoming invite for some reason, add information
		about the reason why we are doing this in clear text */
	if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
		char buf[10];

		add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
		snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
		add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
	}
	return send_response(p, &resp, reliable, seqno);
}

static void temp_pvt_cleanup(void *data)
{
	struct sip_pvt *p = data;

	ast_string_field_free_pools(p);

	free(data);
}

/*! \brief Transmit response, no retransmits, using a temporary pvt structure */
static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
{
	struct sip_pvt *p = NULL;

	if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
		ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
		return -1;
	}

	/* if the structure was just allocated, initialize it */
	if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
		ast_set_flag(&p->flags[0], SIP_NO_HISTORY);
		if (ast_string_field_init(p, 512))
			return -1;
	}

	/* Initialize the bare minimum */
	p->method = intended_method;

	if (sin) {
		p->sa = *sin;
		if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
			p->ourip = __ourip;
	} else
		p->ourip = __ourip;

	p->branch = ast_random();
	make_our_tag(p->tag, sizeof(p->tag));
	p->ocseq = INITIAL_CSEQ;

	if (useglobal_nat && sin) {
		ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
		p->recv = *sin;
		do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
	}

	ast_string_field_set(p, fromdomain, default_fromdomain);
	build_via(p);
	ast_string_field_set(p, callid, callid);

	/* Use this temporary pvt structure to send the message */
	__transmit_response(p, msg, req, XMIT_UNRELIABLE);

	/* Free the string fields, but not the pool space */
	ast_string_field_free_all(p);

	return 0;
}

/*! \brief Transmit response, no retransmits */
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
{
	return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
}

/*! \brief Transmit response, no retransmits */
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
{
	struct sip_request resp;
	respprep(&resp, p, msg, req);
	append_date(&resp);
	add_header(&resp, "Unsupported", unsupported);
	return send_response(p, &resp, XMIT_UNRELIABLE, 0);
}

/*! \brief Transmit response, Make sure you get an ACK
	This is only used for responses to INVITEs, where we need to make sure we get an ACK
*/
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
{
	return __transmit_response(p, msg, req, XMIT_CRITICAL);
}

/*! \brief Append date to SIP message */
static void append_date(struct sip_request *req)
{
	char tmpdat[256];
	struct tm tm;
	time_t t = time(NULL);

	gmtime_r(&t, &tm);
	strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
	add_header(req, "Date", tmpdat);
}

/*! \brief Append date and content length before transmitting response */
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
{
	struct sip_request resp;
	respprep(&resp, p, msg, req);
	append_date(&resp);
	add_header_contentLength(&resp, 0);
	return send_response(p, &resp, XMIT_UNRELIABLE, 0);
}

/*! \brief Append Accept header, content length before transmitting response */
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
{
	struct sip_request resp;
	respprep(&resp, p, msg, req);
	add_header(&resp, "Accept", "application/sdp");
	add_header_contentLength(&resp, 0);
	return send_response(p, &resp, reliable, 0);
}

/*! \brief Respond with authorization request */
static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
{
	struct sip_request resp;
	char tmp[512];
	int seqno = 0;

	if (reliable && (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1)) {
		ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
		return -1;
	}
	/* Stale means that they sent us correct authentication, but 
	   based it on an old challenge (nonce) */
	snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
	respprep(&resp, p, msg, req);
	add_header(&resp, header, tmp);
	add_header_contentLength(&resp, 0);
	append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
	return send_response(p, &resp, reliable, seqno);
}

/*! \brief Add text body to SIP message */
static int add_text(struct sip_request *req, const char *text)
{
	/* XXX Convert \n's to \r\n's XXX */
	add_header(req, "Content-Type", "text/plain");
	add_header_contentLength(req, strlen(text));
	add_line(req, text);
	return 0;
}

/*! \brief Add DTMF INFO tone to sip message */
/* Always adds default duration 250 ms, regardless of what came in over the line */
static int add_digit(struct sip_request *req, char digit)
{
	char tmp[256];

	snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
	add_header(req, "Content-Type", "application/dtmf-relay");
	add_header_contentLength(req, strlen(tmp));
	add_line(req, tmp);
	return 0;
}

/*! \brief add XML encoded media control with update 
	\note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
static int add_vidupdate(struct sip_request *req)
{
	const char *xml_is_a_huge_waste_of_space =
		"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
		" <media_control>\r\n"
		"  <vc_primitive>\r\n"
		"   <to_encoder>\r\n"
		"    <picture_fast_update>\r\n"
		"    </picture_fast_update>\r\n"
		"   </to_encoder>\r\n"
		"  </vc_primitive>\r\n"
		" </media_control>\r\n";
	add_header(req, "Content-Type", "application/media_control+xml");
	add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
	add_line(req, xml_is_a_huge_waste_of_space);
	return 0;
}

/*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
			     char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
			     int debug, int *min_packet_size)
{
	int rtp_code;
	struct ast_format_list fmt;


	if (debug)
		ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
	if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
		return;

	if (p->rtp) {
		struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
		fmt = ast_codec_pref_getsize(pref, codec);
	} else /* I dont see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
		return;
	ast_build_string(m_buf, m_size, " %d", rtp_code);
	ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
			 ast_rtp_lookup_mime_subtype(1, codec,
						     ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
			 sample_rate);
	if (codec == AST_FORMAT_G729A) {
		/* Indicate that we don't support VAD (G.729 annex B) */
		ast_build_string(a_buf, a_size, "a=fmtp:%d annexb=no\r\n", rtp_code);
	} else if (codec == AST_FORMAT_ILBC) {
		/* Add information about us using only 20/30 ms packetization */
		ast_build_string(a_buf, a_size, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
	}

	if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
		*min_packet_size = fmt.cur_ms;

	/* Our first codec packetization processed cannot be less than zero */
	if ((*min_packet_size) == 0  && fmt.cur_ms)
		*min_packet_size = fmt.cur_ms;
}

/*! \brief Get Max T.38 Transmission rate from T38 capabilities */
static int t38_get_rate(int t38cap)
{
	int maxrate = (t38cap & (T38FAX_RATE_14400 | T38FAX_RATE_12000 | T38FAX_RATE_9600 | T38FAX_RATE_7200 | T38FAX_RATE_4800 | T38FAX_RATE_2400));
	
	if (maxrate & T38FAX_RATE_14400) {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "T38MaxFaxRate 14400 found\n");
		return 14400;
	} else if (maxrate & T38FAX_RATE_12000) {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "T38MaxFaxRate 12000 found\n");
		return 12000;
	} else if (maxrate & T38FAX_RATE_9600) {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "T38MaxFaxRate 9600 found\n");
		return 9600;
	} else if (maxrate & T38FAX_RATE_7200) {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "T38MaxFaxRate 7200 found\n");
		return 7200;
	} else if (maxrate & T38FAX_RATE_4800) {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "T38MaxFaxRate 4800 found\n");
		return 4800;
	} else if (maxrate & T38FAX_RATE_2400) {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "T38MaxFaxRate 2400 found\n");
		return 2400;
	} else {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "Strange, T38MaxFaxRate NOT found in peers T38 SDP.\n");
		return 0;
	}
}

/*! \brief Add T.38 Session Description Protocol message */
static int add_t38_sdp(struct sip_request *resp, struct sip_pvt *p)
{
	int len = 0;
	int x = 0;
	struct sockaddr_in udptlsin;
	char v[256] = "";
	char s[256] = "";
	char o[256] = "";
	char c[256] = "";
	char t[256] = "";
	char m_modem[256];
	char a_modem[1024];
	char *m_modem_next = m_modem;
	size_t m_modem_left = sizeof(m_modem);
	char *a_modem_next = a_modem;
	size_t a_modem_left = sizeof(a_modem);
	struct sockaddr_in udptldest = { 0, };
	int debug;
	
	debug = sip_debug_test_pvt(p);
	len = 0;
	if (!p->udptl) {
		ast_log(LOG_WARNING, "No way to add SDP without an UDPTL structure\n");
		return -1;
	}
	
	if (!p->sessionid) {
		p->sessionid = getpid();
		p->sessionversion = p->sessionid;
	} else
		p->sessionversion++;
	
	/* Our T.38 end is */
	ast_udptl_get_us(p->udptl, &udptlsin);
	
	/* Determine T.38 UDPTL destination */
	if (p->udptlredirip.sin_addr.s_addr) {
		udptldest.sin_port = p->udptlredirip.sin_port;
		udptldest.sin_addr = p->udptlredirip.sin_addr;
	} else {
		udptldest.sin_addr = p->ourip;
		udptldest.sin_port = udptlsin.sin_port;
	}
	
	if (debug) 
		ast_log(LOG_DEBUG, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(udptlsin.sin_port));
	
	/* We break with the "recommendation" and send our IP, in order that our
	   peer doesn't have to ast_gethostbyname() us */
	
	if (debug) {
		ast_log(LOG_DEBUG, "Our T38 capability (%d), peer T38 capability (%d), joint capability (%d)\n",
			p->t38.capability,
			p->t38.peercapability,
			p->t38.jointcapability);
	}
	snprintf(v, sizeof(v), "v=0\r\n");
	snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(udptldest.sin_addr));
	snprintf(s, sizeof(s), "s=session\r\n");
	snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(udptldest.sin_addr));
	snprintf(t, sizeof(t), "t=0 0\r\n");
	ast_build_string(&m_modem_next, &m_modem_left, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
	
	if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_0)
		ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:0\r\n");
	if ((p->t38.jointcapability & T38FAX_VERSION) == T38FAX_VERSION_1)
		ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxVersion:1\r\n");
	if ((x = t38_get_rate(p->t38.jointcapability)))
		ast_build_string(&a_modem_next, &a_modem_left, "a=T38MaxBitRate:%d\r\n",x);
	ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxFillBitRemoval:%d\r\n", (p->t38.jointcapability & T38FAX_FILL_BIT_REMOVAL) ? 1 : 0);
	ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingMMR:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_MMR) ? 1 : 0);
	ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxTranscodingJBIG:%d\r\n", (p->t38.jointcapability & T38FAX_TRANSCODING_JBIG) ? 1 : 0);
	ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxRateManagement:%s\r\n", (p->t38.jointcapability & T38FAX_RATE_MANAGEMENT_LOCAL_TCF) ? "localTCF" : "transferredTCF");
	x = ast_udptl_get_local_max_datagram(p->udptl);
	ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxBuffer:%d\r\n",x);
	ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxMaxDatagram:%d\r\n",x);
	if (p->t38.jointcapability != T38FAX_UDP_EC_NONE)
		ast_build_string(&a_modem_next, &a_modem_left, "a=T38FaxUdpEC:%s\r\n", (p->t38.jointcapability & T38FAX_UDP_EC_REDUNDANCY) ? "t38UDPRedundancy" : "t38UDPFEC");
	len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m_modem) + strlen(a_modem);
	add_header(resp, "Content-Type", "application/sdp");
	add_header_contentLength(resp, len);
	add_line(resp, v);
	add_line(resp, o);
	add_line(resp, s);
	add_line(resp, c);
	add_line(resp, t);
	add_line(resp, m_modem);
	add_line(resp, a_modem);
	
	/* Update lastrtprx when we send our SDP */
	p->lastrtprx = p->lastrtptx = time(NULL);
	
	return 0;
}


/*! \brief Add RFC 2833 DTMF offer to SDP */
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
				char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
				int debug)
{
	int rtp_code;

	if (debug)
		ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
	if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
		return;

	ast_build_string(m_buf, m_size, " %d", rtp_code);
	ast_build_string(a_buf, a_size, "a=rtpmap:%d %s/%d\r\n", rtp_code,
			 ast_rtp_lookup_mime_subtype(0, format, 0),
			 sample_rate);
	if (format == AST_RTP_DTMF)
		/* Indicate we support DTMF and FLASH... */
		ast_build_string(a_buf, a_size, "a=fmtp:%d 0-16\r\n", rtp_code);
}

#define SDP_SAMPLE_RATE(x) (x == AST_FORMAT_G722) ? 16000 : 8000

/*! \brief Add Session Description Protocol message */
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p)
{
	int len = 0;
	int alreadysent = 0;

	struct sockaddr_in sin;
	struct sockaddr_in vsin;
	struct sockaddr_in dest;
	struct sockaddr_in vdest = { 0, };

	/* SDP fields */
	char *version = 	"v=0\r\n";		/* Protocol version */
	char *subject = 	"s=session\r\n";	/* Subject of the session */
	char owner[256];				/* Session owner/creator */
	char connection[256];				/* Connection data */
	char *stime = "t=0 0\r\n"; 			/* Time the session is active */
	char bandwidth[256] = "";			/* Max bitrate */
	char *hold;
	char m_audio[256];				/* Media declaration line for audio */
	char m_video[256];				/* Media declaration line for video */
	char a_audio[1024];				/* Attributes for audio */
	char a_video[1024];				/* Attributes for video */
	char *m_audio_next = m_audio;
	char *m_video_next = m_video;
	size_t m_audio_left = sizeof(m_audio);
	size_t m_video_left = sizeof(m_video);
	char *a_audio_next = a_audio;
	char *a_video_next = a_video;
	size_t a_audio_left = sizeof(a_audio);
	size_t a_video_left = sizeof(a_video);

	int x;
	int capability;
	int needvideo = FALSE;
	int debug = sip_debug_test_pvt(p);
	int min_audio_packet_size = 0;
	int min_video_packet_size = 0;

	m_video[0] = '\0';	/* Reset the video media string if it's not needed */

	if (!p->rtp) {
		ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
		return AST_FAILURE;
	}

	/* Set RTP Session ID and version */
	if (!p->sessionid) {
		p->sessionid = getpid();
		p->sessionversion = p->sessionid;
	} else
		p->sessionversion++;

	/* Get our addresses */
	ast_rtp_get_us(p->rtp, &sin);
	if (p->vrtp)
		ast_rtp_get_us(p->vrtp, &vsin);

	/* Is this a re-invite to move the media out, then use the original offer from caller  */
	if (p->redirip.sin_addr.s_addr) {
		dest.sin_port = p->redirip.sin_port;
		dest.sin_addr = p->redirip.sin_addr;
	} else {
		dest.sin_addr = p->ourip;
		dest.sin_port = sin.sin_port;
	}

	capability = p->jointcapability;


	if (option_debug > 1) {
		char codecbuf[BUFSIZ];
		ast_log(LOG_DEBUG, "** Our capability: %s Video flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), ast_test_flag(&p->flags[0], SIP_NOVIDEO) ? "True" : "False");
		ast_log(LOG_DEBUG, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
	}
	
#ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
	if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT_RTP)) {
		ast_build_string(&m_audio_next, &m_audio_left, " %d", 191);
		ast_build_string(&a_audio_next, &a_audio_left, "a=rtpmap:%d %s/%d\r\n", 191, "t38", 8000);
	}
#endif

	/* Check if we need video in this call */
	if ((capability & AST_FORMAT_VIDEO_MASK) && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
		if (p->vrtp) {
			needvideo = TRUE;
			if (option_debug > 1)
				ast_log(LOG_DEBUG, "This call needs video offers!\n");
		} else if (option_debug > 1)
			ast_log(LOG_DEBUG, "This call needs video offers, but there's no video support enabled!\n");
	}
		

	/* Ok, we need video. Let's add what we need for video and set codecs.
	   Video is handled differently than audio since we can not transcode. */
	if (needvideo) {
		/* Determine video destination */
		if (p->vredirip.sin_addr.s_addr) {
			vdest.sin_addr = p->vredirip.sin_addr;
			vdest.sin_port = p->vredirip.sin_port;
		} else {
			vdest.sin_addr = p->ourip;
			vdest.sin_port = vsin.sin_port;
		}
		ast_build_string(&m_video_next, &m_video_left, "m=video %d RTP/AVP", ntohs(vdest.sin_port));

		/* Build max bitrate string */
		if (p->maxcallbitrate)
			snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
		if (debug) 
			ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(vsin.sin_port));	
	}

	if (debug) 
		ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip), ntohs(sin.sin_port));	

	/* Start building generic SDP headers */

	/* We break with the "recommendation" and send our IP, in order that our
	   peer doesn't have to ast_gethostbyname() us */

	snprintf(owner, sizeof(owner), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
	snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
	ast_build_string(&m_audio_next, &m_audio_left, "m=audio %d RTP/AVP", ntohs(dest.sin_port));

	if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR))
		hold = "a=recvonly\r\n";
	else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE))
		hold = "a=inactive\r\n";
	else
		hold = "a=sendrecv\r\n";

	/* Now, start adding audio codecs. These are added in this order:
		- First what was requested by the calling channel
		- Then preferences in order from sip.conf device config for this peer/user
		- Then other codecs in capabilities, including video
	*/

	/* Prefer the audio codec we were requested to use, first, no matter what 
		Note that p->prefcodec can include video codecs, so mask them out
	 */
	if (capability & p->prefcodec) {
		int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;

		add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
				 &m_audio_next, &m_audio_left,
				 &a_audio_next, &a_audio_left,
				 debug, &min_audio_packet_size);
		alreadysent |= codec;
	}

	/* Start by sending our preferred audio codecs */
	for (x = 0; x < 32; x++) {
		int codec;

		if (!(codec = ast_codec_pref_index(&p->prefs, x)))
			break; 

		if (!(capability & codec))
			continue;

		if (alreadysent & codec)
			continue;

		add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
				 &m_audio_next, &m_audio_left,
				 &a_audio_next, &a_audio_left,
				 debug, &min_audio_packet_size);
		alreadysent |= codec;
	}

	/* Now send any other common audio and video codecs, and non-codec formats: */
	for (x = 1; x <= (needvideo ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
		if (!(capability & x))	/* Codec not requested */
			continue;

		if (alreadysent & x)	/* Already added to SDP */
			continue;

		if (x <= AST_FORMAT_MAX_AUDIO)
			add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
					 &m_audio_next, &m_audio_left,
					 &a_audio_next, &a_audio_left,
					 debug, &min_audio_packet_size);
		else 
			add_codec_to_sdp(p, x, 90000,
					 &m_video_next, &m_video_left,
					 &a_video_next, &a_video_left,
					 debug, &min_video_packet_size);
	}

	/* Now add DTMF RFC2833 telephony-event as a codec */
	for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
		if (!(p->noncodeccapability & x))
			continue;

		add_noncodec_to_sdp(p, x, 8000,
				    &m_audio_next, &m_audio_left,
				    &a_audio_next, &a_audio_left,
				    debug);
	}

	if (option_debug > 2)
		ast_log(LOG_DEBUG, "-- Done with adding codecs to SDP\n");

	if (!p->owner || !ast_internal_timing_enabled(p->owner))
		ast_build_string(&a_audio_next, &a_audio_left, "a=silenceSupp:off - - - -\r\n");

	if (min_audio_packet_size)
		ast_build_string(&a_audio_next, &a_audio_left, "a=ptime:%d\r\n", min_audio_packet_size);

	if (min_video_packet_size)
		ast_build_string(&a_video_next, &a_video_left, "a=ptime:%d\r\n", min_video_packet_size);

	if ((m_audio_left < 2) || (m_video_left < 2) || (a_audio_left == 0) || (a_video_left == 0))
		ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");

	ast_build_string(&m_audio_next, &m_audio_left, "\r\n");
	if (needvideo)
		ast_build_string(&m_video_next, &m_video_left, "\r\n");

	len = strlen(version) + strlen(subject) + strlen(owner) + strlen(connection) + strlen(stime) + strlen(m_audio) + strlen(a_audio) + strlen(hold);
	if (needvideo) /* only if video response is appropriate */
		len += strlen(m_video) + strlen(a_video) + strlen(bandwidth) + strlen(hold);

	add_header(resp, "Content-Type", "application/sdp");
	add_header_contentLength(resp, len);
	add_line(resp, version);
	add_line(resp, owner);
	add_line(resp, subject);
	add_line(resp, connection);
	if (needvideo)	 	/* only if video response is appropriate */
		add_line(resp, bandwidth);
	add_line(resp, stime);
	add_line(resp, m_audio);
	add_line(resp, a_audio);
	add_line(resp, hold);
	if (needvideo) { /* only if video response is appropriate */
		add_line(resp, m_video);
		add_line(resp, a_video);
		add_line(resp, hold);	/* Repeat hold for the video stream */
	}

	/* Update lastrtprx when we send our SDP */
	p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */

	if (option_debug > 2) {
		char buf[BUFSIZ];
		ast_log(LOG_DEBUG, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, BUFSIZ, capability));
	}

	return AST_SUCCESS;
}

/*! \brief Used for 200 OK and 183 early media */
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
{
	struct sip_request resp;
	int seqno;
	
	if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
		ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
		return -1;
	}
	respprep(&resp, p, msg, req);
	if (p->udptl) {
		ast_udptl_offered_from_local(p->udptl, 0);
		add_t38_sdp(&resp, p);
	} else 
		ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
	if (retrans && !p->pendinginvite)
		p->pendinginvite = seqno;		/* Buggy clients sends ACK on RINGING too */
	return send_response(p, &resp, retrans, seqno);
}

/*! \brief copy SIP request (mostly used to save request for responses) */
static void copy_request(struct sip_request *dst, const struct sip_request *src)
{
	long offset;
	int x;
	offset = ((void *)dst) - ((void *)src);
	/* First copy stuff */
	memcpy(dst, src, sizeof(*dst));
	/* Now fix pointer arithmetic */
	for (x=0; x < src->headers; x++)
		dst->header[x] += offset;
	for (x=0; x < src->lines; x++)
		dst->line[x] += offset;
}

/*! \brief Used for 200 OK and 183 early media */
static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
{
	struct sip_request resp;
	int seqno;
	if (sscanf(get_header(req, "CSeq"), "%d ", &seqno) != 1) {
		ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
		return -1;
	}
	respprep(&resp, p, msg, req);
	if (p->rtp) {
		if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
			if (option_debug)
				ast_log(LOG_DEBUG, "Setting framing from config on incoming call\n");
			ast_rtp_codec_setpref(p->rtp, &p->prefs);
		}
		try_suggested_sip_codec(p);	
		add_sdp(&resp, p);
	} else 
		ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
	if (reliable && !p->pendinginvite)
		p->pendinginvite = seqno;		/* Buggy clients sends ACK on RINGING too */
	return send_response(p, &resp, reliable, seqno);
}

/*! \brief Parse first line of incoming SIP request */
static int determine_firstline_parts(struct sip_request *req) 
{
	char *e = ast_skip_blanks(req->header[0]);	/* there shouldn't be any */

	if (!*e)
		return -1;
	req->rlPart1 = e;	/* method or protocol */
	e = ast_skip_nonblanks(e);
	if (*e)
		*e++ = '\0';
	/* Get URI or status code */
	e = ast_skip_blanks(e);
	if ( !*e )
		return -1;
	ast_trim_blanks(e);

	if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
		if (strlen(e) < 3)	/* status code is 3 digits */
			return -1;
		req->rlPart2 = e;
	} else { /* We have a request */
		if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
			ast_log(LOG_WARNING, "bogus uri in <> %s\n", e);
			e++;
			if (!*e)
				return -1; 
		}
		req->rlPart2 = e;	/* URI */
		e = ast_skip_nonblanks(e);
		if (*e)
			*e++ = '\0';
		e = ast_skip_blanks(e);
		if (strcasecmp(e, "SIP/2.0") ) {
			ast_log(LOG_WARNING, "Bad request protocol %s\n", e);
			return -1;
		}
	}
	return 1;
}

/*! \brief Transmit reinvite with SDP
\note 	A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
	INVITE that opened the SIP dialogue 
	We reinvite so that the audio stream (RTP) go directly between
	the SIP UAs. SIP Signalling stays with * in the path.
*/
static int transmit_reinvite_with_sdp(struct sip_pvt *p)
{
	struct sip_request req;

	reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
	
	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
	if (sipdebug)
		add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
	if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
		append_history(p, "ReInv", "Re-invite sent");
	add_sdp(&req, p);
	/* Use this as the basis */
	initialize_initreq(p, &req);
	p->lastinvite = p->ocseq;
	ast_set_flag(&p->flags[0], SIP_OUTGOING);		/* Change direction of this dialog */
	return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
}

/*! \brief Transmit reinvite with T38 SDP 
       We reinvite so that the T38 processing can take place.
       SIP Signalling stays with * in the path.
*/
static int transmit_reinvite_with_t38_sdp(struct sip_pvt *p)
{
	struct sip_request req;

	reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
	
	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
	if (sipdebug)
		add_header(&req, "X-asterisk-info", "SIP re-invite (T38 switchover)");
	ast_udptl_offered_from_local(p->udptl, 1);
	add_t38_sdp(&req, p);
	/* Use this as the basis */
	initialize_initreq(p, &req);
	ast_set_flag(&p->flags[0], SIP_OUTGOING);		/* Change direction of this dialog */
	p->lastinvite = p->ocseq;
	return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
}

/*! \brief Check Contact: URI of SIP message */
static void extract_uri(struct sip_pvt *p, struct sip_request *req)
{
	char stripped[256];
	char *c;

	ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
	c = get_in_brackets(stripped);
	c = strsep(&c, ";");	/* trim ; and beyond */
	if (!ast_strlen_zero(c))
		ast_string_field_set(p, uri, c);
}

/*! \brief Build contact header - the contact header we send out */
static void build_contact(struct sip_pvt *p)
{
	/* Construct Contact: header */
	if (ourport != STANDARD_SIP_PORT)
		ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip), ourport);
	else
		ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip));
}

/*! \brief Build the Remote Party-ID & From using callingpres options */
static void build_rpid(struct sip_pvt *p)
{
	int send_pres_tags = TRUE;
	const char *privacy=NULL;
	const char *screen=NULL;
	char buf[256];
	const char *clid = default_callerid;
	const char *clin = NULL;
	const char *fromdomain;

	if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
		return;

	if (p->owner && p->owner->cid.cid_num)
		clid = p->owner->cid.cid_num;
	if (p->owner && p->owner->cid.cid_name)
		clin = p->owner->cid.cid_name;
	if (ast_strlen_zero(clin))
		clin = clid;

	switch (p->callingpres) {
	case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
		privacy = "off";
		screen = "no";
		break;
	case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
		privacy = "off";
		screen = "yes";
		break;
	case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
		privacy = "off";
		screen = "no";
		break;
	case AST_PRES_ALLOWED_NETWORK_NUMBER:
		privacy = "off";
		screen = "yes";
		break;
	case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
		privacy = "full";
		screen = "no";
		break;
	case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
		privacy = "full";
		screen = "yes";
		break;
	case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
		privacy = "full";
		screen = "no";
		break;
	case AST_PRES_PROHIB_NETWORK_NUMBER:
		privacy = "full";
		screen = "yes";
		break;
	case AST_PRES_NUMBER_NOT_AVAILABLE:
		send_pres_tags = FALSE;
		break;
	default:
		ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
		if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
			privacy = "full";
		else
			privacy = "off";
		screen = "no";
		break;
	}
	
	fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip));

	snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
	if (send_pres_tags)
		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
	ast_string_field_set(p, rpid, buf);

	ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
			       S_OR(p->fromuser, clid),
			       fromdomain, p->tag);
}

/*! \brief Initiate new SIP request to peer/user */
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
{
	char invite_buf[256] = "";
	char *invite = invite_buf;
	size_t invite_max = sizeof(invite_buf);
	char from[256];
	char to[256];
	char tmp[BUFSIZ/2];
	char tmp2[BUFSIZ/2];
	const char *l = NULL, *n = NULL;
	const char *urioptions = "";

	if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
	 	const char *s = p->username;	/* being a string field, cannot be NULL */

		/* Test p->username against allowed characters in AST_DIGIT_ANY
			If it matches the allowed characters list, then sipuser = ";user=phone"
			If not, then sipuser = ""
		*/
		/* + is allowed in first position in a tel: uri */
		if (*s == '+')
			s++;
		for (; *s; s++) {
			if (!strchr(AST_DIGIT_ANYNUM, *s) )
				break;
		}
		/* If we have only digits, add ;user=phone to the uri */
		if (*s)
			urioptions = ";user=phone";
	}


	snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);

	if (p->owner) {
		l = p->owner->cid.cid_num;
		n = p->owner->cid.cid_name;
	}
	/* if we are not sending RPID and user wants his callerid restricted */
	if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
	    ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
		l = CALLERID_UNKNOWN;
		n = l;
	}
	if (ast_strlen_zero(l))
		l = default_callerid;
	if (ast_strlen_zero(n))
		n = l;
	/* Allow user to be overridden */
	if (!ast_strlen_zero(p->fromuser))
		l = p->fromuser;
	else /* Save for any further attempts */
		ast_string_field_set(p, fromuser, l);

	/* Allow user to be overridden */
	if (!ast_strlen_zero(p->fromname))
		n = p->fromname;
	else /* Save for any further attempts */
		ast_string_field_set(p, fromname, n);

	if (pedanticsipchecking) {
		ast_uri_encode(n, tmp, sizeof(tmp), 0);
		n = tmp;
		ast_uri_encode(l, tmp2, sizeof(tmp2), 0);
		l = tmp2;
	}

	if (ourport != STANDARD_SIP_PORT && ast_strlen_zero(p->fromdomain))
		snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), ourport, p->tag);
	else
		snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)), p->tag);

	/* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
	if (!ast_strlen_zero(p->fullcontact)) {
		/* If we have full contact, trust it */
		ast_build_string(&invite, &invite_max, "%s", p->fullcontact);
	} else {
		/* Otherwise, use the username while waiting for registration */
		ast_build_string(&invite, &invite_max, "sip:");
		if (!ast_strlen_zero(p->username)) {
			n = p->username;
			if (pedanticsipchecking) {
				ast_uri_encode(n, tmp, sizeof(tmp), 0);
				n = tmp;
			}
			ast_build_string(&invite, &invite_max, "%s@", n);
		}
		ast_build_string(&invite, &invite_max, "%s", p->tohost);
		if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
			ast_build_string(&invite, &invite_max, ":%d", ntohs(p->sa.sin_port));
		ast_build_string(&invite, &invite_max, "%s", urioptions);
	}

	/* If custom URI options have been provided, append them */
	if (p->options && p->options->uri_options)
		ast_build_string(&invite, &invite_max, ";%s", p->options->uri_options);
	
	ast_string_field_set(p, uri, invite_buf);

	if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
		/* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
		snprintf(to, sizeof(to), "<sip:%s>;tag=%s", p->uri, p->theirtag);
	} else if (p->options && p->options->vxml_url) {
		/* If there is a VXML URL append it to the SIP URL */
		snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
	} else 
		snprintf(to, sizeof(to), "<%s>", p->uri);
	
	init_req(req, sipmethod, p->uri);
	snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);

	add_header(req, "Via", p->via);
	/* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
	 * OTOH, then we won't have anything in p->route anyway */
	/* Build Remote Party-ID and From */
	if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
		build_rpid(p);
		add_header(req, "From", p->rpid_from);
	} else 
		add_header(req, "From", from);
	add_header(req, "To", to);
	ast_string_field_set(p, exten, l);
	build_contact(p);
	add_header(req, "Contact", p->our_contact);
	add_header(req, "Call-ID", p->callid);
	add_header(req, "CSeq", tmp);
	add_header(req, "User-Agent", global_useragent);
	add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
	if (!ast_strlen_zero(p->rpid))
		add_header(req, "Remote-Party-ID", p->rpid);
}

/*! \brief Build REFER/INVITE/OPTIONS message and transmit it */
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
{
	struct sip_request req;
	
	req.method = sipmethod;
	if (init) {		/* Seems like init always is 2 */
		/* Bump branch even on initial requests */
		p->branch ^= ast_random();
		build_via(p);
		if (init > 1)
			initreqprep(&req, p, sipmethod);
		else
			reqprep(&req, p, sipmethod, 0, 1);
	} else
		reqprep(&req, p, sipmethod, 0, 1);
		
	if (p->options && p->options->auth)
		add_header(&req, p->options->authheader, p->options->auth);
	append_date(&req);
	if (sipmethod == SIP_REFER) {	/* Call transfer */
		if (p->refer) {
			char buf[BUFSIZ];
			if (!ast_strlen_zero(p->refer->refer_to))
				add_header(&req, "Refer-To", p->refer->refer_to);
			if (!ast_strlen_zero(p->refer->referred_by)) {
				sprintf(buf, "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
				add_header(&req, "Referred-By", buf);
			}
		}
	}
	/* This new INVITE is part of an attended transfer. Make sure that the
	other end knows and replace the current call with this new call */
	if (p->options && p->options->replaces && !ast_strlen_zero(p->options->replaces)) {
		add_header(&req, "Replaces", p->options->replaces);
		add_header(&req, "Require", "replaces");
	}

	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
	if (p->options && p->options->addsipheaders && p->owner) {
		struct ast_channel *ast = p->owner; /* The owner channel */
		struct varshead *headp = &ast->varshead;

			if (!headp)
				ast_log(LOG_WARNING,"No Headp for the channel...ooops!\n");
			else {
				const struct ast_var_t *current;
				AST_LIST_TRAVERSE(headp, current, entries) {  
					/* SIPADDHEADER: Add SIP header to outgoing call */
					if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
						char *content, *end;
						const char *header = ast_var_value(current);
						char *headdup = ast_strdupa(header);

						/* Strip of the starting " (if it's there) */
						if (*headdup == '"')
					 		headdup++;
						if ((content = strchr(headdup, ':'))) {
							*content++ = '\0';
							content = ast_skip_blanks(content); /* Skip white space */
							/* Strip the ending " (if it's there) */
					 		end = content + strlen(content) -1;	
							if (*end == '"')
								*end = '\0';
						
							add_header(&req, headdup, content);
							if (sipdebug)
								ast_log(LOG_DEBUG, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
						}
					}
				}
			}
	}
	if (sdp) {
		if (p->udptl && p->t38.state == T38_LOCAL_DIRECT) {
			ast_udptl_offered_from_local(p->udptl, 1);
			if (option_debug)
				ast_log(LOG_DEBUG, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
			add_t38_sdp(&req, p);
		} else if (p->rtp) 
			add_sdp(&req, p);
	} else {
		add_header_contentLength(&req, 0);
	}

	if (!p->initreq.headers)
		initialize_initreq(p, &req);
	p->lastinvite = p->ocseq;
	return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
}

/*! \brief Used in the SUBSCRIBE notification subsystem */
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
{
	char tmp[4000], from[256], to[256];
	char *t = tmp, *c, *mfrom, *mto;
	size_t maxbytes = sizeof(tmp);
	struct sip_request req;
	char hint[AST_MAX_EXTENSION];
	char *statestring = "terminated";
	const struct cfsubscription_types *subscriptiontype;
	enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
	char *pidfstate = "--";
	char *pidfnote= "Ready";

	memset(from, 0, sizeof(from));
	memset(to, 0, sizeof(to));
	memset(tmp, 0, sizeof(tmp));

	switch (state) {
	case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
		statestring = (global_notifyringing) ? "early" : "confirmed";
		local_state = NOTIFY_INUSE;
		pidfstate = "busy";
		pidfnote = "Ringing";
		break;
	case AST_EXTENSION_RINGING:
		statestring = "early";
		local_state = NOTIFY_INUSE;
		pidfstate = "busy";
		pidfnote = "Ringing";
		break;
	case AST_EXTENSION_INUSE:
		statestring = "confirmed";
		local_state = NOTIFY_INUSE;
		pidfstate = "busy";
		pidfnote = "On the phone";
		break;
	case AST_EXTENSION_BUSY:
		statestring = "confirmed";
		local_state = NOTIFY_CLOSED;
		pidfstate = "busy";
		pidfnote = "On the phone";
		break;
	case AST_EXTENSION_UNAVAILABLE:
		statestring = "confirmed";
		local_state = NOTIFY_CLOSED;
		pidfstate = "away";
		pidfnote = "Unavailable";
		break;
	case AST_EXTENSION_ONHOLD:
		break;
	case AST_EXTENSION_NOT_INUSE:
	default:
		/* Default setting */
		break;
	}

	subscriptiontype = find_subscription_type(p->subscribed);
	
	/* Check which device/devices we are watching  and if they are registered */
	if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
		/* If they are not registered, we will override notification and show no availability */
		if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
			local_state = NOTIFY_CLOSED;
			pidfstate = "away";
			pidfnote = "Not online";
		}
	}

	ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
	c = get_in_brackets(from);
	if (strncmp(c, "sip:", 4)) {
		ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
		return -1;
	}
	mfrom = strsep(&c, ";");	/* trim ; and beyond */

	ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
	c = get_in_brackets(to);
	if (strncmp(c, "sip:", 4)) {
		ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
		return -1;
	}
	mto = strsep(&c, ";");	/* trim ; and beyond */

	reqprep(&req, p, SIP_NOTIFY, 0, 1);

	
	add_header(&req, "Event", subscriptiontype->event);
	add_header(&req, "Content-Type", subscriptiontype->mediatype);
	switch(state) {
	case AST_EXTENSION_DEACTIVATED:
		if (timeout)
			add_header(&req, "Subscription-State", "terminated;reason=timeout");
		else {
			add_header(&req, "Subscription-State", "terminated;reason=probation");
			add_header(&req, "Retry-After", "60");
		}
		break;
	case AST_EXTENSION_REMOVED:
		add_header(&req, "Subscription-State", "terminated;reason=noresource");
		break;
	default:
		if (p->expiry)
			add_header(&req, "Subscription-State", "active");
		else	/* Expired */
			add_header(&req, "Subscription-State", "terminated;reason=timeout");
	}
	switch (p->subscribed) {
	case XPIDF_XML:
	case CPIM_PIDF_XML:
		ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
		ast_build_string(&t, &maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
		ast_build_string(&t, &maxbytes, "<presence>\n");
		ast_build_string(&t, &maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
		ast_build_string(&t, &maxbytes, "<atom id=\"%s\">\n", p->exten);
		ast_build_string(&t, &maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
		ast_build_string(&t, &maxbytes, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
		ast_build_string(&t, &maxbytes, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
		ast_build_string(&t, &maxbytes, "</address>\n</atom>\n</presence>\n");
		break;
	case PIDF_XML: /* Eyebeam supports this format */
		ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
		ast_build_string(&t, &maxbytes, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
		ast_build_string(&t, &maxbytes, "<pp:person><status>\n");
		if (pidfstate[0] != '-')
			ast_build_string(&t, &maxbytes, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
		ast_build_string(&t, &maxbytes, "</status></pp:person>\n");
		ast_build_string(&t, &maxbytes, "<note>%s</note>\n", pidfnote); /* Note */
		ast_build_string(&t, &maxbytes, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
		ast_build_string(&t, &maxbytes, "<contact priority=\"1\">%s</contact>\n", mto);
		if (pidfstate[0] == 'b') /* Busy? Still open ... */
			ast_build_string(&t, &maxbytes, "<status><basic>open</basic></status>\n");
		else
			ast_build_string(&t, &maxbytes, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
		ast_build_string(&t, &maxbytes, "</tuple>\n</presence>\n");
		break;
	case DIALOG_INFO_XML: /* SNOM subscribes in this format */
		ast_build_string(&t, &maxbytes, "<?xml version=\"1.0\"?>\n");
		ast_build_string(&t, &maxbytes, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
		if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
			ast_build_string(&t, &maxbytes, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
		else
			ast_build_string(&t, &maxbytes, "<dialog id=\"%s\">\n", p->exten);
		ast_build_string(&t, &maxbytes, "<state>%s</state>\n", statestring);
		ast_build_string(&t, &maxbytes, "</dialog>\n</dialog-info>\n");
		break;
	case NONE:
	default:
		break;
	}

	if (t > tmp + sizeof(tmp))
		ast_log(LOG_WARNING, "Buffer overflow detected!!  (Please file a bug report)\n");

	add_header_contentLength(&req, strlen(tmp));
	add_line(&req, tmp);

	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Notify user of messages waiting in voicemail
\note	- Notification only works for registered peers with mailbox= definitions
	in sip.conf
	- We use the SIP Event package message-summary
	 MIME type defaults to  "application/simple-message-summary";
 */
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
{
	struct sip_request req;
	char tmp[500];
	char *t = tmp;
	size_t maxbytes = sizeof(tmp);

	initreqprep(&req, p, SIP_NOTIFY);
	add_header(&req, "Event", "message-summary");
	add_header(&req, "Content-Type", default_notifymime);

	ast_build_string(&t, &maxbytes, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
	ast_build_string(&t, &maxbytes, "Message-Account: sip:%s@%s\r\n",
		S_OR(vmexten, default_vmexten), S_OR(p->fromdomain, ast_inet_ntoa(p->ourip)));
	/* Cisco has a bug in the SIP stack where it can't accept the
		(0/0) notification. This can temporarily be disabled in
		sip.conf with the "buggymwi" option */
	ast_build_string(&t, &maxbytes, "Voice-Message: %d/%d%s\r\n", newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));

	if (p->subscribed) {
		if (p->expiry)
			add_header(&req, "Subscription-State", "active");
		else	/* Expired */
			add_header(&req, "Subscription-State", "terminated;reason=timeout");
	}

	if (t > tmp + sizeof(tmp))
		ast_log(LOG_WARNING, "Buffer overflow detected!!  (Please file a bug report)\n");

	add_header_contentLength(&req, strlen(tmp));
	add_line(&req, tmp);

	if (!p->initreq.headers) 
		initialize_initreq(p, &req);
	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
{
	if (!p->initreq.headers) 	/* Initialize first request before sending */
		initialize_initreq(p, req);
	return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
}

/*! \brief Notify a transferring party of the status of transfer */
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
{
	struct sip_request req;
	char tmp[BUFSIZ/2];

	reqprep(&req, p, SIP_NOTIFY, 0, 1);
	snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
	add_header(&req, "Event", tmp);
	add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
	add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);

	snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
	add_header_contentLength(&req, strlen(tmp));
	add_line(&req, tmp);

	if (!p->initreq.headers)
		initialize_initreq(p, &req);

	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Convert registration state status to string */
static char *regstate2str(enum sipregistrystate regstate)
{
	switch(regstate) {
	case REG_STATE_FAILED:
		return "Failed";
	case REG_STATE_UNREGISTERED:
		return "Unregistered";
	case REG_STATE_REGSENT:
		return "Request Sent";
	case REG_STATE_AUTHSENT:
		return "Auth. Sent";
	case REG_STATE_REGISTERED:
		return "Registered";
	case REG_STATE_REJECTED:
		return "Rejected";
	case REG_STATE_TIMEOUT:
		return "Timeout";
	case REG_STATE_NOAUTH:
		return "No Authentication";
	default:
		return "Unknown";
	}
}

/*! \brief Update registration with SIP Proxy */
static int sip_reregister(void *data) 
{
	/* if we are here, we know that we need to reregister. */
	struct sip_registry *r= ASTOBJ_REF((struct sip_registry *) data);

	/* if we couldn't get a reference to the registry object, punt */
	if (!r)
		return 0;

	if (r->call && !ast_test_flag(&r->call->flags[0], SIP_NO_HISTORY))
		append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
	/* Since registry's are only added/removed by the the monitor thread, this
	   may be overkill to reference/dereference at all here */
	if (sipdebug)
		ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);

	r->expire = -1;
	__sip_do_register(r);
	ASTOBJ_UNREF(r, sip_registry_destroy);
	return 0;
}

/*! \brief Register with SIP proxy */
static int __sip_do_register(struct sip_registry *r)
{
	int res;

	res = transmit_register(r, SIP_REGISTER, NULL, NULL);
	return res;
}

/*! \brief Registration timeout, register again */
static int sip_reg_timeout(void *data)
{

	/* if we are here, our registration timed out, so we'll just do it over */
	struct sip_registry *r = ASTOBJ_REF((struct sip_registry *) data);
	struct sip_pvt *p;
	int res;

	/* if we couldn't get a reference to the registry object, punt */
	if (!r)
		return 0;

	ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
	if (r->call) {
		/* Unlink us, destroy old call.  Locking is not relevant here because all this happens
		   in the single SIP manager thread. */
		p = r->call;
		if (p->registry)
			ASTOBJ_UNREF(p->registry, sip_registry_destroy);
		r->call = NULL;
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		/* Pretend to ACK anything just in case */
		__sip_pretend_ack(p); /* XXX we need p locked, not sure we have */
	}
	/* If we have a limit, stop registration and give up */
	if (global_regattempts_max && (r->regattempts > global_regattempts_max)) {
		/* Ok, enough is enough. Don't try any more */
		/* We could add an external notification here... 
			steal it from app_voicemail :-) */
		ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
		r->regstate = REG_STATE_FAILED;
	} else {
		r->regstate = REG_STATE_UNREGISTERED;
		r->timeout = -1;
		res=transmit_register(r, SIP_REGISTER, NULL, NULL);
	}
	manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
	ASTOBJ_UNREF(r, sip_registry_destroy);
	return 0;
}

/*! \brief Transmit register to SIP proxy or UA */
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
{
	struct sip_request req;
	char from[256];
	char to[256];
	char tmp[80];
	char addr[80];
	struct sip_pvt *p;

	/* exit if we are already in process with this registrar ?*/
	if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
		ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
		return 0;
	}

	if (r->call) {	/* We have a registration */
		if (!auth) {
			ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
			return 0;
		} else {
			p = r->call;
			make_our_tag(p->tag, sizeof(p->tag));	/* create a new local tag for every register attempt */
			ast_string_field_free(p, theirtag);	/* forget their old tag, so we don't match tags when getting response */
		}
	} else {
		/* Build callid for registration if we haven't registered before */
		if (!r->callid_valid) {
			build_callid_registry(r, __ourip, default_fromdomain);
			r->callid_valid = TRUE;
		}
		/* Allocate SIP packet for registration */
		if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER))) {
			ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
			return 0;
		}
		if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
			append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
		/* Find address to hostname */
		if (create_addr(p, r->hostname)) {
			/* we have what we hope is a temporary network error,
			 * probably DNS.  We need to reschedule a registration try */
			sip_destroy(p);
			if (r->timeout > -1) {
				ast_sched_del(sched, r->timeout);
				r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
				ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
			} else {
				r->timeout = ast_sched_add(sched, global_reg_timeout*1000, sip_reg_timeout, r);
				ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
			}
			r->regattempts++;
			return 0;
		}
		/* Copy back Call-ID in case create_addr changed it */
		ast_string_field_set(r, callid, p->callid);
		if (r->portno)
			p->sa.sin_port = htons(r->portno);
		else 	/* Set registry port to the port set from the peer definition/srv or default */
			r->portno = ntohs(p->sa.sin_port);
		ast_set_flag(&p->flags[0], SIP_OUTGOING);	/* Registration is outgoing call */
		r->call=p;			/* Save pointer to SIP packet */
		p->registry = ASTOBJ_REF(r);	/* Add pointer to registry in packet */
		if (!ast_strlen_zero(r->secret))	/* Secret (password) */
			ast_string_field_set(p, peersecret, r->secret);
		if (!ast_strlen_zero(r->md5secret))
			ast_string_field_set(p, peermd5secret, r->md5secret);
		/* User name in this realm  
		- if authuser is set, use that, otherwise use username */
		if (!ast_strlen_zero(r->authuser)) {	
			ast_string_field_set(p, peername, r->authuser);
			ast_string_field_set(p, authname, r->authuser);
		} else if (!ast_strlen_zero(r->username)) {
			ast_string_field_set(p, peername, r->username);
			ast_string_field_set(p, authname, r->username);
			ast_string_field_set(p, fromuser, r->username);
		}
		if (!ast_strlen_zero(r->username))
			ast_string_field_set(p, username, r->username);
		/* Save extension in packet */
		ast_string_field_set(p, exten, r->contact);

		/*
		  check which address we should use in our contact header 
		  based on whether the remote host is on the external or
		  internal network so we can register through nat
		 */
		if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
			p->ourip = bindaddr.sin_addr;
		build_contact(p);
	}

	/* set up a timeout */
	if (auth == NULL)  {
		if (r->timeout > -1) {
			ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
			ast_sched_del(sched, r->timeout);
		}
		r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
		if (option_debug)
			ast_log(LOG_DEBUG, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
	}

	if (strchr(r->username, '@')) {
		snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
		if (!ast_strlen_zero(p->theirtag))
			snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
		else
			snprintf(to, sizeof(to), "<sip:%s>", r->username);
	} else {
		snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
		if (!ast_strlen_zero(p->theirtag))
			snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
		else
			snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
	}
	
	/* Fromdomain is what we are registering to, regardless of actual
	   host name from SRV */
	snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain, r->hostname));
	ast_string_field_set(p, uri, addr);

	p->branch ^= ast_random();

	init_req(&req, sipmethod, addr);

	/* Add to CSEQ */
	snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
	p->ocseq = r->ocseq;

	build_via(p);
	add_header(&req, "Via", p->via);
	add_header(&req, "From", from);
	add_header(&req, "To", to);
	add_header(&req, "Call-ID", p->callid);
	add_header(&req, "CSeq", tmp);
	add_header(&req, "User-Agent", global_useragent);
	add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);

	
	if (auth) 	/* Add auth header */
		add_header(&req, authheader, auth);
	else if (!ast_strlen_zero(r->nonce)) {
		char digest[1024];

		/* We have auth data to reuse, build a digest header! */
		if (sipdebug)
			ast_log(LOG_DEBUG, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
		ast_string_field_set(p, realm, r->realm);
		ast_string_field_set(p, nonce, r->nonce);
		ast_string_field_set(p, domain, r->domain);
		ast_string_field_set(p, opaque, r->opaque);
		ast_string_field_set(p, qop, r->qop);
		r->noncecount++;
		p->noncecount = r->noncecount;

		memset(digest,0,sizeof(digest));
		if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
			add_header(&req, "Authorization", digest);
		else
			ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
	
	}

	snprintf(tmp, sizeof(tmp), "%d", default_expiry);
	add_header(&req, "Expires", tmp);
	add_header(&req, "Contact", p->our_contact);
	add_header(&req, "Event", "registration");
	add_header_contentLength(&req, 0);

	initialize_initreq(p, &req);
	if (sip_debug_test_pvt(p))
		ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
	r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
	r->regattempts++;	/* Another attempt */
	if (option_debug > 3)
		ast_verbose("REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
	return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
}

/*! \brief Transmit text with SIP MESSAGE method */
static int transmit_message_with_text(struct sip_pvt *p, const char *text)
{
	struct sip_request req;

	reqprep(&req, p, SIP_MESSAGE, 0, 1);
	add_text(&req, text);
	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Allocate SIP refer structure */
static int sip_refer_allocate(struct sip_pvt *p)
{
	p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
	return p->refer ? 1 : 0;
}

/*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
	\note this is currently broken as we have no way of telling the dialplan
	engine whether a transfer succeeds or fails.
	\todo Fix the transfer() dialplan function so that a transfer may fail
*/
static int transmit_refer(struct sip_pvt *p, const char *dest)
{
	struct sip_request req = { 
		.headers = 0,	
	};
	char from[256];
	const char *of;
	char *c;
	char referto[256];
	char *ttag, *ftag;
	char *theirtag = ast_strdupa(p->theirtag);

	if (option_debug || sipdebug)
		ast_log(LOG_DEBUG, "SIP transfer of %s to %s\n", p->callid, dest);

	/* Are we transfering an inbound or outbound call ? */
	if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
		of = get_header(&p->initreq, "To");
		ttag = theirtag;
		ftag = p->tag;
	} else {
		of = get_header(&p->initreq, "From");
		ftag = theirtag;
		ttag = p->tag;
	}

	ast_copy_string(from, of, sizeof(from));
	of = get_in_brackets(from);
	ast_string_field_set(p, from, of);
	if (strncmp(of, "sip:", 4))
		ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
	else
		of += 4;
	/* Get just the username part */
	if ((c = strchr(dest, '@')))
		c = NULL;
	else if ((c = strchr(of, '@')))
		*c++ = '\0';
	if (c) 
		snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
	else
		snprintf(referto, sizeof(referto), "<sip:%s>", dest);

	/* save in case we get 407 challenge */
	sip_refer_allocate(p);
	ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
	ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
	p->refer->status = REFER_SENT;   /* Set refer status */

	reqprep(&req, p, SIP_REFER, 0, 1);
	add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);

	add_header(&req, "Refer-To", referto);
	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
	if (!ast_strlen_zero(p->our_contact))
		add_header(&req, "Referred-By", p->our_contact);

	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
	/* We should propably wait for a NOTIFY here until we ack the transfer */
	/* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */

	/*! \todo In theory, we should hang around and wait for a reply, before
	returning to the dial plan here. Don't know really how that would
	affect the transfer() app or the pbx, but, well, to make this
	useful we should have a STATUS code on transfer().
	*/
}


/*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
static int transmit_info_with_digit(struct sip_pvt *p, const char digit)
{
	struct sip_request req;

	reqprep(&req, p, SIP_INFO, 0, 1);
	add_digit(&req, digit);
	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Send SIP INFO with video update request */
static int transmit_info_with_vidupdate(struct sip_pvt *p)
{
	struct sip_request req;

	reqprep(&req, p, SIP_INFO, 0, 1);
	add_vidupdate(&req);
	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Transmit generic SIP request */
static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
{
	struct sip_request resp;

	if (sipmethod == SIP_ACK)
		p->invitestate = INV_CONFIRMED;

	reqprep(&resp, p, sipmethod, seqno, newbranch);
	add_header_contentLength(&resp, 0);
	return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
}

/*! \brief Transmit SIP request, auth added */
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
{
	struct sip_request resp;

	reqprep(&resp, p, sipmethod, seqno, newbranch);
	if (!ast_strlen_zero(p->realm)) {
		char digest[1024];

		memset(digest, 0, sizeof(digest));
		if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
			if (p->options && p->options->auth_type == PROXY_AUTH)
				add_header(&resp, "Proxy-Authorization", digest);
			else if (p->options && p->options->auth_type == WWW_AUTH)
				add_header(&resp, "Authorization", digest);
			else	/* Default, to be backwards compatible (maybe being too careful, but leaving it for now) */
				add_header(&resp, "Proxy-Authorization", digest);
		} else
			ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
	}
	/* If we are hanging up and know a cause for that, send it in clear text to make
		debugging easier. */
	if (sipmethod == SIP_BYE && p->owner && p->owner->hangupcause)	{
		char buf[10];

		add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
		snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
		add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
	}

	add_header_contentLength(&resp, 0);
	return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);	
}

/*! \brief Remove registration data from realtime database or AST/DB when registration expires */
static void destroy_association(struct sip_peer *peer)
{
	if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE)) {
		if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT))
			ast_update_realtime("sippeers", "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "username", "", "regserver", "", NULL);
		else 
			ast_db_del("SIP/Registry", peer->name);
	}
}

/*! \brief Expire registration of SIP peer */
static int expire_register(void *data)
{
	struct sip_peer *peer = data;
	
	if (!peer)		/* Hmmm. We have no peer. Weird. */
		return 0;

	memset(&peer->addr, 0, sizeof(peer->addr));

	destroy_association(peer);	/* remove registration data from storage */
	
	manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
	register_peer_exten(peer, FALSE);	/* Remove regexten */
	peer->expire = -1;
	ast_device_state_changed("SIP/%s", peer->name);

	/* Do we need to release this peer from memory? 
		Only for realtime peers and autocreated peers
	*/
	if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT) ||
	    ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
		peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);	/* Remove from peer list */
		ASTOBJ_UNREF(peer, sip_destroy_peer);		/* Remove from memory */
	}

	return 0;
}

/*! \brief Poke peer (send qualify to check if peer is alive and well) */
static int sip_poke_peer_s(void *data)
{
	struct sip_peer *peer = data;

	peer->pokeexpire = -1;
	sip_poke_peer(peer);
	return 0;
}

/*! \brief Get registration details from Asterisk DB */
static void reg_source_db(struct sip_peer *peer)
{
	char data[256];
	struct in_addr in;
	int expiry;
	int port;
	char *scan, *addr, *port_str, *expiry_str, *username, *contact;

	if (ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT)) 
		return;
	if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
		return;

	scan = data;
	addr = strsep(&scan, ":");
	port_str = strsep(&scan, ":");
	expiry_str = strsep(&scan, ":");
	username = strsep(&scan, ":");
	contact = scan;	/* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */

	if (!inet_aton(addr, &in))
		return;

	if (port_str)
		port = atoi(port_str);
	else
		return;

	if (expiry_str)
		expiry = atoi(expiry_str);
	else
		return;

	if (username)
		ast_copy_string(peer->username, username, sizeof(peer->username));
	if (contact)
		ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));

	if (option_verbose > 2)
		ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
			    peer->name, peer->username, ast_inet_ntoa(in), port, expiry);

	memset(&peer->addr, 0, sizeof(peer->addr));
	peer->addr.sin_family = AF_INET;
	peer->addr.sin_addr = in;
	peer->addr.sin_port = htons(port);
	if (sipsock < 0) {
		/* SIP isn't up yet, so schedule a poke only, pretty soon */
		if (peer->pokeexpire > -1)
			ast_sched_del(sched, peer->pokeexpire);
		peer->pokeexpire = ast_sched_add(sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
	} else
		sip_poke_peer(peer);
	if (peer->expire > -1)
		ast_sched_del(sched, peer->expire);
	peer->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
	register_peer_exten(peer, TRUE);
}

/*! \brief Save contact header for 200 OK on INVITE */
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
{
	char contact[250]; 
	char *c;

	/* Look for brackets */
	ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
	c = get_in_brackets(contact);

	/* Save full contact to call pvt for later bye or re-invite */
	ast_string_field_set(pvt, fullcontact, c);

	/* Save URI for later ACKs, BYE or RE-invites */
	ast_string_field_set(pvt, okcontacturi, c);

	/* We should return false for URI:s we can't handle,
		like sips:, tel:, mailto:,ldap: etc */
	return TRUE;		
}

/*! \brief Change the other partys IP address based on given contact */
static int set_address_from_contact(struct sip_pvt *pvt)
{
	struct hostent *hp;
	struct ast_hostent ahp;
	int port;
	char *c, *host, *pt;
	char *contact;


	if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
		/* NAT: Don't trust the contact field.  Just use what they came to us
		   with. */
		pvt->sa = pvt->recv;
		return 0;
	}


	/* Work on a copy */
	contact = ast_strdupa(pvt->fullcontact);

	/* XXX this code is repeated all over */
	/* Make sure it's a SIP URL */
	if (strncasecmp(contact, "sip:", 4)) {
		ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
	} else
		contact += 4;

	/* Ditch arguments */
	/* XXX this code is replicated also shortly below */
	contact = strsep(&contact, ";");	/* trim ; and beyond */

	/* Grab host */
	host = strchr(contact, '@');
	if (!host) {	/* No username part */
		host = contact;
		c = NULL;
	} else {
		*host++ = '\0';
	}
	pt = strchr(host, ':');
	if (pt) {
		*pt++ = '\0';
		port = atoi(pt);
	} else
		port = STANDARD_SIP_PORT;

	/* XXX This could block for a long time XXX */
	/* We should only do this if it's a name, not an IP */
	hp = ast_gethostbyname(host, &ahp);
	if (!hp)  {
		ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
		return -1;
	}
	pvt->sa.sin_family = AF_INET;
	memcpy(&pvt->sa.sin_addr, hp->h_addr, sizeof(pvt->sa.sin_addr));
	pvt->sa.sin_port = htons(port);

	return 0;
}


/*! \brief Parse contact header and save registration (peer registration) */
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
{
	char contact[BUFSIZ]; 
	char data[BUFSIZ];
	const char *expires = get_header(req, "Expires");
	int expiry = atoi(expires);
	char *curi, *n, *pt;
	int port;
	const char *useragent;
	struct hostent *hp;
	struct ast_hostent ahp;
	struct sockaddr_in oldsin;

	ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));

	if (ast_strlen_zero(expires)) {	/* No expires header */
		expires = strcasestr(contact, ";expires=");
		if (expires) {
			/* XXX bug here, we overwrite the string */
			expires = strsep((char **) &expires, ";"); /* trim ; and beyond */
			if (sscanf(expires + 9, "%d", &expiry) != 1)
				expiry = default_expiry;
		} else {
			/* Nothing has been specified */
			expiry = default_expiry;
		}
	}

	/* Look for brackets */
	curi = contact;
	if (strchr(contact, '<') == NULL)	/* No <, check for ; and strip it */
		strsep(&curi, ";");	/* This is Header options, not URI options */
	curi = get_in_brackets(contact);

	/* if they did not specify Contact: or Expires:, they are querying
	   what we currently have stored as their contact address, so return
	   it
	*/
	if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
		/* If we have an active registration, tell them when the registration is going to expire */
		if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
			pvt->expiry = ast_sched_when(sched, peer->expire);
		return PARSE_REGISTER_QUERY;
	} else if (!strcasecmp(curi, "*") || !expiry) {	/* Unregister this peer */
		/* This means remove all registrations and return OK */
		memset(&peer->addr, 0, sizeof(peer->addr));
		if (peer->expire > -1)
			ast_sched_del(sched, peer->expire);
		peer->expire = -1;

		destroy_association(peer);
		
		register_peer_exten(peer, 0);	/* Add extension from regexten= setting in sip.conf */
		peer->fullcontact[0] = '\0';
		peer->useragent[0] = '\0';
		peer->sipoptions = 0;
		peer->lastms = 0;

		if (option_verbose > 2)
			ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", peer->name);
			manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
		return PARSE_REGISTER_UPDATE;
	}

	/* Store whatever we got as a contact from the client */
	ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));

	/* For the 200 OK, we should use the received contact */
	ast_string_field_build(pvt, our_contact, "<%s>", curi);

	/* Make sure it's a SIP URL */
	if (strncasecmp(curi, "sip:", 4)) {
		ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", curi);
	} else
		curi += 4;
	/* Ditch q */
	curi = strsep(&curi, ";");
	/* Grab host */
	n = strchr(curi, '@');
	if (!n) {
		n = curi;
		curi = NULL;
	} else
		*n++ = '\0';
	pt = strchr(n, ':');
	if (pt) {
		*pt++ = '\0';
		port = atoi(pt);
	} else
		port = STANDARD_SIP_PORT;
	oldsin = peer->addr;
	if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
		/* XXX This could block for a long time XXX */
		hp = ast_gethostbyname(n, &ahp);
		if (!hp)  {
			ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
			return PARSE_REGISTER_FAILED;
		}
		peer->addr.sin_family = AF_INET;
		memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
		peer->addr.sin_port = htons(port);
	} else {
		/* Don't trust the contact field.  Just use what they came to us
		   with */
		peer->addr = pvt->recv;
	}

	/* Save SIP options profile */
	peer->sipoptions = pvt->sipoptions;

	if (curi)	/* Overwrite the default username from config at registration */
		ast_copy_string(peer->username, curi, sizeof(peer->username));
	else
		peer->username[0] = '\0';

	if (peer->expire > -1) {
		ast_sched_del(sched, peer->expire);
		peer->expire = -1;
	}
	if (expiry > max_expiry)
		expiry = max_expiry;
	if (expiry < min_expiry)
		expiry = min_expiry;
	peer->expire = ast_test_flag(&peer->flags[0], SIP_REALTIME) ? -1 :
		ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
	pvt->expiry = expiry;
	snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expiry, peer->username, peer->fullcontact);
	if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT)) 
		ast_db_put("SIP/Registry", peer->name, data);
	manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);

	/* Is this a new IP address for us? */
	if (inaddrcmp(&peer->addr, &oldsin)) {
		sip_poke_peer(peer);
		if (option_verbose > 2)
			ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expiry);
		register_peer_exten(peer, 1);
	}
	
	/* Save User agent */
	useragent = get_header(req, "User-Agent");
	if (strcasecmp(useragent, peer->useragent)) {	/* XXX copy if they are different ? */
		ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
		if (option_verbose > 3)
			ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);  
	}
	return PARSE_REGISTER_UPDATE;
}

/*! \brief Remove route from route list */
static void free_old_route(struct sip_route *route)
{
	struct sip_route *next;

	while (route) {
		next = route->next;
		free(route);
		route = next;
	}
}

/*! \brief List all routes - mostly for debugging */
static void list_route(struct sip_route *route)
{
	if (!route)
		ast_verbose("list_route: no route\n");
	else {
		for (;route; route = route->next)
			ast_verbose("list_route: hop: <%s>\n", route->hop);
	}
}

/*! \brief Build route list from Record-Route header */
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
{
	struct sip_route *thishop, *head, *tail;
	int start = 0;
	int len;
	const char *rr, *contact, *c;

	/* Once a persistant route is set, don't fool with it */
	if (p->route && p->route_persistant) {
		if (option_debug)
			ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
		return;
	}

	if (p->route) {
		free_old_route(p->route);
		p->route = NULL;
	}
	
	p->route_persistant = backwards;
	
	/* Build a tailq, then assign it to p->route when done.
	 * If backwards, we add entries from the head so they end up
	 * in reverse order. However, we do need to maintain a correct
	 * tail pointer because the contact is always at the end.
	 */
	head = NULL;
	tail = head;
	/* 1st we pass through all the hops in any Record-Route headers */
	for (;;) {
		/* Each Record-Route header */
		rr = __get_header(req, "Record-Route", &start);
		if (*rr == '\0')
			break;
		for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
			++rr;
			len = strcspn(rr, ">") + 1;
			/* Make a struct route */
			if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
				/* ast_calloc is not needed because all fields are initialized in this block */
				ast_copy_string(thishop->hop, rr, len);
				if (option_debug > 1)
					ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
				/* Link in */
				if (backwards) {
					/* Link in at head so they end up in reverse order */
					thishop->next = head;
					head = thishop;
					/* If this was the first then it'll be the tail */
					if (!tail)
						tail = thishop;
				} else {
					thishop->next = NULL;
					/* Link in at the end */
					if (tail)
						tail->next = thishop;
					else
						head = thishop;
					tail = thishop;
				}
			}
		}
	}

	/* Only append the contact if we are dealing with a strict router */
	if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop,";lr") == NULL) ) {
		/* 2nd append the Contact: if there is one */
		/* Can be multiple Contact headers, comma separated values - we just take the first */
		contact = get_header(req, "Contact");
		if (!ast_strlen_zero(contact)) {
			if (option_debug > 1)
				ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
			/* Look for <: delimited address */
			c = strchr(contact, '<');
			if (c) {
				/* Take to > */
				++c;
				len = strcspn(c, ">") + 1;
			} else {
				/* No <> - just take the lot */
				c = contact;
				len = strlen(contact) + 1;
			}
			if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
				/* ast_calloc is not needed because all fields are initialized in this block */
				ast_copy_string(thishop->hop, c, len);
				thishop->next = NULL;
				/* Goes at the end */
				if (tail)
					tail->next = thishop;
				else
					head = thishop;
			}
		}
	}

	/* Store as new route */
	p->route = head;

	/* For debugging dump what we ended up with */
	if (sip_debug_test_pvt(p))
		list_route(p->route);
}


/*! \brief  Check user authorization from peer definition 
	Some actions, like REGISTER and INVITEs from peers require
	authentication (if peer have secret set) 
    \return 0 on success, non-zero on error
*/
static enum check_auth_result 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)
{
	const char *response = "407 Proxy Authentication Required";
	const char *reqheader = "Proxy-Authorization";
	const char *respheader = "Proxy-Authenticate";
	const char *authtoken;
	char a1_hash[256];
	char resp_hash[256]="";
	char tmp[BUFSIZ * 2];                /* Make a large enough buffer */
	char *c;
	int  wrongnonce = FALSE;
	int  good_response;
	const char *usednonce = p->randdata;

	/* table of recognised keywords, and their value in the digest */
	enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
	struct x {
		const char *key;
		const char *s;
	} *i, keys[] = {
		[K_RESP] = { "response=", "" },
		[K_URI] = { "uri=", "" },
		[K_USER] = { "username=", "" },
		[K_NONCE] = { "nonce=", "" },
		[K_LAST] = { NULL, NULL}
	};

	/* Always OK if no secret */
	if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
		return AUTH_SUCCESSFUL;
	if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
		/* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
		   of headers -- GO SIP!  Whoo hoo!  Two things that do the same thing but are used in
		   different circumstances! What a surprise. */
		response = "401 Unauthorized";
		reqheader = "Authorization";
		respheader = "WWW-Authenticate";
	}
	authtoken =  get_header(req, reqheader);	
	if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
		/* This is a retransmitted invite/register/etc, don't reconstruct authentication
		   information */
		if (!reliable) {
			/* Resend message if this was NOT a reliable delivery.   Otherwise the
			   retransmission should get it */
			transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
			/* Schedule auto destroy in 32 seconds (according to RFC 3261) */
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		}
		return AUTH_CHALLENGE_SENT;
	} else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
		/* We have no auth, so issue challenge and request authentication */
		ast_string_field_build(p, randdata, "%08lx", ast_random());	/* Create nonce for challenge */
		transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
		/* Schedule auto destroy in 32 seconds */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return AUTH_CHALLENGE_SENT;
	} 

	/* --- We have auth, so check it */

	/* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
   	   an example in the spec of just what it is you're doing a hash on. */


	/* Make a copy of the response and parse it */
	ast_copy_string(tmp, authtoken, sizeof(tmp));
	c = tmp;

	while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
		for (i = keys; i->key != NULL; i++) {
			const char *separator = ",";	/* default */

			if (strncasecmp(c, i->key, strlen(i->key)) != 0)
				continue;
			/* Found. Skip keyword, take text in quotes or up to the separator. */
			c += strlen(i->key);
			if (*c == '"') { /* in quotes. Skip first and look for last */
				c++;
				separator = "\"";
			}
			i->s = c;
			strsep(&c, separator);
			break;
		}
		if (i->key == NULL) /* not found, jump after space or comma */
			strsep(&c, " ,");
	}

	/* Verify that digest username matches  the username we auth as */
	if (strcmp(username, keys[K_USER].s)) {
		ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
			username, keys[K_USER].s);
		/* Oops, we're trying something here */
		return AUTH_USERNAME_MISMATCH;
	}

	/* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
	if (strcasecmp(p->randdata, keys[K_NONCE].s)) { /* XXX it was 'n'casecmp ? */
		wrongnonce = TRUE;
		usednonce = keys[K_NONCE].s;
	}

	if (!ast_strlen_zero(md5secret))
		ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
	else {
		char a1[256];
		snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
		ast_md5_hash(a1_hash, a1);
	}

	/* compute the expected response to compare with what we received */
	{
		char a2[256];
		char a2_hash[256];
		char resp[256];

		snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
				S_OR(keys[K_URI].s, uri));
		ast_md5_hash(a2_hash, a2);
		snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
		ast_md5_hash(resp_hash, resp);
	}

	good_response = keys[K_RESP].s &&
			!strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
	if (wrongnonce) {
		ast_string_field_build(p, randdata, "%08lx", ast_random());
		if (good_response) {
			if (sipdebug)
				ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
			/* We got working auth token, based on stale nonce . */
			transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
		} else {
			/* Everything was wrong, so give the device one more try with a new challenge */
			if (sipdebug)
				ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
			transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
		}

		/* Schedule auto destroy in 32 seconds */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return AUTH_CHALLENGE_SENT;
	} 
	if (good_response) {
		append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
		return AUTH_SUCCESSFUL;
	}

	/* Ok, we have a bad username/secret pair */
	/* Challenge again, and again, and again */
	transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
	sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

	return AUTH_CHALLENGE_SENT;
}

/*! \brief Change onhold state of a peer using a pvt structure */
static void sip_peer_hold(struct sip_pvt *p, int hold)
{
	struct sip_peer *peer = find_peer(p->peername, NULL, 1);

	if (!peer)
		return;

	/* If they put someone on hold, increment the value... otherwise decrement it */
	if (hold)
		peer->onHold++;
	else if (hold > 0)
		peer->onHold--;

	/* Request device state update */
	ast_device_state_changed("SIP/%s", peer->name);

	return;
}

/*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
\note	If you add an "hint" priority to the extension in the dial plan,
	you will get notifications on device state changes */
static int cb_extensionstate(char *context, char* exten, int state, void *data)
{
	struct sip_pvt *p = data;

	switch(state) {
	case AST_EXTENSION_DEACTIVATED:	/* Retry after a while */
	case AST_EXTENSION_REMOVED:	/* Extension is gone */
		if (p->autokillid > -1)
			sip_cancel_destroy(p);	/* Remove subscription expiry for renewals */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);	/* Delete subscription in 32 secs */
		ast_verbose(VERBOSE_PREFIX_2 "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
		p->stateid = -1;
		p->subscribed = NONE;
		append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
		break;
	default:	/* Tell user */
		p->laststate = state;
		break;
	}
	if (p->subscribed != NONE)	/* Only send state NOTIFY if we know the format */
		transmit_state_notify(p, state, 1, FALSE);

	if (option_verbose > 1)
		ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %s for Notify User %s\n", exten, ast_extension_state2str(state), p->username);
	return 0;
}

/*! \brief Send a fake 401 Unauthorized response when the administrator
  wants to hide the names of local users/peers from fishers
 */
static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable)
{
	ast_string_field_build(p, randdata, "%08lx", ast_random());	/* Create nonce for challenge */
	transmit_response_with_auth(p, "401 Unauthorized", req, p->randdata, reliable, "WWW-Authenticate", 0);
}

/*! \brief Verify registration of user 
	- Registration is done in several steps, first a REGISTER without auth
	  to get a challenge (nonce) then a second one with auth
	- Registration requests are only matched with peers that are marked as "dynamic"
 */
static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
					      struct sip_request *req, char *uri)
{
	enum check_auth_result res = AUTH_NOT_FOUND;
	struct sip_peer *peer;
	char tmp[256];
	char *name, *c;
	char *t;
	char *domain;

	/* Terminate URI */
	t = uri;
	while(*t && (*t > 32) && (*t != ';'))
		t++;
	*t = '\0';
	
	ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
	if (pedanticsipchecking)
		ast_uri_decode(tmp);

	c = get_in_brackets(tmp);
	c = strsep(&c, ";");	/* Ditch ;user=phone */

	if (!strncmp(c, "sip:", 4)) {
		name = c + 4;
	} else {
		name = c;
		ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
	}

	/* Strip off the domain name */
	if ((c = strchr(name, '@'))) {
		*c++ = '\0';
		domain = c;
		if ((c = strchr(domain, ':')))	/* Remove :port */
			*c = '\0';
		if (!AST_LIST_EMPTY(&domain_list)) {
			if (!check_sip_domain(domain, NULL, 0)) {
				transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
				return AUTH_UNKNOWN_DOMAIN;
			}
		}
	}

	ast_string_field_set(p, exten, name);
	build_contact(p);
	peer = find_peer(name, NULL, 1);
	if (!(peer && ast_apply_ha(peer->ha, sin))) {
		/* Peer fails ACL check */
		if (peer)
			ASTOBJ_UNREF(peer, sip_destroy_peer);
		peer = NULL;
	}
	if (peer) {
		/* Set Frame packetization */
		if (p->rtp) {
			ast_rtp_codec_setpref(p->rtp, &peer->prefs);
			p->autoframing = peer->autoframing;
		}
		if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)) {
			ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
		} else {
			ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
			transmit_response(p, "100 Trying", req);
			if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, ast_test_flag(req, SIP_PKT_IGNORE)))) {
				sip_cancel_destroy(p);

				/* We have a succesful registration attemp with proper authentication,
				   now, update the peer */
				switch (parse_register_contact(p, peer, req)) {
				case PARSE_REGISTER_FAILED:
					ast_log(LOG_WARNING, "Failed to parse contact info\n");
					transmit_response_with_date(p, "400 Bad Request", req);
					peer->lastmsgssent = -1;
					res = 0;
					break;
				case PARSE_REGISTER_QUERY:
					transmit_response_with_date(p, "200 OK", req);
					peer->lastmsgssent = -1;
					res = 0;
					break;
				case PARSE_REGISTER_UPDATE:
					update_peer(peer, p->expiry);
					/* Say OK and ask subsystem to retransmit msg counter */
					transmit_response_with_date(p, "200 OK", req);
					if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
						peer->lastmsgssent = -1;
					res = 0;
					break;
				}
			} 
		}
	}
	if (!peer && autocreatepeer) {
		/* Create peer if we have autocreate mode enabled */
		peer = temp_peer(name);
		if (peer) {
			ASTOBJ_CONTAINER_LINK(&peerl, peer);
			sip_cancel_destroy(p);
			switch (parse_register_contact(p, peer, req)) {
			case PARSE_REGISTER_FAILED:
				ast_log(LOG_WARNING, "Failed to parse contact info\n");
				transmit_response_with_date(p, "400 Bad Request", req);
				peer->lastmsgssent = -1;
				res = 0;
				break;
			case PARSE_REGISTER_QUERY:
				transmit_response_with_date(p, "200 OK", req);
				peer->lastmsgssent = -1;
				res = 0;
				break;
			case PARSE_REGISTER_UPDATE:
				/* Say OK and ask subsystem to retransmit msg counter */
				transmit_response_with_date(p, "200 OK", req);
				manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
				peer->lastmsgssent = -1;
				res = 0;
				break;
			}
		}
	}
	if (!res) {
		ast_device_state_changed("SIP/%s", peer->name);
	}
	if (res < 0) {
		switch (res) {
		case AUTH_SECRET_FAILED:
			/* Wrong password in authentication. Go away, don't try again until you fixed it */
			transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
			break;
		case AUTH_USERNAME_MISMATCH:
			/* Username and digest username does not match. 
			   Asterisk uses the From: username for authentication. We need the
			   users to use the same authentication user name until we support
			   proper authentication by digest auth name */
			transmit_response(p, "403 Authentication user name does not match account name", &p->initreq);
			break;
		case AUTH_NOT_FOUND:
			if (global_alwaysauthreject) {
				transmit_fake_auth_response(p, &p->initreq, 1);
			} else {
				/* URI not found */
				transmit_response(p, "404 Not found", &p->initreq);
			}
			break;
		default:
			break;
		}
		if (option_debug > 1) {
			const char *reason = "";

			switch (res) {
			case AUTH_SECRET_FAILED:
				reason = "Bad password";
				break;
			case AUTH_USERNAME_MISMATCH:
				reason = "Bad digest user";
				break;
			case AUTH_NOT_FOUND:
				reason = "Peer not found";
				break;
			default:
				break;
			}
			ast_log(LOG_DEBUG, "SIP REGISTER attempt failed for %s : %s\n",
				peer->name, reason);
		}
	}
	if (peer)
		ASTOBJ_UNREF(peer, sip_destroy_peer);

	return res;
}

/*! \brief Get referring dnis */
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
{
	char tmp[256], *c, *a;
	struct sip_request *req;
	
	req = oreq;
	if (!req)
		req = &p->initreq;
	ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
	if (ast_strlen_zero(tmp))
		return 0;
	c = get_in_brackets(tmp);
	if (strncmp(c, "sip:", 4)) {
		ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", c);
		return -1;
	}
	c += 4;
	a = c;
	strsep(&a, "@;");	/* trim anything after @ or ; */
	if (sip_debug_test_pvt(p))
		ast_verbose("RDNIS is %s\n", c);
	ast_string_field_set(p, rdnis, c);

	return 0;
}

/*! \brief Find out who the call is for 
	We use the INVITE uri to find out
*/
static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
{
	char tmp[256] = "", *uri, *a;
	char tmpf[256] = "", *from;
	struct sip_request *req;
	char *colon;
	
	req = oreq;
	if (!req)
		req = &p->initreq;

	/* Find the request URI */
	if (req->rlPart2)
		ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
	
	if (pedanticsipchecking)
		ast_uri_decode(tmp);

	uri = get_in_brackets(tmp);

	if (strncmp(uri, "sip:", 4)) {
		ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
		return -1;
	}
	uri += 4;

	/* Now find the From: caller ID and name */
	ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
	if (!ast_strlen_zero(tmpf)) {
		if (pedanticsipchecking)
			ast_uri_decode(tmpf);
		from = get_in_brackets(tmpf);
	} else {
		from = NULL;
	}
	
	if (!ast_strlen_zero(from)) {
		if (strncmp(from, "sip:", 4)) {
			ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
			return -1;
		}
		from += 4;
		if ((a = strchr(from, '@')))
			*a++ = '\0';
		else
			a = from;	/* just a domain */
		from = strsep(&from, ";");	/* Remove userinfo options */
		a = strsep(&a, ";");		/* Remove URI options */
		ast_string_field_set(p, fromdomain, a);
	}

	/* Skip any options and find the domain */

	/* Get the target domain */
	if ((a = strchr(uri, '@'))) {
		*a++ = '\0';
	} else {	/* No username part */
		a = uri;
		uri = "s";	/* Set extension to "s" */
	}
	colon = strchr(a, ':'); /* Remove :port */
	if (colon)
		*colon = '\0';

	uri = strsep(&uri, ";");	/* Remove userinfo options */
	a = strsep(&a, ";");		/* Remove URI options */

	ast_string_field_set(p, domain, a);

	if (!AST_LIST_EMPTY(&domain_list)) {
		char domain_context[AST_MAX_EXTENSION];

		domain_context[0] = '\0';
		if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
			if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
				if (option_debug)
					ast_log(LOG_DEBUG, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
				return -2;
			}
		}
		/* If we have a context defined, overwrite the original context */
		if (!ast_strlen_zero(domain_context))
			ast_string_field_set(p, context, domain_context);
	}

	if (sip_debug_test_pvt(p))
		ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);

	/* Check the dialplan for the username part of the request URI,
	   the domain will be stored in the SIPDOMAIN variable
		Return 0 if we have a matching extension */
	if (ast_exists_extension(NULL, p->context, uri, 1, from) ||
		!strcmp(uri, ast_pickup_ext())) {
		if (!oreq)
			ast_string_field_set(p, exten, uri);
		return 0;
	}

	/* Return 1 for pickup extension or overlap dialling support (if we support it) */
	if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
 	    ast_canmatch_extension(NULL, p->context, uri, 1, from)) ||
	    !strncmp(uri, ast_pickup_ext(), strlen(uri))) {
		return 1;
	}
	
	return -1;
}

/*! \brief Lock interface lock and find matching pvt lock  
	- Their tag is fromtag, our tag is to-tag
	- This means that in some transactions, totag needs to be their tag :-)
	  depending upon the direction
*/
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
{
	struct sip_pvt *sip_pvt_ptr;

	ast_mutex_lock(&iflock);

	if (option_debug > 3 && totag)
		ast_log(LOG_DEBUG, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");

	/* Search interfaces and find the match */
	for (sip_pvt_ptr = iflist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
		if (!strcmp(sip_pvt_ptr->callid, callid)) {
			int match = 1;
			char *ourtag = sip_pvt_ptr->tag;

			/* Go ahead and lock it (and its owner) before returning */
			ast_mutex_lock(&sip_pvt_ptr->lock);

			/* Check if tags match. If not, this is not the call we want
			   (With a forking SIP proxy, several call legs share the
			   call id, but have different tags)
			*/
			if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || strcmp(totag, ourtag)))
				match = 0;

			if (!match) {
				ast_mutex_unlock(&sip_pvt_ptr->lock);
				continue;
			}

			if (option_debug > 3 && totag)				 
				ast_log(LOG_DEBUG, "Matched %s call - their tag is %s Our tag is %s\n",
					ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
					sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);

			/* deadlock avoidance... */
			while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
				ast_mutex_unlock(&sip_pvt_ptr->lock);
				usleep(1);
				ast_mutex_lock(&sip_pvt_ptr->lock);
			}
			break;
		}
	}
	ast_mutex_unlock(&iflock);
	if (option_debug > 3 && !sip_pvt_ptr)
		ast_log(LOG_DEBUG, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
	return sip_pvt_ptr;
}

/*! \brief Call transfer support (the REFER method) 
 * 	Extracts Refer headers into pvt dialog structure */
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
{

	const char *p_referred_by = NULL;
	char *h_refer_to = NULL; 
	char *h_referred_by = NULL;
	char *refer_to;
	const char *p_refer_to;
	char *referred_by_uri = NULL;
	char *ptr;
	struct sip_request *req = NULL;
	const char *transfer_context = NULL;
	struct sip_refer *referdata;


	req = outgoing_req;
	referdata = transferer->refer;

	if (!req)
		req = &transferer->initreq;

	p_refer_to = get_header(req, "Refer-To");
	if (ast_strlen_zero(p_refer_to)) {
		ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
		return -2;	/* Syntax error */
	}
	h_refer_to = ast_strdupa(p_refer_to);
	refer_to = get_in_brackets(h_refer_to);
	if (pedanticsipchecking)
		ast_uri_decode(refer_to);

	if (strncasecmp(refer_to, "sip:", 4)) {
		ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
		return -3;
	}
	refer_to += 4;			/* Skip sip: */

	/* Get referred by header if it exists */
	p_referred_by = get_header(req, "Referred-By");
	if (!ast_strlen_zero(p_referred_by)) {
		char *lessthan;
		h_referred_by = ast_strdupa(p_referred_by);
		if (pedanticsipchecking)
			ast_uri_decode(h_referred_by);

		/* Store referrer's caller ID name */
		ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
		if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
			*(lessthan - 1) = '\0';	/* Space */
		}

		referred_by_uri = get_in_brackets(h_referred_by);
		if(strncasecmp(referred_by_uri, "sip:", 4)) {
			ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
			referred_by_uri = (char *) NULL;
		} else {
			referred_by_uri += 4;		/* Skip sip: */
		}
	}

	/* Check for arguments in the refer_to header */
	if ((ptr = strchr(refer_to, '?'))) { /* Search for arguments */
		*ptr++ = '\0';
		if (!strncasecmp(ptr, "REPLACES=", 9)) {
			char *to = NULL, *from = NULL;

			/* This is an attended transfer */
			referdata->attendedtransfer = 1;
			ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
			ast_uri_decode(referdata->replaces_callid);
			if ((ptr = strchr(referdata->replaces_callid, ';'))) 	/* Find options */ {
				*ptr++ = '\0';
			}

			if (ptr) {
				/* Find the different tags before we destroy the string */
				to = strcasestr(ptr, "to-tag=");
				from = strcasestr(ptr, "from-tag=");
			}

			/* Grab the to header */
			if (to) {
				ptr = to + 7;
				if ((to = strchr(ptr, '&')))
					*to = '\0';
				if ((to = strchr(ptr, ';')))
					*to = '\0';
				ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
			}

			if (from) {
				ptr = from + 9;
				if ((to = strchr(ptr, '&')))
					*to = '\0';
				if ((to = strchr(ptr, ';')))
					*to = '\0';
				ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
			}

			if (option_debug > 1) {
				if (!pedanticsipchecking)
					ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
				else
					ast_log(LOG_DEBUG,"Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
			}
		}
	}
	
	if ((ptr = strchr(refer_to, '@'))) {	/* Separate domain */
		char *urioption;

		*ptr++ = '\0';
		if ((urioption = strchr(ptr, ';')))
			*urioption++ = '\0';
		/* Save the domain for the dial plan */
		ast_copy_string(referdata->refer_to_domain, ptr, sizeof(referdata->refer_to_domain));
		if (urioption)
			ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
	}

	if ((ptr = strchr(refer_to, ';'))) 	/* Remove options */
		*ptr = '\0';
	ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
	
	if (referred_by_uri) {
		if ((ptr = strchr(referred_by_uri, ';'))) 	/* Remove options */
			*ptr = '\0';
		ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
	} else {
		referdata->referred_by[0] = '\0';
	}

	/* Determine transfer context */
	if (transferer->owner)	/* Mimic behaviour in res_features.c */
		transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");

	/* By default, use the context in the channel sending the REFER */
	if (ast_strlen_zero(transfer_context)) {
		transfer_context = S_OR(transferer->owner->macrocontext,
					S_OR(transferer->context, default_context));
	}

	ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
	
	/* Either an existing extension or the parking extension */
	if (ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
		if (sip_debug_test_pvt(transferer)) {
			ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
		}
		/* We are ready to transfer to the extension */
		return 0;
	} 
	if (sip_debug_test_pvt(transferer))
		ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);

	/* Failure, we can't find this extension */
	return -1;
}


/*! \brief Call transfer support (old way, deprecated by the IETF)--*/
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
{
	char tmp[256] = "", *c, *a;
	struct sip_request *req = oreq ? oreq : &p->initreq;
	struct sip_refer *referdata = p->refer;
	const char *transfer_context = NULL;
	
	ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
	c = get_in_brackets(tmp);

	if (pedanticsipchecking)
		ast_uri_decode(c);
	
	if (strncmp(c, "sip:", 4)) {
		ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
		return -1;
	}
	c += 4;
	if ((a = strchr(c, ';'))) 	/* Remove arguments */
		*a = '\0';
	
	if ((a = strchr(c, '@'))) {	/* Separate Domain */
		*a++ = '\0';
		ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
	}
	
	if (sip_debug_test_pvt(p))
		ast_verbose("Looking for %s in %s\n", c, p->context);

	if (p->owner)	/* Mimic behaviour in res_features.c */
		transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");

	/* By default, use the context in the channel sending the REFER */
	if (ast_strlen_zero(transfer_context)) {
		transfer_context = S_OR(p->owner->macrocontext,
					S_OR(p->context, default_context));
	}
	if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
		/* This is a blind transfer */
		if (option_debug)
			ast_log(LOG_DEBUG,"SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
		ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
		ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
		ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
		referdata->refer_call = NULL;
		/* Set new context */
		ast_string_field_set(p, context, transfer_context);
		return 0;
	} else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
		return 1;
	}

	return -1;
}
/*! \brief check Via: header for hostname, port and rport request/answer */
static void check_via(struct sip_pvt *p, struct sip_request *req)
{
	char via[256];
	char *c, *pt;
	struct hostent *hp;
	struct ast_hostent ahp;

	ast_copy_string(via, get_header(req, "Via"), sizeof(via));

	/* Check for rport */
	c = strstr(via, ";rport");
	if (c && (c[6] != '='))	/* rport query, not answer */
		ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);

	c = strchr(via, ';');
	if (c) 
		*c = '\0';

	c = strchr(via, ' ');
	if (c) {
		*c = '\0';
		c = ast_skip_blanks(c+1);
		if (strcasecmp(via, "SIP/2.0/UDP")) {
			ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
			return;
		}
		pt = strchr(c, ':');
		if (pt)
			*pt++ = '\0';	/* remember port pointer */
		hp = ast_gethostbyname(c, &ahp);
		if (!hp) {
			ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
			return;
		}
		memset(&p->sa, 0, sizeof(p->sa));
		p->sa.sin_family = AF_INET;
		memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
		p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);

		if (sip_debug_test_pvt(p)) {
			const struct sockaddr_in *dst = sip_real_dst(p);
			ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
		}
	}
}

/*! \brief  Get caller id name from SIP headers */
static char *get_calleridname(const char *input, char *output, size_t outputsize)
{
	const char *end = strchr(input,'<');	/* first_bracket */
	const char *tmp = strchr(input,'"');	/* first quote */
	int bytes = 0;
	int maxbytes = outputsize - 1;

	if (!end || end == input)	/* we require a part in brackets */
		return NULL;

	end--; /* move just before "<" */

	if (tmp && tmp <= end) {
		/* The quote (tmp) precedes the bracket (end+1).
		 * Find the matching quote and return the content.
		 */
		end = strchr(tmp+1, '"');
		if (!end)
			return NULL;
		bytes = (int) (end - tmp);
		/* protect the output buffer */
		if (bytes > maxbytes)
			bytes = maxbytes;
		ast_copy_string(output, tmp + 1, bytes);
	} else {
		/* No quoted string, or it is inside brackets. */
		/* clear the empty characters in the begining*/
		input = ast_skip_blanks(input);
		/* clear the empty characters in the end */
		while(*end && *end < 33 && end > input)
			end--;
		if (end >= input) {
			bytes = (int) (end - input) + 2;
			/* protect the output buffer */
			if (bytes > maxbytes)
				bytes = maxbytes;
			ast_copy_string(output, input, bytes);
		} else
			return NULL;
	}
	return output;
}

/*! \brief  Get caller id number from Remote-Party-ID header field 
 *	Returns true if number should be restricted (privacy setting found)
 *	output is set to NULL if no number found
 */
static int get_rpid_num(const char *input, char *output, int maxlen)
{
	char *start;
	char *end;

	start = strchr(input,':');
	if (!start) {
		output[0] = '\0';
		return 0;
	}
	start++;

	/* we found "number" */
	ast_copy_string(output,start,maxlen);
	output[maxlen-1] = '\0';

	end = strchr(output,'@');
	if (end)
		*end = '\0';
	else
		output[0] = '\0';
	if (strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
		return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;

	return 0;
}


/*! \brief  Check if matching user or peer is defined 
 	Match user on From: user name and peer on IP/port
	This is used on first invite (not re-invites) and subscribe requests 
    \return 0 on success, non-zero on failure
*/
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
					      int sipmethod, char *uri, enum xmittype reliable,
					      struct sockaddr_in *sin, struct sip_peer **authpeer)
{
	struct sip_user *user = NULL;
	struct sip_peer *peer;
	char from[256], *c;
	char *of;
	char rpid_num[50];
	const char *rpid;
	enum check_auth_result res = AUTH_SUCCESSFUL;
	char *t;
	char calleridname[50];
	int debug=sip_debug_test_addr(sin);
	struct ast_variable *tmpvar = NULL, *v = NULL;
	char *uri2 = ast_strdupa(uri);

	/* Terminate URI */
	t = uri2;
	while (*t && *t > 32 && *t != ';')
		t++;
	*t = '\0';
	ast_copy_string(from, get_header(req, "From"), sizeof(from));	/* XXX bug in original code, overwrote string */
	if (pedanticsipchecking)
		ast_uri_decode(from);
	/* XXX here tries to map the username for invite things */
	memset(calleridname, 0, sizeof(calleridname));
	get_calleridname(from, calleridname, sizeof(calleridname));
	if (calleridname[0])
		ast_string_field_set(p, cid_name, calleridname);

	rpid = get_header(req, "Remote-Party-ID");
	memset(rpid_num, 0, sizeof(rpid_num));
	if (!ast_strlen_zero(rpid)) 
		p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));

	of = get_in_brackets(from);
	if (ast_strlen_zero(p->exten)) {
		t = uri2;
		if (!strncmp(t, "sip:", 4))
			t+= 4;
		ast_string_field_set(p, exten, t);
		t = strchr(p->exten, '@');
		if (t)
			*t = '\0';
		if (ast_strlen_zero(p->our_contact))
			build_contact(p);
	}
	/* save the URI part of the From header */
	ast_string_field_set(p, from, of);
	if (strncmp(of, "sip:", 4)) {
		ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
	} else
		of += 4;
	/* Get just the username part */
	if ((c = strchr(of, '@'))) {
		char *tmp;
		*c = '\0';
		if ((c = strchr(of, ':')))
			*c = '\0';
		tmp = ast_strdupa(of);
		if (ast_is_shrinkable_phonenumber(tmp))
			ast_shrink_phone_number(tmp);
		ast_string_field_set(p, cid_num, tmp);
	}
	if (ast_strlen_zero(of))
		return AUTH_SUCCESSFUL;

	if (!authpeer)	/* If we are looking for a peer, don't check the user objects (or realtime) */
		user = find_user(of, 1);

	/* Find user based on user name in the from header */
	if (user && ast_apply_ha(user->ha, sin)) {
		ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
		ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
		/* copy channel vars */
		for (v = user->chanvars ; v ; v = v->next) {
			if ((tmpvar = ast_variable_new(v->name, v->value))) {
				tmpvar->next = p->chanvars; 
				p->chanvars = tmpvar;
			}
		}
		p->prefs = user->prefs;
		/* Set Frame packetization */
		if (p->rtp) {
			ast_rtp_codec_setpref(p->rtp, &p->prefs);
			p->autoframing = user->autoframing;
		}
		/* replace callerid if rpid found, and not restricted */
		if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
			char *tmp;
			if (*calleridname)
				ast_string_field_set(p, cid_name, calleridname);
			tmp = ast_strdupa(rpid_num);
			if (ast_is_shrinkable_phonenumber(tmp))
				ast_shrink_phone_number(tmp);
			ast_string_field_set(p, cid_num, tmp);
		}
		
		do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );

		if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
			sip_cancel_destroy(p);
			ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
			ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
			/* Copy SIP extensions profile from INVITE */
			if (p->sipoptions)
				user->sipoptions = p->sipoptions;

			/* If we have a call limit, set flag */
			if (user->call_limit)
				ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
			if (!ast_strlen_zero(user->context))
				ast_string_field_set(p, context, user->context);
			if (!ast_strlen_zero(user->cid_num) && !ast_strlen_zero(p->cid_num)) {
				char *tmp = ast_strdupa(user->cid_num);
				if (ast_is_shrinkable_phonenumber(tmp))
					ast_shrink_phone_number(tmp);
				ast_string_field_set(p, cid_num, tmp);
			}
			if (!ast_strlen_zero(user->cid_name) && !ast_strlen_zero(p->cid_num))
				ast_string_field_set(p, cid_name, user->cid_name);
			ast_string_field_set(p, username, user->name);
			ast_string_field_set(p, peername, user->name);
			ast_string_field_set(p, peersecret, user->secret);
			ast_string_field_set(p, peermd5secret, user->md5secret);
			ast_string_field_set(p, subscribecontext, user->subscribecontext);
			ast_string_field_set(p, accountcode, user->accountcode);
			ast_string_field_set(p, language, user->language);
			ast_string_field_set(p, mohsuggest, user->mohsuggest);
			ast_string_field_set(p, mohinterpret, user->mohinterpret);
			p->allowtransfer = user->allowtransfer;
			p->amaflags = user->amaflags;
			p->callgroup = user->callgroup;
			p->pickupgroup = user->pickupgroup;
			if (user->callingpres)	/* User callingpres setting will override RPID header */
				p->callingpres = user->callingpres;
			
			/* Set default codec settings for this call */
			p->capability = user->capability;		/* User codec choice */
			p->jointcapability = user->capability;		/* Our codecs */
			if (p->peercapability)				/* AND with peer's codecs */
				p->jointcapability &= p->peercapability;
			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;
			else
				p->noncodeccapability &= ~AST_RTP_DTMF;
			if (p->t38.peercapability)
				p->t38.jointcapability &= p->t38.peercapability;
			p->maxcallbitrate = user->maxcallbitrate;
			/* If we do not support video, remove video from call structure */
			if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
				ast_rtp_destroy(p->vrtp);
				p->vrtp = NULL;
			}
		}
		if (user && debug)
			ast_verbose("Found user '%s'\n", user->name);
	} else {
		if (user) {
			if (!authpeer && debug)
				ast_verbose("Found user '%s', but fails host access\n", user->name);
			ASTOBJ_UNREF(user,sip_destroy_user);
		}
		user = NULL;
	}

	if (!user) {
		/* If we didn't find a user match, check for peers */
		if (sipmethod == SIP_SUBSCRIBE)
			/* For subscribes, match on peer name only */
			peer = find_peer(of, NULL, 1);
		else
			/* Look for peer based on the IP address we received data from */
			/* If peer is registered from this IP address or have this as a default
			   IP address, this call is from the peer 
			*/
			peer = find_peer(NULL, &p->recv, 1);

		if (peer) {
			/* Set Frame packetization */
			if (p->rtp) {
				ast_rtp_codec_setpref(p->rtp, &peer->prefs);
				p->autoframing = peer->autoframing;
			}
			if (debug)
				ast_verbose("Found peer '%s'\n", peer->name);

			/* Take the peer */
			ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
			ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);

			/* Copy SIP extensions profile to peer */
			if (p->sipoptions)
				peer->sipoptions = p->sipoptions;

			/* replace callerid if rpid found, and not restricted */
			if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
				char *tmp = ast_strdupa(rpid_num);
				if (*calleridname)
					ast_string_field_set(p, cid_name, calleridname);
				if (ast_is_shrinkable_phonenumber(tmp))
					ast_shrink_phone_number(tmp);
				ast_string_field_set(p, cid_num, tmp);
			}
			do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));

			ast_string_field_set(p, peersecret, peer->secret);
			ast_string_field_set(p, peermd5secret, peer->md5secret);
			ast_string_field_set(p, subscribecontext, peer->subscribecontext);
			ast_string_field_set(p, mohinterpret, peer->mohinterpret);
			ast_string_field_set(p, mohsuggest, peer->mohsuggest);
			if (peer->callingpres)	/* Peer calling pres setting will override RPID */
				p->callingpres = peer->callingpres;
			if (peer->maxms && peer->lastms)
				p->timer_t1 = peer->lastms;
			if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
				/* Pretend there is no required authentication */
				ast_string_field_free(p, peersecret);
				ast_string_field_free(p, peermd5secret);
			}
			if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, ast_test_flag(req, SIP_PKT_IGNORE)))) {
				ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
				ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
				/* If we have a call limit, set flag */
				if (peer->call_limit)
					ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
				ast_string_field_set(p, peername, peer->name);
				ast_string_field_set(p, authname, peer->name);

				/* copy channel vars */
				for (v = peer->chanvars ; v ; v = v->next) {
					if ((tmpvar = ast_variable_new(v->name, v->value))) {
						tmpvar->next = p->chanvars; 
						p->chanvars = tmpvar;
					}
				}
				if (authpeer) {
					(*authpeer) = ASTOBJ_REF(peer);	/* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
				}

				if (!ast_strlen_zero(peer->username)) {
					ast_string_field_set(p, username, peer->username);
					/* Use the default username for authentication on outbound calls */
					/* XXX this takes the name from the caller... can we override ? */
					ast_string_field_set(p, authname, peer->username);
				}
				if (!ast_strlen_zero(peer->cid_num) && !ast_strlen_zero(p->cid_num)) {
					char *tmp = ast_strdupa(peer->cid_num);
					if (ast_is_shrinkable_phonenumber(tmp))
						ast_shrink_phone_number(tmp);
					ast_string_field_set(p, cid_num, tmp);
				}
				if (!ast_strlen_zero(peer->cid_name) && !ast_strlen_zero(p->cid_name)) 
					ast_string_field_set(p, cid_name, peer->cid_name);
				ast_string_field_set(p, fullcontact, peer->fullcontact);
				if (!ast_strlen_zero(peer->context))
					ast_string_field_set(p, context, peer->context);
				ast_string_field_set(p, peersecret, peer->secret);
				ast_string_field_set(p, peermd5secret, peer->md5secret);
				ast_string_field_set(p, language, peer->language);
				ast_string_field_set(p, accountcode, peer->accountcode);
				p->amaflags = peer->amaflags;
				p->callgroup = peer->callgroup;
				p->pickupgroup = peer->pickupgroup;
				p->capability = peer->capability;
				p->prefs = peer->prefs;
				p->jointcapability = peer->capability;
				if (p->peercapability)
					p->jointcapability &= p->peercapability;
				p->maxcallbitrate = peer->maxcallbitrate;
				if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
					ast_rtp_destroy(p->vrtp);
					p->vrtp = NULL;
				}
				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;
				else
					p->noncodeccapability &= ~AST_RTP_DTMF;
				if (p->t38.peercapability)
					p->t38.jointcapability &= p->t38.peercapability;
			}
			ASTOBJ_UNREF(peer, sip_destroy_peer);
		} else { 
			if (debug)
				ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));

			/* do we allow guests? */
			if (!global_allowguest) {
				if (global_alwaysauthreject)
					res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
				else
					res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
			}
		}

	}

	if (user)
		ASTOBJ_UNREF(user, sip_destroy_user);
	return res;
}

/*! \brief  Find user 
	If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
*/
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
{
	return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
}

/*! \brief  Get text out of a SIP MESSAGE packet */
static int get_msg_text(char *buf, int len, struct sip_request *req)
{
	int x;
	int y;

	buf[0] = '\0';
	y = len - strlen(buf) - 5;
	if (y < 0)
		y = 0;
	for (x=0;x<req->lines;x++) {
		strncat(buf, req->line[x], y); /* safe */
		y -= strlen(req->line[x]) + 1;
		if (y < 0)
			y = 0;
		if (y != 0)
			strcat(buf, "\n"); /* safe */
	}
	return 0;
}


/*! \brief  Receive SIP MESSAGE method messages
\note	We only handle messages within current calls currently 
	Reference: RFC 3428 */
static void receive_message(struct sip_pvt *p, struct sip_request *req)
{
	char buf[1024];
	struct ast_frame f;
	const char *content_type = get_header(req, "Content-Type");

	if (strcmp(content_type, "text/plain")) { /* No text/plain attachment */
		transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return;
	}

	if (get_msg_text(buf, sizeof(buf), req)) {
		ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
		transmit_response(p, "202 Accepted", req);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return;
	}

	if (p->owner) {
		if (sip_debug_test_pvt(p))
			ast_verbose("Message received: '%s'\n", buf);
		memset(&f, 0, sizeof(f));
		f.frametype = AST_FRAME_TEXT;
		f.subclass = 0;
		f.offset = 0;
		f.data = buf;
		f.datalen = strlen(buf);
		ast_queue_frame(p->owner, &f);
		transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
	} else { /* Message outside of a call, we do not support that */
		ast_log(LOG_WARNING,"Received message to %s from %s, dropped it...\n  Content-Type:%s\n  Message: %s\n", get_header(req,"To"), get_header(req,"From"), content_type, buf);
		transmit_response(p, "405 Method Not Allowed", req); /* Good enough, or? */
	}
	sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	return;
}

/*! \brief  CLI Command to show calls within limits set by call_limit */
static int sip_show_inuse(int fd, int argc, char *argv[])
{
#define FORMAT  "%-25.25s %-15.15s %-15.15s \n"
#define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
	char ilimits[40];
	char iused[40];
	int showall = FALSE;

	if (argc < 3) 
		return RESULT_SHOWUSAGE;

	if (argc == 4 && !strcmp(argv[3],"all")) 
			showall = TRUE;
	
	ast_cli(fd, FORMAT, "* User name", "In use", "Limit");
	ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
		ASTOBJ_RDLOCK(iterator);
		if (iterator->call_limit)
			snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
		else 
			ast_copy_string(ilimits, "N/A", sizeof(ilimits));
		snprintf(iused, sizeof(iused), "%d", iterator->inUse);
		if (showall || iterator->call_limit)
			ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
		ASTOBJ_UNLOCK(iterator);
	} while (0) );

	ast_cli(fd, FORMAT, "* Peer name", "In use", "Limit");

	ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
		ASTOBJ_RDLOCK(iterator);
		if (iterator->call_limit)
			snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
		else 
			ast_copy_string(ilimits, "N/A", sizeof(ilimits));
		snprintf(iused, sizeof(iused), "%d/%d", iterator->inUse, iterator->inRinging);
		if (showall || iterator->call_limit)
			ast_cli(fd, FORMAT2, iterator->name, iused, ilimits);
		ASTOBJ_UNLOCK(iterator);
	} while (0) );

	return RESULT_SUCCESS;
#undef FORMAT
#undef FORMAT2
}

/*! \brief Convert transfer mode to text string */
static char *transfermode2str(enum transfermodes mode)
{
	if (mode == TRANSFER_OPENFORALL)
		return "open";
	else if (mode == TRANSFER_CLOSED)
		return "closed";
	return "strict";
}

/*! \brief  Convert NAT setting to text string */
static char *nat2str(int nat)
{
	switch(nat) {
	case SIP_NAT_NEVER:
		return "No";
	case SIP_NAT_ROUTE:
		return "Route";
	case SIP_NAT_ALWAYS:
		return "Always";
	case SIP_NAT_RFC3581:
		return "RFC3581";
	default:
		return "Unknown";
	}
}

/*! \brief  Report Peer status in character string
 *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
 */
static int peer_status(struct sip_peer *peer, char *status, int statuslen)
{
	int res = 0;
	if (peer->maxms) {
		if (peer->lastms < 0) {
			ast_copy_string(status, "UNREACHABLE", statuslen);
		} else if (peer->lastms > peer->maxms) {
			snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
			res = 1;
		} else if (peer->lastms) {
			snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
			res = 1;
		} else {
			ast_copy_string(status, "UNKNOWN", statuslen);
		}
	} else { 
		ast_copy_string(status, "Unmonitored", statuslen);
		/* Checking if port is 0 */
		res = -1;
	}
	return res;
}

/*! \brief  CLI Command 'SIP Show Users' */
static int sip_show_users(int fd, int argc, char *argv[])
{
	regex_t regexbuf;
	int havepattern = FALSE;

#define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"

	switch (argc) {
	case 5:
		if (!strcasecmp(argv[3], "like")) {
			if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
				return RESULT_SHOWUSAGE;
			havepattern = TRUE;
		} else
			return RESULT_SHOWUSAGE;
	case 3:
		break;
	default:
		return RESULT_SHOWUSAGE;
	}

	ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
	ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
		ASTOBJ_RDLOCK(iterator);

		if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
			ASTOBJ_UNLOCK(iterator);
			continue;
		}

		ast_cli(fd, FORMAT, iterator->name, 
			iterator->secret, 
			iterator->accountcode,
			iterator->context,
			iterator->ha ? "Yes" : "No",
			nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
		ASTOBJ_UNLOCK(iterator);
	} while (0)
	);

	if (havepattern)
		regfree(&regexbuf);

	return RESULT_SUCCESS;
#undef FORMAT
}

static char mandescr_show_peers[] = 
"Description: Lists SIP peers in text format with details on current status.\n"
"Variables: \n"
"  ActionID: <id>	Action ID for this transaction. Will be returned.\n";

/*! \brief  Show SIP peers in the manager API */
/*    Inspired from chan_iax2 */
static int manager_sip_show_peers( struct mansession *s, struct message *m )
{
	char *id = astman_get_header(m,"ActionID");
	char *a[] = { "sip", "show", "peers" };
	char idtext[256] = "";
	int total = 0;

	if (!ast_strlen_zero(id))
		snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);

	astman_send_ack(s, m, "Peer status list will follow");
	/* List the peers in separate manager events */
	_sip_show_peers(-1, &total, s, m, 3, a);
	/* Send final confirmation */
	astman_append(s,
	"Event: PeerlistComplete\r\n"
	"ListItems: %d\r\n"
	"%s"
	"\r\n", total, idtext);
	return 0;
}

/*! \brief  CLI Show Peers command */
static int sip_show_peers(int fd, int argc, char *argv[])
{
	return _sip_show_peers(fd, NULL, NULL, NULL, argc, argv);
}

/*! \brief  _sip_show_peers: Execute sip show peers command */
static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[])
{
	regex_t regexbuf;
	int havepattern = FALSE;

#define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %-10s\n"
#define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %-10s\n"

	char name[256];
	int total_peers = 0;
	int peers_mon_online = 0;
	int peers_mon_offline = 0;
	int peers_unmon_offline = 0;
	int peers_unmon_online = 0;
	char *id;
	char idtext[256] = "";
	int realtimepeers;

	realtimepeers = ast_check_realtime("sippeers");

	if (s) {	/* Manager - get ActionID */
		id = astman_get_header(m,"ActionID");
		if (!ast_strlen_zero(id))
			snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
	}

	switch (argc) {
	case 5:
		if (!strcasecmp(argv[3], "like")) {
			if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
				return RESULT_SHOWUSAGE;
			havepattern = TRUE;
		} else
			return RESULT_SHOWUSAGE;
	case 3:
		break;
	default:
		return RESULT_SHOWUSAGE;
	}

	if (!s) /* Normal list */
		ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
	
	ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
		char status[20] = "";
		char srch[2000];
		char pstatus;
		
		ASTOBJ_RDLOCK(iterator);

		if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
			ASTOBJ_UNLOCK(iterator);
			continue;
		}

		if (!ast_strlen_zero(iterator->username) && !s)
			snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
		else
			ast_copy_string(name, iterator->name, sizeof(name));
		
		pstatus = peer_status(iterator, status, sizeof(status));
		if (pstatus == 1)
			peers_mon_online++;
		else if (pstatus == 0)
			peers_mon_offline++;
		else {
			if (iterator->addr.sin_port == 0)
				peers_unmon_offline++;
			else
				peers_unmon_online++;
		}

		snprintf(srch, sizeof(srch), FORMAT, name,
			iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
			ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : "   ", 	/* Dynamic or not? */
			ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : "   ",	/* NAT=yes? */
			iterator->ha ? " A " : "   ", 	/* permit/deny */
			ntohs(iterator->addr.sin_port), status,
			realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");

		if (!s)  {/* Normal CLI list */
			ast_cli(fd, FORMAT, name, 
			iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
			ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? " D " : "   ", 	/* Dynamic or not? */
			ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : "   ",	/* NAT=yes? */
			iterator->ha ? " A " : "   ",       /* permit/deny */
			
			ntohs(iterator->addr.sin_port), status,
			realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "Cached RT":"") : "");
		} else {	/* Manager format */
			/* The names here need to be the same as other channels */
			astman_append(s, 
			"Event: PeerEntry\r\n%s"
			"Channeltype: SIP\r\n"
			"ObjectName: %s\r\n"
			"ChanObjectType: peer\r\n"	/* "peer" or "user" */
			"IPaddress: %s\r\n"
			"IPport: %d\r\n"
			"Dynamic: %s\r\n"
			"Natsupport: %s\r\n"
			"VideoSupport: %s\r\n"
			"ACL: %s\r\n"
			"Status: %s\r\n"
			"RealtimeDevice: %s\r\n\r\n", 
			idtext,
			iterator->name, 
			iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
			ntohs(iterator->addr.sin_port), 
			ast_test_flag(&iterator->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no", 	/* Dynamic or not? */
			ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",	/* NAT=yes? */
			ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",	/* VIDEOSUPPORT=yes? */
			iterator->ha ? "yes" : "no",       /* permit/deny */
			status,
			realtimepeers ? (ast_test_flag(&iterator->flags[0], SIP_REALTIME) ? "yes":"no") : "no");
		}

		ASTOBJ_UNLOCK(iterator);

		total_peers++;
	} while(0) );
	
	if (!s)
		ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
		        total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);

	if (havepattern)
		regfree(&regexbuf);

	if (total)
		*total = total_peers;
	

	return RESULT_SUCCESS;
#undef FORMAT
#undef FORMAT2
}

/*! \brief List all allocated SIP Objects (realtime or static) */
static int sip_show_objects(int fd, int argc, char *argv[])
{
	char tmp[256];
	if (argc != 3)
		return RESULT_SHOWUSAGE;
	ast_cli(fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
	ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &userl);
	ast_cli(fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
	ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &peerl);
	ast_cli(fd, "-= Registry objects: %d =-\n\n", regobjs);
	ASTOBJ_CONTAINER_DUMP(fd, tmp, sizeof(tmp), &regl);
	return RESULT_SUCCESS;
}
/*! \brief Print call group and pickup group */
static void  print_group(int fd, ast_group_t group, int crlf)
{
	char buf[256];
	ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
}

/*! \brief Convert DTMF mode to printable string */
static const char *dtmfmode2str(int mode)
{
	switch (mode) {
	case SIP_DTMF_RFC2833:
		return "rfc2833";
	case SIP_DTMF_INFO:
		return "info";
	case SIP_DTMF_INBAND:
		return "inband";
	case SIP_DTMF_AUTO:
		return "auto";
	}
	return "<error>";
}

/*! \brief Convert Insecure setting to printable string */
static const char *insecure2str(int port, int invite)
{
	if (port && invite)
		return "port,invite";
	else if (port)
		return "port";
	else if (invite)
		return "invite";
	else
		return "no";
}

/*! \brief Destroy disused contexts between reloads
	Only used in reload_config so the code for regcontext doesn't get ugly
*/
static void cleanup_stale_contexts(char *new, char *old)
{
	char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];

	while ((oldcontext = strsep(&old, "&"))) {
		stalecontext = '\0';
		ast_copy_string(newlist, new, sizeof(newlist));
		stringp = newlist;
		while ((newcontext = strsep(&stringp, "&"))) {
			if (strcmp(newcontext, oldcontext) == 0) {
				/* This is not the context you're looking for */
				stalecontext = '\0';
				break;
			} else if (strcmp(newcontext, oldcontext)) {
				stalecontext = oldcontext;
			}
			
		}
		if (stalecontext)
			ast_context_destroy(ast_context_find(stalecontext), "SIP");
	}
}

/*! \brief Remove temporary realtime objects from memory (CLI) */
static int sip_prune_realtime(int fd, int argc, char *argv[])
{
	struct sip_peer *peer;
	struct sip_user *user;
	int pruneuser = FALSE;
	int prunepeer = FALSE;
	int multi = FALSE;
	char *name = NULL;
	regex_t regexbuf;

	switch (argc) {
	case 4:
		if (!strcasecmp(argv[3], "user"))
			return RESULT_SHOWUSAGE;
		if (!strcasecmp(argv[3], "peer"))
			return RESULT_SHOWUSAGE;
		if (!strcasecmp(argv[3], "like"))
			return RESULT_SHOWUSAGE;
		if (!strcasecmp(argv[3], "all")) {
			multi = TRUE;
			pruneuser = prunepeer = TRUE;
		} else {
			pruneuser = prunepeer = TRUE;
			name = argv[3];
		}
		break;
	case 5:
		if (!strcasecmp(argv[4], "like"))
			return RESULT_SHOWUSAGE;
		if (!strcasecmp(argv[3], "all"))
			return RESULT_SHOWUSAGE;
		if (!strcasecmp(argv[3], "like")) {
			multi = TRUE;
			name = argv[4];
			pruneuser = prunepeer = TRUE;
		} else if (!strcasecmp(argv[3], "user")) {
			pruneuser = TRUE;
			if (!strcasecmp(argv[4], "all"))
				multi = TRUE;
			else
				name = argv[4];
		} else if (!strcasecmp(argv[3], "peer")) {
			prunepeer = TRUE;
			if (!strcasecmp(argv[4], "all"))
				multi = TRUE;
			else
				name = argv[4];
		} else
			return RESULT_SHOWUSAGE;
		break;
	case 6:
		if (strcasecmp(argv[4], "like"))
			return RESULT_SHOWUSAGE;
		if (!strcasecmp(argv[3], "user")) {
			pruneuser = TRUE;
			name = argv[5];
		} else if (!strcasecmp(argv[3], "peer")) {
			prunepeer = TRUE;
			name = argv[5];
		} else
			return RESULT_SHOWUSAGE;
		break;
	default:
		return RESULT_SHOWUSAGE;
	}

	if (multi && name) {
		if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
			return RESULT_SHOWUSAGE;
	}

	if (multi) {
		if (prunepeer) {
			int pruned = 0;

			ASTOBJ_CONTAINER_WRLOCK(&peerl);
			ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
				ASTOBJ_RDLOCK(iterator);
				if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
					ASTOBJ_UNLOCK(iterator);
					continue;
				};
				if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
					ASTOBJ_MARK(iterator);
					pruned++;
				}
				ASTOBJ_UNLOCK(iterator);
			} while (0) );
			if (pruned) {
				ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
				ast_cli(fd, "%d peers pruned.\n", pruned);
			} else
				ast_cli(fd, "No peers found to prune.\n");
			ASTOBJ_CONTAINER_UNLOCK(&peerl);
		}
		if (pruneuser) {
			int pruned = 0;

			ASTOBJ_CONTAINER_WRLOCK(&userl);
			ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
				ASTOBJ_RDLOCK(iterator);
				if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
					ASTOBJ_UNLOCK(iterator);
					continue;
				};
				if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
					ASTOBJ_MARK(iterator);
					pruned++;
				}
				ASTOBJ_UNLOCK(iterator);
			} while (0) );
			if (pruned) {
				ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
				ast_cli(fd, "%d users pruned.\n", pruned);
			} else
				ast_cli(fd, "No users found to prune.\n");
			ASTOBJ_CONTAINER_UNLOCK(&userl);
		}
	} else {
		if (prunepeer) {
			if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
				if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
					ast_cli(fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
					ASTOBJ_CONTAINER_LINK(&peerl, peer);
				} else
					ast_cli(fd, "Peer '%s' pruned.\n", name);
				ASTOBJ_UNREF(peer, sip_destroy_peer);
			} else
				ast_cli(fd, "Peer '%s' not found.\n", name);
		}
		if (pruneuser) {
			if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
				if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
					ast_cli(fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
					ASTOBJ_CONTAINER_LINK(&userl, user);
				} else
					ast_cli(fd, "User '%s' pruned.\n", name);
				ASTOBJ_UNREF(user, sip_destroy_user);
			} else
				ast_cli(fd, "User '%s' not found.\n", name);
		}
	}

	return RESULT_SUCCESS;
}

/*! \brief Print codec list from preference to CLI/manager */
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
{
	int x, codec;

	for(x = 0; x < 32 ; x++) {
		codec = ast_codec_pref_index(pref, x);
		if (!codec)
			break;
		ast_cli(fd, "%s", ast_getformatname(codec));
		ast_cli(fd, ":%d", pref->framing[x]);
		if (x < 31 && ast_codec_pref_index(pref, x + 1))
			ast_cli(fd, ",");
	}
	if (!x)
		ast_cli(fd, "none");
}

/*! \brief Print domain mode to cli */
static const char *domain_mode_to_text(const enum domain_mode mode)
{
	switch (mode) {
	case SIP_DOMAIN_AUTO:
		return "[Automatic]";
	case SIP_DOMAIN_CONFIG:
		return "[Configured]";
	}

	return "";
}

/*! \brief CLI command to list local domains */
static int sip_show_domains(int fd, int argc, char *argv[])
{
	struct domain *d;
#define FORMAT "%-40.40s %-20.20s %-16.16s\n"

	if (AST_LIST_EMPTY(&domain_list)) {
		ast_cli(fd, "SIP Domain support not enabled.\n\n");
		return RESULT_SUCCESS;
	} else {
		ast_cli(fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
		AST_LIST_LOCK(&domain_list);
		AST_LIST_TRAVERSE(&domain_list, d, list)
			ast_cli(fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
				domain_mode_to_text(d->mode));
		AST_LIST_UNLOCK(&domain_list);
		ast_cli(fd, "\n");
		return RESULT_SUCCESS;
	}
}
#undef FORMAT

static char mandescr_show_peer[] = 
"Description: Show one SIP peer with details on current status.\n"
"Variables: \n"
"  Peer: <name>           The peer name you want to check.\n"
"  ActionID: <id>	  Optional action ID for this AMI transaction.\n";

/*! \brief Show SIP peers in the manager API  */
static int manager_sip_show_peer( struct mansession *s, struct message *m)
{
	char *id = astman_get_header(m,"ActionID");
	char *a[4];
	char *peer;
	int ret;

	peer = astman_get_header(m,"Peer");
	if (ast_strlen_zero(peer)) {
		astman_send_error(s, m, "Peer: <name> missing.\n");
		return 0;
	}
	a[0] = "sip";
	a[1] = "show";
	a[2] = "peer";
	a[3] = peer;

	if (!ast_strlen_zero(id))
		astman_append(s, "ActionID: %s\r\n",id);
	ret = _sip_show_peer(1, -1, s, m, 4, a );
	astman_append(s, "\r\n\r\n" );
	return ret;
}



/*! \brief Show one peer in detail */
static int sip_show_peer(int fd, int argc, char *argv[])
{
	return _sip_show_peer(0, fd, NULL, NULL, argc, argv);
}

/*! \brief Show one peer in detail (main function) */
static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[])
{
	char status[30] = "";
	char cbuf[256];
	struct sip_peer *peer;
	char codec_buf[512];
	struct ast_codec_pref *pref;
	struct ast_variable *v;
	struct sip_auth *auth;
	int x = 0, codec = 0, load_realtime;
	int realtimepeers;

	realtimepeers = ast_check_realtime("sippeers");

	if (argc < 4)
		return RESULT_SHOWUSAGE;

	load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
	peer = find_peer(argv[3], NULL, load_realtime);
	if (s) { 	/* Manager */
		if (peer)
			astman_append(s, "Response: Success\r\n");
		else {
			snprintf (cbuf, sizeof(cbuf), "Peer %s not found.\n", argv[3]);
			astman_send_error(s, m, cbuf);
			return 0;
		}
	}
	if (peer && type==0 ) { /* Normal listing */
		ast_cli(fd,"\n\n");
		ast_cli(fd, "  * Name       : %s\n", peer->name);
		if (realtimepeers) {	/* Realtime is enabled */
			ast_cli(fd, "  Realtime peer: %s\n", ast_test_flag(&peer->flags[0], SIP_REALTIME) ? "Yes, cached" : "No");
		}
		ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
		ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
		for (auth = peer->auth; auth; auth = auth->next) {
			ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
			ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
		}
		ast_cli(fd, "  Context      : %s\n", peer->context);
		ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
		ast_cli(fd, "  Language     : %s\n", peer->language);
		if (!ast_strlen_zero(peer->accountcode))
			ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
		ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
		ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
		ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
		if (!ast_strlen_zero(peer->fromuser))
			ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
		if (!ast_strlen_zero(peer->fromdomain))
			ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
		ast_cli(fd, "  Callgroup    : ");
		print_group(fd, peer->callgroup, 0);
		ast_cli(fd, "  Pickupgroup  : ");
		print_group(fd, peer->pickupgroup, 0);
		ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
		ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
		ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
		ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
		ast_cli(fd, "  Dynamic      : %s\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Yes":"No"));
		ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
		ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
		ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
		ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT), ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)));
		ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
		ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
		ast_cli(fd, "  T38 pt UDPTL : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_UDPTL)?"Yes":"No");
#ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
		ast_cli(fd, "  T38 pt RTP   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_RTP)?"Yes":"No");
		ast_cli(fd, "  T38 pt TCP   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT_TCP)?"Yes":"No");
#endif
		ast_cli(fd, "  CanReinvite  : %s\n", ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Yes":"No");
		ast_cli(fd, "  PromiscRedir : %s\n", ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Yes":"No");
		ast_cli(fd, "  User=Phone   : %s\n", ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Yes":"No");
		ast_cli(fd, "  Video Support: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Yes":"No");
		ast_cli(fd, "  Trust RPID   : %s\n", ast_test_flag(&peer->flags[0], SIP_TRUSTRPID) ? "Yes" : "No");
		ast_cli(fd, "  Send RPID    : %s\n", ast_test_flag(&peer->flags[0], SIP_SENDRPID) ? "Yes" : "No");
		ast_cli(fd, "  Subscriptions: %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
		ast_cli(fd, "  Overlap dial : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");

		/* - is enumerated */
		ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
		ast_cli(fd, "  LastMsg      : %d\n", peer->lastmsg);
		ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
		ast_cli(fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
		ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
		if (!ast_strlen_zero(global_regcontext))
			ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
		ast_cli(fd, "  Def. Username: %s\n", peer->username);
		ast_cli(fd, "  SIP Options  : ");
		if (peer->sipoptions) {
			int lastoption = -1;
			for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
				if (sip_options[x].id != lastoption) {
					if (peer->sipoptions & sip_options[x].id)
						ast_cli(fd, "%s ", sip_options[x].text);
					lastoption = x;
				}
			}
		} else
			ast_cli(fd, "(none)");

		ast_cli(fd, "\n");
		ast_cli(fd, "  Codecs       : ");
		ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
		ast_cli(fd, "%s\n", codec_buf);
		ast_cli(fd, "  Codec Order  : (");
		print_codec_to_cli(fd, &peer->prefs);
		ast_cli(fd, ")\n");

		ast_cli(fd, "  Auto-Framing:  %s \n", peer->autoframing ? "Yes" : "No");
		ast_cli(fd, "  Status       : ");
		peer_status(peer, status, sizeof(status));
		ast_cli(fd, "%s\n",status);
 		ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
 		ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
		if (peer->chanvars) {
 			ast_cli(fd, "  Variables    :\n");
			for (v = peer->chanvars ; v ; v = v->next)
 				ast_cli(fd, "                 %s = %s\n", v->name, v->value);
		}
		ast_cli(fd,"\n");
		ASTOBJ_UNREF(peer,sip_destroy_peer);
	} else  if (peer && type == 1) { /* manager listing */
		char buf[256];
		astman_append(s, "Channeltype: SIP\r\n");
		astman_append(s, "ObjectName: %s\r\n", peer->name);
		astman_append(s, "ChanObjectType: peer\r\n");
		astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
		astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
		astman_append(s, "Context: %s\r\n", peer->context);
		astman_append(s, "Language: %s\r\n", peer->language);
		if (!ast_strlen_zero(peer->accountcode))
			astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
		astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
		astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
		if (!ast_strlen_zero(peer->fromuser))
			astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
		if (!ast_strlen_zero(peer->fromdomain))
			astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
		astman_append(s, "Callgroup: ");
		astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
		astman_append(s, "Pickupgroup: ");
		astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
		astman_append(s, "VoiceMailbox: %s\r\n", peer->mailbox);
		astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
		astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
		astman_append(s, "Call limit: %d\r\n", peer->call_limit);
		astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
		astman_append(s, "Dynamic: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC)?"Y":"N"));
		astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
		astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched,peer->expire));
		astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT), ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)));
		astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
		astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
		astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
		astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
		astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
		astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));

		/* - is enumerated */
		astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
		astman_append(s, "SIPLastMsg: %d\r\n", peer->lastmsg);
		astman_append(s, "ToHost: %s\r\n", peer->tohost);
		astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
		astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
		astman_append(s, "Default-Username: %s\r\n", peer->username);
		if (!ast_strlen_zero(global_regcontext))
			astman_append(s, "RegExtension: %s\r\n", peer->regexten);
		astman_append(s, "Codecs: ");
		ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
		astman_append(s, "%s\r\n", codec_buf);
		astman_append(s, "CodecOrder: ");
		pref = &peer->prefs;
		for(x = 0; x < 32 ; x++) {
			codec = ast_codec_pref_index(pref,x);
			if (!codec)
				break;
			astman_append(s, "%s", ast_getformatname(codec));
			if (x < 31 && ast_codec_pref_index(pref,x+1))
				astman_append(s, ",");
		}

		astman_append(s, "\r\n");
		astman_append(s, "Status: ");
		peer_status(peer, status, sizeof(status));
		astman_append(s, "%s\r\n", status);
 		astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
 		astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
		if (peer->chanvars) {
			for (v = peer->chanvars ; v ; v = v->next) {
 				astman_append(s, "ChanVariable:\n");
 				astman_append(s, " %s,%s\r\n", v->name, v->value);
			}
		}

		ASTOBJ_UNREF(peer,sip_destroy_peer);

	} else {
		ast_cli(fd,"Peer %s not found.\n", argv[3]);
		ast_cli(fd,"\n");
	}

	return RESULT_SUCCESS;
}

/*! \brief Show one user in detail */
static int sip_show_user(int fd, int argc, char *argv[])
{
	char cbuf[256];
	struct sip_user *user;
	struct ast_variable *v;
	int load_realtime;

	if (argc < 4)
		return RESULT_SHOWUSAGE;

	/* Load from realtime storage? */
	load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;

	user = find_user(argv[3], load_realtime);
	if (user) {
		ast_cli(fd,"\n\n");
		ast_cli(fd, "  * Name       : %s\n", user->name);
		ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
		ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
		ast_cli(fd, "  Context      : %s\n", user->context);
		ast_cli(fd, "  Language     : %s\n", user->language);
		if (!ast_strlen_zero(user->accountcode))
			ast_cli(fd, "  Accountcode  : %s\n", user->accountcode);
		ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
		ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
		ast_cli(fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
		ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
		ast_cli(fd, "  Call limit   : %d\n", user->call_limit);
		ast_cli(fd, "  Callgroup    : ");
		print_group(fd, user->callgroup, 0);
		ast_cli(fd, "  Pickupgroup  : ");
		print_group(fd, user->pickupgroup, 0);
		ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
		ast_cli(fd, "  ACL          : %s\n", (user->ha?"Yes":"No"));
		ast_cli(fd, "  Codec Order  : (");
		print_codec_to_cli(fd, &user->prefs);
		ast_cli(fd, ")\n");

		ast_cli(fd, "  Auto-Framing:  %s \n", user->autoframing ? "Yes" : "No");
		if (user->chanvars) {
 			ast_cli(fd, "  Variables    :\n");
			for (v = user->chanvars ; v ; v = v->next)
 				ast_cli(fd, "                 %s = %s\n", v->name, v->value);
		}
		ast_cli(fd,"\n");
		ASTOBJ_UNREF(user,sip_destroy_user);
	} else {
		ast_cli(fd,"User %s not found.\n", argv[3]);
		ast_cli(fd,"\n");
	}

	return RESULT_SUCCESS;
}

/*! \brief  Show SIP Registry (registrations with other SIP proxies */
static int sip_show_registry(int fd, int argc, char *argv[])
{
#define FORMAT2 "%-30.30s  %-12.12s  %8.8s %-20.20s %-25.25s\n"
#define FORMAT  "%-30.30s  %-12.12s  %8d %-20.20s %-25.25s\n"
	char host[80];
	char tmpdat[256];
	struct tm tm;


	if (argc != 3)
		return RESULT_SHOWUSAGE;
	ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
	ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
		ASTOBJ_RDLOCK(iterator);
		snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
		if (iterator->regtime) {
			ast_localtime(&iterator->regtime, &tm, NULL);
			strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
		} else {
			tmpdat[0] = 0;
		}
		ast_cli(fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
		ASTOBJ_UNLOCK(iterator);
	} while(0));
	return RESULT_SUCCESS;
#undef FORMAT
#undef FORMAT2
}

/*! \brief List global settings for the SIP channel */
static int sip_show_settings(int fd, int argc, char *argv[])
{
	int realtimepeers;
	int realtimeusers;

	realtimepeers = ast_check_realtime("sippeers");
	realtimeusers = ast_check_realtime("sipusers");

	if (argc != 3)
		return RESULT_SHOWUSAGE;
	ast_cli(fd, "\n\nGlobal Settings:\n");
	ast_cli(fd, "----------------\n");
	ast_cli(fd, "  SIP Port:               %d\n", ntohs(bindaddr.sin_port));
	ast_cli(fd, "  Bindaddress:            %s\n", ast_inet_ntoa(bindaddr.sin_addr));
	ast_cli(fd, "  Videosupport:           %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "Yes" : "No");
	ast_cli(fd, "  AutoCreatePeer:         %s\n", autocreatepeer ? "Yes" : "No");
	ast_cli(fd, "  Allow unknown access:   %s\n", global_allowguest ? "Yes" : "No");
	ast_cli(fd, "  Allow subscriptions:    %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE) ? "Yes" : "No");
	ast_cli(fd, "  Allow overlap dialing:  %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) ? "Yes" : "No");
	ast_cli(fd, "  Promsic. redir:         %s\n", ast_test_flag(&global_flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
	ast_cli(fd, "  SIP domain support:     %s\n", AST_LIST_EMPTY(&domain_list) ? "No" : "Yes");
	ast_cli(fd, "  Call to non-local dom.: %s\n", allow_external_domains ? "Yes" : "No");
	ast_cli(fd, "  URI user is phone no:   %s\n", ast_test_flag(&global_flags[0], SIP_USEREQPHONE) ? "Yes" : "No");
	ast_cli(fd, "  Our auth realm          %s\n", global_realm);
	ast_cli(fd, "  Realm. auth:            %s\n", authl ? "Yes": "No");
 	ast_cli(fd, "  Always auth rejects:    %s\n", global_alwaysauthreject ? "Yes" : "No");
	ast_cli(fd, "  Call limit peers only:  %s\n", global_limitonpeers ? "Yes" : "No");
	ast_cli(fd, "  User Agent:             %s\n", global_useragent);
	ast_cli(fd, "  MWI checking interval:  %d secs\n", global_mwitime);
	ast_cli(fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
	ast_cli(fd, "  Caller ID:              %s\n", default_callerid);
	ast_cli(fd, "  From: Domain:           %s\n", default_fromdomain);
	ast_cli(fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
	ast_cli(fd, "  Call Events:            %s\n", global_callevents ? "On" : "Off");
	ast_cli(fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
	ast_cli(fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
	ast_cli(fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
	ast_cli(fd, "  T38 fax pt UDPTL:       %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_UDPTL) ? "Yes" : "No");
#ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
	ast_cli(fd, "  T38 fax pt RTP:         %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_RTP) ? "Yes" : "No");
	ast_cli(fd, "  T38 fax pt TCP:         %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT_TCP) ? "Yes" : "No");
#endif
	ast_cli(fd, "  RFC2833 Compensation:   %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE) ? "Yes" : "No");
	if (!realtimepeers && !realtimeusers)
		ast_cli(fd, "  SIP realtime:           Disabled\n" );
	else
		ast_cli(fd, "  SIP realtime:           Enabled\n" );

	ast_cli(fd, "\nGlobal Signalling Settings:\n");
	ast_cli(fd, "---------------------------\n");
	ast_cli(fd, "  Codecs:                 ");
	print_codec_to_cli(fd, &default_prefs);
	ast_cli(fd, "\n");
	ast_cli(fd, "  T1 minimum:             %d\n", global_t1min);
	ast_cli(fd, "  Relax DTMF:             %s\n", global_relaxdtmf ? "Yes" : "No");
	ast_cli(fd, "  Compact SIP headers:    %s\n", compactheaders ? "Yes" : "No");
	ast_cli(fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
	ast_cli(fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
	ast_cli(fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
	ast_cli(fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
	ast_cli(fd, "  DNS SRV lookup:         %s\n", srvlookup ? "Yes" : "No");
	ast_cli(fd, "  Pedantic SIP support:   %s\n", pedanticsipchecking ? "Yes" : "No");
	ast_cli(fd, "  Reg. min duration       %d secs\n", min_expiry);
	ast_cli(fd, "  Reg. max duration:      %d secs\n", max_expiry);
	ast_cli(fd, "  Reg. default duration:  %d secs\n", default_expiry);
	ast_cli(fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
	ast_cli(fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
	ast_cli(fd, "  Notify ringing state:   %s\n", global_notifyringing ? "Yes" : "No");
	ast_cli(fd, "  Notify hold state:      %s\n", global_notifyhold ? "Yes" : "No");
	ast_cli(fd, "  SIP Transfer mode:      %s\n", transfermode2str(global_allowtransfer));
	ast_cli(fd, "  Max Call Bitrate:       %d kbps\r\n", default_maxcallbitrate);
	ast_cli(fd, "  Auto-Framing:           %s \r\n", global_autoframing ? "Yes" : "No");
	ast_cli(fd, "\nDefault Settings:\n");
	ast_cli(fd, "-----------------\n");
	ast_cli(fd, "  Context:                %s\n", default_context);
	ast_cli(fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
	ast_cli(fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
	ast_cli(fd, "  Qualify:                %d\n", default_qualify);
	ast_cli(fd, "  Use ClientCode:         %s\n", ast_test_flag(&global_flags[0], SIP_USECLIENTCODE) ? "Yes" : "No");
	ast_cli(fd, "  Progress inband:        %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
	ast_cli(fd, "  Language:               %s\n", S_OR(default_language, "(Defaults to English)"));
	ast_cli(fd, "  MOH Interpret:          %s\n", default_mohinterpret);
	ast_cli(fd, "  MOH Suggest:            %s\n", default_mohsuggest);
	ast_cli(fd, "  Voice Mail Extension:   %s\n", default_vmexten);

	
	if (realtimepeers || realtimeusers) {
		ast_cli(fd, "\nRealtime SIP Settings:\n");
		ast_cli(fd, "----------------------\n");
		ast_cli(fd, "  Realtime Peers:         %s\n", realtimepeers ? "Yes" : "No");
		ast_cli(fd, "  Realtime Users:         %s\n", realtimeusers ? "Yes" : "No");
		ast_cli(fd, "  Cache Friends:          %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? "Yes" : "No");
		ast_cli(fd, "  Update:                 %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) ? "Yes" : "No");
		ast_cli(fd, "  Ignore Reg. Expire:     %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) ? "Yes" : "No");
		ast_cli(fd, "  Save sys. name:         %s\n", ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME) ? "Yes" : "No");
		ast_cli(fd, "  Auto Clear:             %d\n", global_rtautoclear);
	}
	ast_cli(fd, "\n----\n");
	return RESULT_SUCCESS;
}

/*! \brief Show subscription type in string format */
static const char *subscription_type2str(enum subscriptiontype subtype)
{
	int i;

	for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
		if (subscription_types[i].type == subtype) {
			return subscription_types[i].text;
		}
	}
	return subscription_types[0].text;
}

/*! \brief Find subscription type in array */
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
{
	int i;

	for (i = 1; (i < (sizeof(subscription_types) / sizeof(subscription_types[0]))); i++) {
		if (subscription_types[i].type == subtype) {
			return &subscription_types[i];
		}
	}
	return &subscription_types[0];
}

/*! \brief Show active SIP channels */
static int sip_show_channels(int fd, int argc, char *argv[])  
{
        return __sip_show_channels(fd, argc, argv, 0);
}
 
/*! \brief Show active SIP subscriptions */
static int sip_show_subscriptions(int fd, int argc, char *argv[])
{
        return __sip_show_channels(fd, argc, argv, 1);
}

/*! \brief SIP show channels CLI (main function) */
static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
{
#define FORMAT3 "%-15.15s  %-10.10s  %-11.11s  %-15.15s  %-13.13s  %-15.15s %-10.10s\n"
#define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-4.4s  %-7.7s  %-15.15s\n"
#define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-4.4s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
	struct sip_pvt *cur;
	int numchans = 0;
	char *referstatus = NULL;

	if (argc != 3)
		return RESULT_SHOWUSAGE;
	ast_mutex_lock(&iflock);
	cur = iflist;
	if (!subscriptions)
		ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format", "Hold", "Last Message");
	else 
		ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");
	for (; cur; cur = cur->next) {
		referstatus = "";
		if (cur->refer) { /* SIP transfer in progress */
			referstatus = referstatus2str(cur->refer->status);
		}
		if (cur->subscribed == NONE && !subscriptions) {
			ast_cli(fd, FORMAT, ast_inet_ntoa(cur->sa.sin_addr), 
				S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
				cur->callid, 
				cur->ocseq, cur->icseq, 
				ast_getformatname(cur->owner ? cur->owner->nativeformats : 0), 
				ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD) ? "Yes" : "No",
				ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY) ? "(d)" : "",
				cur->lastmsg ,
				referstatus
			);
			numchans++;
		}
		if (cur->subscribed != NONE && subscriptions) {
			ast_cli(fd, FORMAT3, ast_inet_ntoa(cur->sa.sin_addr),
				S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
			   	cur->callid,
				/* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
				cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
				cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
				subscription_type2str(cur->subscribed),
				cur->subscribed == MWI_NOTIFICATION ? (cur->relatedpeer ? cur->relatedpeer->mailbox : "<none>") : "<none>"
);
			numchans++;
		}
	}
	ast_mutex_unlock(&iflock);
	if (!subscriptions)
		ast_cli(fd, "%d active SIP channel%s\n", numchans, (numchans != 1) ? "s" : "");
	else
		ast_cli(fd, "%d active SIP subscription%s\n", numchans, (numchans != 1) ? "s" : "");
	return RESULT_SUCCESS;
#undef FORMAT
#undef FORMAT2
#undef FORMAT3
}

/*! \brief Support routine for 'sip show channel' CLI */
static char *complete_sipch(const char *line, const char *word, int pos, int state)
{
	int which=0;
	struct sip_pvt *cur;
	char *c = NULL;
	int wordlen = strlen(word);

	ast_mutex_lock(&iflock);
	for (cur = iflist; cur; cur = cur->next) {
		if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
			c = ast_strdup(cur->callid);
			break;
		}
	}
	ast_mutex_unlock(&iflock);
	return c;
}

/*! \brief Do completion on peer name */
static char *complete_sip_peer(const char *word, int state, int flags2)
{
	char *result = NULL;
	int wordlen = strlen(word);
	int which = 0;

	ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
		/* locking of the object is not required because only the name and flags are being compared */
		if (!strncasecmp(word, iterator->name, wordlen) &&
				(!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
				++which > state)
			result = ast_strdup(iterator->name);
	} while(0) );
	return result;
}

/*! \brief Support routine for 'sip show peer' CLI */
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
{
	if (pos == 3)
		return complete_sip_peer(word, state, 0);

	return NULL;
}

/*! \brief Support routine for 'sip debug peer' CLI */
static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state)
{
	if (pos == 3)
		return complete_sip_peer(word, state, 0);

	return NULL;
}

/*! \brief Do completion on user name */
static char *complete_sip_user(const char *word, int state, int flags2)
{
	char *result = NULL;
	int wordlen = strlen(word);
	int which = 0;

	ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
		/* locking of the object is not required because only the name and flags are being compared */
		if (!strncasecmp(word, iterator->name, wordlen)) {
			if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
				continue;
			if (++which > state) {
				result = ast_strdup(iterator->name);
			}
		}
	} while(0) );
	return result;
}

/*! \brief Support routine for 'sip show user' CLI */
static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
{
	if (pos == 3)
		return complete_sip_user(word, state, 0);

	return NULL;
}

/*! \brief Support routine for 'sip notify' CLI */
static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
{
	char *c = NULL;

	if (pos == 2) {
		int which = 0;
		char *cat = NULL;
		int wordlen = strlen(word);

		/* do completion for notify type */

		if (!notify_types)
			return NULL;
		
		while ( (cat = ast_category_browse(notify_types, cat)) ) {
			if (!strncasecmp(word, cat, wordlen) && ++which > state) {
				c = ast_strdup(cat);
				break;
			}
		}
		return c;
	}

	if (pos > 2)
		return complete_sip_peer(word, state, 0);

	return NULL;
}

/*! \brief Support routine for 'sip prune realtime peer' CLI */
static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state)
{
	if (pos == 4)
		return complete_sip_peer(word, state, SIP_PAGE2_RTCACHEFRIENDS);
	return NULL;
}

/*! \brief Support routine for 'sip prune realtime user' CLI */
static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state)
{
	if (pos == 4)
		return complete_sip_user(word, state, SIP_PAGE2_RTCACHEFRIENDS);

	return NULL;
}

/*! \brief Show details of one active dialog */
static int sip_show_channel(int fd, int argc, char *argv[])
{
	struct sip_pvt *cur;
	size_t len;
	int found = 0;

	if (argc != 4)
		return RESULT_SHOWUSAGE;
	len = strlen(argv[3]);
	ast_mutex_lock(&iflock);
	for (cur = iflist; cur; cur = cur->next) {
		if (!strncasecmp(cur->callid, argv[3], len)) {
			char formatbuf[BUFSIZ/2];
			ast_cli(fd,"\n");
			if (cur->subscribed != NONE)
				ast_cli(fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
			else
				ast_cli(fd, "  * SIP Call\n");
			ast_cli(fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
			ast_cli(fd, "  Call-ID:                %s\n", cur->callid);
			ast_cli(fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
			ast_cli(fd, "  Our Codec Capability:   %d\n", cur->capability);
			ast_cli(fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
			ast_cli(fd, "  Their Codec Capability:   %d\n", cur->peercapability);
			ast_cli(fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
			ast_cli(fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
			ast_cli(fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
			ast_cli(fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
			ast_cli(fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
			ast_cli(fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
			ast_cli(fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
			ast_cli(fd, "  Audio IP:               %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
			ast_cli(fd, "  Our Tag:                %s\n", cur->tag);
			ast_cli(fd, "  Their Tag:              %s\n", cur->theirtag);
			ast_cli(fd, "  SIP User agent:         %s\n", cur->useragent);
			if (!ast_strlen_zero(cur->username))
				ast_cli(fd, "  Username:               %s\n", cur->username);
			if (!ast_strlen_zero(cur->peername))
				ast_cli(fd, "  Peername:               %s\n", cur->peername);
			if (!ast_strlen_zero(cur->uri))
				ast_cli(fd, "  Original uri:           %s\n", cur->uri);
			if (!ast_strlen_zero(cur->cid_num))
				ast_cli(fd, "  Caller-ID:              %s\n", cur->cid_num);
			ast_cli(fd, "  Need Destroy:           %d\n", ast_test_flag(&cur->flags[0], SIP_NEEDDESTROY));
			ast_cli(fd, "  Last Message:           %s\n", cur->lastmsg);
			ast_cli(fd, "  Promiscuous Redir:      %s\n", ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR) ? "Yes" : "No");
			ast_cli(fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
			ast_cli(fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
			ast_cli(fd, "  SIP Options:            ");
			if (cur->sipoptions) {
				int x;
				for (x=0 ; (x < (sizeof(sip_options) / sizeof(sip_options[0]))); x++) {
					if (cur->sipoptions & sip_options[x].id)
						ast_cli(fd, "%s ", sip_options[x].text);
				}
			} else
				ast_cli(fd, "(none)\n");
			ast_cli(fd, "\n\n");
			found++;
		}
	}
	ast_mutex_unlock(&iflock);
	if (!found) 
		ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
	return RESULT_SUCCESS;
}

/*! \brief Show history details of one dialog */
static int sip_show_history(int fd, int argc, char *argv[])
{
	struct sip_pvt *cur;
	size_t len;
	int found = 0;

	if (argc != 4)
		return RESULT_SHOWUSAGE;
	if (!recordhistory)
		ast_cli(fd, "\n***Note: History recording is currently DISABLED.  Use 'sip history' to ENABLE.\n");
	len = strlen(argv[3]);
	ast_mutex_lock(&iflock);
	for (cur = iflist; cur; cur = cur->next) {
		if (!strncasecmp(cur->callid, argv[3], len)) {
			struct sip_history *hist;
			int x = 0;

			ast_cli(fd,"\n");
			if (cur->subscribed != NONE)
				ast_cli(fd, "  * Subscription\n");
			else
				ast_cli(fd, "  * SIP Call\n");
			if (cur->history)
				AST_LIST_TRAVERSE(cur->history, hist, list)
					ast_cli(fd, "%d. %s\n", ++x, hist->event);
			if (x == 0)
				ast_cli(fd, "Call '%s' has no history\n", cur->callid);
			found++;
		}
	}
	ast_mutex_unlock(&iflock);
	if (!found) 
		ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
	return RESULT_SUCCESS;
}

/*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
static void sip_dump_history(struct sip_pvt *dialog)
{
	int x = 0;
	struct sip_history *hist;
	static int errmsg = 0;

	if (!dialog)
		return;

	if (!option_debug && !sipdebug) {
		if (!errmsg) {
			ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
			errmsg = 1;
		}
		return;
	}

	ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
	if (dialog->subscribed)
		ast_log(LOG_DEBUG, "  * Subscription\n");
	else
		ast_log(LOG_DEBUG, "  * SIP Call\n");
	if (dialog->history)
		AST_LIST_TRAVERSE(dialog->history, hist, list)
			ast_log(LOG_DEBUG, "  %-3.3d. %s\n", ++x, hist->event);
	if (!x)
		ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
	ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
}


/*! \brief  Receive SIP INFO Message
\note    Doesn't read the duration of the DTMF signal */
static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
{
	char buf[1024];
	unsigned int event;
	const char *c = get_header(req, "Content-Type");

	/* Need to check the media/type */
	if (!strcasecmp(c, "application/dtmf-relay") ||
	    !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {

		/* Try getting the "signal=" part */
		if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
			ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
			transmit_response(p, "200 OK", req); /* Should return error */
			return;
		} else {
			ast_copy_string(buf, c, sizeof(buf));
		}
	
		if (!p->owner) {	/* not a PBX call */
			transmit_response(p, "481 Call leg/transaction does not exist", req);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return;
		}

		if (ast_strlen_zero(buf)) {
			transmit_response(p, "200 OK", req);
			return;
		}

		if (buf[0] == '*')
			event = 10;
		else if (buf[0] == '#')
			event = 11;
		else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
			event = 12 + buf[0] - 'A';
		else
			event = atoi(buf);
		if (event == 16) {
			/* send a FLASH event */
			struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
			ast_queue_frame(p->owner, &f);
			if (sipdebug)
				ast_verbose("* DTMF-relay event received: FLASH\n");
		} else {
			/* send a DTMF event */
			struct ast_frame f = { AST_FRAME_DTMF, };
			if (event < 10) {
				f.subclass = '0' + event;
			} else if (event < 11) {
				f.subclass = '*';
			} else if (event < 12) {
				f.subclass = '#';
			} else if (event < 16) {
				f.subclass = 'A' + (event - 12);
			}
			ast_queue_frame(p->owner, &f);
			if (sipdebug)
				ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
		}
		transmit_response(p, "200 OK", req);
		return;
	} else if (!strcasecmp(c, "application/media_control+xml")) {
		/* Eh, we'll just assume it's a fast picture update for now */
		if (p->owner)
			ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
		transmit_response(p, "200 OK", req);
		return;
	} else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
		/* Client code (from SNOM phone) */
		if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
			if (p->owner && p->owner->cdr)
				ast_cdr_setuserfield(p->owner, c);
			if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
				ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
			transmit_response(p, "200 OK", req);
		} else {
			transmit_response(p, "403 Unauthorized", req);
		}
		return;
	}
	/* Other type of INFO message, not really understood by Asterisk */
	/* if (get_msg_text(buf, sizeof(buf), req)) { */

	ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
	transmit_response(p, "415 Unsupported media type", req);
	return;
}

/*! \brief Enable SIP Debugging in CLI */
static int sip_do_debug_ip(int fd, int argc, char *argv[])
{
	struct hostent *hp;
	struct ast_hostent ahp;
	int port = 0;
	char *p, *arg;

	/* sip set debug ip <ip> */
	if (argc != 5)
		return RESULT_SHOWUSAGE;
	p = arg = argv[4];
	strsep(&p, ":");
	if (p)
		port = atoi(p);
	hp = ast_gethostbyname(arg, &ahp);
	if (hp == NULL)
		return RESULT_SHOWUSAGE;

	debugaddr.sin_family = AF_INET;
	memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
	debugaddr.sin_port = htons(port);
	if (port == 0)
		ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
	else
		ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);

	ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);

	return RESULT_SUCCESS;
}

/*! \brief  sip_do_debug_peer: Turn on SIP debugging with peer mask */
static int sip_do_debug_peer(int fd, int argc, char *argv[])
{
	struct sip_peer *peer;
	if (argc != 5)
		return RESULT_SHOWUSAGE;
	peer = find_peer(argv[4], NULL, 1);
	if (peer) {
		if (peer->addr.sin_addr.s_addr) {
			debugaddr.sin_family = AF_INET;
			debugaddr.sin_addr = peer->addr.sin_addr;
			debugaddr.sin_port = peer->addr.sin_port;
			ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
			ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
		} else
			ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[4]);
		ASTOBJ_UNREF(peer,sip_destroy_peer);
	} else
		ast_cli(fd, "No such peer '%s'\n", argv[4]);
	return RESULT_SUCCESS;
}

/*! \brief Turn on SIP debugging (CLI command) */
static int sip_do_debug(int fd, int argc, char *argv[])
{
	int oldsipdebug = sipdebug_console;
	if (argc != 3) {
		if (argc != 5) 
			return RESULT_SHOWUSAGE;
		else if (strcmp(argv[3], "ip") == 0)
			return sip_do_debug_ip(fd, argc, argv);
		else if (strcmp(argv[3], "peer") == 0)
			return sip_do_debug_peer(fd, argc, argv);
		else
			return RESULT_SHOWUSAGE;
	}
	ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
	memset(&debugaddr, 0, sizeof(debugaddr));
	ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
	return RESULT_SUCCESS;
}

static int sip_do_debug_deprecated(int fd, int argc, char *argv[])
{
	int oldsipdebug = sipdebug_console;
	char *newargv[6] = { "sip", "set", "debug", NULL };
	if (argc != 2) {
		if (argc != 4) 
			return RESULT_SHOWUSAGE;
		else if (strcmp(argv[2], "ip") == 0) {
			newargv[3] = argv[2];
			newargv[4] = argv[3];
			return sip_do_debug_ip(fd, argc + 1, newargv);
		} else if (strcmp(argv[2], "peer") == 0) {
			newargv[3] = argv[2];
			newargv[4] = argv[3];
			return sip_do_debug_peer(fd, argc + 1, newargv);
		} else
			return RESULT_SHOWUSAGE;
	}
	ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
	memset(&debugaddr, 0, sizeof(debugaddr));
	ast_cli(fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
	return RESULT_SUCCESS;
}

/*! \brief Cli command to send SIP notify to peer */
static int sip_notify(int fd, int argc, char *argv[])
{
	struct ast_variable *varlist;
	int i;

	if (argc < 4)
		return RESULT_SHOWUSAGE;

	if (!notify_types) {
		ast_cli(fd, "No %s file found, or no types listed there\n", notify_config);
		return RESULT_FAILURE;
	}

	varlist = ast_variable_browse(notify_types, argv[2]);

	if (!varlist) {
		ast_cli(fd, "Unable to find notify type '%s'\n", argv[2]);
		return RESULT_FAILURE;
	}

	for (i = 3; i < argc; i++) {
		struct sip_pvt *p;
		struct sip_request req;
		struct ast_variable *var;

		if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) {
			ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
			return RESULT_FAILURE;
		}

		if (create_addr(p, argv[i])) {
			/* Maybe they're not registered, etc. */
			sip_destroy(p);
			ast_cli(fd, "Could not create address for '%s'\n", argv[i]);
			continue;
		}

		initreqprep(&req, p, SIP_NOTIFY);

		for (var = varlist; var; var = var->next)
			add_header(&req, var->name, var->value);

		/* Recalculate our side, and recalculate Call ID */
		if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
			p->ourip = __ourip;
		build_via(p);
		build_callid_pvt(p);
		ast_cli(fd, "Sending NOTIFY of type '%s' to '%s'\n", argv[2], argv[i]);
		transmit_sip_request(p, &req);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	}

	return RESULT_SUCCESS;
}

/*! \brief Disable SIP Debugging in CLI */
static int sip_no_debug(int fd, int argc, char *argv[])
{
	if (argc != 4)
		return RESULT_SHOWUSAGE;
	ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
	ast_cli(fd, "SIP Debugging Disabled\n");
	return RESULT_SUCCESS;
}

static int sip_no_debug_deprecated(int fd, int argc, char *argv[])
{
	if (argc != 3)
		return RESULT_SHOWUSAGE;
	ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
	ast_cli(fd, "SIP Debugging Disabled\n");
	return RESULT_SUCCESS;
}

/*! \brief Enable SIP History logging (CLI) */
static int sip_do_history(int fd, int argc, char *argv[])
{
	if (argc != 2) {
		return RESULT_SHOWUSAGE;
	}
	recordhistory = TRUE;
	ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
	return RESULT_SUCCESS;
}

/*! \brief Disable SIP History logging (CLI) */
static int sip_no_history(int fd, int argc, char *argv[])
{
	if (argc != 3) {
		return RESULT_SHOWUSAGE;
	}
	recordhistory = FALSE;
	ast_cli(fd, "SIP History Recording Disabled\n");
	return RESULT_SUCCESS;
}

/*! \brief Authenticate for outbound registration */
static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader)
{
	char digest[1024];
	p->authtries++;
	memset(digest,0,sizeof(digest));
	if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
		/* There's nothing to use for authentication */
 		/* No digest challenge in request */
 		if (sip_debug_test_pvt(p) && p->registry)
 			ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
 			/* No old challenge */
		return -1;
	}
	if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
		append_history(p, "RegistryAuth", "Try: %d", p->authtries);
 	if (sip_debug_test_pvt(p) && p->registry)
 		ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
	return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
}

/*! \brief Add authentication on outbound SIP packet */
static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init)
{
	char digest[1024];

	if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
		return -2;

	p->authtries++;
	if (option_debug > 1)
		ast_log(LOG_DEBUG, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
	memset(digest, 0, sizeof(digest));
	if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
		/* No way to authenticate */
		return -1;
	}
	/* Now we have a reply digest */
	p->options->auth = digest;
	p->options->authheader = respheader;
	return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
}

/*! \brief  reply to authentication for outbound registrations
\return	Returns -1 if we have no auth 
\note	This is used for register= servers in sip.conf, SIP proxies we register
	with  for receiving calls from.  */
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
{
	char tmp[512];
	char *c;
	char oldnonce[256];

	/* table of recognised keywords, and places where they should be copied */
	const struct x {
		const char *key;
		int field_index;
	} *i, keys[] = {
		{ "realm=", ast_string_field_index(p, realm) },
		{ "nonce=", ast_string_field_index(p, nonce) },
		{ "opaque=", ast_string_field_index(p, opaque) },
		{ "qop=", ast_string_field_index(p, qop) },
		{ "domain=", ast_string_field_index(p, domain) },
		{ NULL, 0 },
	};

	ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
	if (ast_strlen_zero(tmp)) 
		return -1;
	if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
		ast_log(LOG_WARNING, "missing Digest.\n");
		return -1;
	}
	c = tmp + strlen("Digest ");
	ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
	while (c && *(c = ast_skip_blanks(c))) {	/* lookup for keys */
		for (i = keys; i->key != NULL; i++) {
			char *src, *separator;
			if (strncasecmp(c, i->key, strlen(i->key)) != 0)
				continue;
			/* Found. Skip keyword, take text in quotes or up to the separator. */
			c += strlen(i->key);
			if (*c == '"') {
				src = ++c;
				separator = "\"";
			} else {
				src = c;
				separator = ",";
			}
			strsep(&c, separator); /* clear separator and move ptr */
			ast_string_field_index_set(p, i->field_index, src);
			break;
		}
		if (i->key == NULL) /* not found, try ',' */
			strsep(&c, ",");
	}
	/* Reset nonce count */
	if (strcmp(p->nonce, oldnonce)) 
		p->noncecount = 0;

	/* Save auth data for following registrations */
	if (p->registry) {
		struct sip_registry *r = p->registry;

		if (strcmp(r->nonce, p->nonce)) {
			ast_string_field_set(r, realm, p->realm);
			ast_string_field_set(r, nonce, p->nonce);
			ast_string_field_set(r, domain, p->domain);
			ast_string_field_set(r, opaque, p->opaque);
			ast_string_field_set(r, qop, p->qop);
			r->noncecount = 0;
		}
	}
	return build_reply_digest(p, sipmethod, digest, digest_len); 
}

/*! \brief  Build reply digest 
\return	Returns -1 if we have no auth 
\note	Build digest challenge for authentication of peers (for registration) 
	and users (for calls). Also used for authentication of CANCEL and BYE 
*/
static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
{
	char a1[256];
	char a2[256];
	char a1_hash[256];
	char a2_hash[256];
	char resp[256];
	char resp_hash[256];
	char uri[256];
	char cnonce[80];
	const char *username;
	const char *secret;
	const char *md5secret;
	struct sip_auth *auth = NULL;	/* Realm authentication */

	if (!ast_strlen_zero(p->domain))
		ast_copy_string(uri, p->domain, sizeof(uri));
	else if (!ast_strlen_zero(p->uri))
		ast_copy_string(uri, p->uri, sizeof(uri));
	else
		snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(p->sa.sin_addr));

	snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());

 	/* Check if we have separate auth credentials */
 	if ((auth = find_realm_authentication(authl, p->realm))) {
		ast_log(LOG_WARNING, "use realm [%s] from peer [%s][%s]\n",
			auth->username, p->peername, p->username);
 		username = auth->username;
 		secret = auth->secret;
 		md5secret = auth->md5secret;
		if (sipdebug)
 			ast_log(LOG_DEBUG,"Using realm %s authentication for call %s\n", p->realm, p->callid);
 	} else {
 		/* No authentication, use peer or register= config */
 		username = p->authname;
 		secret =  p->peersecret;
 		md5secret = p->peermd5secret;
 	}
	if (ast_strlen_zero(username))	/* We have no authentication */
		return -1;

 	/* Calculate SIP digest response */
 	snprintf(a1,sizeof(a1),"%s:%s:%s", username, p->realm, secret);
	snprintf(a2,sizeof(a2),"%s:%s", sip_methods[method].text, uri);
	if (!ast_strlen_zero(md5secret))
		ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
	else
		ast_md5_hash(a1_hash,a1);
	ast_md5_hash(a2_hash,a2);

	p->noncecount++;
	if (!ast_strlen_zero(p->qop))
		snprintf(resp,sizeof(resp),"%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
	else
		snprintf(resp,sizeof(resp),"%s:%s:%s", a1_hash, p->nonce, a2_hash);
	ast_md5_hash(resp_hash, resp);
	/* XXX We hard code our qop to "auth" for now.  XXX */
	if (!ast_strlen_zero(p->qop))
		snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\", qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, p->opaque, cnonce, p->noncecount);
	else
		snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"", username, p->realm, uri, p->nonce, resp_hash, p->opaque);

	append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);

	return 0;
}
	
static char show_domains_usage[] = 
"Usage: sip show domains\n"
"       Lists all configured SIP local domains.\n"
"       Asterisk only responds to SIP messages to local domains.\n";

static char notify_usage[] =
"Usage: sip notify <type> <peer> [<peer>...]\n"
"       Send a NOTIFY message to a SIP peer or peers\n"
"       Message types are defined in sip_notify.conf\n";

static char show_users_usage[] = 
"Usage: sip show users [like <pattern>]\n"
"       Lists all known SIP users.\n"
"       Optional regular expression pattern is used to filter the user list.\n";

static char show_user_usage[] =
"Usage: sip show user <name> [load]\n"
"       Shows all details on one SIP user and the current status.\n"
"       Option \"load\" forces lookup of peer in realtime storage.\n";

static char show_inuse_usage[] = 
"Usage: sip show inuse [all]\n"
"       List all SIP users and peers usage counters and limits.\n"
"       Add option \"all\" to show all devices, not only those with a limit.\n";

static char show_channels_usage[] = 
"Usage: sip show channels\n"
"       Lists all currently active SIP channels.\n";

static char show_channel_usage[] = 
"Usage: sip show channel <channel>\n"
"       Provides detailed status on a given SIP channel.\n";

static char show_history_usage[] = 
"Usage: sip show history <channel>\n"
"       Provides detailed dialog history on a given SIP channel.\n";

static char show_peers_usage[] = 
"Usage: sip show peers [like <pattern>]\n"
"       Lists all known SIP peers.\n"
"       Optional regular expression pattern is used to filter the peer list.\n";

static char show_peer_usage[] =
"Usage: sip show peer <name> [load]\n"
"       Shows all details on one SIP peer and the current status.\n"
"       Option \"load\" forces lookup of peer in realtime storage.\n";

static char prune_realtime_usage[] =
"Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
"       Prunes object(s) from the cache.\n"
"       Optional regular expression pattern is used to filter the objects.\n";

static char show_reg_usage[] =
"Usage: sip show registry\n"
"       Lists all registration requests and status.\n";

static char debug_usage[] = 
"Usage: sip set debug\n"
"       Enables dumping of SIP packets for debugging purposes\n\n"
"       sip set debug ip <host[:PORT]>\n"
"       Enables dumping of SIP packets to and from host.\n\n"
"       sip set debug peer <peername>\n"
"       Enables dumping of SIP packets to and from host.\n"
"       Require peer to be registered.\n";

static char no_debug_usage[] = 
"Usage: sip set debug off\n"
"       Disables dumping of SIP packets for debugging purposes\n";

static char no_history_usage[] = 
"Usage: sip history off\n"
"       Disables recording of SIP dialog history for debugging purposes\n";

static char history_usage[] = 
"Usage: sip history\n"
"       Enables recording of SIP dialog history for debugging purposes.\n"
"Use 'sip show history' to view the history of a call number.\n";

static char sip_reload_usage[] =
"Usage: sip reload\n"
"       Reloads SIP configuration from sip.conf\n";

static char show_subscriptions_usage[] =
"Usage: sip show subscriptions\n" 
"       Lists active SIP subscriptions for extension states\n";

static char show_objects_usage[] =
"Usage: sip show objects\n" 
"       Lists status of known SIP objects\n";

static char show_settings_usage[] = 
"Usage: sip show settings\n"
"       Provides detailed list of the configuration of the SIP channel.\n";

/*! \brief Read SIP header (dialplan function) */
static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len) 
{
	struct sip_pvt *p;
	const char *content = NULL;
	AST_DECLARE_APP_ARGS(args,
		AST_APP_ARG(header);
		AST_APP_ARG(number);
	);
	int i, number, start = 0;

 	if (ast_strlen_zero(data)) {
		ast_log(LOG_WARNING, "This function requires a header name.\n");
		return -1;
	}

	ast_channel_lock(chan);
	if (chan->tech != &sip_tech) {
		ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
		ast_channel_unlock(chan);
		return -1;
	}

	AST_STANDARD_APP_ARGS(args, data);
	if (!args.number) {
		number = 1;
	} else {
		sscanf(args.number, "%d", &number);
		if (number < 1)
			number = 1;
	}

	p = chan->tech_pvt;

	/* If there is no private structure, this channel is no longer alive */
	if (!p) {
		ast_channel_unlock(chan);
		return -1;
	}

	for (i = 0; i < number; i++)
		content = __get_header(&p->initreq, args.header, &start);

	if (ast_strlen_zero(content)) {
		ast_channel_unlock(chan);
		return -1;
	}

	ast_copy_string(buf, content, len);
	ast_channel_unlock(chan);

	return 0;
}

static struct ast_custom_function sip_header_function = {
	.name = "SIP_HEADER",
	.synopsis = "Gets the specified SIP header",
	.syntax = "SIP_HEADER(<name>[,<number>])",
	.desc = "Since there are several headers (such as Via) which can occur multiple\n"
	"times, SIP_HEADER takes an optional second argument to specify which header with\n"
	"that name to retrieve. Headers start at offset 1.\n",
	.read = func_header_read,
};

/*! \brief  Dial plan function to check if domain is local */
static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
{
	if (ast_strlen_zero(data)) {
		ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
		return -1;
	}
	if (check_sip_domain(data, NULL, 0))
		ast_copy_string(buf, data, len);
	else
		buf[0] = '\0';
	return 0;
}

static struct ast_custom_function checksipdomain_function = {
	.name = "CHECKSIPDOMAIN",
	.synopsis = "Checks if domain is a local domain",
	.syntax = "CHECKSIPDOMAIN(<domain|IP>)",
	.read = func_check_sipdomain,
	.desc = "This function checks if the domain in the argument is configured\n"
		"as a local SIP domain that this Asterisk server is configured to handle.\n"
		"Returns the domain name if it is locally handled, otherwise an empty string.\n"
		"Check the domain= configuration in sip.conf\n",
};

/*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
{
	struct sip_peer *peer;
	char *colname;

	if ((colname = strchr(data, ':')))	/*! \todo Will be deprecated after 1.4 */
		*colname++ = '\0';
	else if ((colname = strchr(data, '|')))
		*colname++ = '\0';
	else
		colname = "ip";

	if (!(peer = find_peer(data, NULL, 1)))
		return -1;

	if (!strcasecmp(colname, "ip")) {
		ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
	} else  if (!strcasecmp(colname, "status")) {
		peer_status(peer, buf, len);
	} else  if (!strcasecmp(colname, "language")) {
		ast_copy_string(buf, peer->language, len);
	} else  if (!strcasecmp(colname, "regexten")) {
		ast_copy_string(buf, peer->regexten, len);
	} else  if (!strcasecmp(colname, "limit")) {
		snprintf(buf, len, "%d", peer->call_limit);
	} else  if (!strcasecmp(colname, "curcalls")) {
		snprintf(buf, len, "%d", peer->inUse);
	} else  if (!strcasecmp(colname, "accountcode")) {
		ast_copy_string(buf, peer->accountcode, len);
	} else  if (!strcasecmp(colname, "useragent")) {
		ast_copy_string(buf, peer->useragent, len);
	} else  if (!strcasecmp(colname, "mailbox")) {
		ast_copy_string(buf, peer->mailbox, len);
	} else  if (!strcasecmp(colname, "context")) {
		ast_copy_string(buf, peer->context, len);
	} else  if (!strcasecmp(colname, "expire")) {
		snprintf(buf, len, "%d", peer->expire);
	} else  if (!strcasecmp(colname, "dynamic")) {
		ast_copy_string(buf, (ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) ? "yes" : "no"), len);
	} else  if (!strcasecmp(colname, "callerid_name")) {
		ast_copy_string(buf, peer->cid_name, len);
	} else  if (!strcasecmp(colname, "callerid_num")) {
		ast_copy_string(buf, peer->cid_num, len);
	} else  if (!strcasecmp(colname, "codecs")) {
		ast_getformatname_multiple(buf, len -1, peer->capability);
	} else  if (!strncasecmp(colname, "codec[", 6)) {
		char *codecnum;
		int index = 0, codec = 0;
		
		codecnum = colname + 6;	/* move past the '[' */
		codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
		index = atoi(codecnum);
		if((codec = ast_codec_pref_index(&peer->prefs, index))) {
			ast_copy_string(buf, ast_getformatname(codec), len);
		}
	}

	ASTOBJ_UNREF(peer, sip_destroy_peer);

	return 0;
}

/*! \brief Structure to declare a dialplan function: SIPPEER */
struct ast_custom_function sippeer_function = {
	.name = "SIPPEER",
	.synopsis = "Gets SIP peer information",
	.syntax = "SIPPEER(<peername>[|item])",
	.read = function_sippeer,
	.desc = "Valid items are:\n"
	"- ip (default)          The IP address.\n"
	"- mailbox               The configured mailbox.\n"
	"- context               The configured context.\n"
	"- expire                The epoch time of the next expire.\n"
	"- dynamic               Is it dynamic? (yes/no).\n"
	"- callerid_name         The configured Caller ID name.\n"
	"- callerid_num          The configured Caller ID number.\n"
	"- codecs                The configured codecs.\n"
	"- status                Status (if qualify=yes).\n"
	"- regexten              Registration extension\n"
	"- limit                 Call limit (call-limit)\n"
	"- curcalls              Current amount of calls \n"
	"                        Only available if call-limit is set\n"
	"- language              Default language for peer\n"
	"- accountcode           Account code for this peer\n"
	"- useragent             Current user agent id for peer\n"
	"- codec[x]              Preferred codec index number 'x' (beginning with zero).\n"
	"\n"
};

/*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
{
	struct sip_pvt *p;

	*buf = 0;
	
 	if (!data) {
		ast_log(LOG_WARNING, "This function requires a parameter name.\n");
		return -1;
	}

	ast_channel_lock(chan);
	if (chan->tech != &sip_tech) {
		ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
		ast_channel_unlock(chan);
		return -1;
	}

	p = chan->tech_pvt;

	/* If there is no private structure, this channel is no longer alive */
	if (!p) {
		ast_channel_unlock(chan);
		return -1;
	}

	if (!strcasecmp(data, "peerip")) {
		ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
	} else  if (!strcasecmp(data, "recvip")) {
		ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
	} else  if (!strcasecmp(data, "from")) {
		ast_copy_string(buf, p->from, len);
	} else  if (!strcasecmp(data, "uri")) {
		ast_copy_string(buf, p->uri, len);
	} else  if (!strcasecmp(data, "useragent")) {
		ast_copy_string(buf, p->useragent, len);
	} else  if (!strcasecmp(data, "peername")) {
		ast_copy_string(buf, p->peername, len);
	} else if (!strcasecmp(data, "t38passthrough")) {
		if (p->t38.state == T38_DISABLED)
			ast_copy_string(buf, "0", sizeof("0"));
		else    /* T38 is offered or enabled in this call */
			ast_copy_string(buf, "1", sizeof("1"));
	} else {
		ast_channel_unlock(chan);
		return -1;
	}
	ast_channel_unlock(chan);

	return 0;
}

/*! \brief Structure to declare a dialplan function: SIPCHANINFO */
static struct ast_custom_function sipchaninfo_function = {
	.name = "SIPCHANINFO",
	.synopsis = "Gets the specified SIP parameter from the current channel",
	.syntax = "SIPCHANINFO(item)",
	.read = function_sipchaninfo_read,
	.desc = "Valid items are:\n"
	"- peerip                The IP address of the peer.\n"
	"- recvip                The source IP address of the peer.\n"
	"- from                  The URI from the From: header.\n"
	"- uri                   The URI from the Contact: header.\n"
	"- useragent             The useragent.\n"
	"- peername              The name of the peer.\n"
	"- t38passthrough        1 if T38 is offered or enabled in this channel, otherwise 0\n"
};

/*! \brief Parse 302 Moved temporalily response */
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
{
	char tmp[256];
	char *s, *e;
	char *domain;

	ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
	s = get_in_brackets(tmp);
	s = strsep(&s, ";");	/* strip ; and beyond */
	if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
		if (!strncasecmp(s, "sip:", 4))
			s += 4;
		e = strchr(s, '/');
		if (e)
			*e = '\0';
		if (option_debug)
			ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
		if (p->owner)
			ast_string_field_build(p->owner, call_forward, "SIP/%s", s);
	} else {
		e = strchr(tmp, '@');
		if (e) {
			*e++ = '\0';
			domain = e;
		} else {
			/* No username part */
			domain = tmp;
		}
		e = strchr(tmp, '/');
		if (e)
			*e = '\0';
		if (!strncasecmp(s, "sip:", 4))
			s += 4;
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
		if (p->owner) {
			pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
			ast_string_field_set(p->owner, call_forward, s);
		}
	}
}

/*! \brief Check pending actions on SIP call */
static void check_pendings(struct sip_pvt *p)
{
	if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
		/* if we can't BYE, then this is really a pending CANCEL */
		if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
			transmit_request(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, FALSE);
			/* 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. */
		else 
			transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
		ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);	
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	} else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
		/* Didn't get to reinvite yet, so do it now */
		transmit_reinvite_with_sdp(p);
		ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);	
	}
}

/*! \brief Handle SIP response to INVITE dialogue */
static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
{
	int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
	int res = 0;
	int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
	struct ast_channel *bridgepeer = NULL;
	
	if (option_debug > 3) {
		if (reinvite)
			ast_log(LOG_DEBUG, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
		else
			ast_log(LOG_DEBUG, "SIP response %d to standard invite\n", resp);
	}

	if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) { /* This call is already gone */
		if (option_debug)
			ast_log(LOG_DEBUG, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
		return;
	}

	/* Acknowledge sequence number - This only happens on INVITE from SIP-call */
	if (p->initid > -1) {
		/* Don't auto congest anymore since we've gotten something useful back */
		ast_sched_del(sched, p->initid);
		p->initid = -1;
	}

	/* RFC3261 says we must treat every 1xx response (but not 100)
	   that we don't recognize as if it was 183.
	*/
	if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 183)
		resp = 183;

 	/* Any response between 100 and 199 is PROCEEDING */
 	if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
 		p->invitestate = INV_PROCEEDING;
 
 	/* Final response, not 200 ? */
 	if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
 		p->invitestate = INV_COMPLETED;
 		

	switch (resp) {
	case 100:	/* Trying */
	case 101:	/* Dialog establishment */
		if (!ast_test_flag(req, SIP_PKT_IGNORE))
			sip_cancel_destroy(p);
		check_pendings(p);
		break;

	case 180:	/* 180 Ringing */
		if (!ast_test_flag(req, SIP_PKT_IGNORE))
			sip_cancel_destroy(p);
		if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
			ast_queue_control(p->owner, AST_CONTROL_RINGING);
			if (p->owner->_state != AST_STATE_UP) {
				ast_setstate(p->owner, AST_STATE_RINGING);
			}
		}
		if (find_sdp(req)) {
			p->invitestate = INV_EARLY_MEDIA;
			res = process_sdp(p, req);
			if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
				/* Queue a progress frame only if we have SDP in 180 */
				ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
			}
		}
		check_pendings(p);
		break;

	case 183:	/* Session progress */
		if (!ast_test_flag(req, SIP_PKT_IGNORE))
			sip_cancel_destroy(p);
		/* Ignore 183 Session progress without SDP */
		if (find_sdp(req)) {
			p->invitestate = INV_EARLY_MEDIA;
			res = process_sdp(p, req);
			if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
				/* Queue a progress frame */
				ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
			}
		}
		check_pendings(p);
		break;

	case 200:	/* 200 OK on invite - someone's answering our call */
		if (!ast_test_flag(req, SIP_PKT_IGNORE))
			sip_cancel_destroy(p);
		p->authtries = 0;
		if (find_sdp(req)) {
			if ((res = process_sdp(p, req)) && !ast_test_flag(req, SIP_PKT_IGNORE))
				if (!reinvite)
					/* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
					/* For re-invites, we try to recover */
					ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
		}

		/* Parse contact header for continued conversation */
		/* When we get 200 OK, we know which device (and IP) to contact for this call */
		/* This is important when we have a SIP proxy between us and the phone */
		if (outgoing) {
			update_call_counter(p, DEC_CALL_RINGING);
			parse_ok_contact(p, req);
			if(set_address_from_contact(p)) {
				/* Bad contact - we don't know how to reach this device */
				/* We need to ACK, but then send a bye */
				/* OEJ: Possible issue that may need a check:
					If we have a proxy route between us and the device,
					should we care about resolving the contact
					or should we just send it?
				*/
				if (!ast_test_flag(req, SIP_PKT_IGNORE))
					ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
			} 

			/* Save Record-Route for any later requests we make on this dialogue */
			build_route(p, req, 1);
		}
		
		if (p->owner && (p->owner->_state == AST_STATE_UP) && (bridgepeer = ast_bridged_channel(p->owner))) { /* if this is a re-invite */
			struct sip_pvt *bridgepvt = NULL;

			if (!bridgepeer->tech) {
				ast_log(LOG_WARNING, "Ooooh.. no tech!  That's REALLY bad\n");
				break;
			}
			if (bridgepeer->tech == &sip_tech) {
				bridgepvt = (struct sip_pvt*)(bridgepeer->tech_pvt);
				if (bridgepvt->udptl) {
					if (p->t38.state == T38_PEER_REINVITE) {
						sip_handle_t38_reinvite(bridgepeer, p, 0);
						ast_rtp_set_rtptimers_onhold(p->rtp);
						if (p->vrtp)
							ast_rtp_set_rtptimers_onhold(p->vrtp);	/* Turn off RTP timers while we send fax */
					} else if (p->t38.state == T38_DISABLED && bridgepeer && (bridgepvt->t38.state == T38_ENABLED)) {
						ast_log(LOG_WARNING, "RTP re-inivte after T38 session not handled yet !\n");
						/* Insted of this we should somehow re-invite the other side of the bridge to RTP */
						/* XXXX Should we really destroy this session here, without any response at all??? */
						sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
					}
				} else {
					if (option_debug > 1)
						ast_log(LOG_DEBUG, "Strange... The other side of the bridge does not have a udptl struct\n");
					ast_mutex_lock(&bridgepvt->lock);
					bridgepvt->t38.state = T38_DISABLED;
					ast_mutex_unlock(&bridgepvt->lock);
					if (option_debug)
						ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->tech->type);
					p->t38.state = T38_DISABLED;
					if (option_debug > 1)
						ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
				}
			} else {
				/* Other side is not a SIP channel */
				if (option_debug > 1)
					ast_log(LOG_DEBUG, "Strange... The other side of the bridge is not a SIP channel\n");
				p->t38.state = T38_DISABLED;
				if (option_debug > 1)
					ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
			}
		}
		if ((p->t38.state == T38_LOCAL_REINVITE) || (p->t38.state == T38_LOCAL_DIRECT)) {
			/* If there was T38 reinvite and we are supposed to answer with 200 OK than this should set us to T38 negotiated mode */
			p->t38.state = T38_ENABLED;
			if (option_debug)
				ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
		}

		if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner) {
			if (!reinvite) {
				ast_queue_control(p->owner, AST_CONTROL_ANSWER);
			} else {	/* RE-invite */
				ast_queue_frame(p->owner, &ast_null_frame);
			}
		} else {
			 /* It's possible we're getting an 200 OK after we've tried to disconnect
				  by sending CANCEL */
			/* First send ACK, then send bye */
			if (!ast_test_flag(req, SIP_PKT_IGNORE))
				ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
		}
		/* If I understand this right, the branch is different for a non-200 ACK only */
		p->invitestate = INV_TERMINATED;
		transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
		check_pendings(p);
		break;
	case 407: /* Proxy authentication */
	case 401: /* Www auth */
		/* First we ACK */
		transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->options)
			p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);

		/* Then we AUTH */
		ast_string_field_free(p, theirtag);	/* forget their old tag, so we don't match tags when getting response */
		if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
			char *authenticate = (resp == 401 ? "WWW-Authenticate" : "Proxy-Authenticate");
			char *authorization = (resp == 401 ? "Authorization" : "Proxy-Authorization");
			if (p->authtries < MAX_AUTHTRIES)
				p->invitestate = INV_CALLING;
			if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, authenticate, authorization, SIP_INVITE, 1)) {
				ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
				sip_alreadygone(p);
				if (p->owner)
					ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
			}
		}
		break;

	case 403: /* Forbidden */
		/* First we ACK */
		transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
		if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->owner)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		sip_alreadygone(p);
		break;

	case 404: /* Not found */
		transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		sip_alreadygone(p);
		break;

	case 481: /* Call leg does not exist */
		/* Could be REFER caused INVITE with replaces */
		ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
		transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->owner)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		break;
	case 487: /* Cancelled transaction */
		/* We have sent CANCEL on an outbound INVITE 
			This transaction is already scheduled to be killed by sip_hangup().
		*/
		transmit_request(p, SIP_ACK, seqno, 0, 0);
		if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
			ast_queue_hangup(p->owner);
		else if (!ast_test_flag(req, SIP_PKT_IGNORE))
			update_call_counter(p, DEC_CALL_LIMIT);
		break;
	case 491: /* Pending */
		/* we really should have to wait a while, then retransmit */
			/* We should support the retry-after at some point */
		/* At this point, we treat this as a congestion */
		transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->owner && !ast_test_flag(req, SIP_PKT_IGNORE))
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		break;

	case 501: /* Not implemented */
		transmit_request(p, SIP_ACK, seqno, 0, 0);
		if (p->owner)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		break;
	}
}

/* \brief Handle SIP response in REFER transaction
	We've sent a REFER, now handle responses to it 
  */
static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
{
	char *auth = "Proxy-Authenticate";
	char *auth2 = "Proxy-Authorization";

	/* If no refer structure exists, then do nothing */
	if (!p->refer)
		return;

	switch (resp) {
	case 202:   /* Transfer accepted */
		/* We need  to do something here */
		/* The transferee is now sending INVITE to target */
		p->refer->status = REFER_ACCEPTED;
		/* Now wait for next message */
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Got 202 accepted on transfer\n");
		/* We should hang along, waiting for NOTIFY's here */
		break;

	case 401:   /* Not www-authorized on SIP method */
	case 407:   /* Proxy auth */
		if (ast_strlen_zero(p->authname)) {
			ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
				ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
		}
		if (resp == 401) {
			auth = "WWW-Authenticate";
			auth2 = "Authorization";
		}
		if ((p->authtries > 1) || do_proxy_auth(p, req, auth, auth2, SIP_REFER, 0)) {
			ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
			p->refer->status = REFER_NOAUTH;
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
		}
		break;
	case 481: /* Call leg does not exist */

		/* A transfer with Replaces did not work */
		/* OEJ: We should Set flag, cancel the REFER, go back
		to original call - but right now we can't */
		ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
		if (p->owner)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
		break;

	case 500:   /* Server error */
	case 501:   /* Method not implemented */
		/* Return to the current call onhold */
		/* Status flag needed to be reset */
		ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
		p->refer->status = REFER_FAILED;
		break;
	case 603:   /* Transfer declined */
		ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
		p->refer->status = REFER_FAILED;
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
		break;
	}
}

/*! \brief Handle responses on REGISTER to services */
static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
{
	int expires, expires_ms;
	struct sip_registry *r;
	r=p->registry;

	switch (resp) {
	case 401:	/* Unauthorized */
		if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
			ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			}
		break;
	case 403:	/* Forbidden */
		ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
		if (global_regattempts_max)
			p->registry->regattempts = global_regattempts_max+1;
		ast_sched_del(sched, r->timeout);
		r->timeout = -1;
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		break;
	case 404:	/* Not found */
		ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username,p->registry->hostname);
		if (global_regattempts_max)
			p->registry->regattempts = global_regattempts_max+1;
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		r->call = NULL;
		ast_sched_del(sched, r->timeout);
		r->timeout = -1;
		break;
	case 407:	/* Proxy auth */
		if ((p->authtries == MAX_AUTHTRIES) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
			ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		}
		break;
	case 479:	/* SER: Not able to process the URI - address is wrong in register*/
		ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username,p->registry->hostname);
		if (global_regattempts_max)
			p->registry->regattempts = global_regattempts_max+1;
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		r->call = NULL;
		ast_sched_del(sched, r->timeout);
		r->timeout = -1;
		break;
	case 200:	/* 200 OK */
		if (!r) {
			ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			return 0;
		}

		r->regstate = REG_STATE_REGISTERED;
		r->regtime = time(NULL);		/* Reset time of last succesful registration */
		manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
		r->regattempts = 0;
		if (option_debug)
			ast_log(LOG_DEBUG, "Registration successful\n");
		if (r->timeout > -1) {
			if (option_debug)
				ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
			ast_sched_del(sched, r->timeout);
		}
		r->timeout=-1;
		r->call = NULL;
		p->registry = NULL;
		/* Let this one hang around until we have all the responses */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		/* ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	*/

		/* set us up for re-registering */
		/* figure out how long we got registered for */
		if (r->expire > -1)
			ast_sched_del(sched, r->expire);
		/* according to section 6.13 of RFC, contact headers override
		   expires headers, so check those first */
		expires = 0;

		/* XXX todo: try to save the extra call */
		if (!ast_strlen_zero(get_header(req, "Contact"))) {
			const char *contact = NULL;
			const char *tmptmp = NULL;
			int start = 0;
			for(;;) {
				contact = __get_header(req, "Contact", &start);
				/* this loop ensures we get a contact header about our register request */
				if(!ast_strlen_zero(contact)) {
					if( (tmptmp=strstr(contact, p->our_contact))) {
						contact=tmptmp;
						break;
					}
				} else
					break;
			}
			tmptmp = strcasestr(contact, "expires=");
			if (tmptmp) {
				if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
					expires = 0;
			}

		}
		if (!expires) 
			expires=atoi(get_header(req, "expires"));
		if (!expires)
			expires=default_expiry;

		expires_ms = expires * 1000;
		if (expires <= EXPIRY_GUARD_LIMIT)
			expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
		else
			expires_ms -= EXPIRY_GUARD_SECS * 1000;
		if (sipdebug)
			ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 

		r->refresh= (int) expires_ms / 1000;

		/* Schedule re-registration before we expire */
		r->expire=ast_sched_add(sched, expires_ms, sip_reregister, r); 
		ASTOBJ_UNREF(r, sip_registry_destroy);
	}
	return 1;
}

/*! \brief Handle qualification responses (OPTIONS) */
static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
{
	struct sip_peer *peer = p->relatedpeer;
	int statechanged, is_reachable, was_reachable;
	int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);

	/*
	 * Compute the response time to a ping (goes in peer->lastms.)
	 * -1 means did not respond, 0 means unknown,
	 * 1..maxms is a valid response, >maxms means late response.
	 */
	if (pingtime < 1)	/* zero = unknown, so round up to 1 */
		pingtime = 1;

	/* Now determine new state and whether it has changed.
	 * Use some helper variables to simplify the writing
	 * of the expressions.
	 */
	was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
	is_reachable = pingtime <= peer->maxms;
	statechanged = peer->lastms == 0 /* yes, unknown before */
		|| was_reachable != is_reachable;

	peer->lastms = pingtime;
	peer->call = NULL;
	if (statechanged) {
		const char *s = is_reachable ? "Reachable" : "Lagged";

		ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
			peer->name, s, pingtime, peer->maxms);
		ast_device_state_changed("SIP/%s", peer->name);
		manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
			"Peer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
			peer->name, s, pingtime);
	}

	if (peer->pokeexpire > -1)
		ast_sched_del(sched, peer->pokeexpire);
	ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	

	/* Try again eventually */
	peer->pokeexpire = ast_sched_add(sched,
		is_reachable ? DEFAULT_FREQ_OK : DEFAULT_FREQ_NOTOK,
		sip_poke_peer_s, peer);
}

/*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
static void stop_media_flows(struct sip_pvt *p)
{
	/* Immediately stop RTP, VRTP and UDPTL as applicable */
	if (p->rtp)
		ast_rtp_stop(p->rtp);
	if (p->vrtp)
		ast_rtp_stop(p->vrtp);
	if (p->udptl)
		ast_udptl_stop(p->udptl);
}

/*! \brief Handle SIP response in dialogue */
/* XXX only called by handle_request */
static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore, int seqno)
{
	struct ast_channel *owner;
	int sipmethod;
	int res = 1;
	const char *c = get_header(req, "Cseq");
	const char *msg = strchr(c, ' ');

	if (!msg)
		msg = "";
	else
		msg++;
	sipmethod = find_sip_method(msg);

	owner = p->owner;
	if (owner) 
		owner->hangupcause = hangup_sip2cause(resp);

	/* Acknowledge whatever it is destined for */
	if ((resp >= 100) && (resp <= 199))
		__sip_semi_ack(p, seqno, 0, sipmethod);
	else
		__sip_ack(p, seqno, 0, sipmethod);

	/* Get their tag if we haven't already */
	if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
		char tag[128];

		gettag(req, "To", tag, sizeof(tag));
		ast_string_field_set(p, theirtag, tag);
	}
	if (p->relatedpeer && p->method == SIP_OPTIONS) {
		/* We don't really care what the response is, just that it replied back. 
		   Well, as long as it's not a 100 response...  since we might
		   need to hang around for something more "definitive" */
		if (resp != 100)
			handle_response_peerpoke(p, resp, req);
	} else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
		switch(resp) {
		case 100:	/* 100 Trying */
		case 101:	/* 101 Dialog establishment */
			if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 183:	/* 183 Session Progress */
			if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 180:	/* 180 Ringing */
			if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 200:	/* 200 OK */
			p->authtries = 0;	/* Reset authentication counter */
			if (sipmethod == SIP_MESSAGE) {
				/* We successfully transmitted a message */
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			} else if (sipmethod == SIP_INVITE) {
				handle_response_invite(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_NOTIFY) {
				/* They got the notify, this is the end */
				if (p->owner) {
					if (!p->refer) {
						ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
						ast_queue_hangup(p->owner);
					} else if (option_debug > 3) 
						ast_log(LOG_DEBUG, "Got OK on REFER Notify message\n");
				} else {
					if (p->subscribed == NONE) 
						ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); 
				}
			} else if (sipmethod == SIP_REGISTER) 
				res = handle_response_register(p, resp, rest, req, ignore, seqno);
			else if (sipmethod == SIP_BYE)		/* Ok, we're ready to go */
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY); 
			break;
		case 202:   /* Transfer accepted */
			if (sipmethod == SIP_REFER) 
				handle_response_refer(p, resp, rest, req, seqno);
			break;
		case 401: /* Not www-authorized on SIP method */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_REFER)
				handle_response_refer(p, resp, rest, req, seqno);
			else if (p->registry && sipmethod == SIP_REGISTER)
				res = handle_response_register(p, resp, rest, req, ignore, seqno);
			else {
				ast_log(LOG_WARNING, "Got authentication request (401) on unknown %s to '%s'\n", sip_methods[sipmethod].text, get_header(req, "To"));
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			}
			break;
		case 403: /* Forbidden - we failed authentication */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (p->registry && sipmethod == SIP_REGISTER) 
				res = handle_response_register(p, resp, rest, req, ignore, seqno);
			else {
				ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			}
			break;
		case 404: /* Not found */
			if (p->registry && sipmethod == SIP_REGISTER)
				res = handle_response_register(p, resp, rest, req, ignore, seqno);
			else if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (owner)
				ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
			break;
		case 407: /* Proxy auth required */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_REFER)
				handle_response_refer(p, resp, rest, req, seqno);
			else if (p->registry && sipmethod == SIP_REGISTER)
				res = handle_response_register(p, resp, rest, req, ignore, seqno);
			else if (sipmethod == SIP_BYE) {
				if (ast_strlen_zero(p->authname))
					ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
							msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
					ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
				if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", sipmethod, 0)) {
					ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
					ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
				}
			} else	/* We can't handle this, giving up in a bad way */
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	

			break;
		case 481: /* Call leg does not exist */
			if (sipmethod == SIP_INVITE) {
				handle_response_invite(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_REFER) {
				handle_response_refer(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_BYE) {
				/* The other side has no transaction to bye,
				just assume it's all right then */
				ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
			} else if (sipmethod == SIP_CANCEL) {
				/* The other side has no transaction to cancel,
				just assume it's all right then */
				ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
			} else {
				ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
				/* Guessing that this is not an important request */
			}
			break;
		case 487:
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 491: /* Pending */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else {
				if (option_debug)
					ast_log(LOG_DEBUG, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			}
			break;
		case 501: /* Not Implemented */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_REFER)
				handle_response_refer(p, resp, rest, req, seqno);
			else
				ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
			break;
		case 603:	/* Declined transfer */
			if (sipmethod == SIP_REFER) {
				handle_response_refer(p, resp, rest, req, seqno);
				break;
			}
			/* Fallthrough */
		default:
			if ((resp >= 300) && (resp < 700)) {
				/* Fatal response */
				if ((option_verbose > 2) && (resp != 487))
					ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
	
				stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */

				/* XXX Locking issues?? XXX */
				switch(resp) {
				case 300: /* Multiple Choices */
				case 301: /* Moved permenantly */
				case 302: /* Moved temporarily */
				case 305: /* Use Proxy */
					parse_moved_contact(p, req);
					/* Fall through */
				case 486: /* Busy here */
				case 600: /* Busy everywhere */
				case 603: /* Decline */
					if (p->owner)
						ast_queue_control(p->owner, AST_CONTROL_BUSY);
					break;
				case 482: /*
					\note SIP is incapable of performing a hairpin call, which
					is yet another failure of not having a layer 2 (again, YAY
					 IETF for thinking ahead).  So we treat this as a call
					 forward and hope we end up at the right place... */
					if (option_debug)
						ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
					if (p->owner)
						ast_string_field_build(p->owner, call_forward,
								       "Local/%s@%s", p->username, p->context);
					/* Fall through */
				case 488: /* Not acceptable here - codec error */
				case 480: /* Temporarily Unavailable */
				case 404: /* Not Found */
				case 410: /* Gone */
				case 400: /* Bad Request */
				case 500: /* Server error */
					if (sipmethod == SIP_REFER) {
						handle_response_refer(p, resp, rest, req, seqno);
						break;
					}
					/* Fall through */
				case 503: /* Service Unavailable */
				case 504: /* Server Timeout */
					if (owner)
						ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
					break;
				default:
					/* Send hangup */	
					if (owner)
						ast_queue_hangup(p->owner);
					break;
				}
				/* ACK on invite */
				if (sipmethod == SIP_INVITE) 
					transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
				sip_alreadygone(p);
				if (!p->owner)
					ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			} else if ((resp >= 100) && (resp < 200)) {
				if (sipmethod == SIP_INVITE) {
					if (!ast_test_flag(req, SIP_PKT_IGNORE))
						sip_cancel_destroy(p);
					if (find_sdp(req))
						process_sdp(p, req);
					if (p->owner) {
						/* Queue a progress frame */
						ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
					}
				}
			} else
				ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
		}
	} else {	
		/* Responses to OUTGOING SIP requests on INCOMING calls 
		   get handled here. As well as out-of-call message responses */
		if (ast_test_flag(req, SIP_PKT_DEBUG))
			ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);

		if (sipmethod == SIP_INVITE && resp == 200) {
			/* Tags in early session is replaced by the tag in 200 OK, which is 
		  	the final reply to our INVITE */
			char tag[128];

			gettag(req, "To", tag, sizeof(tag));
			ast_string_field_set(p, theirtag, tag);
		}

		switch(resp) {
		case 200:
			if (sipmethod == SIP_INVITE) {
				handle_response_invite(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_CANCEL) {
				if (option_debug)
					ast_log(LOG_DEBUG, "Got 200 OK on CANCEL\n");

				/* Wait for 487, then destroy */
			} else if (sipmethod == SIP_NOTIFY) {
				/* They got the notify, this is the end */
				if (p->owner) {
					ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
					/* ast_queue_hangup(p->owner); Disabled */
				} else {
					if (!p->subscribed && !p->refer)
						ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
				}
			} else if (sipmethod == SIP_BYE)
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			else if (sipmethod == SIP_MESSAGE)
				/* We successfully transmitted a message */
				/* XXX Why destroy this pvt after message transfer? Bad */
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			else if (sipmethod == SIP_BYE) 
				/* Ok, we're ready to go */
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			break;
		case 202:   /* Transfer accepted */
			if (sipmethod == SIP_REFER) 
				handle_response_refer(p, resp, rest, req, seqno);
			break;
		case 401:	/* www-auth */
		case 407:
			if (sipmethod == SIP_REFER)
				handle_response_refer(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_BYE) {
				char *auth, *auth2;

				auth = (resp == 407 ? "Proxy-Authenticate" : "WWW-Authenticate");
				auth2 = (resp == 407 ? "Proxy-Authorization" : "Authorization");
				if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, auth, auth2, sipmethod, 0)) {
					ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
					ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
				}
			}
			break;
		case 481:	/* Call leg does not exist */
			if (sipmethod == SIP_INVITE) {
				/* Re-invite failed */
				handle_response_invite(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_BYE) {
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			} else if (sipdebug) {
				ast_log	(LOG_DEBUG, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
			}
			break;
		case 501: /* Not Implemented */
			if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_REFER) 
				handle_response_refer(p, resp, rest, req, seqno);
			break;
		case 603:	/* Declined transfer */
			if (sipmethod == SIP_REFER) {
				handle_response_refer(p, resp, rest, req, seqno);
				break;
			}
			/* Fallthrough */
		default:	/* Errors without handlers */
			if ((resp >= 100) && (resp < 200)) {
				if (sipmethod == SIP_INVITE) { 	/* re-invite */
					if (!ast_test_flag(req, SIP_PKT_IGNORE))
						sip_cancel_destroy(p);
				}
			}
			if ((resp >= 300) && (resp < 700)) {
				if ((option_verbose > 2) && (resp != 487))
					ast_verbose(VERBOSE_PREFIX_3 "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
				switch(resp) {
				case 488: /* Not acceptable here - codec error */
				case 603: /* Decline */
				case 500: /* Server error */
				case 503: /* Service Unavailable */
				case 504: /* Server timeout */

					if (sipmethod == SIP_INVITE) {	/* re-invite failed */
						sip_cancel_destroy(p);
					}
					break;
				}
			}
			break;
		}
	}
}


/*! \brief Park SIP call support function 
	Starts in a new thread, then parks the call
	XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
		audio can't be heard before hangup
*/
static void *sip_park_thread(void *stuff)
{
	struct ast_channel *transferee, *transferer;	/* Chan1: The transferee, Chan2: The transferer */
	struct sip_dual *d;
	struct sip_request req;
	int ext;
	int res;

	d = stuff;
	transferee = d->chan1;
	transferer = d->chan2;
	copy_request(&req, &d->req);
	free(d);

	if (!transferee || !transferer) {
		ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
		return NULL;
	}
	if (option_debug > 3) 
		ast_log(LOG_DEBUG, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);

	ast_channel_lock(transferee);
	if (ast_do_masquerade(transferee)) {
		ast_log(LOG_WARNING, "Masquerade failed.\n");
		transmit_response(transferer->tech_pvt, "503 Internal error", &req);
		ast_channel_unlock(transferee);
		return NULL;
	} 
	ast_channel_unlock(transferee);

	res = ast_park_call(transferee, transferer, 0, &ext);
	

#ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
	if (!res) {
		transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
	} else {
		/* Then tell the transferer what happened */
		sprintf(buf, "Call parked on extension '%d'", ext);
		transmit_message_with_text(transferer->tech_pvt, buf);
	}
#endif

	/* Any way back to the current call??? */
	/* Transmit response to the REFER request */
	transmit_response(transferer->tech_pvt, "202 Accepted", &req);
	if (!res)	{
		/* Transfer succeeded */
		append_history(transferer->tech_pvt, "SIPpark","Parked call on %d", ext);
		transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
		transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
		ast_hangup(transferer); /* This will cause a BYE */
		if (option_debug)
			ast_log(LOG_DEBUG, "SIP Call parked on extension '%d'\n", ext);
	} else {
		transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
		append_history(transferer->tech_pvt, "SIPpark","Parking failed\n");
		if (option_debug)
			ast_log(LOG_DEBUG, "SIP Call parked failed \n");
		/* Do not hangup call */
	}
	return NULL;
}

/*! \brief Park a call using the subsystem in res_features.c 
	This is executed in a separate thread
*/
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
{
	struct sip_dual *d;
	struct ast_channel *transferee, *transferer;
		/* Chan2m: The transferer, chan1m: The transferee */
	pthread_t th;

	transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "Parking/%s", chan1->name);
	transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "SIPPeer/%s", chan2->name);
	if ((!transferer) || (!transferee)) {
		if (transferee) {
			transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
			ast_hangup(transferee);
		}
		if (transferer) {
			transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
			ast_hangup(transferer);
		}
		return -1;
	}

	/* Make formats okay */
	transferee->readformat = chan1->readformat;
	transferee->writeformat = chan1->writeformat;

	/* Prepare for taking over the channel */
	ast_channel_masquerade(transferee, chan1);

	/* Setup the extensions and such */
	ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
	ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
	transferee->priority = chan1->priority;
		
	/* We make a clone of the peer channel too, so we can play
	   back the announcement */

	/* Make formats okay */
	transferer->readformat = chan2->readformat;
	transferer->writeformat = chan2->writeformat;

	/* Prepare for taking over the channel */
	ast_channel_masquerade(transferer, chan2);

	/* Setup the extensions and such */
	ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
	ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
	transferer->priority = chan2->priority;

	ast_channel_lock(transferer);
	if (ast_do_masquerade(transferer)) {
		ast_log(LOG_WARNING, "Masquerade failed :(\n");
		ast_channel_unlock(transferer);
		transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
		ast_hangup(transferer);
		return -1;
	}
	ast_channel_unlock(transferer);
	if (!transferer || !transferee) {
		if (!transferer) { 
			if (option_debug)
				ast_log(LOG_DEBUG, "No transferer channel, giving up parking\n");
		}
		if (!transferee) {
			if (option_debug)
				ast_log(LOG_DEBUG, "No transferee channel, giving up parking\n");
		}
		return -1;
	}
	if ((d = ast_calloc(1, sizeof(*d)))) {
		/* Save original request for followup */
		copy_request(&d->req, req);
		d->chan1 = transferee;	/* Transferee */
		d->chan2 = transferer;	/* Transferer */
		d->seqno = seqno;
		if (ast_pthread_create_background(&th, NULL, sip_park_thread, d) < 0) {
			/* Could not start thread */
			free(d);	/* We don't need it anymore. If thread is created, d will be free'd
					   by sip_park_thread() */
			return 0;
		}
	} 
	return -1;
}

/*! \brief Turn off generator data 
	XXX Does this function belong in the SIP channel?
*/
static void ast_quiet_chan(struct ast_channel *chan) 
{
	if (chan && chan->_state == AST_STATE_UP) {
		if (chan->generatordata)
			ast_deactivate_generator(chan);
	}
}

/*! \brief Attempt transfer of SIP call 
	This fix for attended transfers on a local PBX */
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
{
	int res = 0;
	struct ast_channel *peera = NULL,	
		*peerb = NULL,
		*peerc = NULL,
		*peerd = NULL;


	/* We will try to connect the transferee with the target and hangup
   	all channels to the transferer */	
	if (option_debug > 3) {
		ast_log(LOG_DEBUG, "Sip transfer:--------------------\n");
		if (transferer->chan1)
			ast_log(LOG_DEBUG, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
		else
			ast_log(LOG_DEBUG, "-- No transferer first channel - odd??? \n");
		if (target->chan1)
			ast_log(LOG_DEBUG, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
		else
			ast_log(LOG_DEBUG, "-- No target first channel ---\n");
		if (transferer->chan2)
			ast_log(LOG_DEBUG, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
		else
			ast_log(LOG_DEBUG, "-- No bridged call to transferee\n");
		if (target->chan2)
			ast_log(LOG_DEBUG, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
		else
			ast_log(LOG_DEBUG, "-- No target second channel ---\n");
		ast_log(LOG_DEBUG, "-- END Sip transfer:--------------------\n");
	}
	if (transferer->chan2) {			/* We have a bridge on the transferer's channel */
		peera = transferer->chan1;	/* Transferer - PBX -> transferee channel * the one we hangup */
		peerb = target->chan1;		/* Transferer - PBX -> target channel - This will get lost in masq */
		peerc = transferer->chan2;	/* Asterisk to Transferee */
		peerd = target->chan2;		/* Asterisk to Target */
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "SIP transfer: Four channels to handle\n");
	} else if (target->chan2) {	/* Transferer has no bridge (IVR), but transferee */
		peera = target->chan1;		/* Transferer to PBX -> target channel */
		peerb = transferer->chan1;	/* Transferer to IVR*/
		peerc = target->chan2;		/* Asterisk to Target */
		peerd = transferer->chan2;	/* Nothing */
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "SIP transfer: Three channels to handle\n");
	}

	if (peera && peerb && peerc && (peerb != peerc)) {
		ast_quiet_chan(peera);		/* Stop generators */
		ast_quiet_chan(peerb);	
		ast_quiet_chan(peerc);
		if (peerd)
			ast_quiet_chan(peerd);

		/* Fix CDRs so they're attached to the remaining channel */
		if (peera->cdr && peerb->cdr)
			peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
		else if (peera->cdr) 
			peerb->cdr = peera->cdr;
		peera->cdr = NULL;

		if (peerb->cdr && peerc->cdr) 
			peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
		else if (peerc->cdr)
			peerb->cdr = peerc->cdr;
		peerc->cdr = NULL;
	
		if (option_debug > 3)
			ast_log(LOG_DEBUG, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
		if (ast_channel_masquerade(peerb, peerc)) {
			ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
			res = -1;
		} else
			ast_log(LOG_DEBUG, "SIP transfer: Succeeded to masquerade channels.\n");
		return res;
	} else {
		ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
		if (transferer->chan1)
			ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
		if (target->chan1)
			ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
		return -1;
	}
	return 0;
}

/*! \brief Get tag from packet 
 *
 * \return Returns the pointer to the provided tag buffer,
 *         or NULL if the tag was not found.
 */
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
{
	const char *thetag;

	if (!tagbuf)
		return NULL;
	tagbuf[0] = '\0'; 	/* reset the buffer */
	thetag = get_header(req, header);
	thetag = strcasestr(thetag, ";tag=");
	if (thetag) {
		thetag += 5;
		ast_copy_string(tagbuf, thetag, tagbufsize);
		return strsep(&tagbuf, ";");
	}
	return NULL;
}

/*! \brief Handle incoming notifications */
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
{
	/* This is mostly a skeleton for future improvements */
	/* Mostly created to return proper answers on notifications on outbound REFER's */
	int res = 0;
	const char *event = get_header(req, "Event");
	char *eventid = NULL;
	char *sep;

	if( (sep = strchr(event, ';')) ) {	/* XXX bug here - overwriting string ? */
		*sep++ = '\0';
		eventid = sep;
	}
	
	if (option_debug > 1 && sipdebug)
		ast_log(LOG_DEBUG, "Got NOTIFY Event: %s\n", event);

	if (strcmp(event, "refer")) {
		/* We don't understand this event. */
		/* Here's room to implement incoming voicemail notifications :-) */
		transmit_response(p, "489 Bad event", req);
		res = -1;
	} else {
		/* Save nesting depth for now, since there might be other events we will
			support in the future */

		/* Handle REFER notifications */

		char buf[1024];
		char *cmd, *code;
		int respcode;
		int success = TRUE;

		/* EventID for each transfer... EventID is basically the REFER cseq 

		 We are getting notifications on a call that we transfered
		 We should hangup when we are getting a 200 OK in a sipfrag
		 Check if we have an owner of this event */
		
		/* Check the content type */
		if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
			/* We need a sipfrag */
			transmit_response(p, "400 Bad request", req);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return -1;
		}

		/* Get the text of the attachment */
		if (get_msg_text(buf, sizeof(buf), req)) {
			ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
			transmit_response(p, "400 Bad request", req);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return -1;
		}

		/*
		From the RFC...
		A minimal, but complete, implementation can respond with a single
   		NOTIFY containing either the body:
      			SIP/2.0 100 Trying
		
   		if the subscription is pending, the body:
      			SIP/2.0 200 OK
   		if the reference was successful, the body:
      			SIP/2.0 503 Service Unavailable
   		if the reference failed, or the body:
      			SIP/2.0 603 Declined

   		if the REFER request was accepted before approval to follow the
   		reference could be obtained and that approval was subsequently denied
   		(see Section 2.4.7).
		
		If there are several REFERs in the same dialog, we need to
		match the ID of the event header...
		*/
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
		cmd = ast_skip_blanks(buf);
		code = cmd;
		/* We are at SIP/2.0 */
		while(*code && (*code > 32)) {	/* Search white space */
			code++;
		}
		*code++ = '\0';
		code = ast_skip_blanks(code);
		sep = code;
		sep++;
		while(*sep && (*sep > 32)) {	/* Search white space */
			sep++;
		}
		*sep++ = '\0';			/* Response string */
		respcode = atoi(code);
		switch (respcode) {
		case 100:	/* Trying: */
		case 101:	/* dialog establishment */
			/* Don't do anything yet */
			break;
		case 183:	/* Ringing: */
			/* Don't do anything yet */
			break;
		case 200:	/* OK: The new call is up, hangup this call */
			/* Hangup the call that we are replacing */
			break;
		case 301: /* Moved permenantly */
		case 302: /* Moved temporarily */
			/* Do we get the header in the packet in this case? */
			success = FALSE;
			break;
		case 503:	/* Service Unavailable: The new call failed */
				/* Cancel transfer, continue the call */
			success = FALSE;
			break;
		case 603:	/* Declined: Not accepted */
				/* Cancel transfer, continue the current call */
			success = FALSE;
			break;
		}
		if (!success) {
			ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
		}
		
		/* Confirm that we received this packet */
		transmit_response(p, "200 OK", req);
	};

	if (!p->lastinvite)
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

	return res;
}

/*! \brief Handle incoming OPTIONS request */
static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
{
	int res;

	res = get_destination(p, req);
	build_contact(p);
	/* XXX Should we authenticate OPTIONS? XXX */
	if (ast_strlen_zero(p->context))
		ast_string_field_set(p, context, default_context);
	if (res < 0)
		transmit_response_with_allow(p, "404 Not Found", req, 0);
	else 
		transmit_response_with_allow(p, "200 OK", req, 0);
	/* Destroy if this OPTIONS was the opening request, but not if
	   it's in the middle of a normal call flow. */
	if (!p->lastinvite)
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

	return res;
}

/*! \brief Handle the transfer part of INVITE with a replaces: header, 
    meaning a target pickup or an attended transfer */
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin)
{
	struct ast_frame *f;
	int earlyreplace = 0;
	int oneleggedreplace = 0;		/* Call with no bridge, propably IVR or voice message */
	struct ast_channel *c = p->owner;	/* Our incoming call */
	struct ast_channel *replacecall = p->refer->refer_call->owner;	/* The channel we're about to take over */
	struct ast_channel *targetcall;		/* The bridge to the take-over target */

	/* Check if we're in ring state */
	if (replacecall->_state == AST_STATE_RING)
		earlyreplace = 1;

	/* Check if we have a bridge */
	if (!(targetcall = ast_bridged_channel(replacecall))) {
		/* We have no bridge */
		if (!earlyreplace) {
			if (option_debug > 1)
				ast_log(LOG_DEBUG, "	Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
			oneleggedreplace = 1;
		}
	} 
	if (option_debug > 3 && targetcall && targetcall->_state == AST_STATE_RINGING)
			ast_log(LOG_DEBUG, "SIP transfer: Target channel is in ringing state\n");

	if (option_debug > 3) {
		if (targetcall) 
			ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
		else
			ast_log(LOG_DEBUG, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
	}

	if (ignore) {
		ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
		/* We should answer something here. If we are here, the
			call we are replacing exists, so an accepted 
			can't harm */
		transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
		/* Do something more clever here */
		ast_channel_unlock(c);
		ast_mutex_unlock(&p->refer->refer_call->lock);
		return 1;
	} 
	if (!c) {
		/* What to do if no channel ??? */
		ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
		transmit_response_reliable(p, "503 Service Unavailable", req);
		append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		ast_mutex_unlock(&p->refer->refer_call->lock);
		return 1;
	}
	append_history(p, "Xfer", "INVITE/Replace received");
	/* We have three channels to play with
		channel c: New incoming call
		targetcall: Call from PBX to target
		p->refer->refer_call: SIP pvt dialog from transferer to pbx.
		replacecall: The owner of the previous
		We need to masq C into refer_call to connect to 
		targetcall;
		If we are talking to internal audio stream, target call is null.
	*/

	/* Fake call progress */
	transmit_response(p, "100 Trying", req);
	ast_setstate(c, AST_STATE_RING);

	/* Masquerade the new call into the referred call to connect to target call 
	   Targetcall is not touched by the masq */

	/* Answer the incoming call and set channel to UP state */
	transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE);
	ast_setstate(c, AST_STATE_UP);
	
	/* Stop music on hold and other generators */
	ast_quiet_chan(replacecall);
	ast_quiet_chan(targetcall);
	if (option_debug > 3)
		ast_log(LOG_DEBUG, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
	/* Unlock clone, but not original (replacecall) */
	ast_channel_unlock(c);

	/* Unlock PVT */
	ast_mutex_unlock(&p->refer->refer_call->lock);

	/* Make sure that the masq does not free our PVT for the old call */
	ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Delay hangup */
		
	/* Prepare the masquerade - if this does not happen, we will be gone */
	if(ast_channel_masquerade(replacecall, c))
		ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
	else if (option_debug > 3)
		ast_log(LOG_DEBUG, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);

	/* The masquerade will happen as soon as someone reads a frame from the channel */

	/* C should now be in place of replacecall */
	/* ast_read needs to lock channel */
	ast_channel_unlock(c);
	
	if (earlyreplace || oneleggedreplace ) {
		/* Force the masq to happen */
		if ((f = ast_read(replacecall))) {	/* Force the masq to happen */
			ast_frfree(f);
			f = NULL;
			if (option_debug > 3)
				ast_log(LOG_DEBUG, "Invite/Replace:  Could successfully read frame from RING channel!\n");
		} else {
			ast_log(LOG_WARNING, "Invite/Replace:  Could not read frame from RING channel \n");
		}
		c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
		ast_channel_unlock(replacecall);
	} else {	/* Bridged call, UP channel */
		if ((f = ast_read(replacecall))) {	/* Force the masq to happen */
			/* Masq ok */
			ast_frfree(f);
			f = NULL;
			if (option_debug > 2)
				ast_log(LOG_DEBUG, "Invite/Replace:  Could successfully read frame from channel! Masq done.\n");
		} else {
			ast_log(LOG_WARNING, "Invite/Replace:  Could not read frame from channel. Transfer failed\n");
		}
		ast_channel_unlock(replacecall);
	}
	ast_mutex_unlock(&p->refer->refer_call->lock);

	ast_setstate(c, AST_STATE_DOWN);
	if (option_debug > 3) {
		struct ast_channel *test;
		ast_log(LOG_DEBUG, "After transfer:----------------------------\n");
		ast_log(LOG_DEBUG, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
		if (replacecall)
			ast_log(LOG_DEBUG, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
		if (p->owner) {
			ast_log(LOG_DEBUG, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
			test = ast_bridged_channel(p->owner);
			if (test)
				ast_log(LOG_DEBUG, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
			else
				ast_log(LOG_DEBUG, " -- No call bridged to C->owner \n");
		} else 
			ast_log(LOG_DEBUG, " -- No channel yet \n");
		ast_log(LOG_DEBUG, "End After transfer:----------------------------\n");
	}

	ast_channel_unlock(p->owner);	/* Unlock new owner */
	ast_mutex_unlock(&p->lock);	/* Unlock SIP structure */

	/* The call should be down with no ast_channel, so hang it up */
	c->tech_pvt = NULL;
	ast_hangup(c);
	return 0;
}


/*! \brief Handle incoming INVITE request
\note 	If the INVITE has a Replaces header, it is part of an
 *	attended transfer. If so, we do not go through the dial
 *	plan but tries to find the active call and masquerade
 *	into it 
 */
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e)
{
	int res = 1;
	int gotdest;
	const char *p_replaces;
	char *replace_id = NULL;
	const char *required;
	unsigned int required_profile = 0;
	struct ast_channel *c = NULL;		/* New channel */

	/* Find out what they support */
	if (!p->sipoptions) {
		const char *supported = get_header(req, "Supported");
		if (!ast_strlen_zero(supported))
			parse_sip_options(p, supported);
	}

	/* Find out what they require */
	required = get_header(req, "Require");
	if (!ast_strlen_zero(required)) {
		required_profile = parse_sip_options(NULL, required);
		if (required_profile && required_profile != SIP_OPT_REPLACES) {
			/* At this point we only support REPLACES */
			transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
			ast_log(LOG_WARNING,"Received SIP INVITE with unsupported required extension: %s\n", required);
			if (!p->lastinvite)
				sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return -1;
		}
	}

	/* Check if this is a loop */
	if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->owner->_state != AST_STATE_UP)) {
		/* This is a call to ourself.  Send ourselves an error code and stop
	   	processing immediately, as SIP really has no good mechanism for
	   	being able to call yourself */
		/* If pedantic is on, we need to check the tags. If they're different, this is
	   	in fact a forked call through a SIP proxy somewhere. */
		transmit_response(p, "482 Loop Detected", req);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return 0;
	}
	
	if (!ast_test_flag(req, SIP_PKT_IGNORE) && p->pendinginvite) {
		/* We already have a pending invite. Sorry. You are on hold. */
		transmit_response(p, "491 Request Pending", req);
		if (option_debug)
			ast_log(LOG_DEBUG, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
		/* Don't destroy dialog here */
		return 0;
	}

	p_replaces = get_header(req, "Replaces");
	if (!ast_strlen_zero(p_replaces)) {
		/* We have a replaces header */
		char *ptr;
		char *fromtag = NULL;
		char *totag = NULL;
		char *start, *to;
		int error = 0;

		if (p->owner) {
			if (option_debug > 2)
				ast_log(LOG_DEBUG, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
			transmit_response(p, "400 Bad request", req);	/* The best way to not not accept the transfer */
			/* Do not destroy existing call */
			return -1;
		}

		if (sipdebug && option_debug > 2)
			ast_log(LOG_DEBUG, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
		/* Create a buffer we can manipulate */
		replace_id = ast_strdupa(p_replaces);
		ast_uri_decode(replace_id);

		if (!p->refer && !sip_refer_allocate(p)) {
			transmit_response(p, "500 Server Internal Error", req);
			append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return -1;
		}

		/*  Todo: (When we find phones that support this)
			if the replaces header contains ";early-only"
			we can only replace the call in early
			stage, not after it's up.

			If it's not in early mode, 486 Busy.
		*/
		
		/* Skip leading whitespace */
		replace_id = ast_skip_blanks(replace_id);

		start = replace_id;
		while ( (ptr = strsep(&start, ";")) ) {
			ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
			if ( (to = strcasestr(ptr, "to-tag=") ) )
				totag = to + 7;	/* skip the keyword */
			else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
				fromtag = to + 9;	/* skip the keyword */
				fromtag = strsep(&fromtag, "&"); /* trim what ? */
			}
		}

		if (sipdebug && option_debug > 3) 
			ast_log(LOG_DEBUG,"Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n", replace_id, fromtag ? fromtag : "<no from tag>", totag ? totag : "<no to tag>");


		/* Try to find call that we are replacing 
			If we have a Replaces  header, we need to cancel that call if we succeed with this call 
		*/
		if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
			ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
			transmit_response(p, "481 Call Leg Does Not Exist (Replaces)", req);
			error = 1;
		}

		/* At this point, bot the pvt and the owner of the call to be replaced is locked */

		/* The matched call is the call from the transferer to Asterisk .
			We want to bridge the bridged part of the call to the 
			incoming invite, thus taking over the refered call */

		if (p->refer->refer_call == p) {
			ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
			p->refer->refer_call = NULL;
			transmit_response(p, "400 Bad request", req);	/* The best way to not not accept the transfer */
			error = 1;
		}

		if (!error && !p->refer->refer_call->owner) {
			/* Oops, someting wrong anyway, no owner, no call */
			ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
			/* Check for better return code */
			transmit_response(p, "481 Call Leg Does Not Exist (Replace)", req);
			error = 1;
		}

		if (!error && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
			ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
			transmit_response(p, "603 Declined (Replaces)", req);
			error = 1;
		}

		if (error) {	/* Give up this dialog */
			append_history(p, "Xfer", "INVITE/Replace Failed.");
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			ast_mutex_unlock(&p->lock);
			if (p->refer->refer_call) {
				ast_mutex_unlock(&p->refer->refer_call->lock);
				ast_channel_unlock(p->refer->refer_call->owner);
			}
			return -1;
		}
	}


	/* Check if this is an INVITE that sets up a new dialog or
	   a re-invite in an existing dialog */

	if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
		int newcall = (p->initreq.headers ? TRUE : FALSE);

		sip_cancel_destroy(p);
		/* This also counts as a pending invite */
		p->pendinginvite = seqno;
		check_via(p, req);

		copy_request(&p->initreq, req);		/* Save this INVITE as the transaction basis */
		if (!p->owner) {	/* Not a re-invite */
			if (debug)
				ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
			if (newcall)
				append_history(p, "Invite", "New call: %s", p->callid);
			parse_ok_contact(p, req);
		} else {	/* Re-invite on existing call */
			ast_clear_flag(&p->flags[0], SIP_OUTGOING);	/* This is now an inbound dialog */
			/* Handle SDP here if we already have an owner */
			if (find_sdp(req)) {
				if (process_sdp(p, req)) {
					transmit_response(p, "488 Not acceptable here", req);
					if (!p->lastinvite)
						sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
					return -1;
				}
			} else {
				p->jointcapability = p->capability;
				if (option_debug)
					ast_log(LOG_DEBUG, "Hm....  No sdp for the moment\n");
			}
			if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a response, note what it was for */
				append_history(p, "ReInv", "Re-invite received");
		}
	} else if (debug)
		ast_verbose("Ignoring this INVITE request\n");

	
	if (!p->lastinvite && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) {
		/* This is a new invite */
		/* Handle authentication if this is our first invite */
		res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
		if (res == AUTH_CHALLENGE_SENT)
			return 0; 
		if (res < 0) { /* Something failed in authentication */
			if (res == AUTH_FAKE_AUTH) {
				ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
				transmit_fake_auth_response(p, req, 1);
			} else {
  				ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
				transmit_response_reliable(p, "403 Forbidden", req);
  			}
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			ast_string_field_free(p, theirtag);
			return 0;
		}

		/* We have a succesful authentication, process the SDP portion if there is one */
		if (find_sdp(req)) {
			if (process_sdp(p, req)) {
				/* Unacceptable codecs */
				transmit_response_reliable(p, "488 Not acceptable here", req);
				sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				if (option_debug)
					ast_log(LOG_DEBUG, "No compatible codecs for this SIP call.\n");
				return -1;
			}
		} else {	/* No SDP in invite, call control session */
			p->jointcapability = p->capability;
			if (option_debug > 1)
				ast_log(LOG_DEBUG, "No SDP in Invite, third party call control\n");
		}

		/* Queue NULL frame to prod ast_rtp_bridge if appropriate */
		/* This seems redundant ... see !p-owner above */
		if (p->owner)
			ast_queue_frame(p->owner, &ast_null_frame);


		/* Initialize the context if it hasn't been already */
		if (ast_strlen_zero(p->context))
			ast_string_field_set(p, context, default_context);


		/* Check number of concurrent calls -vs- incoming limit HERE */
		if (option_debug)
			ast_log(LOG_DEBUG, "Checking SIP call limits for device %s\n", p->username);
		if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
			if (res < 0) {
				ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
				transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
				sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			}
			return 0;
		}
		gotdest = get_destination(p, NULL);	/* Get destination right away */
		get_rdnis(p, NULL);			/* Get redirect information */
		extract_uri(p, req);			/* Get the Contact URI */
		build_contact(p);			/* Build our contact header */

		if (p->rtp) {
			ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
			ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
		}

		if (!replace_id && gotdest) {	/* No matching extension found */
			if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
				transmit_response_reliable(p, "484 Address Incomplete", req);
			else
				transmit_response_reliable(p, "404 Not Found", req);
			update_call_counter(p, DEC_CALL_LIMIT);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return 0;
		} else {
			/* If no extension was specified, use the s one */
			/* Basically for calling to IP/Host name only */
			if (ast_strlen_zero(p->exten))
				ast_string_field_set(p, exten, "s");
			/* Initialize our tag */	

			make_our_tag(p->tag, sizeof(p->tag));

			/* First invitation - create the channel */
			c = sip_new(p, AST_STATE_DOWN, S_OR(p->username, NULL));
			*recount = 1;

			/* Save Record-Route for any later requests we make on this dialogue */
			build_route(p, req, 0);

			if (c) {
				/* Pre-lock the call */
				ast_channel_lock(c);
			}
		}
	} else {
		if (option_debug > 1 && sipdebug) {
			if (!ast_test_flag(req, SIP_PKT_IGNORE))
				ast_log(LOG_DEBUG, "Got a SIP re-invite for call %s\n", p->callid);
			else
				ast_log(LOG_DEBUG, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
		}
		c = p->owner;
	}

	if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
		p->lastinvite = seqno;

	if (replace_id) { 	/* Attended transfer or call pickup - we're the target */
		/* Go and take over the target call */
		if (sipdebug && option_debug > 3)
			ast_log(LOG_DEBUG, "Sending this call to the invite/replcaes handler %s\n", p->callid);
		return handle_invite_replaces(p, req, debug, ast_test_flag(req, SIP_PKT_IGNORE), seqno, sin);
	}


	if (c) {	/* We have a call  -either a new call or an old one (RE-INVITE) */
		switch(c->_state) {
		case AST_STATE_DOWN:
			if (option_debug > 1)
				ast_log(LOG_DEBUG, "%s: New call is still down.... Trying... \n", c->name);
			transmit_response(p, "100 Trying", req);
			p->invitestate = INV_PROCEEDING;
			ast_setstate(c, AST_STATE_RING);
			if (strcmp(p->exten, ast_pickup_ext())) {	/* Call to extension -start pbx on this call */
				enum ast_pbx_result res;

				res = ast_pbx_start(c);

				switch(res) {
				case AST_PBX_FAILED:
					ast_log(LOG_WARNING, "Failed to start PBX :(\n");
					p->invitestate = INV_COMPLETED;
					if (ast_test_flag(req, SIP_PKT_IGNORE))
						transmit_response(p, "503 Unavailable", req);
					else
						transmit_response_reliable(p, "503 Unavailable", req);
					break;
				case AST_PBX_CALL_LIMIT:
					ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
					p->invitestate = INV_COMPLETED;
					if (ast_test_flag(req, SIP_PKT_IGNORE))
						transmit_response(p, "480 Temporarily Unavailable", req);
					else
						transmit_response_reliable(p, "480 Temporarily Unavailable", req);
					break;
				case AST_PBX_SUCCESS:
					/* nothing to do */
					break;
				}

				if (res) {

					/* Unlock locks so ast_hangup can do its magic */
					ast_mutex_unlock(&c->lock);
					ast_mutex_unlock(&p->lock);
					ast_hangup(c);
					ast_mutex_lock(&p->lock);
					c = NULL;
				}
			} else {	/* Pickup call in call group */
				ast_channel_unlock(c);
				if (ast_pickup_call(c)) {
					ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
					if (ast_test_flag(req, SIP_PKT_IGNORE))
						transmit_response(p, "503 Unavailable", req);	/* OEJ - Right answer? */
					else
						transmit_response_reliable(p, "503 Unavailable", req);
					sip_alreadygone(p);
					/* Unlock locks so ast_hangup can do its magic */
					ast_mutex_unlock(&p->lock);
					c->hangupcause = AST_CAUSE_CALL_REJECTED;
				} else {
					ast_mutex_unlock(&p->lock);
					ast_setstate(c, AST_STATE_DOWN);
					c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
				}
				p->invitestate = INV_COMPLETED;
				ast_hangup(c);
				ast_mutex_lock(&p->lock);
				c = NULL;
			}
			break;
		case AST_STATE_RING:
			transmit_response(p, "100 Trying", req);
			p->invitestate = INV_PROCEEDING;
			break;
		case AST_STATE_RINGING:
			transmit_response(p, "180 Ringing", req);
			p->invitestate = INV_PROCEEDING;
			break;
		case AST_STATE_UP:
			if (option_debug > 1)
				ast_log(LOG_DEBUG, "%s: This call is UP.... \n", c->name);

			if (p->t38.state == T38_PEER_REINVITE) {
				struct ast_channel *bridgepeer = NULL;
				struct sip_pvt *bridgepvt = NULL;
				
				if ((bridgepeer = ast_bridged_channel(p->owner))) {
					/* We have a bridge, and this is re-invite to switchover to T38 so we send re-invite with T38 SDP, to other side of bridge*/
					/*! XXX: we should also check here does the other side supports t38 at all !!! XXX */
					if (bridgepeer->tech == &sip_tech) {
						bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
						if (bridgepvt->t38.state == T38_DISABLED) {
							if (bridgepvt->udptl) { /* If everything is OK with other side's udptl struct */
								/* Send re-invite to the bridged channel */
								sip_handle_t38_reinvite(bridgepeer, p, 1);
							} else { /* Something is wrong with peers udptl struct */
								ast_log(LOG_WARNING, "Strange... The other side of the bridge don't have udptl struct\n");
								ast_mutex_lock(&bridgepvt->lock);
								bridgepvt->t38.state = T38_DISABLED;
								ast_mutex_unlock(&bridgepvt->lock);
								if (option_debug > 1)
									ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", bridgepvt->t38.state, bridgepeer->name);
								if (ast_test_flag(req, SIP_PKT_IGNORE))
									transmit_response(p, "488 Not acceptable here", req);
								else
									transmit_response_reliable(p, "488 Not acceptable here", req);
							
							}
						} else {
							/* The other side is already setup for T.38 most likely so we need to acknowledge this too */
							transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
							p->t38.state = T38_ENABLED;
							if (option_debug)
								ast_log(LOG_DEBUG, "T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
						}
					} else {
						/* Other side is not a SIP channel */
						if (ast_test_flag(req, SIP_PKT_IGNORE))
							transmit_response(p, "488 Not acceptable here", req);
						else
							transmit_response_reliable(p, "488 Not acceptable here", req);
						p->t38.state = T38_DISABLED;
						if (option_debug > 1)
							ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");

						if (!p->lastinvite) /* Only destroy if this is *not* a re-invite */
							sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
					}
				} else {
					/* we are not bridged in a call */
					transmit_response_with_t38_sdp(p, "200 OK", req, XMIT_CRITICAL);
					p->t38.state = T38_ENABLED;
					if (option_debug)
						ast_log(LOG_DEBUG,"T38 state changed to %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
				}
			} else if (p->t38.state == T38_DISABLED) { /* Channel doesn't have T38 offered or enabled */
				int sendok = TRUE;

				/* If we are bridged to a channel that has T38 enabled than this is a case of RTP re-invite after T38 session */
				/* so handle it here (re-invite other party to RTP) */
				struct ast_channel *bridgepeer = NULL;
				struct sip_pvt *bridgepvt = NULL;
				if ((bridgepeer = ast_bridged_channel(p->owner))) {
					if (bridgepeer->tech == &sip_tech) {
						bridgepvt = (struct sip_pvt*)bridgepeer->tech_pvt;
						/* Does the bridged peer have T38 ? */
						if (bridgepvt->t38.state == T38_ENABLED) {
							ast_log(LOG_WARNING, "RTP re-invite after T38 session not handled yet !\n");
							/* Insted of this we should somehow re-invite the other side of the bridge to RTP */
							if (ast_test_flag(req, SIP_PKT_IGNORE))
								transmit_response(p, "488 Not Acceptable Here (unsupported)", req);
							else
								transmit_response_reliable(p, "488 Not Acceptable Here (unsupported)", req);
							sendok = FALSE;
						} 
						/* No bridged peer with T38 enabled*/
					}
				} 
				if (sendok)
					transmit_response_with_sdp(p, "200 OK", req, XMIT_CRITICAL);

			}
			p->invitestate = INV_TERMINATED;
			break;
		default:
			ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
			transmit_response(p, "100 Trying", req);
			break;
		}
	} else {
		if (p && (p->autokillid == -1)) {
			const char *msg;

			if (!p->jointcapability)
				msg = "488 Not Acceptable Here (codec error)";
			else {
				ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
				msg = "503 Unavailable";
			}
			if (ast_test_flag(req, SIP_PKT_IGNORE))
				transmit_response(p, msg, req);
			else
				transmit_response_reliable(p, msg, req);
			p->invitestate = INV_COMPLETED;
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		}
	}
	return res;
}

/*! \brief  Find all call legs and bridge transferee with target 
 *	called from handle_request_refer */
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
{
	struct sip_dual target;		/* Chan 1: Call from tranferer to Asterisk */
					/* Chan 2: Call from Asterisk to target */
	int res = 0;
	struct sip_pvt *targetcall_pvt;
	int error = 0;

	/* Check if the call ID of the replaces header does exist locally */
	if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
		transferer->refer->replaces_callid_fromtag))) {
		if (transferer->refer->localtransfer) {
			/* We did not find the refered call. Sorry, can't accept then */
			transmit_response(transferer, "202 Accepted", req);
			/* Let's fake a response from someone else in order
		   	to follow the standard */
			transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
			append_history(transferer, "Xfer", "Refer failed");
			ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);	
			transferer->refer->status = REFER_FAILED;
			return -1;
		}
		/* Fall through for remote transfers that we did not find locally */
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
		return 0;
	}

	/* Ok, we can accept this transfer */
	transmit_response(transferer, "202 Accepted", req);
	append_history(transferer, "Xfer", "Refer accepted");
	if (!targetcall_pvt->owner) {	/* No active channel */
		if (option_debug > 3)
			ast_log(LOG_DEBUG, "SIP attended transfer: Error: No owner of target call\n");
		error = 1;
	}
	/* We have a channel, find the bridge */
	target.chan1 = targetcall_pvt->owner;				/* Transferer to Asterisk */

	if (!error) {
		target.chan2 = ast_bridged_channel(targetcall_pvt->owner);	/* Asterisk to target */

		if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
			/* Wrong state of new channel */
			if (option_debug > 3) {
				if (target.chan2) 
					ast_log(LOG_DEBUG, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
				else if (target.chan1->_state != AST_STATE_RING)
					ast_log(LOG_DEBUG, "SIP attended transfer: Error: No target channel\n");
				else
					ast_log(LOG_DEBUG, "SIP attended transfer: Attempting transfer in ringing state\n");
			}
			if (target.chan1->_state != AST_STATE_RING)
				error = 1;
		}
	}
	if (error) {	/* Cancel transfer */
		transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
		append_history(transferer, "Xfer", "Refer failed");
		ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);	
		transferer->refer->status = REFER_FAILED;
		ast_mutex_unlock(&targetcall_pvt->lock);
		ast_channel_unlock(current->chan1);
		ast_channel_unlock(target.chan1);
		return -1;
	}

	/* Transfer */
	if (option_debug > 3 && sipdebug) {
		if (current->chan2)	/* We have two bridges */
			ast_log(LOG_DEBUG, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
		else			/* One bridge, propably transfer of IVR/voicemail etc */
			ast_log(LOG_DEBUG, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
	}

	ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Delay hangup */

	/* Perform the transfer */
	res = attempt_transfer(current, &target);
	ast_mutex_unlock(&targetcall_pvt->lock);
	if (res) {
		/* Failed transfer */
		/* Could find better message, but they will get the point */
		transmit_notify_with_sipfrag(transferer, seqno, "486 Busy", TRUE);
		append_history(transferer, "Xfer", "Refer failed");
		if (targetcall_pvt->owner)
			ast_channel_unlock(targetcall_pvt->owner);
		/* Right now, we have to hangup, sorry. Bridge is destroyed */
		ast_hangup(transferer->owner);
	} else {
		/* Transfer succeeded! */

		/* Tell transferer that we're done. */
		transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
		append_history(transferer, "Xfer", "Refer succeeded");
		transferer->refer->status = REFER_200OK;
		if (targetcall_pvt->owner) {
			if (option_debug)
				ast_log(LOG_DEBUG, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
			ast_channel_unlock(targetcall_pvt->owner);
		}
	}
	return 1;
}


/*! \brief Handle incoming REFER request */
/*! \page SIP_REFER SIP transfer Support (REFER)

	REFER is used for call transfer in SIP. We get a REFER
	to place a new call with an INVITE somwhere and then
	keep the transferor up-to-date of the transfer. If the
	transfer fails, get back on line with the orginal call. 

	- REFER can be sent outside or inside of a dialog.
	  Asterisk only accepts REFER inside of a dialog.

	- If we get a replaces header, it is an attended transfer

	\par Blind transfers
	The transferor provides the transferee
	with the transfer targets contact. The signalling between
	transferer or transferee should not be cancelled, so the
	call is recoverable if the transfer target can not be reached 
	by the transferee.

	In this case, Asterisk receives a TRANSFER from
	the transferor, thus is the transferee. We should
	try to set up a call to the contact provided
	and if that fails, re-connect the current session.
	If the new call is set up, we issue a hangup.
	In this scenario, we are following section 5.2
	in the SIP CC Transfer draft. (Transfer without
	a GRUU)

	\par Transfer with consultation hold
	In this case, the transferor
	talks to the transfer target before the transfer takes place.
	This is implemented with SIP hold and transfer.
	Note: The invite From: string could indicate a transfer.
	(Section 6. Transfer with consultation hold)
	The transferor places the transferee on hold, starts a call
	with the transfer target to alert them to the impending
	transfer, terminates the connection with the target, then
	proceeds with the transfer (as in Blind transfer above)

	\par Attended transfer
	The transferor places the transferee
	on hold, calls the transfer target to alert them,
	places the target on hold, then proceeds with the transfer
	using a Replaces header field in the Refer-to header. This
	will force the transfee to send an Invite to the target,
	with a replaces header that instructs the target to
	hangup the call between the transferor and the target.
	In this case, the Refer/to: uses the AOR address. (The same
	URI that the transferee used to establish the session with
	the transfer target (To: ). The Require: replaces header should
	be in the INVITE to avoid the wrong UA in a forked SIP proxy
	scenario to answer and have no call to replace with.

	The referred-by header is *NOT* required, but if we get it,
	can be copied into the INVITE to the transfer target to 
	inform the target about the transferor

	"Any REFER request has to be appropriately authenticated.".
	
	We can't destroy dialogs, since we want the call to continue.
	
	*/
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, int *nounlock)
{
	struct sip_dual current;	/* Chan1: Call between asterisk and transferer */
					/* Chan2: Call between asterisk and transferee */

	int res = 0;

	if (ast_test_flag(req, SIP_PKT_DEBUG))
		ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");

	if (!p->owner) {
		/* This is a REFER outside of an existing SIP dialog */
		/* We can't handle that, so decline it */
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
		transmit_response(p, "603 Declined (No dialog)", req);
		if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
			append_history(p, "Xfer", "Refer failed. Outside of dialog.");
			sip_alreadygone(p);
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		}
		return 0;
	}	


	/* Check if transfer is allowed from this device */
	if (p->allowtransfer == TRANSFER_CLOSED ) {
		/* Transfer not allowed, decline */
		transmit_response(p, "603 Declined (policy)", req);
		append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
		/* Do not destroy SIP session */
		return 0;
	}

	if(!ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
		/* Already have a pending REFER */	
		transmit_response(p, "491 Request pending", req);
		append_history(p, "Xfer", "Refer failed. Request pending.");
		return 0;
	}

	/* Allocate memory for call transfer data */
	if (!p->refer && !sip_refer_allocate(p)) {
		transmit_response(p, "500 Internal Server Error", req);
		append_history(p, "Xfer", "Refer failed. Memory allocation error.");
		return -3;
	}

	res = get_refer_info(p, req);	/* Extract headers */

	p->refer->status = REFER_SENT;

	if (res != 0) {
		switch (res) {
		case -2:	/* Syntax error */
			transmit_response(p, "400 Bad Request (Refer-to missing)", req);
			append_history(p, "Xfer", "Refer failed. Refer-to missing.");
			if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
				ast_log(LOG_DEBUG, "SIP transfer to black hole can't be handled (no refer-to: )\n");
			break;
		case -3:
			transmit_response(p, "603 Declined (Non sip: uri)", req);
			append_history(p, "Xfer", "Refer failed. Non SIP uri");
			if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
				ast_log(LOG_DEBUG, "SIP transfer to non-SIP uri denied\n");
			break;
		default:
			/* Refer-to extension not found, fake a failed transfer */
			transmit_response(p, "202 Accepted", req);
			append_history(p, "Xfer", "Refer failed. Bad extension.");
			transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
			ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
			if (ast_test_flag(req, SIP_PKT_DEBUG) && option_debug)
				ast_log(LOG_DEBUG, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
			break;
		} 
		return 0;
	}
	if (ast_strlen_zero(p->context))
		ast_string_field_set(p, context, default_context);

	/* If we do not support SIP domains, all transfers are local */
	if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
		p->refer->localtransfer = 1;
		if (sipdebug && option_debug > 2)
			ast_log(LOG_DEBUG, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
	} else if (AST_LIST_EMPTY(&domain_list)) {
		/* This PBX don't bother with SIP domains, so all transfers are local */
		p->refer->localtransfer = 1;
	} else
		if (sipdebug && option_debug > 2)
			ast_log(LOG_DEBUG, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
	
	/* Is this a repeat of a current request? Ignore it */
	/* Don't know what else to do right now. */
	if (ignore) 
		return res;

	/* If this is a blind transfer, we have the following
   	channels to work with:
   	- chan1, chan2: The current call between transferer and transferee (2 channels)
   	- target_channel: A new call from the transferee to the target (1 channel)
   	We need to stay tuned to what happens in order to be able
   	to bring back the call to the transferer */

	/* If this is a attended transfer, we should have all call legs within reach:
   	- chan1, chan2: The call between the transferer and transferee (2 channels)
   	- target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
	We want to bridge chan2 with targetcall_pvt!
	
   	The replaces call id in the refer message points
   	to the call leg between Asterisk and the transferer.
   	So we need to connect the target and the transferee channel
   	and hangup the two other channels silently 
	
   	If the target is non-local, the call ID could be on a remote
   	machine and we need to send an INVITE with replaces to the
   	target. We basically handle this as a blind transfer
   	and let the sip_call function catch that we need replaces
   	header in the INVITE.
	*/


	/* Get the transferer's channel */
	current.chan1 = p->owner;

	/* Find the other part of the bridge (2) - transferee */
	current.chan2 = ast_bridged_channel(current.chan1);
	
	if (sipdebug && option_debug > 2)
		ast_log(LOG_DEBUG, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");

	if (!current.chan2 && !p->refer->attendedtransfer) {
		/* No bridged channel, propably IVR or echo or similar... */
		/* Guess we should masquerade or something here */
		/* Until we figure it out, refuse transfer of such calls */
		if (sipdebug && option_debug > 2)
			ast_log(LOG_DEBUG,"Refused SIP transfer on non-bridged channel.\n");
		p->refer->status = REFER_FAILED;
		append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
		transmit_response(p, "603 Declined", req);
		return -1;
	}

	if (current.chan2) {
		if (sipdebug && option_debug > 3)
			ast_log(LOG_DEBUG, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);

		ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
	}

	ast_set_flag(&p->flags[0], SIP_GOTREFER);	

	/* Attended transfer: Find all call legs and bridge transferee with target*/
	if (p->refer->attendedtransfer) {
		if ((res = local_attended_transfer(p, &current, req, seqno)))
			return res;	/* We're done with the transfer */
		/* Fall through for remote transfers that we did not find locally */
		if (sipdebug && option_debug > 3)
			ast_log(LOG_DEBUG, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
		/* Fallthrough if we can't find the call leg internally */
	}


	/* Parking a call */
	if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
		/* Must release c's lock now, because it will not longer be accessible after the transfer! */
		*nounlock = 1;
		ast_channel_unlock(current.chan1);
		copy_request(&current.req, req);
		ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
		p->refer->status = REFER_200OK;
		append_history(p, "Xfer", "REFER to call parking.");
		if (sipdebug && option_debug > 3)
			ast_log(LOG_DEBUG, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
		sip_park(current.chan2, current.chan1, req, seqno);
		return res;
	} 

	/* Blind transfers and remote attended xfers */
	transmit_response(p, "202 Accepted", req);

	if (current.chan1 && current.chan2) {
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "chan1->name: %s\n", current.chan1->name);
		pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
	}
	if (current.chan2) {
		pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
		pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
		pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
		/* One for the new channel */
		pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
		/* Attended transfer to remote host, prepare headers for the INVITE */
		if (p->refer->referred_by) 
			pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
	}
	/* Generate a Replaces string to be used in the INVITE during attended transfer */
	if (p->refer->replaces_callid && !ast_strlen_zero(p->refer->replaces_callid)) {
		char tempheader[BUFSIZ];
		snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
				p->refer->replaces_callid_totag ? ";to-tag=" : "", 
				p->refer->replaces_callid_totag, 
				p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
				p->refer->replaces_callid_fromtag);
		if (current.chan2)
			pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
	}
	/* Must release lock now, because it will not longer
    	   be accessible after the transfer! */
	*nounlock = 1;
	ast_channel_unlock(current.chan1);
	ast_channel_unlock(current.chan2);

	/* Connect the call */

	/* FAKE ringing if not attended transfer */
	if (!p->refer->attendedtransfer)
		transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
		
	/* For blind transfer, this will lead to a new call */
	/* For attended transfer to remote host, this will lead to
   	   a new SIP call with a replaces header, if the dial plan allows it 
  	*/
	if (!current.chan2) {
		/* We have no bridge, so we're talking with Asterisk somehow */
		/* We need to masquerade this call */
		/* What to do to fix this situation:
		   * Set up the new call in a new channel 
		   * Let the new channel masq into this channel
		   Please add that code here :-)
		*/
		p->refer->status = REFER_FAILED;
		transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
		ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
		append_history(p, "Xfer", "Refer failed (only bridged calls).");
		return -1;
	}
	ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Delay hangup */

	/* For blind transfers, move the call to the new extensions. For attended transfers on multiple
	   servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
	res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);

	if (!res) {
		/* Success  - we have a new channel */
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
		transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
		if (p->refer->localtransfer)
			p->refer->status = REFER_200OK;
		if (p->owner)
			p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
		append_history(p, "Xfer", "Refer succeeded.");
		ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
		/* Do not hangup call, the other side do that when we say 200 OK */
		/* We could possibly implement a timer here, auto congestion */
		res = 0;
	} else {
		ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Don't delay hangup */
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
		append_history(p, "Xfer", "Refer failed.");
		/* Failure of some kind */
		p->refer->status = REFER_FAILED;
		transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
		ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
		res = -1;
	}
	return res;
}

/*! \brief Handle incoming CANCEL request */
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
{
		
	check_via(p, req);
	sip_alreadygone(p);
	p->invitestate = INV_CANCELLED;
	
	if (p->owner && p->owner->_state == AST_STATE_UP) {
		/* This call is up, cancel is ignored, we need a bye */
		transmit_response(p, "200 OK", req);
		if (option_debug)
			ast_log(LOG_DEBUG, "Got CANCEL on an answered call. Ignoring... \n");
		return 0;
	}
	stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */

	if (p->owner)
		ast_queue_hangup(p->owner);
	else
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	if (p->initreq.len > 0) {
		transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
		transmit_response(p, "200 OK", req);
		return 1;
	} else {
		transmit_response(p, "481 Call Leg Does Not Exist", req);
		return 0;
	}
}

/*! \brief Handle incoming BYE request */
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
{
	struct ast_channel *c=NULL;
	int res;
	struct ast_channel *bridged_to;
	
	/* If we have an INCOMING invite that we haven't answered, terminate that transaction */
	if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !ast_test_flag(req, SIP_PKT_IGNORE) && !p->owner) 
		transmit_response_reliable(p, "487 Request Terminated", &p->initreq);

	p->invitestate = INV_TERMINATED;

	copy_request(&p->initreq, req);
	check_via(p, req);
	sip_alreadygone(p);

	/* Get RTCP quality before end of call */
	if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY) || p->owner) {
		char *audioqos, *videoqos;
		if (p->rtp) {
			audioqos = ast_rtp_get_quality(p->rtp);
			if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
				append_history(p, "RTCPaudio", "Quality:%s", audioqos);
			if (p->owner)
				pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
		}
		if (p->vrtp) {
			videoqos = ast_rtp_get_quality(p->vrtp);
			if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
				append_history(p, "RTCPvideo", "Quality:%s", videoqos);
			if (p->owner)
				pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
		}
	}

	stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */

	if (!ast_strlen_zero(get_header(req, "Also"))) {
		ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
			ast_inet_ntoa(p->recv.sin_addr));
		if (ast_strlen_zero(p->context))
			ast_string_field_set(p, context, default_context);
		res = get_also_info(p, req);
		if (!res) {
			c = p->owner;
			if (c) {
				bridged_to = ast_bridged_channel(c);
				if (bridged_to) {
					/* Don't actually hangup here... */
					ast_queue_control(c, AST_CONTROL_UNHOLD);
					ast_async_goto(bridged_to, p->context, p->refer->refer_to,1);
				} else
					ast_queue_hangup(p->owner);
			}
		} else {
			ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
			if (p->owner)
				ast_queue_hangup(p->owner);
		}
	} else if (p->owner) {
		ast_queue_hangup(p->owner);
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Received bye, issuing owner hangup\n");
	} else {
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Received bye, no owner, selfdestruct soon.\n");
	}
	transmit_response(p, "200 OK", req);

	return 1;
}

/*! \brief Handle incoming MESSAGE request */
static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
{
	if (!ast_test_flag(req, SIP_PKT_IGNORE)) {
		if (ast_test_flag(req, SIP_PKT_DEBUG))
			ast_verbose("Receiving message!\n");
		receive_message(p, req);
	} else
		transmit_response(p, "202 Accepted", req);
	return 1;
}

/*! \brief  Handle incoming SUBSCRIBE request */
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
{
	int gotdest;
	int res = 0;
	int firststate = AST_EXTENSION_REMOVED;
	struct sip_peer *authpeer = NULL;
	const char *eventheader = get_header(req, "Event");	/* Get Event package name */
	const char *accept = get_header(req, "Accept");
	int resubscribe = (p->subscribed != NONE);
	char *temp, *event;

	if (p->initreq.headers) {	
		/* We already have a dialog */
		if (p->initreq.method != SIP_SUBSCRIBE) {
			/* This is a SUBSCRIBE within another SIP dialog, which we do not support */
			/* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
 			transmit_response(p, "403 Forbidden (within dialog)", req);
			/* Do not destroy session, since we will break the call if we do */
			if (option_debug)
				ast_log(LOG_DEBUG, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
			return 0;
		} else if (ast_test_flag(req, SIP_PKT_DEBUG)) {
			if (option_debug) {
				if (resubscribe)
					ast_log(LOG_DEBUG, "Got a re-subscribe on existing subscription %s\n", p->callid);
				else
					ast_log(LOG_DEBUG, "Got a new subscription %s (possibly with auth)\n", p->callid);
			}
		}
	}

	/* Check if we have a global disallow setting on subscriptions. 
		if so, we don't have to check peer/user settings after auth, which saves a lot of processing
	*/
	if (!global_allowsubscribe) {
 		transmit_response(p, "403 Forbidden (policy)", req);
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		return 0;
	}

	if (!ast_test_flag(req, SIP_PKT_IGNORE) && !resubscribe) {	/* Set up dialog, new subscription */
		/* Use this as the basis */
		if (ast_test_flag(req, SIP_PKT_DEBUG))
			ast_verbose("Creating new subscription\n");

		copy_request(&p->initreq, req);
		check_via(p, req);
	} else if (ast_test_flag(req, SIP_PKT_DEBUG) && ast_test_flag(req, SIP_PKT_IGNORE))
		ast_verbose("Ignoring this SUBSCRIBE request\n");

	/* Find parameters to Event: header value and remove them for now */
	if (ast_strlen_zero(eventheader)) {
		transmit_response(p, "489 Bad Event", req);
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: <none>\n");
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		return 0;
	}

	if ( (strchr(eventheader, ';'))) {
		event = ast_strdupa(eventheader);	/* Since eventheader is a const, we can't change it */
		temp = strchr(event, ';'); 		
		*temp = '\0';				/* Remove any options for now */
							/* We might need to use them later :-) */
	} else
		event = (char *) eventheader;		/* XXX is this legal ? */

	/* Handle authentication */
	res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
	/* if an authentication response was sent, we are done here */
	if (res == AUTH_CHALLENGE_SENT) {
		if (authpeer)
			ASTOBJ_UNREF(authpeer, sip_destroy_peer);
		return 0;
	}
	if (res < 0) {
		if (res == AUTH_FAKE_AUTH) {
			ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
			transmit_fake_auth_response(p, req, 1);
		} else {
			ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
			transmit_response_reliable(p, "403 Forbidden", req);
		}
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		if (authpeer)
			ASTOBJ_UNREF(authpeer, sip_destroy_peer);
		return 0;
	}

	/* Check if this user/peer is allowed to subscribe at all */
	if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
		transmit_response(p, "403 Forbidden (policy)", req);
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
		if (authpeer)
			ASTOBJ_UNREF(authpeer, sip_destroy_peer);
		return 0;
	}

	/* Get destination right away */
	gotdest = get_destination(p, NULL);

	/* Initialize the context if it hasn't been already;
	   note this is done _after_ handling any domain lookups,
	   because the context specified there is for calls, not
	   subscriptions
	*/
	if (!ast_strlen_zero(p->subscribecontext))
		ast_string_field_set(p, context, p->subscribecontext);
	else if (ast_strlen_zero(p->context))
		ast_string_field_set(p, context, default_context);

	build_contact(p);
	if (gotdest) {
		transmit_response(p, "404 Not Found", req);
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		if (authpeer)
			ASTOBJ_UNREF(authpeer, sip_destroy_peer);
		return 0;
	}

	/* Initialize tag for new subscriptions */	
	if (ast_strlen_zero(p->tag))
		make_our_tag(p->tag, sizeof(p->tag));

	if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
		if (authpeer)	/* No need for authpeer here */
			ASTOBJ_UNREF(authpeer, sip_destroy_peer);

		/* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
		/* Polycom phones only handle xpidf+xml, even if they say they can
		   handle pidf+xml as well
		*/
		if (strstr(p->useragent, "Polycom")) {
			p->subscribed = XPIDF_XML;
		} else if (strstr(accept, "application/pidf+xml")) {
			p->subscribed = PIDF_XML;         /* RFC 3863 format */
		} else if (strstr(accept, "application/dialog-info+xml")) {
			p->subscribed = DIALOG_INFO_XML;
			/* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
		} else if (strstr(accept, "application/cpim-pidf+xml")) {
			p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
		} else if (strstr(accept, "application/xpidf+xml")) {
			p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
		} else {
			/* Can't find a format for events that we know about */
			transmit_response(p, "489 Bad Event", req);
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			return 0;
		}
	} else if (!strcmp(event, "message-summary")) { 
		if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
			/* Format requested that we do not support */
			transmit_response(p, "406 Not Acceptable", req);
			if (option_debug > 1)
				ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", accept);
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			if (authpeer)	/* No need for authpeer here */
				ASTOBJ_UNREF(authpeer, sip_destroy_peer);
			return 0;
		}
		/* Looks like they actually want a mailbox status 
		  This version of Asterisk supports mailbox subscriptions
		  The subscribed URI needs to exist in the dial plan
		  In most devices, this is configurable to the voicemailmain extension you use
		*/
		if (!authpeer || ast_strlen_zero(authpeer->mailbox)) {
			transmit_response(p, "404 Not found (no mailbox)", req);
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
			if (authpeer)	/* No need for authpeer here */
				ASTOBJ_UNREF(authpeer, sip_destroy_peer);
			return 0;
		}

		p->subscribed = MWI_NOTIFICATION;
		if (authpeer->mwipvt && authpeer->mwipvt != p)	/* Destroy old PVT if this is a new one */
			/* We only allow one subscription per peer */
			sip_destroy(authpeer->mwipvt);
		authpeer->mwipvt = p;		/* Link from peer to pvt */
		p->relatedpeer = authpeer;	/* Link from pvt to peer */
	} else { /* At this point, Asterisk does not understand the specified event */
		transmit_response(p, "489 Bad Event", req);
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "Received SIP subscribe for unknown event package: %s\n", event);
		ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		if (authpeer)	/* No need for authpeer here */
			ASTOBJ_UNREF(authpeer, sip_destroy_peer);
		return 0;
	}

	if (p->subscribed != MWI_NOTIFICATION && !resubscribe)
		p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);

	if (!ast_test_flag(req, SIP_PKT_IGNORE) && p)
		p->lastinvite = seqno;
	if (p && !ast_test_flag(&p->flags[0], SIP_NEEDDESTROY)) {
		p->expiry = atoi(get_header(req, "Expires"));

		/* check if the requested expiry-time is within the approved limits from sip.conf */
		if (p->expiry > max_expiry)
			p->expiry = max_expiry;
		if (p->expiry < min_expiry && p->expiry > 0)
			p->expiry = min_expiry;

		if (sipdebug || option_debug > 1) {
			if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
				ast_log(LOG_DEBUG, "Adding subscription for mailbox notification - peer %s Mailbox %s\n", p->relatedpeer->name, p->relatedpeer->mailbox);
			else
				ast_log(LOG_DEBUG, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
		}
		if (p->autokillid > -1)
			sip_cancel_destroy(p);	/* Remove subscription expiry for renewals */
		if (p->expiry > 0)
			sip_scheddestroy(p, (p->expiry + 10) * 1000);	/* Set timer for destruction of call at expiration */

		if (p->subscribed == MWI_NOTIFICATION) {
			transmit_response(p, "200 OK", req);
			if (p->relatedpeer) {	/* Send first notification */
				ASTOBJ_WRLOCK(p->relatedpeer);
				sip_send_mwi_to_peer(p->relatedpeer);
				ASTOBJ_UNLOCK(p->relatedpeer);
			}
		} else {
			struct sip_pvt *p_old;

			if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {

				ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_inet_ntoa(p->sa.sin_addr));
				transmit_response(p, "404 Not found", req);
				ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
				return 0;
			}

			transmit_response(p, "200 OK", req);
			transmit_state_notify(p, firststate, 1, FALSE);	/* Send first notification */
			append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
			/* hide the 'complete' exten/context in the refer_to field for later display */
			ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);

			/* remove any old subscription from this peer for the same exten/context,
			as the peer has obviously forgotten about it and it's wasteful to wait
			for it to expire and send NOTIFY messages to the peer only to have them
			ignored (or generate errors)
			*/
			ast_mutex_lock(&iflock);
			for (p_old = iflist; p_old; p_old = p_old->next) {
				if (p_old == p)
					continue;
				if (p_old->initreq.method != SIP_SUBSCRIBE)
					continue;
				if (p_old->subscribed == NONE)
					continue;
				ast_mutex_lock(&p_old->lock);
				if (!strcmp(p_old->username, p->username)) {
					if (!strcmp(p_old->exten, p->exten) &&
					    !strcmp(p_old->context, p->context)) {
						ast_set_flag(&p_old->flags[0], SIP_NEEDDESTROY);
						ast_mutex_unlock(&p_old->lock);
						break;
					}
				}
				ast_mutex_unlock(&p_old->lock);
			}
			ast_mutex_unlock(&iflock);
		}
		if (!p->expiry)
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);
	}
	return 1;
}

/*! \brief Handle incoming REGISTER request */
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
{
	enum check_auth_result res;

	/* Use this as the basis */
	if (ast_test_flag(req, SIP_PKT_DEBUG))
		ast_verbose("Using latest REGISTER request as basis request\n");
	copy_request(&p->initreq, req);
	check_via(p, req);
	if ((res = register_verify(p, sin, req, e)) < 0) {
		const char *reason = "";

		switch (res) {
		case AUTH_SECRET_FAILED:
			reason = "Wrong password";
			break;
		case AUTH_USERNAME_MISMATCH:
			reason = "Username/auth name mismatch";
			break;
		case AUTH_NOT_FOUND:
			reason = "No matching peer found";
			break;
		case AUTH_UNKNOWN_DOMAIN:
			reason = "Not a local domain";
			break;
		default:
			break;
		}
		ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
			get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
			reason);
	}
	if (res < 1) {
		/* Destroy the session, but keep us around for just a bit in case they don't
		   get our 200 OK */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	}
	append_history(p, "RegRequest", "%s : Account %s", res ? "Failed": "Succeeded", get_header(req, "To"));
	return res;
}

/*! \brief Handle incoming SIP requests (methods) 
\note	This is where all incoming requests go first   */
/* called with p and p->owner locked */
static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
{
	/* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
	   relatively static */
	const char *cmd;
	const char *cseq;
	const char *useragent;
	int seqno;
	int len;
	int ignore = FALSE;
	int respid;
	int res = 0;
	int debug = sip_debug_test_pvt(p);
	char *e;
	int error = 0;

	/* Get Method and Cseq */
	cseq = get_header(req, "Cseq");
	cmd = req->header[0];

	/* Must have Cseq */
	if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
		ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
		error = 1;
	}
	if (!error && sscanf(cseq, "%d%n", &seqno, &len) != 1) {
		ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
		error = 1;
	}
	if (error) {
		if (!p->initreq.headers)	/* New call */
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	/* Make sure we destroy this dialog */
		return -1;
	}
	/* Get the command XXX */

	cmd = req->rlPart1;
	e = req->rlPart2;

	/* Save useragent of the client */
	useragent = get_header(req, "User-Agent");
	if (!ast_strlen_zero(useragent))
		ast_string_field_set(p, useragent, useragent);

	/* Find out SIP method for incoming request */
	if (req->method == SIP_RESPONSE) {	/* Response to our request */
		/* Response to our request -- Do some sanity checks */	
		if (!p->initreq.headers) {
			if (option_debug)
				ast_log(LOG_DEBUG, "That's odd...  Got a response on a call we dont know about. Cseq %d Cmd %s\n", seqno, cmd);
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
			return 0;
		} else if (p->ocseq && (p->ocseq < seqno)) {
			if (option_debug)
				ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
			return -1;
		} else if (p->ocseq && (p->ocseq != seqno)) {
			/* ignore means "don't do anything with it" but still have to 
			   respond appropriately  */
			ignore = TRUE;
			ast_set_flag(req, SIP_PKT_IGNORE);
			ast_set_flag(req, SIP_PKT_IGNORE_RESP);
			append_history(p, "Ignore", "Ignoring this retransmit\n");
		}
	
		e = ast_skip_blanks(e);
		if (sscanf(e, "%d %n", &respid, &len) != 1) {
			ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
		} else {
			/* More SIP ridiculousness, we have to ignore bogus contacts in 100 etc responses */
			if ((respid == 200) || ((respid >= 300) && (respid <= 399)))
				extract_uri(p, req);
			handle_response(p, respid, e + len, req, ignore, seqno);
		}
		return 0;
	}

	/* New SIP request coming in 
	   (could be new request in existing SIP dialog as well...) 
	 */			
	
	p->method = req->method;	/* Find out which SIP method they are using */
	if (option_debug > 3)
		ast_log(LOG_DEBUG, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 

	if (p->icseq && (p->icseq > seqno)) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
		if (req->method != SIP_ACK)
			transmit_response(p, "503 Server error", req);	/* We must respond according to RFC 3261 sec 12.2 */
		return -1;
	} else if (p->icseq &&
		   p->icseq == seqno &&
		   req->method != SIP_ACK &&
		   (p->method != SIP_CANCEL || ast_test_flag(&p->flags[0], SIP_ALREADYGONE))) {
		/* ignore means "don't do anything with it" but still have to 
		   respond appropriately.  We do this if we receive a repeat of
		   the last sequence number  */
		ignore = 2;
		ast_set_flag(req, SIP_PKT_IGNORE);
		ast_set_flag(req, SIP_PKT_IGNORE_REQ);
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
	}
		
	if (seqno >= p->icseq)
		/* Next should follow monotonically (but not necessarily 
		   incrementally -- thanks again to the genius authors of SIP --
		   increasing */
		p->icseq = seqno;

	/* Find their tag if we haven't got it */
	if (ast_strlen_zero(p->theirtag)) {
		char tag[128];

		gettag(req, "From", tag, sizeof(tag));
		ast_string_field_set(p, theirtag, tag);
	}
	snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);

	if (pedanticsipchecking) {
		/* If this is a request packet without a from tag, it's not
			correct according to RFC 3261  */
		/* Check if this a new request in a new dialog with a totag already attached to it,
			RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
		if (!p->initreq.headers && ast_test_flag(req, SIP_PKT_WITH_TOTAG)) {
			/* If this is a first request and it got a to-tag, it is not for us */
			if (!ast_test_flag(req, SIP_PKT_IGNORE) && req->method == SIP_INVITE) {
				transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
				/* Will cease to exist after ACK */
			} else if (req->method != SIP_ACK) {
				transmit_response(p, "481 Call/Transaction Does Not Exist", req);
				sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			}
			return res;
		}
	}

	/* Handle various incoming SIP methods in requests */
	switch (p->method) {
	case SIP_OPTIONS:
		res = handle_request_options(p, req);
		break;
	case SIP_INVITE:
		res = handle_request_invite(p, req, debug, seqno, sin, recount, e);
		break;
	case SIP_REFER:
		res = handle_request_refer(p, req, debug, ignore, seqno, nounlock);
		break;
	case SIP_CANCEL:
		res = handle_request_cancel(p, req);
		break;
	case SIP_BYE:
		res = handle_request_bye(p, req);
		break;
	case SIP_MESSAGE:
		res = handle_request_message(p, req);
		break;
	case SIP_SUBSCRIBE:
		res = handle_request_subscribe(p, req, sin, seqno, e);
		break;
	case SIP_REGISTER:
		res = handle_request_register(p, req, sin, e);
		break;
	case SIP_INFO:
		if (ast_test_flag(req, SIP_PKT_DEBUG))
			ast_verbose("Receiving INFO!\n");
		if (!ignore) 
			handle_request_info(p, req);
		else  /* if ignoring, transmit response */
			transmit_response(p, "200 OK", req);
		break;
	case SIP_NOTIFY:
		res = handle_request_notify(p, req, sin, seqno, e);
		break;
	case SIP_ACK:
		/* Make sure we don't ignore this */
		if (seqno == p->pendinginvite) {
			p->invitestate = INV_CONFIRMED;
			p->pendinginvite = 0;
			__sip_ack(p, seqno, FLAG_RESPONSE, 0);
			if (find_sdp(req)) {
				if (process_sdp(p, req))
					return -1;
			} 
			check_pendings(p);
		}
		/* Got an ACK that we did not match. Ignore silently */
		if (!p->lastinvite && ast_strlen_zero(p->randdata))
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		break;
	default:
		transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
		ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
			cmd, ast_inet_ntoa(p->sa.sin_addr));
		/* If this is some new method, and we don't have a call, destroy it now */
		if (!p->initreq.headers)
			ast_set_flag(&p->flags[0], SIP_NEEDDESTROY);	
		break;
	}
	return res;
}

/*! \brief Read data from SIP socket
\note sipsock_read locks the owner channel while we are processing the SIP message
\return 1 on error, 0 on success
\note Successful messages is connected to SIP call and forwarded to handle_request() 
*/
static int sipsock_read(int *id, int fd, short events, void *ignore)
{
	struct sip_request req;
	struct sockaddr_in sin = { 0, };
	struct sip_pvt *p;
	int res;
	socklen_t len = sizeof(sin);
	int nounlock;
	int recount = 0;
	int lockretry;

	memset(&req, 0, sizeof(req));
	res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
	if (res < 0) {
#if !defined(__FreeBSD__)
		if (errno == EAGAIN)
			ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
		else 
#endif
		if (errno != ECONNREFUSED)
			ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
		return 1;
	}
	if (option_debug && res == sizeof(req.data)) {
		ast_log(LOG_DEBUG, "Received packet exceeds buffer. Data is possibly lost\n");
		req.data[sizeof(req.data) - 1] = '\0';
	} else
		req.data[res] = '\0';
	req.len = res;
	if(sip_debug_test_addr(&sin))	/* Set the debug flag early on packet level */
		ast_set_flag(&req, SIP_PKT_DEBUG);
	if (pedanticsipchecking)
		req.len = lws2sws(req.data, req.len);	/* Fix multiline headers */
	if (ast_test_flag(&req, SIP_PKT_DEBUG))
		ast_verbose("\n<--- SIP read from %s:%d --->\n%s\n<------------->\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), req.data);

	parse_request(&req);
	req.method = find_sip_method(req.rlPart1);

	if (ast_test_flag(&req, SIP_PKT_DEBUG))
		ast_verbose("--- (%d headers %d lines)%s ---\n", req.headers, req.lines, (req.headers + req.lines == 0) ? " Nat keepalive" : "");

	if (req.headers < 2)	/* Must have at least two headers */
		return 1;

	/* Process request, with netlock held, and with usual deadlock avoidance */
	for (lockretry = 100; lockretry > 0; lockretry--) {
		ast_mutex_lock(&netlock);

		/* Find the active SIP dialog or create a new one */
		p = find_call(&req, &sin, req.method);	/* returns p locked */
		if (p == NULL) {
			if (option_debug)
				ast_log(LOG_DEBUG, "Invalid SIP message - rejected , no callid, len %d\n", req.len);
			ast_mutex_unlock(&netlock);
			return 1;
		}
		/* Go ahead and lock the owner if it has one -- we may need it */
		/* becaues this is deadlock-prone, we need to try and unlock if failed */
		if (!p->owner || !ast_channel_trylock(p->owner))
			break;	/* locking succeeded */
		if (option_debug)
			ast_log(LOG_DEBUG, "Failed to grab owner channel lock, trying again. (SIP call %s)\n", p->callid);
		ast_mutex_unlock(&p->lock);
		ast_mutex_unlock(&netlock);
		/* Sleep for a very short amount of time */
		usleep(1);
	}
	p->recv = sin;

	if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) /* This is a request or response, note what it was for */
		append_history(p, "Rx", "%s / %s / %s", req.data, get_header(&req, "CSeq"), req.rlPart2);

	if (!lockretry) {
		ast_log(LOG_ERROR, "We could NOT get the channel lock for %s! \n", S_OR(p->owner->name, "- no channel name ??? - "));
		ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
		if (req.method != SIP_ACK)
			transmit_response(p, "503 Server error", &req);	/* We must respond according to RFC 3261 sec 12.2 */
		/* XXX We could add retry-after to make sure they come back */
		append_history(p, "LockFail", "Owner lock failed, transaction failed.");
		return 1;
	}
	nounlock = 0;
	if (handle_request(p, &req, &sin, &recount, &nounlock) == -1) {
		/* Request failed */
		if (option_debug)
			ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
	}
		
	if (p->owner && !nounlock)
		ast_channel_unlock(p->owner);
	ast_mutex_unlock(&p->lock);
	ast_mutex_unlock(&netlock);
	if (recount)
		ast_update_use_count();

	return 1;
}

/*! \brief Send message waiting indication to alert peer that they've got voicemail */
static int sip_send_mwi_to_peer(struct sip_peer *peer)
{
	/* Called with peerl lock, but releases it */
	struct sip_pvt *p;
	int newmsgs, oldmsgs;

	/* Check for messages */
	ast_app_inboxcount(peer->mailbox, &newmsgs, &oldmsgs);
	
	peer->lastmsgcheck = time(NULL);
	
	/* Return now if it's the same thing we told them last time */
	if (((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)) == peer->lastmsgssent) {
		return 0;
	}
	
	
	peer->lastmsgssent = ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs));

	if (peer->mwipvt) {
		/* Base message on subscription */
		p = peer->mwipvt;
	} else {
		/* Build temporary dialog for this message */
		if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY))) 
			return -1;
		if (create_addr_from_peer(p, peer)) {
			/* Maybe they're not registered, etc. */
			sip_destroy(p);
			return 0;
		}
		/* Recalculate our side, and recalculate Call ID */
		if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
			p->ourip = __ourip;
		build_via(p);
		build_callid_pvt(p);
		/* Destroy this session after 32 secs */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	}
	/* Send MWI */
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
	transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
	return 0;
}

/*! \brief Check whether peer needs a new MWI notification check */
static int does_peer_need_mwi(struct sip_peer *peer)
{
	time_t t = time(NULL);

	if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
	    !peer->mwipvt) {	/* We don't have a subscription */
		peer->lastmsgcheck = t;	/* Reset timer */
		return FALSE;
	}

	if (!ast_strlen_zero(peer->mailbox) && (t - peer->lastmsgcheck) > global_mwitime)
		return TRUE;

	return FALSE;
}


/*! \brief The SIP monitoring thread 
\note	This thread monitors all the SIP sessions and peers that needs notification of mwi
	(and thus do not have a separate thread) indefinitely 
*/
static void *do_monitor(void *data)
{
	int res;
	struct sip_pvt *sip;
	struct sip_peer *peer = NULL;
	time_t t;
	int fastrestart = FALSE;
	int lastpeernum = -1;
	int curpeernum;
	int reloading;

	/* Add an I/O event to our SIP UDP socket */
	if (sipsock > -1) 
		sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
	
	/* From here on out, we die whenever asked */
	for(;;) {
		/* Check for a reload request */
		ast_mutex_lock(&sip_reload_lock);
		reloading = sip_reloading;
		sip_reloading = FALSE;
		ast_mutex_unlock(&sip_reload_lock);
		if (reloading) {
			if (option_verbose > 0)
				ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
			sip_do_reload(sip_reloadreason);

			/* Change the I/O fd of our UDP socket */
			if (sipsock > -1)
				sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
		}
		/* Check for interfaces needing to be killed */
		ast_mutex_lock(&iflock);
restartsearch:		
		t = time(NULL);
		/* don't scan the interface list if it hasn't been a reasonable period
		   of time since the last time we did it (when MWI is being sent, we can
		   get back to this point every millisecond or less)
		*/
		for (sip = iflist; !fastrestart && sip; sip = sip->next) {
			ast_mutex_lock(&sip->lock);
			/* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
			if (sip->rtp && sip->owner &&
			    (sip->owner->_state == AST_STATE_UP) &&
			    !sip->redirip.sin_addr.s_addr) {
				if (sip->lastrtptx &&
				    ast_rtp_get_rtpkeepalive(sip->rtp) &&
				    (t > sip->lastrtptx + ast_rtp_get_rtpkeepalive(sip->rtp))) {
					/* Need to send an empty RTP packet */
					sip->lastrtptx = time(NULL);
					ast_rtp_sendcng(sip->rtp, 0);
				}
				if (sip->lastrtprx &&
					(ast_rtp_get_rtptimeout(sip->rtp) || ast_rtp_get_rtpholdtimeout(sip->rtp)) &&
				    (t > sip->lastrtprx + ast_rtp_get_rtptimeout(sip->rtp))) {
					/* Might be a timeout now -- see if we're on hold */
					struct sockaddr_in sin;
					ast_rtp_get_peer(sip->rtp, &sin);
					if (sin.sin_addr.s_addr || 
					    (ast_rtp_get_rtpholdtimeout(sip->rtp) &&
					     (t > sip->lastrtprx + ast_rtp_get_rtpholdtimeout(sip->rtp)))) {
						/* Needs a hangup */
						if (ast_rtp_get_rtptimeout(sip->rtp)) {
							while (sip->owner && ast_channel_trylock(sip->owner)) {
								ast_mutex_unlock(&sip->lock);
								usleep(1);
								ast_mutex_lock(&sip->lock);
							}
							if (sip->owner) {
								if (!(ast_rtp_get_bridged(sip->rtp))) {
									ast_log(LOG_NOTICE,
										"Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
										sip->owner->name,
										(long) (t - sip->lastrtprx));
									/* Issue a softhangup */
									ast_softhangup_nolock(sip->owner, AST_SOFTHANGUP_DEV);
								} else
									ast_log(LOG_NOTICE, "'%s' will not be disconnected in %ld seconds because it is directly bridged to another RTP stream\n", sip->owner->name, (long) (t - sip->lastrtprx));
								ast_channel_unlock(sip->owner);
								/* forget the timeouts for this call, since a hangup
								   has already been requested and we don't want to
								   repeatedly request hangups
								*/
								ast_rtp_set_rtptimeout(sip->rtp, 0);
								ast_rtp_set_rtpholdtimeout(sip->rtp, 0);
								if (sip->vrtp) {
									ast_rtp_set_rtptimeout(sip->vrtp, 0);
									ast_rtp_set_rtpholdtimeout(sip->vrtp, 0);
								}
							}
						}
					}
				}
			}
			/* If we have sessions that needs to be destroyed, do it now */
			if (ast_test_flag(&sip->flags[0], SIP_NEEDDESTROY) && !sip->packets &&
			    !sip->owner) {
				ast_mutex_unlock(&sip->lock);
				__sip_destroy(sip, 1);
				goto restartsearch;
			}
			ast_mutex_unlock(&sip->lock);
		}
		ast_mutex_unlock(&iflock);

		pthread_testcancel();
		/* Wait for sched or io */
		res = ast_sched_wait(sched);
		if ((res < 0) || (res > 1000))
			res = 1000;
		/* If we might need to send more mailboxes, don't wait long at all.*/
		if (fastrestart)
			res = 1;
		res = ast_io_wait(io, res);
		if (option_debug && res > 20)
			ast_log(LOG_DEBUG, "chan_sip: ast_io_wait ran %d all at once\n", res);
		ast_mutex_lock(&monlock);
		if (res >= 0)  {
			res = ast_sched_runq(sched);
			if (option_debug && res >= 20)
				ast_log(LOG_DEBUG, "chan_sip: ast_sched_runq ran %d all at once\n", res);
		}

		/* Send MWI notifications to peers - static and cached realtime peers */
		t = time(NULL);
		fastrestart = FALSE;
		curpeernum = 0;
		peer = NULL;
		/* Find next peer that needs mwi */
		ASTOBJ_CONTAINER_TRAVERSE(&peerl, !peer, do {
			if ((curpeernum > lastpeernum) && does_peer_need_mwi(iterator)) {
				fastrestart = TRUE;
				lastpeernum = curpeernum;
				peer = ASTOBJ_REF(iterator);
			};
			curpeernum++;
		} while (0)
		);
		/* Send MWI to the peer */
		if (peer) {
			ASTOBJ_WRLOCK(peer);
			sip_send_mwi_to_peer(peer);
			ASTOBJ_UNLOCK(peer);
			ASTOBJ_UNREF(peer,sip_destroy_peer);
		} else {
			/* Reset where we come from */
			lastpeernum = -1;
		}
		ast_mutex_unlock(&monlock);
	}
	/* Never reached */
	return NULL;
	
}

/*! \brief Start the channel monitor thread */
static int restart_monitor(void)
{
	/* If we're supposed to be stopped -- stay stopped */
	if (monitor_thread == AST_PTHREADT_STOP)
		return 0;
	ast_mutex_lock(&monlock);
	if (monitor_thread == pthread_self()) {
		ast_mutex_unlock(&monlock);
		ast_log(LOG_WARNING, "Cannot kill myself\n");
		return -1;
	}
	if (monitor_thread != AST_PTHREADT_NULL) {
		/* Wake up the thread */
		pthread_kill(monitor_thread, SIGURG);
	} else {
		/* Start a new monitor */
		if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
			ast_mutex_unlock(&monlock);
			ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
			return -1;
		}
	}
	ast_mutex_unlock(&monlock);
	return 0;
}

/*! \brief React to lack of answer to Qualify poke */
static int sip_poke_noanswer(void *data)
{
	struct sip_peer *peer = data;
	
	peer->pokeexpire = -1;
	if (peer->lastms > -1) {
		ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
		manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
	}
	if (peer->call)
		sip_destroy(peer->call);
	peer->call = NULL;
	peer->lastms = -1;
	ast_device_state_changed("SIP/%s", peer->name);
	/* Try again quickly */
	peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
	return 0;
}

/*! \brief Check availability of peer, also keep NAT open
\note	This is done with the interval in qualify= configuration option
	Default is 2 seconds */
static int sip_poke_peer(struct sip_peer *peer)
{
	struct sip_pvt *p;

	if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
		/* IF we have no IP, or this isn't to be monitored, return
		  imeediately after clearing things out */
		if (peer->pokeexpire > -1)
			ast_sched_del(sched, peer->pokeexpire);
		peer->lastms = 0;
		peer->pokeexpire = -1;
		peer->call = NULL;
		return 0;
	}
	if (peer->call) {
		if (sipdebug)
			ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
		sip_destroy(peer->call);
	}
	if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS)))
		return -1;
	
	p->sa = peer->addr;
	p->recv = peer->addr;
	ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);

	/* Send OPTIONs to peer's fullcontact */
	if (!ast_strlen_zero(peer->fullcontact))
		ast_string_field_set(p, fullcontact, peer->fullcontact);

	if (!ast_strlen_zero(peer->tohost))
		ast_string_field_set(p, tohost, peer->tohost);
	else
		ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));

	/* Recalculate our side, and recalculate Call ID */
	if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
		p->ourip = __ourip;
	build_via(p);
	build_callid_pvt(p);

	if (peer->pokeexpire > -1)
		ast_sched_del(sched, peer->pokeexpire);
	p->relatedpeer = peer;
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
#ifdef VOCAL_DATA_HACK
	ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
	transmit_invite(p, SIP_INVITE, 0, 2);
#else
	transmit_invite(p, SIP_OPTIONS, 0, 2);
#endif
	gettimeofday(&peer->ps, NULL);
	peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);

	return 0;
}

/*! \brief Part of PBX channel interface
\note
\par	Return values:---

	If we have qualify on and the device is not reachable, regardless of registration
	state we return AST_DEVICE_UNAVAILABLE

	For peers with call limit:
		- not registered			AST_DEVICE_UNAVAILABLE
		- registered, no call			AST_DEVICE_NOT_INUSE
		- registered, active calls		AST_DEVICE_INUSE
		- registered, call limit reached	AST_DEVICE_BUSY
		- registered, onhold			AST_DEVICE_ONHOLD
		- registered, ringing			AST_DEVICE_RINGING

	For peers without call limit:
		- not registered			AST_DEVICE_UNAVAILABLE
		- registered				AST_DEVICE_NOT_INUSE
		- fixed IP (!dynamic)			AST_DEVICE_NOT_INUSE

	If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
	out a state by walking the channel list.
*/
static int sip_devicestate(void *data)
{
	char *host;
	char *tmp;

	struct hostent *hp;
	struct ast_hostent ahp;
	struct sip_peer *p;

	int res = AST_DEVICE_INVALID;

	/* make sure data is not null. Maybe unnecessary, but better be safe */
	host = ast_strdupa(data ? data : "");
	if ((tmp = strchr(host, '@')))
		host = tmp + 1;

	if (option_debug > 2) 
		ast_log(LOG_DEBUG, "Checking device state for peer %s\n", host);

	if ((p = find_peer(host, NULL, 1))) {
		if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
			/* we have an address for the peer */
			/* if qualify is turned on, check the status */
			if (p->maxms && (p->lastms > p->maxms)) {
				res = AST_DEVICE_UNAVAILABLE;
			} else {
				/* qualify is not on, or the peer is responding properly */
				/* check call limit */
				if (p->call_limit && (p->inUse == p->call_limit))
					res = AST_DEVICE_BUSY;
				else if (p->call_limit && p->inUse)
					res = AST_DEVICE_INUSE;
				else
					res = AST_DEVICE_NOT_INUSE;
				if (p->onHold)
					res = AST_DEVICE_ONHOLD;
				else if (p->inRinging) {
					if (p->inRinging == p->inUse)
						res = AST_DEVICE_RINGING;
					else
						res = AST_DEVICE_RINGINUSE;
				}
			}
		} else {
			/* there is no address, it's unavailable */
			res = AST_DEVICE_UNAVAILABLE;
		}
		ASTOBJ_UNREF(p,sip_destroy_peer);
	} else {
		hp = ast_gethostbyname(host, &ahp);
		if (hp)
			res = AST_DEVICE_UNKNOWN;
	}

	return res;
}

/*! \brief PBX interface function -build SIP pvt structure 
	SIP calls initiated by the PBX arrive here */
static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
{
	int oldformat;
	struct sip_pvt *p;
	struct ast_channel *tmpc = NULL;
	char *ext, *host;
	char tmp[256];
	char *dest = data;

	oldformat = format;
	if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
		ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
		*cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;	/* Can't find codec to connect to host */
		return NULL;
	}
	if (option_debug)
		ast_log(LOG_DEBUG, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));

	if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE))) {
		ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", (char *)data);
		*cause = AST_CAUSE_SWITCH_CONGESTION;
		return NULL;
	}

	if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
		sip_destroy(p);
		ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
		*cause = AST_CAUSE_SWITCH_CONGESTION;
		return NULL;
	}

	ast_copy_string(tmp, dest, sizeof(tmp));
	host = strchr(tmp, '@');
	if (host) {
		*host++ = '\0';
		ext = tmp;
	} else {
		ext = strchr(tmp, '/');
		if (ext) 
			*ext++ = '\0';
		host = tmp;
	}

	if (create_addr(p, host)) {
		*cause = AST_CAUSE_UNREGISTERED;
		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Cant create SIP call - target device not registred\n");
		sip_destroy(p);
		return NULL;
	}
	if (ast_strlen_zero(p->peername) && ext)
		ast_string_field_set(p, peername, ext);
	/* Recalculate our side, and recalculate Call ID */
	if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
		p->ourip = __ourip;
	build_via(p);
	build_callid_pvt(p);
	
	/* We have an extension to call, don't use the full contact here */
	/* This to enable dialing registered peers with extension dialling,
	   like SIP/peername/extension 	
	   SIP/peername will still use the full contact */
	if (ext) {
		ast_string_field_set(p, username, ext);
		ast_string_field_free(p, fullcontact);
	}
#if 0
	printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
#endif
	p->prefcodec = oldformat;				/* Format for this call */
	ast_mutex_lock(&p->lock);
	tmpc = sip_new(p, AST_STATE_DOWN, host);	/* Place the call */
	ast_mutex_unlock(&p->lock);
	if (!tmpc)
		sip_destroy(p);
	ast_update_use_count();
	restart_monitor();
	return tmpc;
}

/*!
  \brief Handle flag-type options common to configuration of devices - users and peers
  \param flags array of two struct ast_flags
  \param mask array of two struct ast_flags
  \param v linked list of config variables to process
  \returns non-zero if any config options were handled, zero otherwise
*/
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
{
	int res = 0;
	static int dep_insecure_very = 0;
	static int dep_insecure_yes = 0;

	if (!strcasecmp(v->name, "trustrpid")) {
		ast_set_flag(&mask[0], SIP_TRUSTRPID);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
		res = 1;
	} else if (!strcasecmp(v->name, "sendrpid")) {
		ast_set_flag(&mask[0], SIP_SENDRPID);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
		res = 1;
	} else if (!strcasecmp(v->name, "g726nonstandard")) {
		ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
		res = 1;
	} else if (!strcasecmp(v->name, "useclientcode")) {
		ast_set_flag(&mask[0], SIP_USECLIENTCODE);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
		res = 1;
	} else if (!strcasecmp(v->name, "dtmfmode")) {
		ast_set_flag(&mask[0], SIP_DTMF);
		ast_clear_flag(&flags[0], SIP_DTMF);
		if (!strcasecmp(v->value, "inband"))
			ast_set_flag(&flags[0], SIP_DTMF_INBAND);
		else if (!strcasecmp(v->value, "rfc2833"))
			ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
		else if (!strcasecmp(v->value, "info"))
			ast_set_flag(&flags[0], SIP_DTMF_INFO);
		else if (!strcasecmp(v->value, "auto"))
			ast_set_flag(&flags[0], SIP_DTMF_AUTO);
		else {
			ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
			ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
		}
		res = 1;
	} else if (!strcasecmp(v->name, "nat")) {
		ast_set_flag(&mask[0], SIP_NAT);
		ast_clear_flag(&flags[0], SIP_NAT);
		if (!strcasecmp(v->value, "never"))
			ast_set_flag(&flags[0], SIP_NAT_NEVER);
		else if (!strcasecmp(v->value, "route"))
			ast_set_flag(&flags[0], SIP_NAT_ROUTE);
		else if (ast_true(v->value))
			ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
		else
			ast_set_flag(&flags[0], SIP_NAT_RFC3581);
		res = 1;
	} else if (!strcasecmp(v->name, "canreinvite")) {
		ast_set_flag(&mask[0], SIP_REINVITE);
		ast_clear_flag(&flags[0], SIP_REINVITE);
		if (ast_true(v->value)) {
			ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
		} else if (!ast_false(v->value)) {
			char buf[64];
			char *word, *next = buf;

			ast_copy_string(buf, v->value, sizeof(buf));
			while ((word = strsep(&next, ","))) {
				if (!strcasecmp(word, "update")) {
					ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
				} else if (!strcasecmp(word, "nonat")) {
					ast_set_flag(&flags[0], SIP_CAN_REINVITE);
					ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
				} else {
					ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
				}
			}
		}
		res = 1;
	} else if (!strcasecmp(v->name, "insecure")) {
		ast_set_flag(&mask[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
		ast_clear_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
		if (!strcasecmp(v->value, "very")) {
			ast_set_flag(&flags[0], SIP_INSECURE_PORT | SIP_INSECURE_INVITE);
			if (!dep_insecure_very) {
				ast_log(LOG_WARNING, "insecure=very at line %d is deprecated; use insecure=port,invite instead\n", v->lineno);
				dep_insecure_very = 1;
			}
		}
		else if (ast_true(v->value)) {
			ast_set_flag(&flags[0], SIP_INSECURE_PORT);
			if (!dep_insecure_yes) {
				ast_log(LOG_WARNING, "insecure=%s at line %d is deprecated; use insecure=port instead\n", v->value, v->lineno);
				dep_insecure_yes = 1;
			}
		}
		else if (!ast_false(v->value)) {
			char buf[64];
			char *word, *next;

			ast_copy_string(buf, v->value, sizeof(buf));
			next = buf;
			while ((word = strsep(&next, ","))) {
				if (!strcasecmp(word, "port"))
					ast_set_flag(&flags[0], SIP_INSECURE_PORT);
				else if (!strcasecmp(word, "invite"))
					ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
				else
					ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", v->value, v->lineno);
			}
		}
		res = 1;
	} else if (!strcasecmp(v->name, "progressinband")) {
		ast_set_flag(&mask[0], SIP_PROG_INBAND);
		ast_clear_flag(&flags[0], SIP_PROG_INBAND);
		if (ast_true(v->value))
			ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
		else if (strcasecmp(v->value, "never"))
			ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
		res = 1;
	} else if (!strcasecmp(v->name, "promiscredir")) {
		ast_set_flag(&mask[0], SIP_PROMISCREDIR);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
		res = 1;
	} else if (!strcasecmp(v->name, "videosupport")) {
		ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
		res = 1;
	} else if (!strcasecmp(v->name, "allowoverlap")) {
		ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
		res = 1;
	} else if (!strcasecmp(v->name, "allowsubscribe")) {
		ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
		res = 1;
	} else if (!strcasecmp(v->name, "t38pt_udptl")) {
		ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_UDPTL);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_UDPTL);
		res = 1;
#ifdef WHEN_WE_HAVE_T38_FOR_OTHER_TRANSPORTS
	} else if (!strcasecmp(v->name, "t38pt_rtp")) {
		ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_RTP);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_RTP);
		res = 1;
	} else if (!strcasecmp(v->name, "t38pt_tcp")) {
		ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT_TCP);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_T38SUPPORT_TCP);
		res = 1;
#endif
	} else if (!strcasecmp(v->name, "rfc2833compensate")) {
		ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
		res = 1;
	} else if (!strcasecmp(v->name, "buggymwi")) {
		ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
		res = 1;
	} 

	return res;
}

/*! \brief Add SIP domain to list of domains we are responsible for */
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
{
	struct domain *d;

	if (ast_strlen_zero(domain)) {
		ast_log(LOG_WARNING, "Zero length domain.\n");
		return 1;
	}

	if (!(d = ast_calloc(1, sizeof(*d))))
		return 0;

	ast_copy_string(d->domain, domain, sizeof(d->domain));

	if (!ast_strlen_zero(context))
		ast_copy_string(d->context, context, sizeof(d->context));

	d->mode = mode;

	AST_LIST_LOCK(&domain_list);
	AST_LIST_INSERT_TAIL(&domain_list, d, list);
	AST_LIST_UNLOCK(&domain_list);

 	if (sipdebug)	
		ast_log(LOG_DEBUG, "Added local SIP domain '%s'\n", domain);

	return 1;
}

/*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
static int check_sip_domain(const char *domain, char *context, size_t len)
{
	struct domain *d;
	int result = 0;

	AST_LIST_LOCK(&domain_list);
	AST_LIST_TRAVERSE(&domain_list, d, list) {
		if (strcasecmp(d->domain, domain))
			continue;

		if (len && !ast_strlen_zero(d->context))
			ast_copy_string(context, d->context, len);
		
		result = 1;
		break;
	}
	AST_LIST_UNLOCK(&domain_list);

	return result;
}

/*! \brief Clear our domain list (at reload) */
static void clear_sip_domains(void)
{
	struct domain *d;

	AST_LIST_LOCK(&domain_list);
	while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
		free(d);
	AST_LIST_UNLOCK(&domain_list);
}


/*! \brief Add realm authentication in list */
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno)
{
	char authcopy[256];
	char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
	char *stringp;
	struct sip_auth *a, *b, *auth;

	if (ast_strlen_zero(configuration))
		return authlist;

	if (option_debug)
		ast_log(LOG_DEBUG, "Auth config ::  %s\n", configuration);

	ast_copy_string(authcopy, configuration, sizeof(authcopy));
	stringp = authcopy;

	username = stringp;
	realm = strrchr(stringp, '@');
	if (realm)
		*realm++ = '\0';
	if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
		ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
		return authlist;
	}
	stringp = username;
	username = strsep(&stringp, ":");
	if (username) {
		secret = strsep(&stringp, ":");
		if (!secret) {
			stringp = username;
			md5secret = strsep(&stringp,"#");
		}
	}
	if (!(auth = ast_calloc(1, sizeof(*auth))))
		return authlist;

	ast_copy_string(auth->realm, realm, sizeof(auth->realm));
	ast_copy_string(auth->username, username, sizeof(auth->username));
	if (secret)
		ast_copy_string(auth->secret, secret, sizeof(auth->secret));
	if (md5secret)
		ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));

	/* find the end of the list */
	for (b = NULL, a = authlist; a ; b = a, a = a->next)
		;
	if (b)
		b->next = auth;	/* Add structure add end of list */
	else
		authlist = auth;

	if (option_verbose > 2)
		ast_verbose("Added authentication for realm %s\n", realm);

	return authlist;

}

/*! \brief Clear realm authentication list (at reload) */
static int clear_realm_authentication(struct sip_auth *authlist)
{
	struct sip_auth *a = authlist;
	struct sip_auth *b;

	while (a) {
		b = a;
		a = a->next;
		free(b);
	}

	return 1;
}

/*! \brief Find authentication for a specific realm */
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
{
	struct sip_auth *a;

	for (a = authlist; a; a = a->next) {
		if (!strcasecmp(a->realm, realm))
			break;
	}

	return a;
}

/*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime)
{
	struct sip_user *user;
	int format;
	struct ast_ha *oldha = NULL;
	char *varname = NULL, *varval = NULL;
	struct ast_variable *tmpvar = NULL;
	struct ast_flags userflags[2] = {{(0)}};
	struct ast_flags mask[2] = {{(0)}};


	if (!(user = ast_calloc(1, sizeof(*user))))
		return NULL;
		
	suserobjs++;
	ASTOBJ_INIT(user);
	ast_copy_string(user->name, name, sizeof(user->name));
	oldha = user->ha;
	user->ha = NULL;
	ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
	user->capability = global_capability;
	user->allowtransfer = global_allowtransfer;
	user->maxcallbitrate = default_maxcallbitrate;
	user->autoframing = global_autoframing;
	user->prefs = default_prefs;
	/* set default context */
	strcpy(user->context, default_context);
	strcpy(user->language, default_language);
	strcpy(user->mohinterpret, default_mohinterpret);
	strcpy(user->mohsuggest, default_mohsuggest);
	for (; v; v = v->next) {
		if (handle_common_options(&userflags[0], &mask[0], v))
			continue;

		if (!strcasecmp(v->name, "context")) {
			ast_copy_string(user->context, v->value, sizeof(user->context));
		} else if (!strcasecmp(v->name, "subscribecontext")) {
			ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
		} else if (!strcasecmp(v->name, "setvar")) {
			varname = ast_strdupa(v->value);
			if ((varval = strchr(varname,'='))) {
				*varval++ = '\0';
				if ((tmpvar = ast_variable_new(varname, varval))) {
					tmpvar->next = user->chanvars;
					user->chanvars = tmpvar;
				}
			}
		} else if (!strcasecmp(v->name, "permit") ||
				   !strcasecmp(v->name, "deny")) {
			user->ha = ast_append_ha(v->name, v->value, user->ha);
		} else if (!strcasecmp(v->name, "allowtransfer")) {
			user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
		} else if (!strcasecmp(v->name, "secret")) {
			ast_copy_string(user->secret, v->value, sizeof(user->secret)); 
		} else if (!strcasecmp(v->name, "md5secret")) {
			ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
		} else if (!strcasecmp(v->name, "callerid")) {
			ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
		} else if (!strcasecmp(v->name, "fullname")) {
			ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
		} else if (!strcasecmp(v->name, "cid_number")) {
			ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
		} else if (!strcasecmp(v->name, "callgroup")) {
			user->callgroup = ast_get_group(v->value);
		} else if (!strcasecmp(v->name, "pickupgroup")) {
			user->pickupgroup = ast_get_group(v->value);
		} else if (!strcasecmp(v->name, "language")) {
			ast_copy_string(user->language, v->value, sizeof(user->language));
		} else if (!strcasecmp(v->name, "mohinterpret") 
			|| !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
			ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
		} else if (!strcasecmp(v->name, "mohsuggest")) {
			ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
		} else if (!strcasecmp(v->name, "accountcode")) {
			ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
		} else if (!strcasecmp(v->name, "call-limit")) {
			user->call_limit = atoi(v->value);
			if (user->call_limit < 0)
				user->call_limit = 0;
		} else if (!strcasecmp(v->name, "amaflags")) {
			format = ast_cdr_amaflags2int(v->value);
			if (format < 0) {
				ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
			} else {
				user->amaflags = format;
			}
		} else if (!strcasecmp(v->name, "allow")) {
			ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
		} else if (!strcasecmp(v->name, "disallow")) {
			ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
		} else if (!strcasecmp(v->name, "autoframing")) {
			user->autoframing = ast_true(v->value);
		} else if (!strcasecmp(v->name, "callingpres")) {
			user->callingpres = ast_parse_caller_presentation(v->value);
			if (user->callingpres == -1)
				user->callingpres = atoi(v->value);
		} else if (!strcasecmp(v->name, "maxcallbitrate")) {
			user->maxcallbitrate = atoi(v->value);
			if (user->maxcallbitrate < 0)
				user->maxcallbitrate = default_maxcallbitrate;
		}
	}
	ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
	ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
	if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
		global_allowsubscribe = TRUE;	/* No global ban any more */
	ast_free_ha(oldha);
	return user;
}

/*! \brief Set peer defaults before configuring specific configurations */
static void set_peer_defaults(struct sip_peer *peer)
{
	if (peer->expire == 0) {
		/* Don't reset expire or port time during reload 
		   if we have an active registration 
		*/
		peer->expire = -1;
		peer->pokeexpire = -1;
		peer->addr.sin_port = htons(STANDARD_SIP_PORT);
	}
	ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
	strcpy(peer->context, default_context);
	strcpy(peer->subscribecontext, default_subscribecontext);
	strcpy(peer->language, default_language);
	strcpy(peer->mohinterpret, default_mohinterpret);
	strcpy(peer->mohsuggest, default_mohsuggest);
	peer->addr.sin_family = AF_INET;
	peer->defaddr.sin_family = AF_INET;
	peer->capability = global_capability;
	peer->maxcallbitrate = default_maxcallbitrate;
	peer->rtptimeout = global_rtptimeout;
	peer->rtpholdtimeout = global_rtpholdtimeout;
	peer->rtpkeepalive = global_rtpkeepalive;
	peer->allowtransfer = global_allowtransfer;
	peer->autoframing = global_autoframing;
	strcpy(peer->vmexten, default_vmexten);
	peer->secret[0] = '\0';
	peer->md5secret[0] = '\0';
	peer->cid_num[0] = '\0';
	peer->cid_name[0] = '\0';
	peer->fromdomain[0] = '\0';
	peer->fromuser[0] = '\0';
	peer->regexten[0] = '\0';
	peer->mailbox[0] = '\0';
	peer->callgroup = 0;
	peer->pickupgroup = 0;
	peer->maxms = default_qualify;
	peer->prefs = default_prefs;
}

/*! \brief Create temporary peer (used in autocreatepeer mode) */
static struct sip_peer *temp_peer(const char *name)
{
	struct sip_peer *peer;

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

	apeerobjs++;
	ASTOBJ_INIT(peer);
	set_peer_defaults(peer);

	ast_copy_string(peer->name, name, sizeof(peer->name));

	ast_set_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT);
	ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
	peer->prefs = default_prefs;
	reg_source_db(peer);

	return peer;
}

/*! \brief Build peer from configuration (file or realtime static/dynamic) */
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
{
	struct sip_peer *peer = NULL;
	struct ast_ha *oldha = NULL;
	int obproxyfound=0;
	int found=0;
	int firstpass=1;
	int format=0;		/* Ama flags */
	time_t regseconds = 0;
	char *varname = NULL, *varval = NULL;
	struct ast_variable *tmpvar = NULL;
	struct ast_flags peerflags[2] = {{(0)}};
	struct ast_flags mask[2] = {{(0)}};


	if (!realtime)
		/* Note we do NOT use find_peer here, to avoid realtime recursion */
		/* We also use a case-sensitive comparison (unlike find_peer) so
		   that case changes made to the peer name will be properly handled
		   during reload
		*/
		peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);

	if (peer) {
		/* Already in the list, remove it and it will be added back (or FREE'd)  */
		found++;
		if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
			firstpass = 0;
 	} else {
		if (!(peer = ast_calloc(1, sizeof(*peer))))
			return NULL;

		if (realtime)
			rpeerobjs++;
		else
			speerobjs++;
		ASTOBJ_INIT(peer);
	}
	/* Note that our peer HAS had its reference count incrased */
	if (firstpass) {
		peer->lastmsgssent = -1;
		oldha = peer->ha;
		peer->ha = NULL;
		set_peer_defaults(peer);	/* Set peer defaults */
	}
	if (!found && name)
			ast_copy_string(peer->name, name, sizeof(peer->name));

	/* If we have channel variables, remove them (reload) */
	if (peer->chanvars) {
		ast_variables_destroy(peer->chanvars);
		peer->chanvars = NULL;
		/* XXX should unregister ? */
	}
	for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
		if (handle_common_options(&peerflags[0], &mask[0], v))
			continue;
		if (realtime && !strcasecmp(v->name, "regseconds")) {
			ast_get_time_t(v->value, &regseconds, 0, NULL);
		} else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
			inet_aton(v->value, &(peer->addr.sin_addr));
		} else if (realtime && !strcasecmp(v->name, "name"))
			ast_copy_string(peer->name, v->value, sizeof(peer->name));
		else if (realtime && !strcasecmp(v->name, "fullcontact")) {
			ast_copy_string(peer->fullcontact, v->value, sizeof(peer->fullcontact));
			ast_set_flag(&peer->flags[1], SIP_PAGE2_RT_FROMCONTACT);
		} else if (!strcasecmp(v->name, "secret")) 
			ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
		else if (!strcasecmp(v->name, "md5secret")) 
			ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
		else if (!strcasecmp(v->name, "auth"))
			peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
		else if (!strcasecmp(v->name, "callerid")) {
			ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
		} else if (!strcasecmp(v->name, "fullname")) {
			ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
		} else if (!strcasecmp(v->name, "cid_number")) {
			ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
		} else if (!strcasecmp(v->name, "context")) {
			ast_copy_string(peer->context, v->value, sizeof(peer->context));
		} else if (!strcasecmp(v->name, "subscribecontext")) {
			ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
		} else if (!strcasecmp(v->name, "fromdomain")) {
			ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
		} else if (!strcasecmp(v->name, "usereqphone")) {
			ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
		} else if (!strcasecmp(v->name, "fromuser")) {
			ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
		} else if (!strcasecmp(v->name, "host") || !strcasecmp(v->name, "outboundproxy")) {
			if (!strcasecmp(v->value, "dynamic")) {
				if (!strcasecmp(v->name, "outboundproxy") || obproxyfound) {
					ast_log(LOG_WARNING, "You can't have a dynamic outbound proxy, you big silly head at line %d.\n", v->lineno);
				} else {
					/* They'll register with us */
					ast_set_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
					if (!found) {
						/* Initialize stuff iff we're not found, otherwise
						   we keep going with what we had */
						memset(&peer->addr.sin_addr, 0, 4);
						if (peer->addr.sin_port) {
							/* If we've already got a port, make it the default rather than absolute */
							peer->defaddr.sin_port = peer->addr.sin_port;
							peer->addr.sin_port = 0;
						}
					}
				}
			} else {
				/* Non-dynamic.  Make sure we become that way if we're not */
				if (peer->expire > -1)
					ast_sched_del(sched, peer->expire);
				peer->expire = -1;
				ast_clear_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC);
				if (!obproxyfound || !strcasecmp(v->name, "outboundproxy")) {
					if (ast_get_ip_or_srv(&peer->addr, v->value, srvlookup ? "_sip._udp" : NULL)) {
						ASTOBJ_UNREF(peer, sip_destroy_peer);
						return NULL;
					}
				}
				if (!strcasecmp(v->name, "outboundproxy"))
					obproxyfound=1;
				else {
					ast_copy_string(peer->tohost, v->value, sizeof(peer->tohost));
					if (!peer->addr.sin_port)
						peer->addr.sin_port = htons(STANDARD_SIP_PORT);
				}
			}
		} else if (!strcasecmp(v->name, "defaultip")) {
			if (ast_get_ip(&peer->defaddr, v->value)) {
				ASTOBJ_UNREF(peer, sip_destroy_peer);
				return NULL;
			}
		} else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
			peer->ha = ast_append_ha(v->name, v->value, peer->ha);
		} else if (!strcasecmp(v->name, "port")) {
			if (!realtime && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC))
				peer->defaddr.sin_port = htons(atoi(v->value));
			else
				peer->addr.sin_port = htons(atoi(v->value));
		} else if (!strcasecmp(v->name, "callingpres")) {
			peer->callingpres = ast_parse_caller_presentation(v->value);
			if (peer->callingpres == -1)
				peer->callingpres = atoi(v->value);
		} else if (!strcasecmp(v->name, "username")) {
			ast_copy_string(peer->username, v->value, sizeof(peer->username));
		} else if (!strcasecmp(v->name, "language")) {
			ast_copy_string(peer->language, v->value, sizeof(peer->language));
		} else if (!strcasecmp(v->name, "regexten")) {
			ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
		} else if (!strcasecmp(v->name, "call-limit") || !strcasecmp(v->name, "incominglimit")) {
			peer->call_limit = atoi(v->value);
			if (peer->call_limit < 0)
				peer->call_limit = 0;
		} else if (!strcasecmp(v->name, "amaflags")) {
			format = ast_cdr_amaflags2int(v->value);
			if (format < 0) {
				ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
			} else {
				peer->amaflags = format;
			}
		} else if (!strcasecmp(v->name, "accountcode")) {
			ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
		} else if (!strcasecmp(v->name, "mohinterpret")
			|| !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
			ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
		} else if (!strcasecmp(v->name, "mohsuggest")) {
			ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
		} else if (!strcasecmp(v->name, "mailbox")) {
			ast_copy_string(peer->mailbox, v->value, sizeof(peer->mailbox));
		} else if (!strcasecmp(v->name, "subscribemwi")) {
			ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
		} else if (!strcasecmp(v->name, "vmexten")) {
			ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
		} else if (!strcasecmp(v->name, "callgroup")) {
			peer->callgroup = ast_get_group(v->value);
		} else if (!strcasecmp(v->name, "allowtransfer")) {
			peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
		} else if (!strcasecmp(v->name, "pickupgroup")) {
			peer->pickupgroup = ast_get_group(v->value);
		} else if (!strcasecmp(v->name, "allow")) {
			ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
		} else if (!strcasecmp(v->name, "disallow")) {
			ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
		} else if (!strcasecmp(v->name, "autoframing")) {
			peer->autoframing = ast_true(v->value);
		} else if (!strcasecmp(v->name, "rtptimeout")) {
			if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
				peer->rtptimeout = global_rtptimeout;
			}
		} else if (!strcasecmp(v->name, "rtpholdtimeout")) {
			if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
				peer->rtpholdtimeout = global_rtpholdtimeout;
			}
		} else if (!strcasecmp(v->name, "rtpkeepalive")) {
			if ((sscanf(v->value, "%d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
				peer->rtpkeepalive = global_rtpkeepalive;
			}
		} else if (!strcasecmp(v->name, "setvar")) {
			/* Set peer channel variable */
			varname = ast_strdupa(v->value);
			if ((varval = strchr(varname, '='))) {
				*varval++ = '\0';
				if ((tmpvar = ast_variable_new(varname, varval))) {
					tmpvar->next = peer->chanvars;
					peer->chanvars = tmpvar;
				}
			}
		} else if (!strcasecmp(v->name, "qualify")) {
			if (!strcasecmp(v->value, "no")) {
				peer->maxms = 0;
			} else if (!strcasecmp(v->value, "yes")) {
				peer->maxms = DEFAULT_MAXMS;
			} else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
				ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
				peer->maxms = 0;
			}
		} else if (!strcasecmp(v->name, "maxcallbitrate")) {
			peer->maxcallbitrate = atoi(v->value);
			if (peer->maxcallbitrate < 0)
				peer->maxcallbitrate = default_maxcallbitrate;
		}
	}
	if (!ast_test_flag(&global_flags[1], SIP_PAGE2_IGNOREREGEXPIRE) && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && realtime) {
		time_t nowtime = time(NULL);

		if ((nowtime - regseconds) > 0) {
			destroy_association(peer);
			memset(&peer->addr, 0, sizeof(peer->addr));
			if (option_debug)
				ast_log(LOG_DEBUG, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
		}
	}
	ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
	ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
	if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
		global_allowsubscribe = TRUE;	/* No global ban any more */
	if (!found && ast_test_flag(&peer->flags[1], SIP_PAGE2_DYNAMIC) && !ast_test_flag(&peer->flags[0], SIP_REALTIME))
		reg_source_db(peer);
	ASTOBJ_UNMARK(peer);
	ast_free_ha(oldha);
	return peer;
}

/*! \brief Re-read SIP.conf config file
\note	This function reloads all config data, except for
	active peers (with registrations). They will only
	change configuration data at restart, not at reload.
	SIP debug and recordhistory state will not change
 */
static int reload_config(enum channelreloadreason reason)
{
	struct ast_config *cfg, *ucfg;
	struct ast_variable *v;
	struct sip_peer *peer;
	struct sip_user *user;
	struct ast_hostent ahp;
	char *cat, *stringp, *context, *oldregcontext;
	char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
	struct hostent *hp;
	int format;
	struct ast_flags dummy[2];
	int auto_sip_domains = FALSE;
	struct sockaddr_in old_bindaddr = bindaddr;
	int registry_count = 0, peer_count = 0, user_count = 0;
	unsigned int temp_tos = 0;
	struct ast_flags debugflag = {0};

	cfg = ast_config_load(config);

	/* We *must* have a config file otherwise stop immediately */
	if (!cfg) {
		ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
		return -1;
	}
	
	/* Initialize copy of current global_regcontext for later use in removing stale contexts */
	ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
	oldregcontext = oldcontexts;

	/* Clear all flags before setting default values */
	/* Preserve debugging settings for console */
	ast_copy_flags(&debugflag, &global_flags[1], SIP_PAGE2_DEBUG_CONSOLE);
	ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
	ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
	ast_copy_flags(&global_flags[1], &debugflag, SIP_PAGE2_DEBUG_CONSOLE);

	/* Reset IP addresses  */
	memset(&bindaddr, 0, sizeof(bindaddr));
	memset(&localaddr, 0, sizeof(localaddr));
	memset(&externip, 0, sizeof(externip));
	memset(&default_prefs, 0 , sizeof(default_prefs));
	outboundproxyip.sin_port = htons(STANDARD_SIP_PORT);
	outboundproxyip.sin_family = AF_INET;	/* Type of address: IPv4 */
	ourport = STANDARD_SIP_PORT;
	srvlookup = DEFAULT_SRVLOOKUP;
	global_tos_sip = DEFAULT_TOS_SIP;
	global_tos_audio = DEFAULT_TOS_AUDIO;
	global_tos_video = DEFAULT_TOS_VIDEO;
	externhost[0] = '\0';			/* External host name (for behind NAT DynDNS support) */
	externexpire = 0;			/* Expiration for DNS re-issuing */
	externrefresh = 10;
	memset(&outboundproxyip, 0, sizeof(outboundproxyip));

	/* Reset channel settings to default before re-configuring */
	allow_external_domains = DEFAULT_ALLOW_EXT_DOM;				/* Allow external invites */
	global_regcontext[0] = '\0';
	expiry = DEFAULT_EXPIRY;
	global_notifyringing = DEFAULT_NOTIFYRINGING;
	global_limitonpeers = FALSE;
	global_notifyhold = FALSE;
	global_alwaysauthreject = 0;
	global_allowsubscribe = FALSE;
	ast_copy_string(global_useragent, DEFAULT_USERAGENT, sizeof(global_useragent));
	ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
	if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME))
		ast_copy_string(global_realm, DEFAULT_REALM, sizeof(global_realm));
	else
		ast_copy_string(global_realm, ast_config_AST_SYSTEM_NAME, sizeof(global_realm));
	ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
	compactheaders = DEFAULT_COMPACTHEADERS;
	global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
	global_regattempts_max = 0;
	pedanticsipchecking = DEFAULT_PEDANTIC;
	global_mwitime = DEFAULT_MWITIME;
	autocreatepeer = DEFAULT_AUTOCREATEPEER;
	global_autoframing = 0;
	global_allowguest = DEFAULT_ALLOWGUEST;
	global_rtptimeout = 0;
	global_rtpholdtimeout = 0;
	global_rtpkeepalive = 0;
	global_allowtransfer = TRANSFER_OPENFORALL;	/* Merrily accept all transfers by default */
	global_rtautoclear = 120;
	ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);	/* Default for peers, users: TRUE */
	ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);		/* Default for peers, users: TRUE */
	ast_set_flag(&global_flags[1], SIP_PAGE2_RTUPDATE);

	/* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
	ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
	default_subscribecontext[0] = '\0';
	default_language[0] = '\0';
	default_fromdomain[0] = '\0';
	default_qualify = DEFAULT_QUALIFY;
	default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
	ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
	ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
	ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
	ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);			/*!< Default DTMF setting: RFC2833 */
	ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);			/*!< NAT support if requested by device with rport */
	ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);			/*!< Allow re-invites */

	/* Debugging settings, always default to off */
	dumphistory = FALSE;
	recordhistory = FALSE;
	ast_clear_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);

	/* Misc settings for the channel */
	global_relaxdtmf = FALSE;
	global_callevents = FALSE;
	global_t1min = DEFAULT_T1MIN;		

	/* Copy the default jb config over global_jbconf */
	memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));

	ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);

	/* Read the [general] config section of sip.conf (or from realtime config) */
	for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
		if (handle_common_options(&global_flags[0], &dummy[0], v))
			continue;
		/* handle jb conf */
		if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
			continue;

		/* Create the interface list */
		if (!strcasecmp(v->name, "context")) {
			ast_copy_string(default_context, v->value, sizeof(default_context));
  		} else if (!strcasecmp(v->name, "allowguest")) {
			global_allowguest = ast_true(v->value) ? 1 : 0;
		} else if (!strcasecmp(v->name, "realm")) {
			ast_copy_string(global_realm, v->value, sizeof(global_realm));
		} else if (!strcasecmp(v->name, "useragent")) {
			ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
			if (option_debug)
				ast_log(LOG_DEBUG, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
		} else if (!strcasecmp(v->name, "allowtransfer")) {
			global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
		} else if (!strcasecmp(v->name, "rtcachefriends")) {
			ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);	
		} else if (!strcasecmp(v->name, "rtsavesysname")) {
			ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTSAVE_SYSNAME);	
		} else if (!strcasecmp(v->name, "rtupdate")) {
			ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTUPDATE);	
		} else if (!strcasecmp(v->name, "ignoreregexpire")) {
			ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_IGNOREREGEXPIRE);	
		} else if (!strcasecmp(v->name, "t1min")) {
			global_t1min = atoi(v->value);
		} else if (!strcasecmp(v->name, "rtautoclear")) {
			int i = atoi(v->value);
			if (i > 0)
				global_rtautoclear = i;
			else
				i = 0;
			ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
		} else if (!strcasecmp(v->name, "usereqphone")) {
			ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);	
		} else if (!strcasecmp(v->name, "relaxdtmf")) {
			global_relaxdtmf = ast_true(v->value);
		} else if (!strcasecmp(v->name, "checkmwi")) {
			if ((sscanf(v->value, "%d", &global_mwitime) != 1) || (global_mwitime < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid MWI time setting at line %d.  Using default (10).\n", v->value, v->lineno);
				global_mwitime = DEFAULT_MWITIME;
			}
		} else if (!strcasecmp(v->name, "vmexten")) {
			ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
		} else if (!strcasecmp(v->name, "rtptimeout")) {
			if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
				global_rtptimeout = 0;
			}
		} else if (!strcasecmp(v->name, "rtpholdtimeout")) {
			if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
				global_rtpholdtimeout = 0;
			}
		} else if (!strcasecmp(v->name, "rtpkeepalive")) {
			if ((sscanf(v->value, "%d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
				global_rtpkeepalive = 0;
			}
		} else if (!strcasecmp(v->name, "compactheaders")) {
			compactheaders = ast_true(v->value);
		} else if (!strcasecmp(v->name, "notifymimetype")) {
			ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
		} else if (!strcasecmp(v->name, "limitonpeers")) {
			global_limitonpeers = ast_true(v->value);
		} else if (!strcasecmp(v->name, "notifyringing")) {
			global_notifyringing = ast_true(v->value);
		} else if (!strcasecmp(v->name, "notifyhold")) {
			global_notifyhold = ast_true(v->value);
		} else if (!strcasecmp(v->name, "alwaysauthreject")) {
			global_alwaysauthreject = ast_true(v->value);
		} else if (!strcasecmp(v->name, "mohinterpret") 
			|| !strcasecmp(v->name, "musicclass") || !strcasecmp(v->name, "musiconhold")) {
			ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
		} else if (!strcasecmp(v->name, "mohsuggest")) {
			ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
		} else if (!strcasecmp(v->name, "language")) {
			ast_copy_string(default_language, v->value, sizeof(default_language));
		} else if (!strcasecmp(v->name, "regcontext")) {
			ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
			stringp = newcontexts;
			/* Let's remove any contexts that are no longer defined in regcontext */
			cleanup_stale_contexts(stringp, oldregcontext);
			/* Create contexts if they don't exist already */
			while ((context = strsep(&stringp, "&"))) {
				if (!ast_context_find(context))
					ast_context_create(NULL, context,"SIP");
			}
			ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
		} else if (!strcasecmp(v->name, "callerid")) {
			ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
		} else if (!strcasecmp(v->name, "fromdomain")) {
			ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
		} else if (!strcasecmp(v->name, "outboundproxy")) {
			if (ast_get_ip_or_srv(&outboundproxyip, v->value, srvlookup ? "_sip._udp" : NULL) < 0)
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", v->value);
		} else if (!strcasecmp(v->name, "outboundproxyport")) {
			/* Port needs to be after IP */
			sscanf(v->value, "%d", &format);
			outboundproxyip.sin_port = htons(format);
		} else if (!strcasecmp(v->name, "autocreatepeer")) {
			autocreatepeer = ast_true(v->value);
		} else if (!strcasecmp(v->name, "srvlookup")) {
			srvlookup = ast_true(v->value);
		} else if (!strcasecmp(v->name, "pedantic")) {
			pedanticsipchecking = ast_true(v->value);
		} else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
			max_expiry = atoi(v->value);
			if (max_expiry < 1)
				max_expiry = DEFAULT_MAX_EXPIRY;
		} else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
			min_expiry = atoi(v->value);
			if (min_expiry < 1)
				min_expiry = DEFAULT_MIN_EXPIRY;
		} else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
			default_expiry = atoi(v->value);
			if (default_expiry < 1)
				default_expiry = DEFAULT_DEFAULT_EXPIRY;
		} else if (!strcasecmp(v->name, "sipdebug")) {	/* XXX maybe ast_set2_flags ? */
			if (ast_true(v->value))
				ast_set_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG);
		} else if (!strcasecmp(v->name, "dumphistory")) {
			dumphistory = ast_true(v->value);
		} else if (!strcasecmp(v->name, "recordhistory")) {
			recordhistory = ast_true(v->value);
		} else if (!strcasecmp(v->name, "registertimeout")) {
			global_reg_timeout = atoi(v->value);
			if (global_reg_timeout < 1)
				global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
		} else if (!strcasecmp(v->name, "registerattempts")) {
			global_regattempts_max = atoi(v->value);
		} else if (!strcasecmp(v->name, "bindaddr")) {
			if (!(hp = ast_gethostbyname(v->value, &ahp))) {
				ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
			} else {
				memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
			}
		} else if (!strcasecmp(v->name, "localnet")) {
			struct ast_ha *na;
			if (!(na = ast_append_ha("d", v->value, localaddr)))
				ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
			else
				localaddr = na;
		} else if (!strcasecmp(v->name, "localmask")) {
			ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
		} else if (!strcasecmp(v->name, "externip")) {
			if (!(hp = ast_gethostbyname(v->value, &ahp))) 
				ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
			else
				memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
			externexpire = 0;
		} else if (!strcasecmp(v->name, "externhost")) {
			ast_copy_string(externhost, v->value, sizeof(externhost));
			if (!(hp = ast_gethostbyname(externhost, &ahp))) 
				ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
			else
				memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
			externexpire = time(NULL);
		} else if (!strcasecmp(v->name, "externrefresh")) {
			if (sscanf(v->value, "%d", &externrefresh) != 1) {
				ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
				externrefresh = 10;
			}
		} else if (!strcasecmp(v->name, "allow")) {
			ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 1);
		} else if (!strcasecmp(v->name, "disallow")) {
			ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, 0);
		} else if (!strcasecmp(v->name, "autoframing")) {
			global_autoframing = ast_true(v->value);
		} else if (!strcasecmp(v->name, "allowexternaldomains")) {
			allow_external_domains = ast_true(v->value);
		} else if (!strcasecmp(v->name, "autodomain")) {
			auto_sip_domains = ast_true(v->value);
		} else if (!strcasecmp(v->name, "domain")) {
			char *domain = ast_strdupa(v->value);
			char *context = strchr(domain, ',');

			if (context)
				*context++ = '\0';

			if (option_debug && ast_strlen_zero(context))
				ast_log(LOG_DEBUG, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
			if (ast_strlen_zero(domain))
				ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
			else
				add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
		} else if (!strcasecmp(v->name, "register")) {
			if (sip_register(v->value, v->lineno) == 0)
				registry_count++;
		} else if (!strcasecmp(v->name, "tos")) {
			if (!ast_str2tos(v->value, &temp_tos)) {
				global_tos_sip = temp_tos;
				global_tos_audio = temp_tos;
				global_tos_video = temp_tos;
				ast_log(LOG_WARNING, "tos value at line %d is deprecated.  See doc/ip-tos.txt for more information.\n", v->lineno);
			} else
				ast_log(LOG_WARNING, "Invalid tos value at line %d, See doc/ip-tos.txt for more information.\n", v->lineno);
		} else if (!strcasecmp(v->name, "tos_sip")) {
			if (ast_str2tos(v->value, &global_tos_sip))
				ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, recommended value is 'cs3'. See doc/ip-tos.txt.\n", v->lineno);
		} else if (!strcasecmp(v->name, "tos_audio")) {
			if (ast_str2tos(v->value, &global_tos_audio))
				ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, recommended value is 'ef'. See doc/ip-tos.txt.\n", v->lineno);
		} else if (!strcasecmp(v->name, "tos_video")) {
			if (ast_str2tos(v->value, &global_tos_video))
				ast_log(LOG_WARNING, "Invalid tos_video value at line %d, recommended value is 'af41'. See doc/ip-tos.txt.\n", v->lineno);
		} else if (!strcasecmp(v->name, "bindport")) {
			if (sscanf(v->value, "%d", &ourport) == 1) {
				bindaddr.sin_port = htons(ourport);
			} else {
				ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
			}
		} else if (!strcasecmp(v->name, "qualify")) {
			if (!strcasecmp(v->value, "no")) {
				default_qualify = 0;
			} else if (!strcasecmp(v->value, "yes")) {
				default_qualify = DEFAULT_MAXMS;
			} else if (sscanf(v->value, "%d", &default_qualify) != 1) {
				ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
				default_qualify = 0;
			}
		} else if (!strcasecmp(v->name, "callevents")) {
			global_callevents = ast_true(v->value);
		} else if (!strcasecmp(v->name, "maxcallbitrate")) {
			default_maxcallbitrate = atoi(v->value);
			if (default_maxcallbitrate < 0)
				default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
		}
	}

	if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
		ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
		allow_external_domains = 1;
	}
	
	/* Build list of authentication to various SIP realms, i.e. service providers */
 	for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
 		/* Format for authentication is auth = username:password@realm */
 		if (!strcasecmp(v->name, "auth"))
 			authl = add_realm_authentication(authl, v->value, v->lineno);
 	}
	
	ucfg = ast_config_load("users.conf");
	if (ucfg) {
		struct ast_variable *gen;
		int genhassip, genregistersip;
		const char *hassip, *registersip;
		
		genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
		genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
		gen = ast_variable_browse(ucfg, "general");
		cat = ast_category_browse(ucfg, NULL);
		while (cat) {
			if (strcasecmp(cat, "general")) {
				hassip = ast_variable_retrieve(ucfg, cat, "hassip");
				registersip = ast_variable_retrieve(ucfg, cat, "registersip");
				if (ast_true(hassip) || (!hassip && genhassip)) {
					peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
					if (peer) {
						ASTOBJ_CONTAINER_LINK(&peerl,peer);
						ASTOBJ_UNREF(peer, sip_destroy_peer);
						peer_count++;
					}
				}
				if (ast_true(registersip) || (!registersip && genregistersip)) {
					char tmp[256];
					const char *host = ast_variable_retrieve(ucfg, cat, "host");
					const char *username = ast_variable_retrieve(ucfg, cat, "username");
					const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
					const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
					if (!host)
						host = ast_variable_retrieve(ucfg, "general", "host");
					if (!username)
						username = ast_variable_retrieve(ucfg, "general", "username");
					if (!secret)
						secret = ast_variable_retrieve(ucfg, "general", "secret");
					if (!contact)
						contact = "s";
					if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
						if (!ast_strlen_zero(secret))
							snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
						else
							snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
						if (sip_register(tmp, 0) == 0)
							registry_count++;
					}
				}
			}
			cat = ast_category_browse(ucfg, cat);
		}
		ast_config_destroy(ucfg);
	}
	

	/* Load peers, users and friends */
	cat = NULL;
	while ( (cat = ast_category_browse(cfg, cat)) ) {
		const char *utype;
		if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
			continue;
		utype = ast_variable_retrieve(cfg, cat, "type");
		if (!utype) {
			ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
			continue;
		} else {
			int is_user = 0, is_peer = 0;
			if (!strcasecmp(utype, "user"))
				is_user = 1;
			else if (!strcasecmp(utype, "friend"))
				is_user = is_peer = 1;
			else if (!strcasecmp(utype, "peer"))
				is_peer = 1;
			else {
				ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
				continue;
			}
			if (is_user) {
				user = build_user(cat, ast_variable_browse(cfg, cat), 0);
				if (user) {
					ASTOBJ_CONTAINER_LINK(&userl,user);
					ASTOBJ_UNREF(user, sip_destroy_user);
					user_count++;
				}
			}
			if (is_peer) {
				peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
				if (peer) {
					ASTOBJ_CONTAINER_LINK(&peerl,peer);
					ASTOBJ_UNREF(peer, sip_destroy_peer);
					peer_count++;
				}
			}
		}
	}
	if (ast_find_ourip(&__ourip, bindaddr)) {
		ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
		return 0;
	}
	if (!ntohs(bindaddr.sin_port))
		bindaddr.sin_port = ntohs(STANDARD_SIP_PORT);
	bindaddr.sin_family = AF_INET;
	ast_mutex_lock(&netlock);
	if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
		close(sipsock);
		sipsock = -1;
	}
	if (sipsock < 0) {
		sipsock = socket(AF_INET, SOCK_DGRAM, 0);
		if (sipsock < 0) {
			ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
		} else {
			/* Allow SIP clients on the same host to access us: */
			const int reuseFlag = 1;

			setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
				   (const char*)&reuseFlag,
				   sizeof reuseFlag);

			ast_enable_packet_fragmentation(sipsock);

			if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
				ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
				ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
				strerror(errno));
				close(sipsock);
				sipsock = -1;
			} else {
				if (option_verbose > 1) { 
					ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n", 
					ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
					ast_verbose(VERBOSE_PREFIX_2 "Using SIP TOS: %s\n", ast_tos2str(global_tos_sip));
				}
				if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &global_tos_sip, sizeof(global_tos_sip))) 
					ast_log(LOG_WARNING, "Unable to set SIP TOS to %s\n", ast_tos2str(global_tos_sip));
			}
		}
	}
	ast_mutex_unlock(&netlock);

	/* Add default domains - host name, IP address and IP:port */
	/* Only do this if user added any sip domain with "localdomains" */
	/* In order to *not* break backwards compatibility */
	/* 	Some phones address us at IP only, some with additional port number */
	if (auto_sip_domains) {
		char temp[MAXHOSTNAMELEN];

		/* First our default IP address */
		if (bindaddr.sin_addr.s_addr)
			add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
		else
			ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");

		/* Our extern IP address, if configured */
		if (externip.sin_addr.s_addr)
			add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);

		/* Extern host name (NAT traversal support) */
		if (!ast_strlen_zero(externhost))
			add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
		
		/* Our host name */
		if (!gethostname(temp, sizeof(temp)))
			add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
	}

	/* Release configuration from memory */
	ast_config_destroy(cfg);

	/* Load the list of manual NOTIFY types to support */
	if (notify_types)
		ast_config_destroy(notify_types);
	notify_types = ast_config_load(notify_config);

	/* Done, tell the manager */
	manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "Channel: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\nUser_Count: %d\r\n\r\n", channelreloadreason2txt(reason), registry_count, peer_count, user_count);

	return 0;
}

static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
{
	struct sip_pvt *p;
	struct ast_udptl *udptl = NULL;
	
	p = chan->tech_pvt;
	if (!p)
		return NULL;
	
	ast_mutex_lock(&p->lock);
	if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
		udptl = p->udptl;
	ast_mutex_unlock(&p->lock);
	return udptl;
}

static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
{
	struct sip_pvt *p;
	
	p = chan->tech_pvt;
	if (!p)
		return -1;
	ast_mutex_lock(&p->lock);
	if (udptl)
		ast_udptl_get_peer(udptl, &p->udptlredirip);
	else
		memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
	if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
		if (!p->pendinginvite) {
			if (option_debug > 2) {
				ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
			}
			transmit_reinvite_with_t38_sdp(p);
		} else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
			if (option_debug > 2) {
				ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
			}
			ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
		}
	}
	/* Reset lastrtprx timer */
	p->lastrtprx = p->lastrtptx = time(NULL);
	ast_mutex_unlock(&p->lock);
	return 0;
}

/*! \brief Handle T38 reinvite 
	\todo Make sure we don't destroy the call if we can't handle the re-invite. 
	Nothing should be changed until we have processed the SDP and know that we
	can handle it.
*/
static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite)
{
	struct sip_pvt *p;
	int flag = 0;
	
	p = chan->tech_pvt;
	if (!p || !pvt->udptl)
		return -1;
	
	/* Setup everything on the other side like offered/responded from first side */
	ast_mutex_lock(&p->lock);

	/*! \todo check if this is not set earlier when setting up the PVT. If not
		maybe it should move there. */
	p->t38.jointcapability = p->t38.peercapability = pvt->t38.jointcapability;

	ast_udptl_set_far_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
	ast_udptl_set_local_max_datagram(p->udptl, ast_udptl_get_local_max_datagram(pvt->udptl));
	ast_udptl_set_error_correction_scheme(p->udptl, ast_udptl_get_error_correction_scheme(pvt->udptl));
	
	if (reinvite) {		/* If we are handling sending re-invite to the other side of the bridge */
		/*! \note The SIP_CAN_REINVITE flag is for RTP media redirects,
			not really T38 re-invites which are different. In this
			case it's used properly, to see if we can reinvite over
			NAT 
		*/
		if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
			ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
			flag =1;
		} else {
			memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
		}
		if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
			if (!p->pendinginvite) {
				if (option_debug > 2) {
					if (flag)
						ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
					else
						ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
				}
				transmit_reinvite_with_t38_sdp(p);
			} else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
				if (option_debug > 2) {
					if (flag)
						ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
					else
						ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
				}
				ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
			}
		}
		/* Reset lastrtprx timer */
		p->lastrtprx = p->lastrtptx = time(NULL);
		ast_mutex_unlock(&p->lock);
		return 0;
	} else {	/* If we are handling sending 200 OK to the other side of the bridge */
		if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE) && ast_test_flag(&pvt->flags[0], SIP_CAN_REINVITE)) {
			ast_udptl_get_peer(pvt->udptl, &p->udptlredirip);
			flag = 1;
		} else {
			memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
		}
		if (option_debug > 2) {
			if (flag)
				ast_log(LOG_DEBUG, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(p->udptlredirip.sin_addr), ntohs(p->udptlredirip.sin_port));
			else
				ast_log(LOG_DEBUG, "Responding 200 OK on SIP '%s' - It's UDPTL soon redirected to us (IP %s)\n", p->callid, ast_inet_ntoa(p->ourip));
		}
		pvt->t38.state = T38_ENABLED;
		p->t38.state = T38_ENABLED;
		if (option_debug > 1) {
			ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", pvt->t38.state, pvt->owner ? pvt->owner->name : "<none>");
			ast_log(LOG_DEBUG, "T38 changed state to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
		}
		transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
		p->lastrtprx = p->lastrtptx = time(NULL);
		ast_mutex_unlock(&p->lock);
		return 0;
	}
}


/*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
{
	struct sip_pvt *p = NULL;
	enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;

	if (!(p = chan->tech_pvt))
		return AST_RTP_GET_FAILED;

	ast_mutex_lock(&p->lock);
	if (!(p->rtp)) {
		ast_mutex_unlock(&p->lock);
		return AST_RTP_GET_FAILED;
	}

	*rtp = p->rtp;

	if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
		res = AST_RTP_TRY_NATIVE;
	else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
		res = AST_RTP_GET_FAILED;

	ast_mutex_unlock(&p->lock);

	return res;
}

/*! \brief Returns null if we can't reinvite video (part of RTP interface) */
static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
{
	struct sip_pvt *p = NULL;
	enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
	
	if (!(p = chan->tech_pvt))
		return AST_RTP_GET_FAILED;

	ast_mutex_lock(&p->lock);
	if (!(p->vrtp)) {
		ast_mutex_unlock(&p->lock);
		return AST_RTP_GET_FAILED;
	}

	*rtp = p->vrtp;

	if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
		res = AST_RTP_TRY_NATIVE;

	ast_mutex_unlock(&p->lock);

	return res;
}

/*! \brief Set the RTP peer for this call */
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
{
	struct sip_pvt *p;
	int changed = 0;

	p = chan->tech_pvt;
	if (!p) 
		return -1;
	ast_mutex_lock(&p->lock);
	if (ast_test_flag(&p->flags[0], SIP_ALREADYGONE)) {
		/* If we're destroyed, don't bother */
		ast_mutex_unlock(&p->lock);
		return 0;
	}

	/* if this peer cannot handle reinvites of the media stream to devices
	   that are known to be behind a NAT, then stop the process now
	*/
	if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
		ast_mutex_unlock(&p->lock);
		return 0;
	}

	if (rtp) {
		changed |= ast_rtp_get_peer(rtp, &p->redirip);
	} else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
		memset(&p->redirip, 0, sizeof(p->redirip));
		changed = 1;
	}
	if (vrtp) {
		changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
	} else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
		memset(&p->vredirip, 0, sizeof(p->vredirip));
		changed = 1;
	}
	if (codecs && (p->redircodecs != codecs)) {
		p->redircodecs = codecs;
		changed = 1;
	}
	if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
		if (chan->_state != AST_STATE_UP) {	/* We are in early state */
			if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
				append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
			if (option_debug)
				ast_log(LOG_DEBUG, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip));
		} else if (!p->pendinginvite) {		/* We are up, and have no outstanding invite */
			if (option_debug > 2) {
				ast_log(LOG_DEBUG, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip));
			}
			transmit_reinvite_with_sdp(p);
		} else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
			if (option_debug > 2) {
				ast_log(LOG_DEBUG, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip));
			}
			/* We have a pending Invite. Send re-invite when we're done with the invite */
			ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);	
		}
	}
	/* Reset lastrtprx timer */
	p->lastrtprx = p->lastrtptx = time(NULL);
	ast_mutex_unlock(&p->lock);
	return 0;
}

static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
static char *app_dtmfmode = "SIPDtmfMode";

static char *app_sipaddheader = "SIPAddHeader";
static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";

static char *descrip_sipaddheader = ""
"  SIPAddHeader(Header: Content)\n"
"Adds a header to a SIP call placed with DIAL.\n"
"Remember to user the X-header if you are adding non-standard SIP\n"
"headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
"Adding the wrong headers may jeopardize the SIP dialog.\n"
"Always returns 0\n";


/*! \brief Set the DTMFmode for an outbound SIP call (application) */
static int sip_dtmfmode(struct ast_channel *chan, void *data)
{
	struct sip_pvt *p;
	char *mode;
	if (data)
		mode = (char *)data;
	else {
		ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
		return 0;
	}
	ast_channel_lock(chan);
	if (chan->tech != &sip_tech) {
		ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
		ast_channel_unlock(chan);
		return 0;
	}
	p = chan->tech_pvt;
	if (!p) {
		ast_channel_unlock(chan);
		return 0;
	}
	ast_mutex_lock(&p->lock);
	if (!strcasecmp(mode,"info")) {
		ast_clear_flag(&p->flags[0], SIP_DTMF);
		ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
	} else if (!strcasecmp(mode,"rfc2833")) {
		ast_clear_flag(&p->flags[0], SIP_DTMF);
		ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
	} else if (!strcasecmp(mode,"inband")) { 
		ast_clear_flag(&p->flags[0], SIP_DTMF);
		ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
	} else
		ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
	if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
		if (!p->vad) {
			p->vad = ast_dsp_new();
			ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
		}
	} else {
		if (p->vad) {
			ast_dsp_free(p->vad);
			p->vad = NULL;
		}
	}
	ast_mutex_unlock(&p->lock);
	ast_channel_unlock(chan);
	return 0;
}

/*! \brief Add a SIP header to an outbound INVITE */
static int sip_addheader(struct ast_channel *chan, void *data)
{
	int no = 0;
	int ok = FALSE;
	char varbuf[30];
	char *inbuf = (char *) data;
	
	if (ast_strlen_zero(inbuf)) {
		ast_log(LOG_WARNING, "This application requires the argument: Header\n");
		return 0;
	}
	ast_channel_lock(chan);

	/* Check for headers */
	while (!ok && no <= 50) {
		no++;
		snprintf(varbuf, sizeof(varbuf), "_SIPADDHEADER%.2d", no);

		/* Compare without the leading underscore */
		if( (pbx_builtin_getvar_helper(chan, (const char *) varbuf + 1) == (const char *) NULL) )
			ok = TRUE;
	}
	if (ok) {
		pbx_builtin_setvar_helper (chan, varbuf, inbuf);
		if (sipdebug)
			ast_log(LOG_DEBUG,"SIP Header added \"%s\" as %s\n", inbuf, varbuf);
	} else {
		ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
	}
	ast_channel_unlock(chan);
	return 0;
}

/*! \brief Transfer call before connect with a 302 redirect
\note	Called by the transfer() dialplan application through the sip_transfer()
	pbx interface function if the call is in ringing state 
\todo	Fix this function so that we wait for reply to the REFER and
	react to errors, denials or other issues the other end might have.
 */
static int sip_sipredirect(struct sip_pvt *p, const char *dest)
{
	char *cdest;
	char *extension, *host, *port;
	char tmp[80];
	
	cdest = ast_strdupa(dest);
	
	extension = strsep(&cdest, "@");
	host = strsep(&cdest, ":");
	port = strsep(&cdest, ":");
	if (ast_strlen_zero(extension)) {
		ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
		return 0;
	}

	/* we'll issue the redirect message here */
	if (!host) {
		char *localtmp;
		ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
		if (ast_strlen_zero(tmp)) {
			ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
			return 0;
		}
		if ((localtmp = strstr(tmp, "sip:")) && (localtmp = strchr(localtmp, '@'))) {
			char lhost[80], lport[80];
			memset(lhost, 0, sizeof(lhost));
			memset(lport, 0, sizeof(lport));
			localtmp++;
			/* This is okey because lhost and lport are as big as tmp */
			sscanf(localtmp, "%[^<>:; ]:%[^<>:; ]", lhost, lport);
			if (ast_strlen_zero(lhost)) {
				ast_log(LOG_ERROR, "Can't find the host address\n");
				return 0;
			}
			host = ast_strdupa(lhost);
			if (!ast_strlen_zero(lport)) {
				port = ast_strdupa(lport);
			}
		}
	}

	ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
	transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);

	sip_scheddestroy(p, 32000);	/* Make sure we stop send this reply. */

	/* hangup here */
	return -1;
}

/*! \brief Return SIP UA's codec (part of the RTP interface) */
static int sip_get_codec(struct ast_channel *chan)
{
	struct sip_pvt *p = chan->tech_pvt;
	return p->peercapability;	
}

/*! \brief Send a poke to all known peers 
	Space them out 100 ms apart
	XXX We might have a cool algorithm for this or use random - any suggestions?
*/
static void sip_poke_all_peers(void)
{
	int ms = 0;
	
	if (!speerobjs)	/* No peers, just give up */
		return;

	ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
		ASTOBJ_WRLOCK(iterator);
		if (iterator->pokeexpire > -1)
			ast_sched_del(sched, iterator->pokeexpire);
		ms += 100;
		iterator->pokeexpire = ast_sched_add(sched, ms, sip_poke_peer_s, iterator);
		ASTOBJ_UNLOCK(iterator);
	} while (0)
	);
}

/*! \brief Send all known registrations */
static void sip_send_all_registers(void)
{
	int ms;
	int regspacing;
	if (!regobjs)
		return;
	regspacing = default_expiry * 1000/regobjs;
	if (regspacing > 100)
		regspacing = 100;
	ms = regspacing;
	ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
		ASTOBJ_WRLOCK(iterator);
		if (iterator->expire > -1)
			ast_sched_del(sched, iterator->expire);
		ms += regspacing;
		iterator->expire = ast_sched_add(sched, ms, sip_reregister, iterator);
		ASTOBJ_UNLOCK(iterator);
	} while (0)
	);
}

/*! \brief Reload module */
static int sip_do_reload(enum channelreloadreason reason)
{
	if (option_debug > 3)
		ast_log(LOG_DEBUG, "--------------- SIP reload started\n");

	clear_realm_authentication(authl);
	clear_sip_domains();
	authl = NULL;

	/* First, destroy all outstanding registry calls */
	/* This is needed, since otherwise active registry entries will not be destroyed */
	ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
		ASTOBJ_RDLOCK(iterator);
		if (iterator->call) {
			if (option_debug > 2)
				ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
			/* This will also remove references to the registry */
			sip_destroy(iterator->call);
		}
		ASTOBJ_UNLOCK(iterator);
	
	} while(0));

	/* Then, actually destroy users and registry */
	ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
	if (option_debug > 3)
		ast_log(LOG_DEBUG, "--------------- Done destroying user list\n");
	ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
	if (option_debug > 3)
		ast_log(LOG_DEBUG, "--------------- Done destroying registry list\n");
	ASTOBJ_CONTAINER_MARKALL(&peerl);
	reload_config(reason);

	/* Prune peers who still are supposed to be deleted */
	ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
	if (option_debug > 3)
		ast_log(LOG_DEBUG, "--------------- Done destroying pruned peers\n");

	/* Send qualify (OPTIONS) to all peers */
	sip_poke_all_peers();

	/* Register with all services */
	sip_send_all_registers();

	if (option_debug > 3)
		ast_log(LOG_DEBUG, "--------------- SIP reload done\n");

	return 0;
}

/*! \brief Force reload of module from cli */
static int sip_reload(int fd, int argc, char *argv[])
{
	ast_mutex_lock(&sip_reload_lock);
	if (sip_reloading) 
		ast_verbose("Previous SIP reload not yet done\n");
	else {
		sip_reloading = TRUE;
		if (fd)
			sip_reloadreason = CHANNEL_CLI_RELOAD;
		else
			sip_reloadreason = CHANNEL_MODULE_RELOAD;
	}
	ast_mutex_unlock(&sip_reload_lock);
	restart_monitor();

	return 0;
}

/*! \brief Part of Asterisk module interface */
static int reload(void)
{
	return sip_reload(0, 0, NULL);
}

static struct ast_cli_entry cli_sip_debug_deprecated =
	{ { "sip", "debug", NULL },
	sip_do_debug_deprecated, "Enable SIP debugging",
	debug_usage };

static struct ast_cli_entry cli_sip_no_debug_deprecated =
	{ { "sip", "no", "debug", NULL },
	sip_no_debug_deprecated, "Disable SIP debugging",
	debug_usage };

static struct ast_cli_entry cli_sip[] = {
	{ { "sip", "show", "channels", NULL },
	sip_show_channels, "List active SIP channels",
	show_channels_usage },

	{ { "sip", "show", "domains", NULL },
	sip_show_domains, "List our local SIP domains.",
	show_domains_usage },

	{ { "sip", "show", "inuse", NULL },
	sip_show_inuse, "List all inuse/limits",
	show_inuse_usage },

	{ { "sip", "show", "objects", NULL },
	sip_show_objects, "List all SIP object allocations",
	show_objects_usage },

	{ { "sip", "show", "peers", NULL },
	sip_show_peers, "List defined SIP peers",
	show_peers_usage },

	{ { "sip", "show", "registry", NULL },
	sip_show_registry, "List SIP registration status",
	show_reg_usage },

	{ { "sip", "show", "settings", NULL },
	sip_show_settings, "Show SIP global settings",
	show_settings_usage },

	{ { "sip", "show", "subscriptions", NULL },
	sip_show_subscriptions, "List active SIP subscriptions",
	show_subscriptions_usage },

	{ { "sip", "show", "users", NULL },
	sip_show_users, "List defined SIP users",
	show_users_usage },

	{ { "sip", "notify", NULL },
	sip_notify, "Send a notify packet to a SIP peer",
	notify_usage, complete_sipnotify },

	{ { "sip", "show", "channel", NULL },
	sip_show_channel, "Show detailed SIP channel info",
	show_channel_usage, complete_sipch  },

	{ { "sip", "show", "history", NULL },
	sip_show_history, "Show SIP dialog history",
	show_history_usage, complete_sipch  },

	{ { "sip", "show", "peer", NULL },
	sip_show_peer, "Show details on specific SIP peer",
	show_peer_usage, complete_sip_show_peer },

	{ { "sip", "show", "user", NULL },
	sip_show_user, "Show details on specific SIP user",
	show_user_usage, complete_sip_show_user },

	{ { "sip", "prune", "realtime", NULL },
	sip_prune_realtime, "Prune cached Realtime object(s)",
	prune_realtime_usage },

	{ { "sip", "prune", "realtime", "peer", NULL },
	sip_prune_realtime, "Prune cached Realtime peer(s)",
	prune_realtime_usage, complete_sip_prune_realtime_peer },

	{ { "sip", "prune", "realtime", "user", NULL },
	sip_prune_realtime, "Prune cached Realtime user(s)",
	prune_realtime_usage, complete_sip_prune_realtime_user },

	{ { "sip", "set", "debug", NULL },
	sip_do_debug, "Enable SIP debugging",
	debug_usage, NULL, &cli_sip_debug_deprecated },

	{ { "sip", "set", "debug", "ip", NULL },
	sip_do_debug, "Enable SIP debugging on IP",
	debug_usage },

	{ { "sip", "set", "debug", "peer", NULL },
	sip_do_debug, "Enable SIP debugging on Peername",
	debug_usage, complete_sip_debug_peer },

	{ { "sip", "set", "debug", "off", NULL },
	sip_no_debug, "Disable SIP debugging",
	no_debug_usage, NULL, &cli_sip_no_debug_deprecated },

	{ { "sip", "history", NULL },
	sip_do_history, "Enable SIP history",
	history_usage },

	{ { "sip", "history", "off", NULL },
	sip_no_history, "Disable SIP history",
	no_history_usage },

	{ { "sip", "reload", NULL },
	sip_reload, "Reload SIP configuration",
	sip_reload_usage },
};

/*! \brief PBX load module - initialization */
static int load_module(void)
{
	ASTOBJ_CONTAINER_INIT(&userl);	/* User object list */
	ASTOBJ_CONTAINER_INIT(&peerl);	/* Peer object list */
	ASTOBJ_CONTAINER_INIT(&regl);	/* Registry object list */

	if (!(sched = sched_context_create())) {
		ast_log(LOG_ERROR, "Unable to create scheduler context\n");
		return AST_MODULE_LOAD_FAILURE;
	}

	if (!(io = io_context_create())) {
		ast_log(LOG_ERROR, "Unable to create I/O context\n");
		sched_context_destroy(sched);
		return AST_MODULE_LOAD_FAILURE;
	}

	sip_reloadreason = CHANNEL_MODULE_LOAD;

	if(reload_config(sip_reloadreason))	/* Load the configuration from sip.conf */
		return AST_MODULE_LOAD_DECLINE;

	/* Make sure we can register our sip channel type */
	if (ast_channel_register(&sip_tech)) {
		ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
		io_context_destroy(io);
		sched_context_destroy(sched);
		return AST_MODULE_LOAD_FAILURE;
	}

	/* Register all CLI functions for SIP */
	ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));

	/* Tell the RTP subdriver that we're here */
	ast_rtp_proto_register(&sip_rtp);

	/* Tell the UDPTL subdriver that we're here */
	ast_udptl_proto_register(&sip_udptl);

	/* Register dialplan applications */
	ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
	ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);

	/* Register dialplan functions */
	ast_custom_function_register(&sip_header_function);
	ast_custom_function_register(&sippeer_function);
	ast_custom_function_register(&sipchaninfo_function);
	ast_custom_function_register(&checksipdomain_function);

	/* Register manager commands */
	ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM, manager_sip_show_peers,
			"List SIP peers (text format)", mandescr_show_peers);
	ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM, manager_sip_show_peer,
			"Show SIP peer (text format)", mandescr_show_peer);

	sip_poke_all_peers();	
	sip_send_all_registers();
	
	/* And start the monitor for the first time */
	restart_monitor();

	return AST_MODULE_LOAD_SUCCESS;
}

/*! \brief PBX unload module API */
static int unload_module(void)
{
	struct sip_pvt *p, *pl;
	
	/* First, take us out of the channel type list */
	ast_channel_unregister(&sip_tech);

	/* Unregister dial plan functions */
	ast_custom_function_unregister(&sipchaninfo_function);
	ast_custom_function_unregister(&sippeer_function);
	ast_custom_function_unregister(&sip_header_function);
	ast_custom_function_unregister(&checksipdomain_function);

	/* Unregister dial plan applications */
	ast_unregister_application(app_dtmfmode);
	ast_unregister_application(app_sipaddheader);

	/* Unregister CLI commands */
	ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));

	/* Disconnect from the RTP subsystem */
	ast_rtp_proto_unregister(&sip_rtp);

	/* Disconnect from UDPTL */
	ast_udptl_proto_unregister(&sip_udptl);

	/* Unregister AMI actions */
	ast_manager_unregister("SIPpeers");
	ast_manager_unregister("SIPshowpeer");

	ast_mutex_lock(&iflock);
	/* Hangup all interfaces if they have an owner */
	for (p = iflist; p ; p = p->next) {
		if (p->owner)
			ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
	}
	ast_mutex_unlock(&iflock);

	ast_mutex_lock(&monlock);
	if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
		pthread_cancel(monitor_thread);
		pthread_kill(monitor_thread, SIGURG);
		pthread_join(monitor_thread, NULL);
	}
	monitor_thread = AST_PTHREADT_STOP;
	ast_mutex_unlock(&monlock);

	ast_mutex_lock(&iflock);
	/* Destroy all the interfaces and free their memory */
	p = iflist;
	while (p) {
		pl = p;
		p = p->next;
		__sip_destroy(pl, TRUE);
	}
	iflist = NULL;
	ast_mutex_unlock(&iflock);

	/* Free memory for local network address mask */
	ast_free_ha(localaddr);

	ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
	ASTOBJ_CONTAINER_DESTROY(&userl);
	ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
	ASTOBJ_CONTAINER_DESTROY(&peerl);
	ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
	ASTOBJ_CONTAINER_DESTROY(&regl);

	clear_realm_authentication(authl);
	clear_sip_domains();
	close(sipsock);
	sched_context_destroy(sched);
		
	return 0;
}

AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
		.load = load_module,
		.unload = unload_module,
		.reload = reload,
	       );
