Review Board 1.7.16


Use the correct IP address in the c and o sdp lines when using an externally mapped IP address

Review Request #566 - Created March 16, 2010 and submitted

ebroad
/trunk
17044
Reviewers
asterisk-dev
Asterisk
The issue stems from a call to ast_rtp_instance_get_local_address() in chan_sip.c in get_our_media_address(). ast_rtp_instance_get_local_address() will always return the internal IP address of the Asterisk machine, which could pose a problem when using NAT.

A simple solution would be to override {v,t}sin->sin_addr in get_our_media_address() with p->ourip.sin_addr.s_addr if it is different(which is what the attached diff does), though I don't know what that might break.

Edit 1: This patch short-circuits some logic later on in get_our_media_address(). ast_rtp_instance_get_local_address() does exactly as the function name suggests, it gets the local address of the machine the Asterisk is running on, which is bad for NAT setups. Should we be calling this in get_our_media_address() or instead just use p->ourip? or should we try to stick with letting the RTP engine decide, and modifying ast_rtp_instance_get_local_address() to return our externally mapped IP when appropriate, which would break from what the function is supposed to do? Comments anyone? 
Applied to trunk, compiled, fax and voice calls made to and from Asterisk successfully.

Changes between revision 1 and 3

1 2 3 4
1 2 3 4

  1. /trunk/channels/chan_sip.c: Loading...
/trunk/channels/chan_sip.c
Diff Revision 1 Diff Revision 3
[20] 249 lines
[+20] [+] ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
250
#include "asterisk/file.h"
250
#include "asterisk/file.h"
251
#include "asterisk/astobj2.h"
251
#include "asterisk/astobj2.h"
252
#include "asterisk/dnsmgr.h"
252
#include "asterisk/dnsmgr.h"
253
#include "asterisk/devicestate.h"
253
#include "asterisk/devicestate.h"
254
#include "asterisk/monitor.h"
254
#include "asterisk/monitor.h"
255
#include "asterisk/netsock.h"
255
#include "asterisk/netsock2.h"
256
#include "asterisk/localtime.h"
256
#include "asterisk/localtime.h"
257
#include "asterisk/abstract_jb.h"
257
#include "asterisk/abstract_jb.h"
258
#include "asterisk/threadstorage.h"
258
#include "asterisk/threadstorage.h"
259
#include "asterisk/translate.h"
259
#include "asterisk/translate.h"
260
#include "asterisk/ast_version.h"
260
#include "asterisk/ast_version.h"
261
#include "asterisk/event.h"
261
#include "asterisk/event.h"
262
#include "asterisk/stun.h"
262
#include "asterisk/stun.h"
263
#include "asterisk/cel.h"
263
#include "asterisk/cel.h"

    
   
264
#include "asterisk/data.h"

    
   
265
#include "asterisk/aoc.h"
264
#include "sip/include/sip.h"
266
#include "sip/include/sip.h"
265
#include "sip/include/globals.h"
267
#include "sip/include/globals.h"
266
#include "sip/include/config_parser.h"
268
#include "sip/include/config_parser.h"
267
#include "sip/include/reqresp_parser.h"
269
#include "sip/include/reqresp_parser.h"
268
#include "sip/include/sip_utils.h"
270
#include "sip/include/sip_utils.h"

    
   
271
#include "sip/include/srtp.h"

    
   
272
#include "sip/include/sdp_crypto.h"

    
   
273
#include "asterisk/ccss.h"

    
   
274
#include "asterisk/xml.h"
269
#include "sip/include/dialog.h"
275
#include "sip/include/dialog.h"
270
#include "sip/include/dialplan_functions.h"
276
#include "sip/include/dialplan_functions.h"
271

    
   
277

   

    
   
278

   
272
/*** DOCUMENTATION
279
/*** DOCUMENTATION
273
	<application name="SIPDtmfMode" language="en_US">
280
	<application name="SIPDtmfMode" language="en_US">
274
		<synopsis>
281
		<synopsis>
275
			Change the dtmfmode for a SIP call.
282
			Change the dtmfmode for a SIP call.
276
		</synopsis>
283
		</synopsis>
[+20] [20] 131 lines
[+20] ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
408
						<para>Account code for this peer.</para>
415
						<para>Account code for this peer.</para>
409
					</enum>
416
					</enum>
410
					<enum name="useragent">
417
					<enum name="useragent">
411
						<para>Current user agent id for peer.</para>
418
						<para>Current user agent id for peer.</para>
412
					</enum>
419
					</enum>

    
   
420
					<enum name="maxforwards">

    
   
421
						<para>The value used for SIP loop prevention in outbound requests</para>

    
   
422
					</enum>
413
					<enum name="chanvar[name]">
423
					<enum name="chanvar[name]">
414
						<para>A channel variable configured with setvar for this peer.</para>
424
						<para>A channel variable configured with setvar for this peer.</para>
415
					</enum>
425
					</enum>
416
					<enum name="codec[x]">
426
					<enum name="codec[x]">
417
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
427
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
[+20] [20] 205 lines
[+20] [+] static const struct cfsip_methods {
623
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
633
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
624
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
634
	{ SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
625
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
635
	{ SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
626
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
636
	{ SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
627
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
637
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
628
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
638
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
629
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
639
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
630
};
640
};
631

    
   
641

   
632
/*! \brief List of well-known SIP options. If we get this in a require,

   
633
   we should check the list and answer accordingly. */

   
634
static const struct cfsip_options {

   
635
	int id;             /*!< Bitmap ID */

   
636
	int supported;      /*!< Supported by Asterisk ? */

   
637
	char * const text;  /*!< Text id, as in standard */

   
638
} sip_options[] = {	/* XXX used in 3 places */

   
639
	/* RFC3262: PRACK 100% reliability */

   
640
	{ SIP_OPT_100REL,	NOT_SUPPORTED,	"100rel" },

   
641
	/* RFC3959: SIP Early session support */

   
642
	{ SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,	"early-session" },

   
643
	/* SIMPLE events:  RFC4662 */

   
644
	{ SIP_OPT_EVENTLIST,	NOT_SUPPORTED,	"eventlist" },

   
645
	/* RFC 4916- Connected line ID updates */

   
646
	{ SIP_OPT_FROMCHANGE,	NOT_SUPPORTED,	"from-change" },

   
647
	/* GRUU: Globally Routable User Agent URI's */

   
648
	{ SIP_OPT_GRUU,		NOT_SUPPORTED,	"gruu" },

   
649
	/* RFC4244 History info */

   
650
	{ SIP_OPT_HISTINFO,	NOT_SUPPORTED,	"histinfo" },

   
651
	/* RFC3911: SIP Join header support */

   
652
	{ SIP_OPT_JOIN,		NOT_SUPPORTED,	"join" },

   
653
	/* Disable the REFER subscription, RFC 4488 */

   
654
	{ SIP_OPT_NOREFERSUB,	NOT_SUPPORTED,	"norefersub" },

   
655
	/* SIP outbound - the final NAT battle - draft-sip-outbound */

   
656
	{ SIP_OPT_OUTBOUND,	NOT_SUPPORTED,	"outbound" },

   
657
	/* RFC3327: Path support */

   
658
	{ SIP_OPT_PATH,		NOT_SUPPORTED,	"path" },

   
659
	/* RFC3840: Callee preferences */

   
660
	{ SIP_OPT_PREF,		NOT_SUPPORTED,	"pref" },

   
661
	/* RFC3312: Precondition support */

   
662
	{ SIP_OPT_PRECONDITION,	NOT_SUPPORTED,	"precondition" },

   
663
	/* RFC3323: Privacy with proxies*/

   
664
	{ SIP_OPT_PRIVACY,	NOT_SUPPORTED,	"privacy" },

   
665
	/* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */

   
666
	{ SIP_OPT_RECLISTINV,	NOT_SUPPORTED,	"recipient-list-invite" },

   
667
	/* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */

   
668
	{ SIP_OPT_RECLISTSUB,	NOT_SUPPORTED,	"recipient-list-subscribe" },

   
669
	/* RFC3891: Replaces: header for transfer */

   
670
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replaces" },

   
671
	/* One version of Polycom firmware has the wrong label */

   
672
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replace" },

   
673
	/* RFC4412 Resource priorities */

   
674
	{ SIP_OPT_RESPRIORITY,	NOT_SUPPORTED,	"resource-priority" },

   
675
	/* RFC3329: Security agreement mechanism */

   
676
	{ SIP_OPT_SEC_AGREE,	NOT_SUPPORTED,	"sec_agree" },

   
677
	/* RFC4092: Usage of the SDP ANAT Semantics in the SIP */

   
678
	{ SIP_OPT_SDP_ANAT,	NOT_SUPPORTED,	"sdp-anat" },

   
679
	/* RFC4028: SIP Session-Timers */

   
680
	{ SIP_OPT_TIMER,	SUPPORTED,	"timer" },

   
681
	/* RFC4538: Target-dialog */

   
682
	{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,	"tdialog" },

   
683
};

   
684

    
   

   
685
/*! \brief Diversion header reasons
642
/*! \brief Diversion header reasons
686
 *
643
 *
687
 * The core defines a bunch of constants used to define
644
 * The core defines a bunch of constants used to define
688
 * redirecting reasons. This provides a translation table
645
 * redirecting reasons. This provides a translation table
689
 * between those and the strings which may be present in
646
 * between those and the strings which may be present in
[+20] [20] 25 lines
[+20] [+] static const struct sip_reasons {
715
/*@{*/
672
/*@{*/
716
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
673
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
717
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
674
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
718
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
675
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
719
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
676
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */

    
   
677
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
720
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
678
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
721
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
679
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
722
static int default_qualify;                        /*!< Default Qualify= setting */
680
static int default_qualify;                        /*!< Default Qualify= setting */
723
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
681
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
724
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
682
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
[+20] [20] 57 lines
[+20] [+] static enum st_refresher global_st_refresher; /*!< Session-Timer refresher */
782
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
740
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
783

    
   
741

   
784
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
742
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
785
/*@}*/
743
/*@}*/
786

    
   
744

   

    
   
745
/*!

    
   
746
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,

    
   
747
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion

    
   
748
 * event package. This variable is set at module load time and may be checked at runtime to determine

    
   
749
 * if XML parsing support was found.

    
   
750
 */

    
   
751
static int can_parse_xml;

    
   
752

   
787
/*! \name Object counters @{
753
/*! \name Object counters @{
788
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
754
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
789
 *  should be used to modify these values. */
755
 *  should be used to modify these values. */
790
static int speerobjs = 0;     /*!< Static peers */
756
static int speerobjs = 0;     /*!< Static peers */
791
static int rpeerobjs = 0;     /*!< Realtime peers */
757
static int rpeerobjs = 0;     /*!< Realtime peers */
792
static int apeerobjs = 0;     /*!< Autocreated peer objects */
758
static int apeerobjs = 0;     /*!< Autocreated peer objects */
793
static int regobjs = 0;       /*!< Registry objects */
759
static int regobjs = 0;       /*!< Registry objects */
794
/* }@ */
760
/* }@ */
795

    
   
761

   
796
static struct ast_flags global_flags[2] = {{0}};  /*!< global SIP_ flags */
762
static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
797
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
763
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
798

    
   
764

   
799
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
765
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
800

    
   
766

   
801
AST_MUTEX_DEFINE_STATIC(netlock);
767
AST_MUTEX_DEFINE_STATIC(netlock);
[+20] [20] 47 lines
[+20] [+] static const int HASH_PEER_SIZE = 17;
849
#else
815
#else
850
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
816
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
851
static const int HASH_DIALOG_SIZE = 563;
817
static const int HASH_DIALOG_SIZE = 563;
852
#endif
818
#endif
853

    
   
819

   

    
   
820
static const struct {

    
   
821
	enum ast_cc_service_type service;

    
   
822
	const char *service_string;

    
   
823
} sip_cc_service_map [] = {

    
   
824
	[AST_CC_NONE] = { AST_CC_NONE, "" },

    
   
825
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },

    
   
826
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },

    
   
827
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },

    
   
828
};

    
   
829

   

    
   
830
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)

    
   
831
{

    
   
832
	enum ast_cc_service_type service;

    
   
833
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {

    
   
834
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {

    
   
835
			return service;

    
   
836
		}

    
   
837
	}

    
   
838
	return AST_CC_NONE;

    
   
839
}

    
   
840

   

    
   
841
static const struct {

    
   
842
	enum sip_cc_notify_state state;

    
   
843
	const char *state_string;

    
   
844
} sip_cc_notify_state_map [] = {

    
   
845
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},

    
   
846
	[CC_READY] = {CC_READY, "cc-state: ready"},

    
   
847
};

    
   
848

   

    
   
849
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);

    
   
850

   

    
   
851
static int sip_epa_register(const struct epa_static_data *static_data)

    
   
852
{

    
   
853
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));

    
   
854

   

    
   
855
	if (!backend) {

    
   
856
		return -1;

    
   
857
	}

    
   
858

   

    
   
859
	backend->static_data = static_data;

    
   
860

   

    
   
861
	AST_LIST_LOCK(&epa_static_data_list);

    
   
862
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);

    
   
863
	AST_LIST_UNLOCK(&epa_static_data_list);

    
   
864
	return 0;

    
   
865
}

    
   
866

   

    
   
867
static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);

    
   
868

   

    
   
869
static void cc_epa_destructor(void *data)

    
   
870
{

    
   
871
	struct sip_epa_entry *epa_entry = data;

    
   
872
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;

    
   
873
	ast_free(cc_entry);

    
   
874
}

    
   
875

   

    
   
876
static const struct epa_static_data cc_epa_static_data  = {

    
   
877
	.event = CALL_COMPLETION,

    
   
878
	.name = "call-completion",

    
   
879
	.handle_error = cc_handle_publish_error,

    
   
880
	.destructor = cc_epa_destructor,

    
   
881
};

    
   
882

   

    
   
883
static const struct epa_static_data *find_static_data(const char * const event_package)

    
   
884
{

    
   
885
	const struct epa_backend *backend = NULL;

    
   
886

   

    
   
887
	AST_LIST_LOCK(&epa_static_data_list);

    
   
888
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {

    
   
889
		if (!strcmp(backend->static_data->name, event_package)) {
Moved from 2165

    
   
890
			break;
Moved from 2166

    
   
891
		}
Moved from 2167

    
   
892
	}

    
   
893
	AST_LIST_UNLOCK(&epa_static_data_list);

    
   
894
	return backend ? backend->static_data : NULL;

    
   
895
}

    
   
896

   

    
   
897
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)

    
   
898
{

    
   
899
	struct sip_epa_entry *epa_entry;

    
   
900
	const struct epa_static_data *static_data;

    
   
901

   

    
   
902
	if (!(static_data = find_static_data(event_package))) {
Moved from 2075

    
   
903
		return NULL;
Moved from 2076

    
   
904
	}

    
   
905

   

    
   
906
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
Moved from 2075

    
   
907
		return NULL;
Moved from 2076

    
   
908
	}

    
   
909

   

    
   
910
	epa_entry->static_data = static_data;

    
   
911
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));

    
   
912
	return epa_entry;

    
   
913
}

    
   
914

   

    
   
915
/*!

    
   
916
 * Used to create new entity IDs by ESCs.

    
   
917
 */

    
   
918
static int esc_etag_counter;

    
   
919
static const int DEFAULT_PUBLISH_EXPIRES = 3600;

    
   
920

   

    
   
921
#ifdef HAVE_LIBXML2

    
   
922
static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);

    
   
923

   

    
   
924
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {

    
   
925
	.initial_handler = cc_esc_publish_handler,

    
   
926
	.modify_handler = cc_esc_publish_handler,

    
   
927
};

    
   
928
#endif

    
   
929

   

    
   
930
/*!

    
   
931
 * \brief The Event State Compositors

    
   
932
 *

    
   
933
 * An Event State Compositor is an entity which

    
   
934
 * accepts PUBLISH requests and acts appropriately

    
   
935
 * based on these requests.

    
   
936
 *

    
   
937
 * The actual event_state_compositor structure is simply

    
   
938
 * an ao2_container of sip_esc_entrys. When an incoming

    
   
939
 * PUBLISH is received, we can match the appropriate sip_esc_entry

    
   
940
 * using the entity ID of the incoming PUBLISH.

    
   
941
 */

    
   
942
static struct event_state_compositor {

    
   
943
	enum subscriptiontype event;

    
   
944
	const char * name;

    
   
945
	const struct sip_esc_publish_callbacks *callbacks;

    
   
946
	struct ao2_container *compositor;

    
   
947
} event_state_compositors [] = {

    
   
948
#ifdef HAVE_LIBXML2

    
   
949
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},

    
   
950
#endif

    
   
951
};

    
   
952

   

    
   
953
static const int ESC_MAX_BUCKETS = 37;

    
   
954

   

    
   
955
static void esc_entry_destructor(void *obj)

    
   
956
{

    
   
957
	struct sip_esc_entry *esc_entry = obj;

    
   
958
	if (esc_entry->sched_id > -1) {

    
   
959
		AST_SCHED_DEL(sched, esc_entry->sched_id);

    
   
960
	}

    
   
961
}

    
   
962

   

    
   
963
static int esc_hash_fn(const void *obj, const int flags)

    
   
964
{

    
   
965
	const struct sip_esc_entry *entry = obj;

    
   
966
	return ast_str_hash(entry->entity_tag);

    
   
967
}

    
   
968

   

    
   
969
static int esc_cmp_fn(void *obj, void *arg, int flags)

    
   
970
{

    
   
971
	struct sip_esc_entry *entry1 = obj;

    
   
972
	struct sip_esc_entry *entry2 = arg;

    
   
973

   

    
   
974
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;

    
   
975
}

    
   
976

   

    
   
977
static struct event_state_compositor *get_esc(const char * const event_package) {

    
   
978
	int i;

    
   
979
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {

    
   
980
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {

    
   
981
			return &event_state_compositors[i];

    
   
982
		}

    
   
983
	}

    
   
984
	return NULL;

    
   
985
}

    
   
986

   

    
   
987
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {

    
   
988
	struct sip_esc_entry *entry;

    
   
989
	struct sip_esc_entry finder;

    
   
990

   

    
   
991
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));

    
   
992

   

    
   
993
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);

    
   
994

   

    
   
995
	return entry;

    
   
996
}

    
   
997

   

    
   
998
static int publish_expire(const void *data)

    
   
999
{

    
   
1000
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;

    
   
1001
	struct event_state_compositor *esc = get_esc(esc_entry->event);

    
   
1002

   

    
   
1003
	ast_assert(esc != NULL);

    
   
1004

   

    
   
1005
	ao2_unlink(esc->compositor, esc_entry);

    
   
1006
	ao2_ref(esc_entry, -1);

    
   
1007
	return 0;

    
   
1008
}

    
   
1009

   

    
   
1010
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)

    
   
1011
{

    
   
1012
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);

    
   
1013
	struct event_state_compositor *esc = get_esc(esc_entry->event);

    
   
1014

   

    
   
1015
	ast_assert(esc != NULL);

    
   
1016
	if (is_linked) {

    
   
1017
		ao2_unlink(esc->compositor, esc_entry);

    
   
1018
	}

    
   
1019
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);

    
   
1020
	ao2_link(esc->compositor, esc_entry);

    
   
1021
}

    
   
1022

   

    
   
1023
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)

    
   
1024
{

    
   
1025
	struct sip_esc_entry *esc_entry;

    
   
1026
	int expires_ms;

    
   
1027

   

    
   
1028
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
Moved from 2075

    
   
1029
		return NULL;
Moved from 2076

    
   
1030
	}

    
   
1031

   

    
   
1032
	esc_entry->event = esc->name;

    
   
1033

   

    
   
1034
	expires_ms = expires * 1000;

    
   
1035
	/* Bump refcount for scheduler */

    
   
1036
	ao2_ref(esc_entry, +1);

    
   
1037
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);

    
   
1038

   

    
   
1039
	/* Note: This links the esc_entry into the ESC properly */

    
   
1040
	create_new_sip_etag(esc_entry, 0);

    
   
1041

   

    
   
1042
	return esc_entry;

    
   
1043
}

    
   
1044

   

    
   
1045
static int initialize_escs(void)

    
   
1046
{

    
   
1047
	int i, res = 0;

    
   
1048
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {

    
   
1049
		if (!((event_state_compositors[i].compositor) =

    
   
1050
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {

    
   
1051
			res = -1;

    
   
1052
		}

    
   
1053
	}

    
   
1054
	return res;

    
   
1055
}

    
   
1056

   

    
   
1057
static void destroy_escs(void)

    
   
1058
{

    
   
1059
	int i;

    
   
1060
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {

    
   
1061
		ao2_ref(event_state_compositors[i].compositor, -1);

    
   
1062
	}

    
   
1063
}

    
   
1064

   
854
/*! \brief
1065
/*! \brief
855
 * Here we implement the container for dialogs (sip_pvt), defining
1066
 * Here we implement the container for dialogs (sip_pvt), defining
856
 * generic wrapper functions to ease the transition from the current
1067
 * generic wrapper functions to ease the transition from the current
857
 * implementation (a single linked list) to a different container.
1068
 * implementation (a single linked list) to a different container.
858
 * In addition to a reference to the container, we need functions to lock/unlock
1069
 * In addition to a reference to the container, we need functions to lock/unlock
[+20] [20] 48 lines
[+20] [+] static struct sip_auth *authl = NULL;
907
 * bound to fail anyways, so we just live with this event and let
1118
 * bound to fail anyways, so we just live with this event and let
908
 * the protocol handle this above us.
1119
 * the protocol handle this above us.
909
 */
1120
 */
910
static int sipsock  = -1;
1121
static int sipsock  = -1;
911

    
   
1122

   
912
struct sockaddr_in bindaddr;	/*!< UDP: The address we bind to */
1123
struct ast_sockaddr bindaddr;	/*!< UDP: The address we bind to */
913

    
   
1124

   
914
/*! \brief our (internal) default address/port to put in SIP/SDP messages
1125
/*! \brief our (internal) default address/port to put in SIP/SDP messages
915
 *  internip is initialized picking a suitable address from one of the
1126
 *  internip is initialized picking a suitable address from one of the
916
 * interfaces, and the same port number we bind to. It is used as the
1127
 * interfaces, and the same port number we bind to. It is used as the
917
 * default address/port in SIP messages, and as the default address
1128
 * default address/port in SIP messages, and as the default address
918
 * (but not port) in SDP messages.
1129
 * (but not port) in SDP messages.
919
 */
1130
 */
920
static struct sockaddr_in internip;
1131
static struct ast_sockaddr internip;
921

    
   
1132

   
922
/*! \brief our external IP address/port for SIP sessions.
1133
/*! \brief our external IP address/port for SIP sessions.
923
 * externip.sin_addr is only set when we know we might be behind
1134
 * externaddr.sin_addr is only set when we know we might be behind
924
 * a NAT, and this is done using a variety of (mutually exclusive)
1135
 * a NAT, and this is done using a variety of (mutually exclusive)
925
 * ways from the config file:
1136
 * ways from the config file:
926
 *
1137
 *
927
 * + with "externip = host[:port]" we specify the address/port explicitly.
1138
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
928
 *   The address is looked up only once when (re)loading the config file;
1139
 *   The address is looked up only once when (re)loading the config file;
929
 *
1140
 *
930
 * + with "externhost = host[:port]" we do a similar thing, but the
1141
 * + with "externhost = host[:port]" we do a similar thing, but the
931
 *   hostname is stored in externhost, and the hostname->IP mapping
1142
 *   hostname is stored in externhost, and the hostname->IP mapping
932
 *   is refreshed every 'externrefresh' seconds;
1143
 *   is refreshed every 'externrefresh' seconds;
933
 *
1144
 *
934
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1145
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
935
 *   to the specified server, and store the result in externip.
1146
 *   to the specified server, and store the result in externaddr.
936
 *
1147
 *
937
 * Other variables (externhost, externexpire, externrefresh) are used
1148
 * Other variables (externhost, externexpire, externrefresh) are used
938
 * to support the above functions.
1149
 * to support the above functions.
939
 */
1150
 */
940
static struct sockaddr_in externip;       /*!< External IP address if we are behind NAT */
1151
static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
941
static struct sockaddr_in media_address;  /*!< External RTP IP address if we are behind NAT */
1152
static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
942

    
   
1153

   
943
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1154
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
944
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1155
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
945
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1156
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
946
static struct sockaddr_in stunaddr;     /*!< stun server address */
1157
static struct sockaddr_in stunaddr;     /*!< stun server address */
[+20] [20] 8 lines
[+20] [+] static uint16_t externtlsport; /*!< external tls port */
955
 */
1166
 */
956
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1167
static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
957

    
   
1168

   
958
static int ourport_tcp;             /*!< The port used for TCP connections */
1169
static int ourport_tcp;             /*!< The port used for TCP connections */
959
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1170
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
960
static struct sockaddr_in debugaddr;
1171
static struct ast_sockaddr debugaddr;
961

    
   
1172

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

    
   
1174

   
964
/*! some list management macros. */
1175
/*! some list management macros. */
965

    
   
1176

   
[+20] [20] 25 lines
[+20] [+] static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
991
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1202
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
992
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1203
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
993
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1204
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
994
static const char *sip_get_callid(struct ast_channel *chan);
1205
static const char *sip_get_callid(struct ast_channel *chan);
995

    
   
1206

   
996
static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1207
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
997
static int sip_standard_port(enum sip_transport type, int port);
1208
static int sip_standard_port(enum sip_transport type, int port);
998
static int sip_prepare_socket(struct sip_pvt *p);
1209
static int sip_prepare_socket(struct sip_pvt *p);

    
   
1210
static int get_address_family_filter(const struct ast_sockaddr *addr);
999

    
   
1211

   
1000
/*--- Transmitting responses and requests */
1212
/*--- Transmitting responses and requests */
1001
static int sipsock_read(int *id, int fd, short events, void *ignore);
1213
static int sipsock_read(int *id, int fd, short events, void *ignore);
1002
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1214
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1003
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1215
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);

    
   
1216
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1004
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1217
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1005
static int retrans_pkt(const void *data);
1218
static int retrans_pkt(const void *data);
1006
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);
1219
static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1007
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1220
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1008
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1221
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1009
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1222
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1010
static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
1223
static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
1011
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1224
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1012
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);
1225
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);
1013
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1226
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1014
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1227
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1015
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1228
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1016
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1229
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1017
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1230
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1018
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1231
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);

    
   
1232
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1019
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1233
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);

    
   
1234
static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1020
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1235
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1021
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1236
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1022
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1237
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1023
static int transmit_refer(struct sip_pvt *p, const char *dest);
1238
static int transmit_refer(struct sip_pvt *p, const char *dest);
1024
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1239
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1025
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1240
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);

    
   
1241
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1026
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1242
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1027
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1243
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1028
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1244
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1029
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1245
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1030
static void receive_message(struct sip_pvt *p, struct sip_request *req);
1246
static void receive_message(struct sip_pvt *p, struct sip_request *req);
1031
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1247
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1032
static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1248
static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1033

    
   
1249

   
1034
/* Misc dialog routines */
1250
/* Misc dialog routines */
1035
static int __sip_autodestruct(const void *data);
1251
static int __sip_autodestruct(const void *data);
1036
static void *registry_unref(struct sip_registry *reg, char *tag);
1252
static void *registry_unref(struct sip_registry *reg, char *tag);
1037
static int update_call_counter(struct sip_pvt *fup, int event);
1253
static int update_call_counter(struct sip_pvt *fup, int event);
1038
static int auto_congest(const void *arg);
1254
static int auto_congest(const void *arg);
1039
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1255
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1040
static void free_old_route(struct sip_route *route);
1256
static void free_old_route(struct sip_route *route);
1041
static void list_route(struct sip_route *route);
1257
static void list_route(struct sip_route *route);
1042
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1258
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1043
static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1259
static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1044
					      struct sip_request *req, const char *uri);
1260
					      struct sip_request *req, const char *uri);
1045
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1261
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1046
static void check_pendings(struct sip_pvt *p);
1262
static void check_pendings(struct sip_pvt *p);
1047
static void *sip_park_thread(void *stuff);
1263
static void *sip_park_thread(void *stuff);
1048
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1264
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
[+20] [20] 5 lines
[+20] [+] static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1054
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1270
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1055
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1271
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1056
static int find_sdp(struct sip_request *req);
1272
static int find_sdp(struct sip_request *req);
1057
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1273
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1058
static int process_sdp_o(const char *o, struct sip_pvt *p);
1274
static int process_sdp_o(const char *o, struct sip_pvt *p);
1059
static int process_sdp_c(const char *c, struct ast_hostent *hp);
1275
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1060
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1276
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1061
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1277
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1062
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1278
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1063
static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
1279
static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
1064
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1280
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
[+20] [20] 13 lines
[+20] [+] static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1078
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1294
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1079
					 const char *secret, const char *md5secret, int sipmethod,
1295
					 const char *secret, const char *md5secret, int sipmethod,
1080
					 const char *uri, enum xmittype reliable, int ignore);
1296
					 const char *uri, enum xmittype reliable, int ignore);
1081
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1297
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1082
					      int sipmethod, const char *uri, enum xmittype reliable,
1298
					      int sipmethod, const char *uri, enum xmittype reliable,
1083
					      struct sockaddr_in *sin, struct sip_peer **authpeer);
1299
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1084
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1300
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1085

    
   
1301

   
1086
/*--- Domain handling */
1302
/*--- Domain handling */
1087
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1303
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1088
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1304
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1089
static void clear_sip_domains(void);
1305
static void clear_sip_domains(void);
[+20] [20] 10 lines
[+20] [+] static int sip_do_reload(enum channelreloadreason reason);
1100
static int expire_register(const void *data);
1316
static int expire_register(const void *data);
1101
static void *do_monitor(void *data);
1317
static void *do_monitor(void *data);
1102
static int restart_monitor(void);
1318
static int restart_monitor(void);
1103
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1319
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1104
static struct ast_variable *copy_vars(struct ast_variable *src);
1320
static struct ast_variable *copy_vars(struct ast_variable *src);

    
   
1321
static int dialog_find_multiple(void *obj, void *arg, int flags);
1105
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1322
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1106
static int sip_refer_allocate(struct sip_pvt *p);
1323
static int sip_refer_allocate(struct sip_pvt *p);
1107
static int sip_notify_allocate(struct sip_pvt *p);
1324
static int sip_notify_allocate(struct sip_pvt *p);
1108
static void ast_quiet_chan(struct ast_channel *chan);
1325
static void ast_quiet_chan(struct ast_channel *chan);
1109
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1326
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
[+20] [20] 51 lines
[+20] [+] static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1161
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1378
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1162
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1379
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1163
static int sip_addheader(struct ast_channel *chan, const char *data);
1380
static int sip_addheader(struct ast_channel *chan, const char *data);
1164
static int sip_do_reload(enum channelreloadreason reason);
1381
static int sip_do_reload(enum channelreloadreason reason);
1165
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1382
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);

    
   
1383
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,

    
   
1384
				      const char *name, int flag, int family);

    
   
1385
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,

    
   
1386
				      const char *name, int flag);
1166

    
   
1387

   
1167
/*--- Debugging
1388
/*--- Debugging
1168
	Functions for enabling debug per IP or fully, or enabling history logging for
1389
	Functions for enabling debug per IP or fully, or enabling history logging for
1169
	a SIP dialog
1390
	a SIP dialog
1170
*/
1391
*/
1171
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1392
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1172
static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1393
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1173
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1394
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1174
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1395
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1175
static void sip_dump_history(struct sip_pvt *dialog);
1396
static void sip_dump_history(struct sip_pvt *dialog);
1176

    
   
1397

   
1177
/*--- Device object handling */
1398
/*--- Device object handling */
1178
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1399
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1179
static int update_call_counter(struct sip_pvt *fup, int event);
1400
static int update_call_counter(struct sip_pvt *fup, int event);
1180
static void sip_destroy_peer(struct sip_peer *peer);
1401
static void sip_destroy_peer(struct sip_peer *peer);
1181
static void sip_destroy_peer_fn(void *peer);
1402
static void sip_destroy_peer_fn(void *peer);
1182
static void set_peer_defaults(struct sip_peer *peer);
1403
static void set_peer_defaults(struct sip_peer *peer);
1183
static struct sip_peer *temp_peer(const char *name);
1404
static struct sip_peer *temp_peer(const char *name);
1184
static void register_peer_exten(struct sip_peer *peer, int onoff);
1405
static void register_peer_exten(struct sip_peer *peer, int onoff);
1185
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
1406
static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
1186
static int sip_poke_peer_s(const void *data);
1407
static int sip_poke_peer_s(const void *data);
1187
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1408
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1188
static void reg_source_db(struct sip_peer *peer);
1409
static void reg_source_db(struct sip_peer *peer);
1189
static void destroy_association(struct sip_peer *peer);
1410
static void destroy_association(struct sip_peer *peer);
1190
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1411
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1191
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1412
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1192
static void set_socket_transport(struct sip_socket *socket, int transport);
1413
static void set_socket_transport(struct sip_socket *socket, int transport);
1193

    
   
1414

   
1194
/* Realtime device support */
1415
/* Realtime device support */
1195
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1416
static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1196
static void update_peer(struct sip_peer *p, int expire);
1417
static void update_peer(struct sip_peer *p, int expire);
1197
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1418
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1198
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1419
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1199
static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
1420
static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only);
1200
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1421
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1201

    
   
1422

   
1202
/*--- Internal UA client handling (outbound registrations) */
1423
/*--- Internal UA client handling (outbound registrations) */
1203
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
1424
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1204
static void sip_registry_destroy(struct sip_registry *reg);
1425
static void sip_registry_destroy(struct sip_registry *reg);
1205
static int sip_register(const char *value, int lineno);
1426
static int sip_register(const char *value, int lineno);
1206
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1427
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1207
static int sip_reregister(const void *data);
1428
static int sip_reregister(const void *data);
1208
static int __sip_do_register(struct sip_registry *r);
1429
static int __sip_do_register(struct sip_registry *r);
[+20] [20] 5 lines
[+20] [+] static int sip_reinvite_retry(const void *data);
1214
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
1435
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
1215
static int determine_firstline_parts(struct sip_request *req);
1436
static int determine_firstline_parts(struct sip_request *req);
1216
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1437
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1217
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1438
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1218
static int find_sip_method(const char *msg);
1439
static int find_sip_method(const char *msg);
1219
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);

   
1220
static unsigned int parse_allowed_methods(struct sip_request *req);
1440
static unsigned int parse_allowed_methods(struct sip_request *req);
1221
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1441
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1222
static int parse_request(struct sip_request *req);
1442
static int parse_request(struct sip_request *req);
1223
static const char *get_header(const struct sip_request *req, const char *name);
1443
static const char *get_header(const struct sip_request *req, const char *name);
1224
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1444
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
[+20] [20] 9 lines
[+20] [+] static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1234
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1454
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1235
static int set_address_from_contact(struct sip_pvt *pvt);
1455
static int set_address_from_contact(struct sip_pvt *pvt);
1236
static void check_via(struct sip_pvt *p, struct sip_request *req);
1456
static void check_via(struct sip_pvt *p, struct sip_request *req);
1237
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1457
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1238
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1458
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1239
static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1459
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1240
static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1460
static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1241
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1461
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1242
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1462
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1243
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1463
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1244
static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req, struct ast_party_redirecting *redirecting, int set_call_forward);

   
1245
static int get_domain(const char *str, char *domain, int len);
1464
static int get_domain(const char *str, char *domain, int len);
1246
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1465
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1247

    
   
1466

   
1248
/*-- TCP connection handling ---*/
1467
/*-- TCP connection handling ---*/
1249
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1468
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1250
static void *sip_tcp_worker_fn(void *);
1469
static void *sip_tcp_worker_fn(void *);
1251

    
   
1470

   
1252
/*--- Constructing requests and responses */
1471
/*--- Constructing requests and responses */
1253
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1472
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1254
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1473
static int init_req(struct sip_request *req, int sipmethod, const char *recip);

    
   
1474
static void deinit_req(struct sip_request *req);
1255
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1475
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1256
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1476
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1257
static int init_resp(struct sip_request *resp, const char *msg);
1477
static int init_resp(struct sip_request *resp, const char *msg);
1258
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1478
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1259
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1479
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1260
static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1480
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1261
static void build_via(struct sip_pvt *p);
1481
static void build_via(struct sip_pvt *p);
1262
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1482
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1263
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
1483
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1264
static char *generate_random_string(char *buf, size_t size);
1484
static char *generate_random_string(char *buf, size_t size);
1265
static void build_callid_pvt(struct sip_pvt *pvt);
1485
static void build_callid_pvt(struct sip_pvt *pvt);
1266
static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1486
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1267
static void make_our_tag(char *tagbuf, size_t len);
1487
static void make_our_tag(char *tagbuf, size_t len);
1268
static int add_header(struct sip_request *req, const char *var, const char *value);
1488
static int add_header(struct sip_request *req, const char *var, const char *value);
1269
static int add_header_contentLength(struct sip_request *req, int len);
1489
static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1270
static int add_line(struct sip_request *req, const char *line);
1490
static int add_content(struct sip_request *req, const char *line);

    
   
1491
static int finalize_content(struct sip_request *req);
1271
static int add_text(struct sip_request *req, const char *text);
1492
static int add_text(struct sip_request *req, const char *text);
1272
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1493
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1273
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1494
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1274
static int add_vidupdate(struct sip_request *req);
1495
static int add_vidupdate(struct sip_request *req);
1275
static void add_route(struct sip_request *req, struct sip_route *route);
1496
static void add_route(struct sip_request *req, struct sip_route *route);
1276
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1497
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1277
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1498
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1278
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1499
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1279
static void set_destination(struct sip_pvt *p, char *uri);
1500
static void set_destination(struct sip_pvt *p, char *uri);
1280
static void append_date(struct sip_request *req);
1501
static void append_date(struct sip_request *req);
1281
static void build_contact(struct sip_pvt *p);
1502
static void build_contact(struct sip_pvt *p);
1282

    
   
1503

   
1283
/*------Request handling functions */
1504
/*------Request handling functions */
1284
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1505
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1285
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1506
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1286
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, const char *e, int *nounlock);
1507
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
1287
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1508
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1288
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1509
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1289
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, const char *e);
1510
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1290
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1511
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1291
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1512
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1292
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1513
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1293
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1514
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1294
static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1515
static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1295
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
1516
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct ast_sockaddr *addr, int *nounlock);
1296
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1517
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int seqno, const char *e);
1297
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1518
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1298

    
   
1519

   
1299
/*------Response handling functions */
1520
/*------Response handling functions */

    
   
1521
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1300
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1522
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1301
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1523
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1302
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1524
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1303
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1525
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1304
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1526
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1305
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1527
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1306

    
   
1528

   

    
   
1529
/*------ SRTP Support -------- */

    
   
1530
static int setup_srtp(struct sip_srtp **srtp);

    
   
1531
static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);

    
   
1532

   
1307
/*------ T38 Support --------- */
1533
/*------ T38 Support --------- */
1308
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1534
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1309
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1535
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1310
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1536
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1311
static void change_t38_state(struct sip_pvt *p, int state);
1537
static void change_t38_state(struct sip_pvt *p, int state);
[+20] [20] 58 lines
[+20] [+] const struct ast_channel_tech sip_tech = {
1370
 * The struct is initialized just before registering the channel driver,
1596
 * The struct is initialized just before registering the channel driver,
1371
 * and is for use with channels using SIP INFO DTMF.
1597
 * and is for use with channels using SIP INFO DTMF.
1372
 */
1598
 */
1373
struct ast_channel_tech sip_tech_info;
1599
struct ast_channel_tech sip_tech_info;
1374

    
   
1600

   

    
   
1601
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);

    
   
1602
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);

    
   
1603
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);

    
   
1604
static void sip_cc_agent_ack(struct ast_cc_agent *agent);

    
   
1605
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);

    
   
1606
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);

    
   
1607
static int sip_cc_agent_recall(struct ast_cc_agent *agent);

    
   
1608
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);

    
   
1609

   

    
   
1610
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {

    
   
1611
	.type = "SIP",

    
   
1612
	.init = sip_cc_agent_init,

    
   
1613
	.start_offer_timer = sip_cc_agent_start_offer_timer,

    
   
1614
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,

    
   
1615
	.ack = sip_cc_agent_ack,

    
   
1616
	.status_request = sip_cc_agent_status_request,

    
   
1617
	.start_monitoring = sip_cc_agent_start_monitoring,

    
   
1618
	.callee_available = sip_cc_agent_recall,

    
   
1619
	.destructor = sip_cc_agent_destructor,

    
   
1620
};

    
   
1621

   

    
   
1622
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)

    
   
1623
{

    
   
1624
	struct ast_cc_agent *agent = obj;

    
   
1625
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1626
	const char *uri = arg;

    
   
1627

   

    
   
1628
	return !strcmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;

    
   
1629
}

    
   
1630

   

    
   
1631
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)

    
   
1632
{

    
   
1633
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");

    
   
1634
	return agent;

    
   
1635
}

    
   
1636

   

    
   
1637
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)

    
   
1638
{

    
   
1639
	struct ast_cc_agent *agent = obj;

    
   
1640
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1641
	const char *uri = arg;

    
   
1642

   

    
   
1643
	return !strcmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;

    
   
1644
}

    
   
1645

   

    
   
1646
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)

    
   
1647
{

    
   
1648
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");

    
   
1649
	return agent;

    
   
1650
}

    
   
1651

   

    
   
1652
static int find_by_callid_helper(void *obj, void *arg, int flags)

    
   
1653
{

    
   
1654
	struct ast_cc_agent *agent = obj;

    
   
1655
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1656
	struct sip_pvt *call_pvt = arg;

    
   
1657

   

    
   
1658
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;

    
   
1659
}

    
   
1660

   

    
   
1661
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)

    
   
1662
{

    
   
1663
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");

    
   
1664
	return agent;

    
   
1665
}

    
   
1666

   

    
   
1667
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)

    
   
1668
{

    
   
1669
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));

    
   
1670
	struct sip_pvt *call_pvt = chan->tech_pvt;

    
   
1671

   

    
   
1672
	if (!agent_pvt) {

    
   
1673
		return -1;

    
   
1674
	}

    
   
1675

   

    
   
1676
	ast_assert(!strcmp(chan->tech->type, "SIP"));

    
   
1677

   

    
   
1678
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));

    
   
1679
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));

    
   
1680
	agent_pvt->offer_timer_id = -1;

    
   
1681
	agent->private_data = agent_pvt;

    
   
1682
	sip_pvt_lock(call_pvt);

    
   
1683
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);

    
   
1684
	sip_pvt_unlock(call_pvt);

    
   
1685
	return 0;

    
   
1686
}

    
   
1687

   

    
   
1688
static int sip_offer_timer_expire(const void *data)

    
   
1689
{

    
   
1690
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;

    
   
1691
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1692

   

    
   
1693
	agent_pvt->offer_timer_id = -1;

    
   
1694

   

    
   
1695
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);

    
   
1696
}

    
   
1697

   

    
   
1698
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)

    
   
1699
{

    
   
1700
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1701
	int when;

    
   
1702

   

    
   
1703
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;

    
   
1704
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);

    
   
1705
	return 0;

    
   
1706
}

    
   
1707

   

    
   
1708
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)

    
   
1709
{

    
   
1710
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1711

   

    
   
1712
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);

    
   
1713
	return 0;

    
   
1714
}

    
   
1715

   

    
   
1716
static void sip_cc_agent_ack(struct ast_cc_agent *agent)

    
   
1717
{

    
   
1718
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1719

   

    
   
1720
	sip_pvt_lock(agent_pvt->subscribe_pvt);

    
   
1721
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);

    
   
1722
	transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);

    
   
1723
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);

    
   
1724
	sip_pvt_unlock(agent_pvt->subscribe_pvt);

    
   
1725
	agent_pvt->is_available = TRUE;

    
   
1726
}

    
   
1727

   

    
   
1728
static int sip_cc_agent_status_request(struct ast_cc_agent *agent)

    
   
1729
{

    
   
1730
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1731
	enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;

    
   
1732
	return ast_cc_agent_status_response(agent->core_id, state);

    
   
1733
}

    
   
1734

   

    
   
1735
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)

    
   
1736
{

    
   
1737
	/* To start monitoring just means to wait for an incoming PUBLISH

    
   
1738
	 * to tell us that the caller has become available again. No special

    
   
1739
	 * action is needed

    
   
1740
	 */

    
   
1741
	return 0;

    
   
1742
}

    
   
1743

   

    
   
1744
static int sip_cc_agent_recall(struct ast_cc_agent *agent)

    
   
1745
{

    
   
1746
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1747
	/* If we have received a PUBLISH beforehand stating that the caller in question

    
   
1748
	 * is not available, we can save ourself a bit of effort here and just report

    
   
1749
	 * the caller as busy

    
   
1750
	 */

    
   
1751
	if (!agent_pvt->is_available) {

    
   
1752
		return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",

    
   
1753
				agent->device_name);

    
   
1754
	}

    
   
1755
	/* Otherwise, we transmit a NOTIFY to the caller and await either

    
   
1756
	 * a PUBLISH or an INVITE

    
   
1757
	 */

    
   
1758
	sip_pvt_lock(agent_pvt->subscribe_pvt);

    
   
1759
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);

    
   
1760
	sip_pvt_unlock(agent_pvt->subscribe_pvt);

    
   
1761
	return 0;

    
   
1762
}

    
   
1763

   

    
   
1764
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)

    
   
1765
{

    
   
1766
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;

    
   
1767

   

    
   
1768
	if (!agent_pvt) {

    
   
1769
		/* The agent constructor probably failed. */

    
   
1770
		return;

    
   
1771
	}

    
   
1772

   

    
   
1773
	sip_cc_agent_stop_offer_timer(agent);

    
   
1774
	if (agent_pvt->subscribe_pvt) {

    
   
1775
		sip_pvt_lock(agent_pvt->subscribe_pvt);

    
   
1776
		if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {

    
   
1777
			/* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting

    
   
1778
			 * the subscriber know something went wrong

    
   
1779
			 */

    
   
1780
			transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);

    
   
1781
		}

    
   
1782
		sip_pvt_unlock(agent_pvt->subscribe_pvt);

    
   
1783
		agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");

    
   
1784
	}

    
   
1785
	ast_free(agent_pvt);

    
   
1786
}

    
   
1787

   

    
   
1788
struct ao2_container *sip_monitor_instances;

    
   
1789

   

    
   
1790
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)

    
   
1791
{

    
   
1792
	const struct sip_monitor_instance *monitor_instance = obj;

    
   
1793
	return monitor_instance->core_id;

    
   
1794
}

    
   
1795

   

    
   
1796
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)

    
   
1797
{

    
   
1798
	struct sip_monitor_instance *monitor_instance1 = obj;

    
   
1799
	struct sip_monitor_instance *monitor_instance2 = arg;

    
   
1800

   

    
   
1801
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;

    
   
1802
}

    
   
1803

   

    
   
1804
static void sip_monitor_instance_destructor(void *data)

    
   
1805
{

    
   
1806
	struct sip_monitor_instance *monitor_instance = data;

    
   
1807
	if (monitor_instance->subscription_pvt) {

    
   
1808
		sip_pvt_lock(monitor_instance->subscription_pvt);

    
   
1809
		monitor_instance->subscription_pvt->expiry = 0;

    
   
1810
		transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);

    
   
1811
		sip_pvt_unlock(monitor_instance->subscription_pvt);

    
   
1812
		dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");

    
   
1813
	}

    
   
1814
	if (monitor_instance->suspension_entry) {

    
   
1815
		monitor_instance->suspension_entry->body[0] = '\0';

    
   
1816
		transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);

    
   
1817
		ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");

    
   
1818
	}

    
   
1819
	ast_string_field_free_memory(monitor_instance);

    
   
1820
}

    
   
1821

   

    
   
1822
static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)

    
   
1823
{

    
   
1824
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);

    
   
1825

   

    
   
1826
	if (!monitor_instance) {
Moved from 2075

    
   
1827
		return NULL;
Moved from 2076

    
   
1828
	}

    
   
1829

   

    
   
1830
	if (ast_string_field_init(monitor_instance, 256)) {

    
   
1831
		ao2_ref(monitor_instance, -1);
Moved from 2075

    
   
1832
		return NULL;
Moved from 2076

    
   
1833
	}

    
   
1834

   

    
   
1835
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);

    
   
1836
	ast_string_field_set(monitor_instance, peername, peername);

    
   
1837
	ast_string_field_set(monitor_instance, device_name, device_name);

    
   
1838
	monitor_instance->core_id = core_id;

    
   
1839
	ao2_link(sip_monitor_instances, monitor_instance);

    
   
1840
	return monitor_instance;

    
   
1841
}

    
   
1842

   

    
   
1843
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)

    
   
1844
{

    
   
1845
	struct sip_monitor_instance *monitor_instance = obj;

    
   
1846
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;

    
   
1847
}

    
   
1848

   

    
   
1849
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)

    
   
1850
{

    
   
1851
	struct sip_monitor_instance *monitor_instance = obj;

    
   
1852
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;

    
   
1853
}

    
   
1854

   

    
   
1855
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);

    
   
1856
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);

    
   
1857
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);

    
   
1858
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);

    
   
1859
static void sip_cc_monitor_destructor(void *private_data);

    
   
1860

   

    
   
1861
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {

    
   
1862
	.type = "SIP",

    
   
1863
	.request_cc = sip_cc_monitor_request_cc,

    
   
1864
	.suspend = sip_cc_monitor_suspend,

    
   
1865
	.unsuspend = sip_cc_monitor_unsuspend,

    
   
1866
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,

    
   
1867
	.destructor = sip_cc_monitor_destructor,

    
   
1868
};

    
   
1869

   

    
   
1870
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)

    
   
1871
{

    
   
1872
	struct sip_monitor_instance *monitor_instance = monitor->private_data;

    
   
1873
	enum ast_cc_service_type service = monitor->service_offered;

    
   
1874
	int when;

    
   
1875

   

    
   
1876
	if (!monitor_instance) {

    
   
1877
		return -1;

    
   
1878
	}

    
   
1879

   

    
   
1880
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {

    
   
1881
		return -1;

    
   
1882
	}

    
   
1883

   

    
   
1884
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :

    
   
1885
		ast_get_ccnr_available_timer(monitor->interface->config_params);

    
   
1886

   

    
   
1887
	sip_pvt_lock(monitor_instance->subscription_pvt);

    
   
1888
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);

    
   
1889
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);

    
   
1890
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;

    
   
1891
	monitor_instance->subscription_pvt->expiry = when;

    
   
1892

   

    
   
1893
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);

    
   
1894
	sip_pvt_unlock(monitor_instance->subscription_pvt);

    
   
1895

   

    
   
1896
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");

    
   
1897
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);

    
   
1898
	return 0;

    
   
1899
}

    
   
1900

   

    
   
1901
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)

    
   
1902
{

    
   
1903
	struct ast_str *body = ast_str_alloca(size);

    
   
1904
	char tuple_id[32];

    
   
1905

   

    
   
1906
	generate_random_string(tuple_id, sizeof(tuple_id));

    
   
1907

   

    
   
1908
	/* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF

    
   
1909
	 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.

    
   
1910
	 */

    
   
1911
	ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

    
   
1912
	/* XXX The entity attribute is currently set to the peer name associated with the

    
   
1913
	 * dialog. This is because we currently only call this function for call-completion

    
   
1914
	 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other

    
   
1915
	 * event packages, it may be crucial to have a proper URI as the presentity so this

    
   
1916
	 * should be revisited as support is expanded.

    
   
1917
	 */

    
   
1918
	ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);

    
   
1919
	ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);

    
   
1920
	ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");

    
   
1921
	ast_str_append(&body, 0, "</tuple>\n");

    
   
1922
	ast_str_append(&body, 0, "</presence>\n");

    
   
1923
	ast_copy_string(pidf_body, ast_str_buffer(body), size);

    
   
1924
	return 0;

    
   
1925
}

    
   
1926

   

    
   
1927
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)

    
   
1928
{

    
   
1929
	struct sip_monitor_instance *monitor_instance = monitor->private_data;

    
   
1930
	enum sip_publish_type publish_type;

    
   
1931
	struct cc_epa_entry *cc_entry;

    
   
1932

   

    
   
1933
	if (!monitor_instance) {

    
   
1934
		return -1;

    
   
1935
	}

    
   
1936

   

    
   
1937
	if (!monitor_instance->suspension_entry) {

    
   
1938
		/* We haven't yet allocated the suspension entry, so let's give it a shot */

    
   
1939
		if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {

    
   
1940
			ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");

    
   
1941
			ao2_ref(monitor_instance, -1);

    
   
1942
			return -1;

    
   
1943
		}

    
   
1944
		if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {

    
   
1945
			ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");

    
   
1946
			ao2_ref(monitor_instance, -1);

    
   
1947
			return -1;

    
   
1948
		}

    
   
1949
		cc_entry->core_id = monitor->core_id;

    
   
1950
		monitor_instance->suspension_entry->instance_data = cc_entry;

    
   
1951
		publish_type = SIP_PUBLISH_INITIAL;

    
   
1952
	} else {

    
   
1953
		publish_type = SIP_PUBLISH_MODIFY;

    
   
1954
		cc_entry = monitor_instance->suspension_entry->instance_data;

    
   
1955
	}

    
   
1956

   

    
   
1957
	cc_entry->current_state = CC_CLOSED;

    
   
1958

   

    
   
1959
	if (ast_strlen_zero(monitor_instance->notify_uri)) {

    
   
1960
		/* If we have no set notify_uri, then what this means is that we have

    
   
1961
		 * not received a NOTIFY from this destination stating that he is

    
   
1962
		 * currently available.

    
   
1963
		 *

    
   
1964
		 * This situation can arise when the core calls the suspend callbacks

    
   
1965
		 * of multiple destinations. If one of the other destinations aside

    
   
1966
		 * from this one notified Asterisk that he is available, then there

    
   
1967
		 * is no reason to take any suspension action on this device. Rather,

    
   
1968
		 * we should return now and if we receive a NOTIFY while monitoring

    
   
1969
		 * is still "suspended" then we can immediately respond with the

    
   
1970
		 * proper PUBLISH to let this endpoint know what is going on.

    
   
1971
		 */

    
   
1972
		return 0;

    
   
1973
	}

    
   
1974
	construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);

    
   
1975
	return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);

    
   
1976
}

    
   
1977

   

    
   
1978
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)

    
   
1979
{

    
   
1980
	struct sip_monitor_instance *monitor_instance = monitor->private_data;

    
   
1981
	struct cc_epa_entry *cc_entry;

    
   
1982

   

    
   
1983
	if (!monitor_instance) {

    
   
1984
		return -1;

    
   
1985
	}

    
   
1986

   

    
   
1987
	ast_assert(monitor_instance->suspension_entry != NULL);

    
   
1988

   

    
   
1989
	cc_entry = monitor_instance->suspension_entry->instance_data;

    
   
1990
	cc_entry->current_state = CC_OPEN;

    
   
1991
	if (ast_strlen_zero(monitor_instance->notify_uri)) {

    
   
1992
		/* This means we are being asked to unsuspend a call leg we never

    
   
1993
		 * sent a PUBLISH on. As such, there is no reason to send another

    
   
1994
		 * PUBLISH at this point either. We can just return instead.

    
   
1995
		 */

    
   
1996
		return 0;

    
   
1997
	}

    
   
1998
	construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);

    
   
1999
	return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);

    
   
2000
}

    
   
2001

   

    
   
2002
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)

    
   
2003
{

    
   
2004
	if (*sched_id != -1) {

    
   
2005
		AST_SCHED_DEL(sched, *sched_id);

    
   
2006
		ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");

    
   
2007
	}

    
   
2008
	return 0;

    
   
2009
}

    
   
2010

   

    
   
2011
static void sip_cc_monitor_destructor(void *private_data)

    
   
2012
{

    
   
2013
	struct sip_monitor_instance *monitor_instance = private_data;

    
   
2014
	ao2_unlink(sip_monitor_instances, monitor_instance);

    
   
2015
	ast_module_unref(ast_module_info->self);

    
   
2016
}

    
   
2017

   

    
   
2018
static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)

    
   
2019
{

    
   
2020
	char *call_info = ast_strdupa(get_header(req, "Call-Info"));

    
   
2021
	char *uri;

    
   
2022
	char *purpose;

    
   
2023
	char *service_str;

    
   
2024
	static const char cc_purpose[] = "purpose=call-completion";

    
   
2025
	static const int cc_purpose_len = sizeof(cc_purpose) - 1;

    
   
2026

   

    
   
2027
	if (ast_strlen_zero(call_info)) {

    
   
2028
		/* No Call-Info present. Definitely no CC offer */

    
   
2029
		return -1;

    
   
2030
	}

    
   
2031

   

    
   
2032
	uri = strsep(&call_info, ";");

    
   
2033

   

    
   
2034
	while ((purpose = strsep(&call_info, ";"))) {

    
   
2035
		if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
Moved from 2165

    
   
2036
			break;
Moved from 2166

    
   
2037
		}
Moved from 2167

    
   
2038
	}

    
   
2039
	if (!purpose) {

    
   
2040
		/* We didn't find the appropriate purpose= parameter. Oh well */

    
   
2041
		return -1;

    
   
2042
	}

    
   
2043

   

    
   
2044
	/* Okay, call-completion has been offered. Let's figure out what type of service this is */

    
   
2045
	while ((service_str = strsep(&call_info, ";"))) {

    
   
2046
		if (!strncmp(service_str, "m=", 2)) {
Moved from 2165

    
   
2047
			break;
Moved from 2166

    
   
2048
		}
Moved from 2167

    
   
2049
	}

    
   
2050
	if (!service_str) {

    
   
2051
		/* So they didn't offer a particular service, We'll just go with CCBS since it really

    
   
2052
		 * doesn't matter anyway

    
   
2053
		 */

    
   
2054
		service_str = "BS";

    
   
2055
	} else {

    
   
2056
		/* We already determined that there is an "m=" so no need to check

    
   
2057
		 * the result of this strsep

    
   
2058
		 */

    
   
2059
		strsep(&service_str, "=");

    
   
2060
	}

    
   
2061

   

    
   
2062
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {

    
   
2063
		/* Invalid service offered */

    
   
2064
		return -1;

    
   
2065
	}

    
   
2066

   

    
   
2067
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);

    
   
2068

   

    
   
2069
	return 0;

    
   
2070
}

    
   
2071

   

    
   
2072
/*

    
   
2073
 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible

    
   
2074
 *

    
   
2075
 * After taking care of some formalities to be sure that this call is eligible for CC,

    
   
2076
 * we first try to see if we can make use of native CC. We grab the information from

    
   
2077
 * the passed-in sip_request (which is always a response to an INVITE). If we can

    
   
2078
 * use native CC monitoring for the call, then so be it.

    
   
2079
 *

    
   
2080
 * If native cc monitoring is not possible or not supported, then we will instead attempt

    
   
2081
 * to use generic monitoring. Falling back to generic from a failed attempt at using native

    
   
2082
 * monitoring will only work if the monitor policy of the endpoint is "always"

    
   
2083
 *

    
   
2084
 * \param pvt The current dialog. Contains CC parameters for the endpoint

    
   
2085
 * \param req The response to the INVITE we want to inspect

    
   
2086
 * \param service The service to use if generic monitoring is to be used. For native

    
   
2087
 * monitoring, we get the service from the SIP response itself

    
   
2088
 */

    
   
2089
static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)

    
   
2090
{

    
   
2091
	enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);

    
   
2092
	int core_id;

    
   
2093
	char interface_name[AST_CHANNEL_NAME];

    
   
2094

   

    
   
2095
	if (monitor_policy == AST_CC_MONITOR_NEVER) {

    
   
2096
		/* Don't bother, just return */

    
   
2097
		return;

    
   
2098
	}

    
   
2099

   

    
   
2100
	if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {

    
   
2101
		/* For some reason, CC is invalid, so don't try it! */

    
   
2102
		return;

    
   
2103
	}

    
   
2104

   

    
   
2105
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));

    
   
2106

   

    
   
2107
	if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {

    
   
2108
		char subscribe_uri[SIPBUFSIZE];

    
   
2109
		char device_name[AST_CHANNEL_NAME];

    
   
2110
		enum ast_cc_service_type offered_service;

    
   
2111
		struct sip_monitor_instance *monitor_instance;

    
   
2112
		if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {

    
   
2113
			/* If CC isn't being offered to us, or for some reason the CC offer is

    
   
2114
			 * not formatted correctly, then it may still be possible to use generic

    
   
2115
			 * call completion since the monitor policy may be "always"

    
   
2116
			 */

    
   
2117
			goto generic;

    
   
2118
		}

    
   
2119
		ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));

    
   
2120
		if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {

    
   
2121
			/* Same deal. We can try using generic still */

    
   
2122
			goto generic;

    
   
2123
		}

    
   
2124
		/* We bump the refcount of chan_sip because once we queue this frame, the CC core

    
   
2125
		 * will have a reference to callbacks in this module. We decrement the module

    
   
2126
		 * refcount once the monitor destructor is called

    
   
2127
		 */

    
   
2128
		ast_module_ref(ast_module_info->self);

    
   
2129
		ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);

    
   
2130
		ao2_ref(monitor_instance, -1);

    
   
2131
		return;

    
   
2132
	}

    
   
2133

   

    
   
2134
generic:

    
   
2135
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {

    
   
2136
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);

    
   
2137
	}

    
   
2138
}

    
   
2139

   
1375
/*! \brief Working TLS connection configuration */
2140
/*! \brief Working TLS connection configuration */
1376
static struct ast_tls_config sip_tls_cfg;
2141
static struct ast_tls_config sip_tls_cfg;
1377

    
   
2142

   
1378
/*! \brief Default TLS connection configuration */
2143
/*! \brief Default TLS connection configuration */
1379
static struct ast_tls_config default_tls_cfg;
2144
static struct ast_tls_config default_tls_cfg;
[+20] [20] 322 lines
[+20] [+] static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
1702
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
2467
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
1703
	fds[0].fd = tcptls_session->fd;
2468
	fds[0].fd = tcptls_session->fd;
1704
	fds[1].fd = me->alert_pipe[0];
2469
	fds[1].fd = me->alert_pipe[0];
1705
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2470
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
1706

    
   
2471

   
1707
	if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2472
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
1708
		goto cleanup;
2473
		goto cleanup;
1709
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2474
	}

    
   
2475
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
1710
		goto cleanup;
2476
		goto cleanup;

    
   
2477
	}
1711

    
   
2478

   
1712
	for (;;) {
2479
	for (;;) {
1713
		struct ast_str *str_save;
2480
		struct ast_str *str_save;
1714

    
   
2481

   
1715
		res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
2482
		res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
[+20] [20] 36 lines
[+20] static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
1752
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2519
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
1753
					ast_mutex_unlock(&tcptls_session->lock);
2520
					ast_mutex_unlock(&tcptls_session->lock);
1754
					goto cleanup;
2521
					goto cleanup;
1755
				}
2522
				}
1756
				ast_mutex_unlock(&tcptls_session->lock);
2523
				ast_mutex_unlock(&tcptls_session->lock);
1757
				if (me->stop)
2524
				if (me->stop) {
1758
					 goto cleanup;
2525
					 goto cleanup;

    
   
2526
				}
1759
				ast_str_append(&req.data, 0, "%s", buf);
2527
				ast_str_append(&req.data, 0, "%s", buf);
1760
				req.len = req.data->used;
2528
				req.len = req.data->used;
1761
			}
2529
			}
1762
			copy_request(&reqcpy, &req);
2530
			copy_request(&reqcpy, &req);
1763
			parse_request(&reqcpy);
2531
			parse_request(&reqcpy);
[+20] [20] 6 lines
[+20] static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
1770
						ast_mutex_unlock(&tcptls_session->lock);
2538
						ast_mutex_unlock(&tcptls_session->lock);
1771
						goto cleanup;
2539
						goto cleanup;
1772
					}
2540
					}
1773
					buf[bytes_read] = '\0';
2541
					buf[bytes_read] = '\0';
1774
					ast_mutex_unlock(&tcptls_session->lock);
2542
					ast_mutex_unlock(&tcptls_session->lock);
1775
					if (me->stop)
2543
					if (me->stop) {
1776
						goto cleanup;
2544
						goto cleanup;

    
   
2545
					}
1777
					cl -= strlen(buf);
2546
					cl -= strlen(buf);
1778
					ast_str_append(&req.data, 0, "%s", buf);
2547
					ast_str_append(&req.data, 0, "%s", buf);
1779
					req.len = req.data->used;
2548
					req.len = req.data->used;
1780
				}
2549
				}
1781
			}
2550
			}
[+20] [20] 42 lines
[+20] static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
1824
cleanup:
2593
cleanup:
1825
	if (me) {
2594
	if (me) {
1826
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2595
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
1827
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2596
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
1828
	}
2597
	}
1829
	if (reqcpy.data) {
2598
	deinit_req(&reqcpy);
1830
		ast_free(reqcpy.data);
2599
	deinit_req(&req);
1831
	}

   
1832

    
   

   
1833
	if (req.data) {

   
1834
		ast_free(req.data);

   
1835
		req.data = NULL;

   
1836
	}

   
1837

    
   
2600

   
1838
	/* if client, we own the parent session arguments and must decrement ref */
2601
	/* if client, we own the parent session arguments and must decrement ref */
1839
	if (ca) {
2602
	if (ca) {
1840
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
2603
		ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
1841
	}
2604
	}
[+20] [20] 80 lines
[+20] [+] void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
1922
	if (dialog->owner) {
2685
	if (dialog->owner) {
1923
		if (lockowner)
2686
		if (lockowner)
1924
			ast_channel_lock(dialog->owner);
2687
			ast_channel_lock(dialog->owner);
1925
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2688
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
1926
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2689
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
1927
		if (lockowner)
2690
		if (lockowner) {
1928
			ast_channel_unlock(dialog->owner);
2691
			ast_channel_unlock(dialog->owner);
1929
	}
2692
		}

    
   
2693
	}
1930
	if (dialog->registry) {
2694
	if (dialog->registry) {
1931
		if (dialog->registry->call == dialog)
2695
		if (dialog->registry->call == dialog) {
1932
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2696
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");

    
   
2697
		}
1933
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2698
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
1934
	}
2699
	}
1935
	if (dialog->stateid > -1) {
2700
	if (dialog->stateid > -1) {
1936
		ast_extension_state_del(dialog->stateid, NULL);
2701
		ast_extension_state_del(dialog->stateid, NULL);
1937
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2702
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
1938
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2703
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
1939
	}
2704
	}
1940
	/* Remove link from peer to subscription of MWI */
2705
	/* Remove link from peer to subscription of MWI */
1941
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2706
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
1942
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2707
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
1943
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2708
	}

    
   
2709
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
1944
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2710
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");

    
   
2711
	}
1945

    
   
2712

   
1946
	/* remove all current packets in this dialog */
2713
	/* remove all current packets in this dialog */
1947
	while((cp = dialog->packets)) {
2714
	while((cp = dialog->packets)) {
1948
		dialog->packets = dialog->packets->next;
2715
		dialog->packets = dialog->packets->next;
1949
		AST_SCHED_DEL(sched, cp->retransid);
2716
		AST_SCHED_DEL(sched, cp->retransid);
[+20] [20] 6 lines
[+20] void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
1956

    
   
2723

   
1957
	AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
2724
	AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
1958

    
   
2725

   
1959
	AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
2726
	AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
1960
	
2727
	
1961
	if (dialog->autokillid > -1)
2728
	if (dialog->autokillid > -1) {
1962
		AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));
2729
		AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));

    
   
2730
	}
1963

    
   
2731

   
1964
	if (dialog->request_queue_sched_id > -1) {
2732
	if (dialog->request_queue_sched_id > -1) {
1965
		AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
2733
		AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
1966
	}
2734
	}
1967

    
   
2735

   
[+20] [20] 38 lines
[+20] [+] static const char *referstatus2str(enum referstatus rstatus)
2006
	return map_x_s(referstatusstrings, rstatus, "");
2774
	return map_x_s(referstatusstrings, rstatus, "");
2007
}
2775
}
2008

    
   
2776

   
2009
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2777
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2010
{
2778
{

    
   
2779
	if (pvt->final_destruction_scheduled) {

    
   
2780
		return; /* This is already scheduled for final destruction, let the scheduler take care of it. */

    
   
2781
	}
2011
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2782
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2012
	pvt->needdestroy = 1;
2783
	pvt->needdestroy = 1;
2013
}
2784
}
2014

    
   
2785

   
2015
/*! \brief Initialize the initital request packet in the pvt structure.
2786
/*! \brief Initialize the initital request packet in the pvt structure.
2016
 	This packet is used for creating replies and future requests in
2787
 	This packet is used for creating replies and future requests in
2017
	a dialog */
2788
	a dialog */
2018
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2789
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2019
{
2790
{
2020
	if (p->initreq.headers)
2791
	if (p->initreq.headers) {
2021
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2792
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2022
	else
2793
	} else {
2023
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2794
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);

    
   
2795
	}
2024
	/* Use this as the basis */
2796
	/* Use this as the basis */
2025
	copy_request(&p->initreq, req);
2797
	copy_request(&p->initreq, req);
2026
	parse_request(&p->initreq);
2798
	parse_request(&p->initreq);
2027
	if (req->debug)
2799
	if (req->debug) {
2028
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2800
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2029
}
2801
	}

    
   
2802
}
2030

    
   
2803

   
2031
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2804
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2032
static void sip_alreadygone(struct sip_pvt *dialog)
2805
static void sip_alreadygone(struct sip_pvt *dialog)
2033
{
2806
{
2034
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2807
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2035
	dialog->alreadygone = 1;
2808
	dialog->alreadygone = 1;
2036
}
2809
}
2037

    
   
2810

   
2038
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2811
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2039
static int proxy_update(struct sip_proxy *proxy)
2812
static int proxy_update(struct sip_proxy *proxy)
2040
{
2813
{
2041
	/* if it's actually an IP address and not a name,
2814
	/* if it's actually an IP address and not a name,
2042
           there's no need for a managed lookup */
2815
           there's no need for a managed lookup */
2043
	if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2816
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2044
		/* Ok, not an IP address, then let's check if it's a domain or host */
2817
		/* Ok, not an IP address, then let's check if it's a domain or host */
2045
		/* XXX Todo - if we have proxy port, don't do SRV */
2818
		/* XXX Todo - if we have proxy port, don't do SRV */

    
   
2819
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
2046
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2820
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2047
			ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2821
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2048
			return FALSE;
2822
				return FALSE;
2049
		}
2823
		}

    
   
2824

   
2050
	}
2825
	}

    
   
2826

   

    
   
2827
	ast_sockaddr_set_port(&proxy->ip, proxy->port);

    
   
2828

   
2051
	proxy->last_dnsupdate = time(NULL);
2829
	proxy->last_dnsupdate = time(NULL);
2052
	return TRUE;
2830
	return TRUE;
2053
}
2831
}
2054

    
   
2832

   
2055
/*! \brief converts ascii port to int representation. If no
2833
/*! \brief converts ascii port to int representation. If no
[+20] [20] 8 lines
[+20] [+] unsigned int port_str2int(const char *pt, unsigned int standard)
2064
	}
2842
	}
2065

    
   
2843

   
2066
	return port;
2844
	return port;
2067
}
2845
}
2068

    
   
2846

   
2069
/*! \brief Allocate and initialize sip proxy */

   
2070
static struct sip_proxy *proxy_allocate(char *name, char *port, int force)

   
2071
{

   
2072
	struct sip_proxy *proxy;

   
2073

    
   

   
2074
	if (ast_strlen_zero(name)) {

   
2075
		return NULL;

   
2076
	}

   
2077

    
   

   
2078
	proxy = ao2_alloc(sizeof(*proxy), NULL);

   
2079
	if (!proxy)

   
2080
		return NULL;

   
2081
	proxy->force = force;

   
2082
	ast_copy_string(proxy->name, name, sizeof(proxy->name));

   
2083
	proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));

   
2084
	proxy_update(proxy);

   
2085
	return proxy;

   
2086
}

   
2087

    
   

   
2088
/*! \brief Get default outbound proxy or global proxy */
2847
/*! \brief Get default outbound proxy or global proxy */
2089
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2848
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2090
{
2849
{
2091
	if (peer && peer->outboundproxy) {
2850
	if (peer && peer->outboundproxy) {
2092
		if (sipdebug)
2851
		if (sipdebug) {
2093
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2852
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");

    
   
2853
		}
2094
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2854
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2095
		return peer->outboundproxy;
2855
		return peer->outboundproxy;
2096
	}
2856
	}
2097
	if (sip_cfg.outboundproxy.name[0]) {
2857
	if (sip_cfg.outboundproxy.name[0]) {
2098
		if (sipdebug)
2858
		if (sipdebug) {
2099
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2859
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");

    
   
2860
		}
2100
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2861
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2101
		return &sip_cfg.outboundproxy;
2862
		return &sip_cfg.outboundproxy;
2102
	}
2863
	}
2103
	if (sipdebug)
2864
	if (sipdebug) {
2104
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2865
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");

    
   
2866
	}
2105
	return NULL;
2867
	return NULL;
2106
}
2868
}
2107

    
   
2869

   
2108
/*! \brief returns true if 'name' (with optional trailing whitespace)
2870
/*! \brief returns true if 'name' (with optional trailing whitespace)
2109
 * matches the sip method 'id'.
2871
 * matches the sip method 'id'.
[+20] [20] 13 lines
[+20] [+] static int method_match(enum sipmethod id, const char *name)
2123
/*! \brief  find_sip_method: Find SIP method from header */
2885
/*! \brief  find_sip_method: Find SIP method from header */
2124
static int find_sip_method(const char *msg)
2886
static int find_sip_method(const char *msg)
2125
{
2887
{
2126
	int i, res = 0;
2888
	int i, res = 0;
2127
	
2889
	
2128
	if (ast_strlen_zero(msg))
2890
	if (ast_strlen_zero(msg)) {
2129
		return 0;
2891
		return 0;

    
   
2892
	}
2130
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2893
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2131
		if (method_match(i, msg))
2894
		if (method_match(i, msg)) {
2132
			res = sip_methods[i].id;
2895
			res = sip_methods[i].id;
2133
	}
2896
		}

    
   
2897
	}
2134
	return res;
2898
	return res;
2135
}
2899
}
2136

    
   
2900

   
2137
/*! \brief Parse supported header in incoming packet */
2901
/*! \brief See if we pass debug IP filter */
2138
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2902
static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
2139
{
2903
{
2140
	char *next, *sep;
2904
	/* Can't debug if sipdebug is not enabled */
2141
	char *temp;
2905
	if (!sipdebug) {
2142
	unsigned int profile = 0;

   
2143
	int i, found;

   
2144

    
   

   
2145
	if (ast_strlen_zero(supported) )

   
2146
		return 0;
2906
		return 0;
2147
	temp = ast_strdupa(supported);

   
2148

    
   

   
2149
	if (sipdebug)

   
2150
		ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);

   
2151

    
   

   
2152
	for (next = temp; next; next = sep) {

   
2153
		found = FALSE;

   
2154
		if ( (sep = strchr(next, ',')) != NULL)

   
2155
			*sep++ = '\0';

   
2156
		next = ast_skip_blanks(next);

   
2157
		if (sipdebug)

   
2158
			ast_debug(3, "Found SIP option: -%s-\n", next);

   
2159
		for (i = 0; i < ARRAY_LEN(sip_options); i++) {

   
2160
			if (!strcasecmp(next, sip_options[i].text)) {

   
2161
				profile |= sip_options[i].id;

   
2162
				found = TRUE;

   
2163
				if (sipdebug)

   
2164
					ast_debug(3, "Matched SIP option: %s\n", next);

   
2165
				break;

   
2166
			}

   
2167
		}

   
2168

    
   

   
2169
		/* This function is used to parse both Suported: and Require: headers.

   
2170
		Let the caller of this function know that an unknown option tag was

   
2171
		encountered, so that if the UAC requires it then the request can be

   
2172
		rejected with a 420 response. */

   
2173
		if (!found)

   
2174
			profile |= SIP_OPT_UNKNOWN;

   
2175

    
   

   
2176
		if (!found && sipdebug) {

   
2177
			if (!strncasecmp(next, "x-", 2))

   
2178
				ast_debug(3, "Found private SIP option, not supported: %s\n", next);

   
2179
			else

   
2180
				ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);

   
2181
		}

   
2182
	}
2907
	}
2183

    
   
2908

   
2184
	if (pvt)
2909
	/* A null debug_addr means we'll debug any address */
2185
		pvt->sipoptions = profile;
2910
	if (ast_sockaddr_isnull(&debugaddr)) {
2186
	return profile;
2911
		return 1;
2187
}
2912
	}
2188

    
   
2913

   
2189
/*! \brief See if we pass debug IP filter */
2914
	/* If no port was specified for a debug address, just compare the
2190
static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2915
	 * addresses, otherwise compare the address and port
2191
{
2916
	 */
2192
	if (!sipdebug)
2917
	if (ast_sockaddr_port(&debugaddr)) {
2193
		return 0;
2918
		return !ast_sockaddr_cmp(&debugaddr, addr);
2194
	if (debugaddr.sin_addr.s_addr) {
2919
	} else {
2195
		if (((ntohs(debugaddr.sin_port) != 0)
2920
		return !ast_sockaddr_cmp_addr(&debugaddr, addr);
2196
			&& (debugaddr.sin_port != addr->sin_port))

   
2197
			|| (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))

   
2198
			return 0;

   
2199
	}
2921
	}
2200
	return 1;

   
2201
}
2922
}
2202

    
   
2923

   
2203
/*! \brief The real destination address for a write */
2924
/*! \brief The real destination address for a write */
2204
static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2925
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
2205
{
2926
{
2206
	if (p->outboundproxy)
2927
	if (p->outboundproxy) {
2207
		return &p->outboundproxy->ip;
2928
		return &p->outboundproxy->ip;

    
   
2929
	}
2208

    
   
2930

   
2209
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT) ? &p->recv : &p->sa;
2931
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT) ? &p->recv : &p->sa;
2210
}
2932
}
2211

    
   
2933

   
2212
/*! \brief Display SIP nat mode */
2934
/*! \brief Display SIP nat mode */
2213
static const char *sip_nat_mode(const struct sip_pvt *p)
2935
static const char *sip_nat_mode(const struct sip_pvt *p)
2214
{
2936
{
2215
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
2937
	return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
2216
}
2938
}
2217

    
   
2939

   
2218
/*! \brief Test PVT for debugging output */
2940
/*! \brief Test PVT for debugging output */
2219
static inline int sip_debug_test_pvt(struct sip_pvt *p)
2941
static inline int sip_debug_test_pvt(struct sip_pvt *p)
2220
{
2942
{
2221
	if (!sipdebug)
2943
	if (!sipdebug) {
2222
		return 0;
2944
		return 0;

    
   
2945
	}
2223
	return sip_debug_test_addr(sip_real_dst(p));
2946
	return sip_debug_test_addr(sip_real_dst(p));
2224
}
2947
}
2225

    
   
2948

   
2226
/*! \brief Return int representing a bit field of transport types found in const char *transport */
2949
/*! \brief Return int representing a bit field of transport types found in const char *transport */
2227
static int get_transport_str2enum(const char *transport)
2950
static int get_transport_str2enum(const char *transport)
[+20] [20] 51 lines
[+20] [+] static inline const char *get_transport(enum sip_transport t)
2279
	}
3002
	}
2280

    
   
3003

   
2281
	return "UNKNOWN";
3004
	return "UNKNOWN";
2282
}
3005
}
2283

    
   
3006

   

    
   
3007
/*! \brief Return protocol string for srv dns query */

    
   
3008
static inline const char *get_srv_protocol(enum sip_transport t)

    
   
3009
{

    
   
3010
	switch (t) {

    
   
3011
	case SIP_TRANSPORT_UDP:

    
   
3012
		return "udp";

    
   
3013
	case SIP_TRANSPORT_TLS:

    
   
3014
	case SIP_TRANSPORT_TCP:

    
   
3015
		return "tcp";

    
   
3016
	}

    
   
3017

   

    
   
3018
	return "udp";

    
   
3019
}

    
   
3020

   

    
   
3021
/*! \brief Return service string for srv dns query */

    
   
3022
static inline const char *get_srv_service(enum sip_transport t)

    
   
3023
{

    
   
3024
	switch (t) {

    
   
3025
	case SIP_TRANSPORT_TCP:

    
   
3026
	case SIP_TRANSPORT_UDP:

    
   
3027
		return "sip";

    
   
3028
	case SIP_TRANSPORT_TLS:

    
   
3029
		return "sips";

    
   
3030
	}

    
   
3031
	return "sip";

    
   
3032
}

    
   
3033

   
2284
/*! \brief Return transport of dialog.
3034
/*! \brief Return transport of dialog.
2285
	\note this is based on a false assumption. We don't always use the
3035
	\note this is based on a false assumption. We don't always use the
2286
	outbound proxy for all requests in a dialog. It depends on the
3036
	outbound proxy for all requests in a dialog. It depends on the
2287
	"force" parameter. The FIRST request is always sent to the ob proxy.
3037
	"force" parameter. The FIRST request is always sent to the ob proxy.
2288
	\todo Fix this function to work correctly
3038
	\todo Fix this function to work correctly
[+20] [20] 14 lines
[+20] [+] static inline const char *get_transport_pvt(struct sip_pvt *p)
2303
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3053
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
2304
*/
3054
*/
2305
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3055
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
2306
{
3056
{
2307
	int res = 0;
3057
	int res = 0;
2308
	const struct sockaddr_in *dst = sip_real_dst(p);
3058
	const struct ast_sockaddr *dst = sip_real_dst(p);
2309

    
   
3059

   
2310
	ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
3060
	ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
2311

    
   
3061

   
2312
	if (sip_prepare_socket(p) < 0)
3062
	if (sip_prepare_socket(p) < 0) {
2313
		return XMIT_ERROR;
3063
		return XMIT_ERROR;

    
   
3064
	}
2314

    
   
3065

   
2315
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3066
	if (p->socket.type == SIP_TRANSPORT_UDP) {
2316
		res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
3067
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
2317
	} else if (p->socket.tcptls_session) {
3068
	} else if (p->socket.tcptls_session) {
2318
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3069
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
2319
	} else {
3070
	} else {
2320
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3071
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
2321
		return XMIT_ERROR;
3072
		return XMIT_ERROR;
[+20] [20] 7 lines
[+20] static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
2329
		case ENETUNREACH:	/* Network failure */
3080
		case ENETUNREACH:	/* Network failure */
2330
		case ECONNREFUSED:      /* ICMP port unreachable */
3081
		case ECONNREFUSED:      /* ICMP port unreachable */
2331
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3082
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
2332
		}
3083
		}
2333
	}
3084
	}
2334
	if (res != len)
3085
	if (res != len) {
2335
		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));
3086
		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_sockaddr_stringify(dst), res, strerror(errno));

    
   
3087
	}
2336

    
   
3088

   
2337
	return res;
3089
	return res;
2338
}
3090
}
2339

    
   
3091

   
2340
/*! \brief Build a Via header for a request */
3092
/*! \brief Build a Via header for a request */
2341
static void build_via(struct sip_pvt *p)
3093
static void build_via(struct sip_pvt *p)
2342
{
3094
{
2343
	/* Work around buggy UNIDEN UIP200 firmware */
3095
	/* Work around buggy UNIDEN UIP200 firmware */
2344
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3096
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
2345

    
   
3097

   
2346
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3098
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
2347
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
3099
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
2348
		 get_transport_pvt(p),
3100
		 get_transport_pvt(p),
2349
		 ast_inet_ntoa(p->ourip.sin_addr),
3101
		 ast_sockaddr_stringify(&p->ourip),
2350
		 ntohs(p->ourip.sin_port), (int) p->branch, rport);
3102
		 (int) p->branch, rport);
2351
}
3103
}
2352

    
   
3104

   
2353
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3105
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
2354
 *
3106
 *
2355
 * Using the localaddr structure built up with localnet statements in sip.conf
3107
 * Using the localaddr structure built up with localnet statements in sip.conf
2356
 * apply it to their address to see if we need to substitute our
3108
 * apply it to their address to see if we need to substitute our
2357
 * externip or can get away with our internal bindaddr
3109
 * externaddr or can get away with our internal bindaddr
2358
 * 'us' is always overwritten.
3110
 * 'us' is always overwritten.
2359
 */
3111
 */
2360
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
3112
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
2361
{
3113
{
2362
	struct sockaddr_in theirs;
3114
	struct ast_sockaddr theirs;

    
   
3115
	struct sockaddr_in externaddr_sin;

    
   
3116

   
2363
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3117
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
2364
	 * reachable IP address and port. This is done if:
3118
	 * reachable IP address and port. This is done if:
2365
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3119
	 * 1. we have a localaddr list (containing 'internal' addresses marked
2366
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3120
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2367
	 *    and AST_SENSE_ALLOW on 'external' ones);
3121
	 *    and AST_SENSE_ALLOW on 'external' ones);
2368
	 * 2. either stunaddr or externip is set, so we know what to use as the
3122
	 * 2. either stunaddr or externaddr is set, so we know what to use as the
2369
	 *    externally visible address;
3123
	 *    externally visible address;
2370
	 * 3. the remote address, 'them', is external;
3124
	 * 3. the remote address, 'them', is external;
2371
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3125
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2372
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3126
	 *    when passed to ast_apply_ha() so it does need to be remapped.
2373
	 *    This fourth condition is checked later.
3127
	 *    This fourth condition is checked later.
2374
	 */
3128
	 */
2375
	int want_remap;
3129
	int want_remap = 0;
2376

    
   
3130

   
2377
	*us = internip;		/* starting guess for the internal address */
3131
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
2378
	/* now ask the system what would it use to talk to 'them' */
3132
	/* now ask the system what would it use to talk to 'them' */
2379
	ast_ouraddrfor(them, &us->sin_addr);
3133
	ast_ouraddrfor(them, us);
2380
	theirs.sin_addr = *them;
3134
	ast_sockaddr_copy(&theirs, them);
2381

    
   
3135

   

    
   
3136
	if (ast_sockaddr_is_ipv6(&theirs)) {

    
   
3137
		if (localaddr && !ast_sockaddr_isnull(&externaddr)) {

    
   
3138
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "

    
   
3139
				"but we're using IPv6, which doesn't need it. Please "

    
   
3140
				"remove \"localnet\" and/or \"externaddr\" settings.\n");

    
   
3141
		}

    
   
3142
	} else {
2382
	want_remap = localaddr &&
3143
		want_remap = localaddr &&
2383
		(externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
3144
			!(ast_sockaddr_isnull(&externaddr) && stunaddr.sin_addr.s_addr) &&
2384
		ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3145
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;

    
   
3146
	}
2385

    
   
3147

   
2386
	if (want_remap &&
3148
	if (want_remap &&
2387
	    (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
3149
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
2388
		/* if we used externhost or stun, see if it is time to refresh the info */
3150
		/* if we used externhost or stun, see if it is time to refresh the info */
2389
		if (externexpire && time(NULL) >= externexpire) {
3151
		if (externexpire && time(NULL) >= externexpire) {
2390
			if (stunaddr.sin_addr.s_addr) {
3152
			if (stunaddr.sin_addr.s_addr) {
2391
				ast_stun_request(sipsock, &stunaddr, NULL, &externip);
3153
				ast_sockaddr_to_sin(&externaddr, &externaddr_sin);

    
   
3154
				ast_stun_request(sipsock, &stunaddr, NULL, &externaddr_sin);
2392
			} else {
3155
			} else {
2393
				if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
3156
				if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
2394
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3157
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2395
			}
3158
				}

    
   
3159
				externexpire = time(NULL);

    
   
3160
			}
2396
			externexpire = time(NULL) + externrefresh;
3161
			externexpire = time(NULL) + externrefresh;
2397
		}
3162
		}
2398
		if (externip.sin_addr.s_addr) {
3163
		if (!ast_sockaddr_isnull(&externaddr)) {
2399
			*us = externip;
3164
			ast_sockaddr_copy(us, &externaddr);
2400
			switch (p->socket.type) {
3165
			switch (p->socket.type) {
2401
			case SIP_TRANSPORT_TCP:
3166
			case SIP_TRANSPORT_TCP:
2402
				us->sin_port = htons(externtcpport);
3167
				if (!externtcpport && ast_sockaddr_port(&externaddr)) {

    
   
3168
					/* for consistency, default to the externaddr port */

    
   
3169
					externtcpport = ast_sockaddr_port(&externaddr);

    
   
3170
				}

    
   
3171
				ast_sockaddr_set_port(us, externtcpport);
2403
				break;
3172
				break;
2404
			case SIP_TRANSPORT_TLS:
3173
			case SIP_TRANSPORT_TLS:
2405
				us->sin_port = htons(externtlsport);
3174
				ast_sockaddr_set_port(us, externtlsport);
2406
				break;
3175
				break;
2407
			case SIP_TRANSPORT_UDP:
3176
			case SIP_TRANSPORT_UDP:
2408
				break; /* fall through */
3177
				if (!ast_sockaddr_port(&externaddr)) {

    
   
3178
					ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));

    
   
3179
				}

    
   
3180
				break;
2409
			default:
3181
			default:
2410
				us->sin_port = htons(STANDARD_SIP_PORT); /* we should never get here */
3182
				break;
2411
			}
3183
			}
2412
		}
3184
		}
2413
		else
3185
		else {
2414
			ast_log(LOG_WARNING, "stun failed\n");
3186
			ast_log(LOG_WARNING, "stun failed\n");
2415
		ast_debug(1, "Target address %s is not local, substituting externip\n",
3187
		}
2416
			ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
3188
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",

    
   
3189
			  ast_sockaddr_stringify(them));
2417
	} else if (p) {
3190
	} else if (p) {
2418
		/* no remapping, but we bind to a specific address, so use it. */
3191
		/* no remapping, but we bind to a specific address, so use it. */
2419
		switch (p->socket.type) {
3192
		switch (p->socket.type) {
2420
		case SIP_TRANSPORT_TCP:
3193
		case SIP_TRANSPORT_TCP:
2421
			if (sip_tcp_desc.local_address.sin_addr.s_addr) {
3194
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
2422
				*us = sip_tcp_desc.local_address;
3195
				ast_sockaddr_copy(us,

    
   
3196
						  &sip_tcp_desc.local_address);
2423
			} else {
3197
			} else {
2424
				us->sin_port = sip_tcp_desc.local_address.sin_port;
3198
				ast_sockaddr_set_port(us,

    
   
3199
						      ast_sockaddr_port(&sip_tcp_desc.local_address));
2425
			}
3200
			}
2426
			break;
3201
			break;
2427
		case SIP_TRANSPORT_TLS:
3202
		case SIP_TRANSPORT_TLS:
2428
			if (sip_tls_desc.local_address.sin_addr.s_addr) {
3203
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
2429
				*us = sip_tls_desc.local_address;
3204
				ast_sockaddr_copy(us,

    
   
3205
						  &sip_tls_desc.local_address);
2430
			} else {
3206
			} else {
2431
				us->sin_port = sip_tls_desc.local_address.sin_port;
3207
				ast_sockaddr_set_port(us,

    
   
3208
						      ast_sockaddr_port(&sip_tls_desc.local_address));
2432
			}
3209
			}
2433
				break;
3210
			break;
2434
		case SIP_TRANSPORT_UDP:
3211
		case SIP_TRANSPORT_UDP:
2435
			/* fall through on purpose */
3212
			/* fall through on purpose */
2436
		default:
3213
		default:
2437
			if (bindaddr.sin_addr.s_addr) {
3214
			if (!ast_sockaddr_is_any(&bindaddr)) {
2438
				*us = bindaddr;
3215
				ast_sockaddr_copy(us, &bindaddr);

    
   
3216
			}

    
   
3217
			if (!ast_sockaddr_port(us)) {

    
   
3218
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
2439
			}
3219
			}
2440
		}
3220
		}
2441
	} else if (bindaddr.sin_addr.s_addr) {
3221
	} else if (!ast_sockaddr_is_any(&bindaddr)) {
2442
		*us = bindaddr;
3222
		ast_sockaddr_copy(us, &bindaddr);
2443
	}
3223
	}
2444
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
3224
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
2445
}
3225
}
2446

    
   
3226

   
2447
/*! \brief Append to SIP dialog history with arg list  */
3227
/*! \brief Append to SIP dialog history with arg list  */
2448
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3228
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2449
{
3229
{
2450
	char buf[80], *c = buf; /* max history length */
3230
	char buf[80], *c = buf; /* max history length */
2451
	struct sip_history *hist;
3231
	struct sip_history *hist;
2452
	int l;
3232
	int l;
2453

    
   
3233

   
2454
	vsnprintf(buf, sizeof(buf), fmt, ap);
3234
	vsnprintf(buf, sizeof(buf), fmt, ap);
2455
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3235
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2456
	l = strlen(buf) + 1;
3236
	l = strlen(buf) + 1;
2457
	if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
3237
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
2458
		return;
3238
		return;

    
   
3239
	}
2459
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3240
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2460
		ast_free(hist);
3241
		ast_free(hist);
2461
		return;
3242
		return;
2462
	}
3243
	}
2463
	memcpy(hist->event, buf, l);
3244
	memcpy(hist->event, buf, l);
[+20] [20] 10 lines
[+20] static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2474
/*! \brief Append to SIP dialog history with arg list  */
3255
/*! \brief Append to SIP dialog history with arg list  */
2475
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3256
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2476
{
3257
{
2477
	va_list ap;
3258
	va_list ap;
2478

    
   
3259

   
2479
	if (!p)
3260
	if (!p) {
2480
		return;
3261
		return;

    
   
3262
	}
2481

    
   
3263

   
2482
	if (!p->do_history && !recordhistory && !dumphistory)
3264
	if (!p->do_history && !recordhistory && !dumphistory) {
2483
		return;
3265
		return;

    
   
3266
	}
2484

    
   
3267

   
2485
	va_start(ap, fmt);
3268
	va_start(ap, fmt);
2486
	append_history_va(p, fmt, ap);
3269
	append_history_va(p, fmt, ap);
2487
	va_end(ap);
3270
	va_end(ap);
2488

    
   
3271

   
[+20] [20] 4 lines
[+20] static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2493
static int retrans_pkt(const void *data)
3276
static int retrans_pkt(const void *data)
2494
{
3277
{
2495
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3278
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2496
	int reschedule = DEFAULT_RETRANS;
3279
	int reschedule = DEFAULT_RETRANS;
2497
	int xmitres = 0;
3280
	int xmitres = 0;
2498
	
3281
	/* how many ms until retrans timeout is reached */

    
   
3282
	int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);

    
   
3283

   

    
   
3284
	/* Do not retransmit if time out is reached. This will be negative if the time between

    
   
3285
	 * the first transmission and now is larger than our timeout period. This is a fail safe

    
   
3286
	 * check in case the scheduler gets behind or the clock is changed. */

    
   
3287
	if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {

    
   
3288
		pkt->retrans_stop = 1;

    
   
3289
	}

    
   
3290

   
2499
	/* Lock channel PVT */
3291
	/* Lock channel PVT */
2500
	sip_pvt_lock(pkt->owner);
3292
	sip_pvt_lock(pkt->owner);
2501

    
   
3293

   
2502
	if (pkt->retrans < MAX_RETRANS) {
3294
	if (!pkt->retrans_stop) {
2503
		pkt->retrans++;
3295
		pkt->retrans++;
2504
 		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
3296
		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
2505
			if (sipdebug)
3297
			if (sipdebug) {
2506
 				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
3298
				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",

    
   
3299
					pkt->retransid,

    
   
3300
					sip_methods[pkt->method].text,

    
   
3301
					pkt->method);

    
   
3302
			}
2507
		} else {
3303
		} else {
2508
 			int siptimer_a;
3304
			int siptimer_a;
2509

    
   
3305

   
2510
 			if (sipdebug)
3306
			if (sipdebug) {
2511
 				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
3307
				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
2512
 			if (!pkt->timer_a)
3308
					pkt->retransid,

    
   
3309
					pkt->retrans,

    
   
3310
					sip_methods[pkt->method].text,

    
   
3311
					pkt->method);

    
   
3312
			}

    
   
3313
			if (!pkt->timer_a) {
2513
 				pkt->timer_a = 2 ;
3314
				pkt->timer_a = 2 ;
2514
 			else
3315
			} else {
2515
 				pkt->timer_a = 2 * pkt->timer_a;
3316
				pkt->timer_a = 2 * pkt->timer_a;

    
   
3317
			}
2516

    
   
3318

   
2517
 			/* For non-invites, a maximum of 4 secs */
3319
			/* For non-invites, a maximum of 4 secs */
2518
 			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3320
			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
2519
 			if (pkt->method != SIP_INVITE && siptimer_a > 4000)
3321
			if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
2520
 				siptimer_a = 4000;
3322
				siptimer_a = 4000;
2521
 		
3323
			}

    
   
3324

   
2522
 			/* Reschedule re-transmit */
3325
			/* Reschedule re-transmit */
2523
			reschedule = siptimer_a;
3326
			reschedule = siptimer_a;
2524
 			ast_debug(4, "** 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);
3327
			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",

    
   
3328
				pkt->retrans + 1,

    
   
3329
				siptimer_a,

    
   
3330
				pkt->timer_t1,

    
   
3331
				pkt->retransid);
2525
 		}
3332
		}
2526

    
   
3333

   
2527
		if (sip_debug_test_pvt(pkt->owner)) {
3334
		if (sip_debug_test_pvt(pkt->owner)) {
2528
			const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
3335
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
2529
			ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
3336
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
2530
				pkt->retrans, sip_nat_mode(pkt->owner),
3337
				pkt->retrans, sip_nat_mode(pkt->owner),
2531
				ast_inet_ntoa(dst->sin_addr),
3338
				ast_sockaddr_stringify(dst),
2532
				ntohs(dst->sin_port), pkt->data->str);
3339
				pkt->data->str);
2533
		}
3340
		}
2534

    
   
3341

   
2535
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3342
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
2536
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3343
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2537
		sip_pvt_unlock(pkt->owner);
3344
		sip_pvt_unlock(pkt->owner);
2538
		if (xmitres == XMIT_ERROR)
3345

   
2539
			ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
3346
		/* If there was no error during the network transmission, schedule the next retransmission,
2540
		else
3347
		 * but if the next retransmission is going to be beyond our timeout period, mark the packet's

    
   
3348
		 * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will

    
   
3349
		 * allow any responses to the packet to be processed before the packet is destroyed on the next

    
   
3350
		 * call to this function by the scheduler. */

    
   
3351
		if (xmitres != XMIT_ERROR) {

    
   
3352
			if (reschedule >= diff) {

    
   
3353
				pkt->retrans_stop = 1;

    
   
3354
				reschedule = diff;

    
   
3355
			}
2541
			return  reschedule;
3356
			return  reschedule;
2542
	}
3357
		}
2543
	/* Too many retries */
3358
	}

    
   
3359

   

    
   
3360
	/* At this point, either the packet's retransmission timed out, or there was a

    
   
3361
	 * transmission error, either way destroy the scheduler item and this packet. */

    
   
3362

   

    
   
3363
	pkt->retransid = -1; /* Kill this scheduler item */

    
   
3364

   
2544
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3365
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2545
		if (pkt->is_fatal || sipdebug)	/* Tell us if it's critical or if we're debugging */
3366
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
2546
			ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
3367
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n"
2547
				pkt->owner->callid, pkt->seqno,
3368
				"Packet timed out after %dms with no response\n",
2548
				pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
3369
				pkt->owner->callid,

    
   
3370
				pkt->seqno,

    
   
3371
				pkt->is_fatal ? "Critical" : "Non-critical",

    
   
3372
				pkt->is_resp ? "Response" : "Request",

    
   
3373
				(int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));

    
   
3374
		}
2549
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3375
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
2550
			ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
3376
		ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
2551

    
   

   
2552
	}
3377
	}

    
   
3378

   
2553
	if (xmitres == XMIT_ERROR) {
3379
	if (xmitres == XMIT_ERROR) {
2554
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3380
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2555
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3381
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2556
	} else
3382
	} else {
2557
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3383
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2558
 		
3384
	}
2559
	pkt->retransid = -1;

   
2560

    
   
3385

   
2561
	if (pkt->is_fatal) {
3386
	if (pkt->is_fatal) {
2562
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3387
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2563
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3388
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
2564
			usleep(1);
3389
			usleep(1);
2565
			sip_pvt_lock(pkt->owner);
3390
			sip_pvt_lock(pkt->owner);
2566
		}
3391
		}
2567

    
   
3392
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
2568
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause)

   
2569
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3393
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2570
		
3394
		}
2571
		if (pkt->owner->owner) {
3395
		if (pkt->owner->owner) {
2572
			sip_alreadygone(pkt->owner);

   
2573
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3396
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);

    
   
3397

   

    
   
3398
			if (pkt->is_resp &&

    
   
3399
				(pkt->response_code >= 200) &&

    
   
3400
				(pkt->response_code < 300) &&

    
   
3401
				pkt->owner->pendinginvite &&

    
   
3402
				ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {

    
   
3403
				/* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE

    
   
3404
				 * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup

    
   
3405
				 * will send the BYE as long as the dialog is not set as "alreadygone")

    
   
3406
				 * RFC 3261 section 13.3.1.4.

    
   
3407
				 * "If the server retransmits the 2xx response for 64*T1 seconds without receiving

    
   
3408
				 * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is

    
   
3409
				 * accomplished with a BYE, as described in Section 15." */

    
   
3410
				pkt->owner->invitestate = INV_TERMINATED;

    
   
3411
				pkt->owner->pendinginvite = 0;

    
   
3412
			} else {

    
   
3413
				/* there is nothing left to do, mark the dialog as gone */

    
   
3414
				sip_alreadygone(pkt->owner);

    
   
3415
			}
2574
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3416
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
2575
			ast_channel_unlock(pkt->owner->owner);
3417
			ast_channel_unlock(pkt->owner->owner);
2576
		} else {
3418
		} else {
2577
			/* If no channel owner, destroy now */
3419
			/* If no channel owner, destroy now */
2578

    
   
3420

   
[+20] [20] 6 lines
[+20] static int retrans_pkt(const void *data)
2585
		}
3427
		}
2586
	}
3428
	}
2587

    
   
3429

   
2588
	if (pkt->method == SIP_BYE) {
3430
	if (pkt->method == SIP_BYE) {
2589
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3431
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
2590
		if (pkt->owner->owner)
3432
		if (pkt->owner->owner) {
2591
			ast_channel_unlock(pkt->owner->owner);
3433
			ast_channel_unlock(pkt->owner->owner);

    
   
3434
		}
2592
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3435
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2593
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3436
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
2594
	}
3437
	}
2595

    
   
3438

   
2596
	/* Remove the packet */
3439
	/* Remove the packet */
2597
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3440
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2598
		if (cur == pkt) {
3441
		if (cur == pkt) {
2599
			UNLINK(cur, pkt->owner->packets, prev);
3442
			UNLINK(cur, pkt->owner->packets, prev);
2600
			sip_pvt_unlock(pkt->owner);
3443
			sip_pvt_unlock(pkt->owner);
2601
			if (pkt->owner)
3444
			if (pkt->owner) {
2602
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3445
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
2603
			if (pkt->data)
3446
			}

    
   
3447
			if (pkt->data) {
2604
				ast_free(pkt->data);
3448
				ast_free(pkt->data);

    
   
3449
			}
2605
			pkt->data = NULL;
3450
			pkt->data = NULL;
2606
			ast_free(pkt);
3451
			ast_free(pkt);
2607
			return 0;
3452
			return 0;
2608
		}
3453
		}
2609
	}
3454
	}
[+20] [20] 29 lines
[+20] [+] static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
2639
		} else {
3484
		} else {
2640
			return AST_SUCCESS;
3485
			return AST_SUCCESS;
2641
		}
3486
		}
2642
	}
3487
	}
2643

    
   
3488

   
2644
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
3489
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1))) {
2645
		return AST_FAILURE;
3490
		return AST_FAILURE;

    
   
3491
	}
2646
	/* copy data, add a terminator and save length */
3492
	/* copy data, add a terminator and save length */
2647
	if (!(pkt->data = ast_str_create(len))) {
3493
	if (!(pkt->data = ast_str_create(len))) {
2648
		ast_free(pkt);
3494
		ast_free(pkt);
2649
		return AST_FAILURE;
3495
		return AST_FAILURE;
2650
	}
3496
	}
[+20] [20] 13 lines
[+20] static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
2664
			pkt->response_code = respid;
3510
			pkt->response_code = respid;
2665
		}
3511
		}
2666
	}
3512
	}
2667
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3513
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
2668
	pkt->retransid = -1;
3514
	pkt->retransid = -1;
2669
	if (pkt->timer_t1)
3515
	if (pkt->timer_t1) {
2670
		siptimer_a = pkt->timer_t1 * 2;
3516
		siptimer_a = pkt->timer_t1;

    
   
3517
	}

    
   
3518

   

    
   
3519
	pkt->time_sent = ast_tvnow(); /* time packet was sent */

    
   
3520
	pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
2671

    
   
3521

   
2672
	/* Schedule retransmission */
3522
	/* Schedule retransmission */
2673
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3523
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
2674
	if (sipdebug)
3524
	if (sipdebug) {
2675
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3525
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);

    
   
3526
	}
2676

    
   
3527

   
2677
	xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);	/* Send packet */
3528
	xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);	/* Send packet */
2678

    
   
3529

   
2679
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3530
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
2680
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3531
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2681
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3532
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
2682
		AST_SCHED_DEL(sched, pkt->retransid);
3533
		AST_SCHED_DEL(sched, pkt->retransid);
2683
		p->packets = pkt->next;
3534
		p->packets = pkt->next;
2684
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3535
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
2685
		ast_free(pkt->data);
3536
		ast_free(pkt->data);
2686
		ast_free(pkt);
3537
		ast_free(pkt);
2687
		return AST_FAILURE;
3538
		return AST_FAILURE;
2688
	} else {
3539
	} else {

    
   
3540
		/* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread

    
   
3541
		 * only wakes up every 1000ms by default, we have to poke the thread here to make

    
   
3542
		 * sure it successfully detects this must be retransmitted in less time than

    
   
3543
		 * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */

    
   
3544
		if (monitor_thread != AST_PTHREADT_NULL) {

    
   
3545
			pthread_kill(monitor_thread, SIGURG);

    
   
3546
		}
2689
		return AST_SUCCESS;
3547
		return AST_SUCCESS;
2690
	}
3548
	}
2691
}
3549
}
2692

    
   
3550

   
2693
/*! \brief Kill a SIP dialog (called only by the scheduler)
3551
/*! \brief Kill a SIP dialog (called only by the scheduler)
[+20] [20] 4 lines
[+20] static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
2698
static int __sip_autodestruct(const void *data)
3556
static int __sip_autodestruct(const void *data)
2699
{
3557
{
2700
	struct sip_pvt *p = (struct sip_pvt *)data;
3558
	struct sip_pvt *p = (struct sip_pvt *)data;
2701

    
   
3559

   
2702
	/* If this is a subscription, tell the phone that we got a timeout */
3560
	/* If this is a subscription, tell the phone that we got a timeout */
2703
	if (p->subscribed) {
3561
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
2704
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3562
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
2705
		p->subscribed = NONE;
3563
		p->subscribed = NONE;
2706
		append_history(p, "Subscribestatus", "timeout");
3564
		append_history(p, "Subscribestatus", "timeout");
2707
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3565
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
2708
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3566
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
[+20] [20] 15 lines
[+20] static int __sip_autodestruct(const void *data)
2724
			/* They've had their chance to respond. Time to bail */
3582
			/* They've had their chance to respond. Time to bail */
2725
			__sip_pretend_ack(p);
3583
			__sip_pretend_ack(p);
2726
		}
3584
		}
2727
	}
3585
	}
2728

    
   
3586

   
2729
	if (p->subscribed == MWI_NOTIFICATION) {

   
2730
		if (p->relatedpeer) {
3587
	if (p->relatedpeer) {
2731
			p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");	/* Remove link to peer. If it's realtime, make sure it's gone from memory) */
3588
		p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");	/* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2732
		}
3589
	}
2733
	}

   
2734

    
   
3590

   
2735
	/* Reset schedule ID */
3591
	/* Reset schedule ID */
2736
	p->autokillid = -1;
3592
	p->autokillid = -1;
2737

    
   
3593

   
2738
	if (p->owner) {
3594
	if (p->owner) {
[+20] [20] 14 lines
[+20] static int __sip_autodestruct(const void *data)
2753
	}
3609
	}
2754
	dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3610
	dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
2755
	return 0;
3611
	return 0;
2756
}
3612
}
2757

    
   
3613

   

    
   
3614
/*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.

    
   
3615
 *  This function is used to keep a dialog around for a period of time in order

    
   
3616
 *  to properly respond to any retransmits. */

    
   
3617
void sip_scheddestroy_final(struct sip_pvt *p, int ms)

    
   
3618
{

    
   
3619
	if (p->final_destruction_scheduled) {

    
   
3620
		return; /* already set final destruction */

    
   
3621
	}

    
   
3622

   

    
   
3623
	sip_scheddestroy(p, ms);

    
   
3624
	if (p->autokillid != -1) {

    
   
3625
		p->final_destruction_scheduled = 1;

    
   
3626
	}

    
   
3627
}

    
   
3628

   
2758
/*! \brief Schedule destruction of SIP dialog */
3629
/*! \brief Schedule destruction of SIP dialog */
2759
void sip_scheddestroy(struct sip_pvt *p, int ms)
3630
void sip_scheddestroy(struct sip_pvt *p, int ms)
2760
{
3631
{

    
   
3632
	if (p->final_destruction_scheduled) {

    
   
3633
		return; /* already set final destruction */

    
   
3634
	}

    
   
3635

   
2761
	if (ms < 0) {
3636
	if (ms < 0) {
2762
		if (p->timer_t1 == 0) {
3637
		if (p->timer_t1 == 0) {
2763
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3638
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
2764
		}
3639
		}
2765
		if (p->timer_b == 0) {
3640
		if (p->timer_b == 0) {
2766
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3641
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
2767
		}
3642
		}
2768
		ms = p->timer_t1 * 64;
3643
		ms = p->timer_t1 * 64;
2769
	}
3644
	}
2770
	if (sip_debug_test_pvt(p))
3645
	if (sip_debug_test_pvt(p)) {
2771
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3646
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2772
	if (sip_cancel_destroy(p))
3647
	}

    
   
3648
	if (sip_cancel_destroy(p)) {
2773
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3649
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");

    
   
3650
	}
2774

    
   
3651

   
2775
	if (p->do_history)
3652
	if (p->do_history) {
2776
		append_history(p, "SchedDestroy", "%d ms", ms);
3653
		append_history(p, "SchedDestroy", "%d ms", ms);

    
   
3654
	}
2777
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3655
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
2778

    
   
3656

   
2779
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
3657
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
2780
		stop_session_timer(p);
3658
		stop_session_timer(p);
2781
}
3659
	}

    
   
3660
}
2782

    
   
3661

   
2783
/*! \brief Cancel destruction of SIP dialog.
3662
/*! \brief Cancel destruction of SIP dialog.
2784
 * Be careful as this also absorbs the reference - if you call it
3663
 * Be careful as this also absorbs the reference - if you call it
2785
 * from within the scheduler, this might be the last reference.
3664
 * from within the scheduler, this might be the last reference.
2786
 */
3665
 */
2787
int sip_cancel_destroy(struct sip_pvt *p)
3666
int sip_cancel_destroy(struct sip_pvt *p)
2788
{
3667
{
2789
	int res = 0;
3668
	int res = 0;

    
   
3669

   

    
   
3670
	if (p->final_destruction_scheduled) {

    
   
3671
		return res;

    
   
3672
	}

    
   
3673

   
2790
	if (p->autokillid > -1) {
3674
	if (p->autokillid > -1) {
2791
		int res3;
3675
		int res3;
2792

    
   
3676

   
2793
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3677
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
2794
			append_history(p, "CancelDestroy", "");
3678
			append_history(p, "CancelDestroy", "");
[+20] [20] 20 lines
[+20] [+] int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2815
	if (p->outboundproxy && !p->outboundproxy->force){
3699
	if (p->outboundproxy && !p->outboundproxy->force){
2816
		ref_proxy(p, NULL);
3700
		ref_proxy(p, NULL);
2817
	}
3701
	}
2818

    
   
3702

   
2819
	for (cur = p->packets; cur; prev = cur, cur = cur->next) {
3703
	for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2820
		if (cur->seqno != seqno || cur->is_resp != resp)
3704
		if (cur->seqno != seqno || cur->is_resp != resp) {
2821
			continue;
3705
			continue;

    
   
3706
		}
2822
		if (cur->is_resp || cur->method == sipmethod) {
3707
		if (cur->is_resp || cur->method == sipmethod) {
2823
			res = TRUE;
3708
			res = TRUE;
2824
			msg = "Found";
3709
			msg = "Found";
2825
			if (!resp && (seqno == p->pendinginvite)) {
3710
			if (!resp && (seqno == p->pendinginvite)) {
2826
				ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
3711
				ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
[+20] [20] 24 lines
[+20] int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2851
				usleep(1);
3736
				usleep(1);
2852
				sip_pvt_lock(p);
3737
				sip_pvt_lock(p);
2853
			}
3738
			}
2854
			UNLINK(cur, p->packets, prev);
3739
			UNLINK(cur, p->packets, prev);
2855
			dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
3740
			dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
2856
			if (cur->data)
3741
			if (cur->data) {
2857
				ast_free(cur->data);
3742
				ast_free(cur->data);

    
   
3743
			}
2858
			ast_free(cur);
3744
			ast_free(cur);
2859
			break;
3745
			break;
2860
		}
3746
		}
2861
	}
3747
	}
2862
	ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3748
	ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
[+20] [20] 47 lines
[+20] [+] int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2910
static void parse_copy(struct sip_request *dst, const struct sip_request *src)
3796
static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2911
{
3797
{
2912
	copy_request(dst, src);
3798
	copy_request(dst, src);
2913
	parse_request(dst);
3799
	parse_request(dst);
2914
}
3800
}
2915

    
   
3801

   
2916
/*! \brief add a blank line if no body */
3802
/*! \brief add a blank line if no body */
2917
static void add_blank(struct sip_request *req)
3803
static void add_blank(struct sip_request *req)
2918
{
3804
{
2919
	if (!req->lines) {
3805
	if (!req->lines) {
2920
		/* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
3806
		/* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2921
		ast_str_append(&req->data, 0, "\r\n");
3807
		ast_str_append(&req->data, 0, "\r\n");
2922
		req->len = ast_str_strlen(req->data);
3808
		req->len = ast_str_strlen(req->data);
2923
	}
3809
	}
2924
}
3810
}
2925

    
   
3811

   
2926
static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
3812
static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
2927
{
3813
{
2928
	const char *msg = NULL;
3814
	const char *msg = NULL;
2929

    
   
3815

   
2930
	if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
3816
	if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
2931
		msg = "183 Session Progress";
3817
		msg = "183 Session Progress";
2932
	}
3818
	}
2933

    
   
3819

   
2934
	if (pvt->invitestate < INV_COMPLETED) {
3820
	if (pvt->invitestate < INV_COMPLETED) {
2935
		if (with_sdp) {
3821
		if (with_sdp) {
2936
			transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
3822
			transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
2937
		} else {
3823
		} else {
2938
			transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
3824
			transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
2939
		}
3825
		}
2940
		return PROVIS_KEEPALIVE_TIMEOUT;
3826
		return PROVIS_KEEPALIVE_TIMEOUT;
2941
	}
3827
	}
2942

    
   
3828

   
2943
	return 0;
3829
	return 0;
2944
}
3830
}
2945

    
   
3831

   
2946
static int send_provisional_keepalive(const void *data) {
3832
static int send_provisional_keepalive(const void *data) {
2947
	struct sip_pvt *pvt = (struct sip_pvt *) data;
3833
	struct sip_pvt *pvt = (struct sip_pvt *) data;
2948

    
   
3834

   
2949
	return send_provisional_keepalive_full(pvt, 0);
3835
	return send_provisional_keepalive_full(pvt, 0);
2950
}
3836
}
2951

    
   
3837

   
2952
static int send_provisional_keepalive_with_sdp(const void *data) {
3838
static int send_provisional_keepalive_with_sdp(const void *data) {
2953
	struct sip_pvt *pvt = (void *)data;
3839
	struct sip_pvt *pvt = (void *)data;
2954

    
   
3840

   
2955
	return send_provisional_keepalive_full(pvt, 1);
3841
	return send_provisional_keepalive_full(pvt, 1);
2956
}
3842
}
2957

    
   
3843

   
2958
static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
3844
static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
2959
{
3845
{
2960
	AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
3846
	AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
2961

    
   
3847

   
2962
	pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
3848
	pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
2963
		with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
3849
		with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
2964
}
3850
}
2965

    
   
3851

   
2966
/*! \brief Transmit response on SIP request*/
3852
/*! \brief Transmit response on SIP request*/
2967
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3853
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2968
{
3854
{
2969
	int res;
3855
	int res;
2970

    
   
3856

   
2971
	add_blank(req);
3857
	finalize_content(req);
2972
	if (sip_debug_test_pvt(p)) {
3858
	add_blank(req);
2973
		const struct sockaddr_in *dst = sip_real_dst(p);
3859
	if (sip_debug_test_pvt(p)) {
2974

    
   
3860
		const struct ast_sockaddr *dst = sip_real_dst(p);
2975
		ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
3861

   
2976
			reliable ? "Reliably " : "", sip_nat_mode(p),
3862
		ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
2977
			ast_inet_ntoa(dst->sin_addr),
3863
			reliable ? "Reliably " : "", sip_nat_mode(p),
2978
			ntohs(dst->sin_port), req->data->str);
3864
			ast_sockaddr_stringify(dst),
2979
	}
3865
			req->data->str);
2980
	if (p->do_history) {
3866
	}
2981
		struct sip_request tmp = { .rlPart1 = 0, };
3867
	if (p->do_history) {
2982
		parse_copy(&tmp, req);
3868
		struct sip_request tmp = { .rlPart1 = 0, };
2983
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
3869
		parse_copy(&tmp, req);
2984
			(tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
3870
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
2985
		ast_free(tmp.data);
3871
			(tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
2986
	}
3872
		deinit_req(&tmp);
2987

    
   
3873
	}
2988
	/* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
3874

   
2989
	if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
3875
	/* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
2990
		AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
3876
	if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
2991
	}
3877
		AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
2992

    
   
3878
	}
2993
	res = (reliable) ?
3879

   
2994
		 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3880
	res = (reliable) ?
2995
		__sip_xmit(p, req->data, req->len);
3881
		 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2996
	ast_free(req->data);
3882
		__sip_xmit(p, req->data, req->len);
2997
	req->data = NULL;
3883
	deinit_req(req);
2998
	if (res > 0)
3884
	if (res > 0) {
2999
		return 0;
3885
		return 0;
3000
	return res;
3886
	}
3001
}
3887
	return res;
3002

    
   
3888
}
3003
/*! \brief Send SIP Request to the other part of the dialogue 
3889

   
3004
	\return see \ref __sip_xmit
3890
/*! \brief Send SIP Request to the other part of the dialogue 
3005
*/
3891
	\return see \ref __sip_xmit
3006
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3892
*/
3007
{
3893
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3008
	int res;
3894
{
3009

    
   
3895
	int res;
3010
	/* If we have an outbound proxy, reset peer address
3896

   
3011
		Only do this once.
3897
	/* If we have an outbound proxy, reset peer address
3012
	*/
3898
		Only do this once.
3013
	if (p->outboundproxy) {
3899
	*/
3014
		p->sa = p->outboundproxy->ip;
3900
	if (p->outboundproxy) {
3015
	}
3901
		p->sa = p->outboundproxy->ip;
3016

    
   
3902
	}
3017
	add_blank(req);
3903

   
3018
	if (sip_debug_test_pvt(p)) {
3904
	finalize_content(req);
3019
		if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT))
3905
	add_blank(req);
3020
			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->str);
3906
	if (sip_debug_test_pvt(p)) {
3021
		else
3907
		if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
3022
			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->str);
3908
			ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
3023
	}
3909
		} else {

    
   
3910
			ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);

    
   
3911
		}

    
   
3912
	}
3024
	if (p->do_history) {
3913
	if (p->do_history) {
3025
		struct sip_request tmp = { .rlPart1 = 0, };
3914
		struct sip_request tmp = { .rlPart1 = 0, };
3026
		parse_copy(&tmp, req);
3915
		parse_copy(&tmp, req);
3027
		append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
3916
		append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
3028
		ast_free(tmp.data);
3917
		deinit_req(&tmp);
3029
	}
3918
	}
3030
	res = (reliable) ?
3919
	res = (reliable) ?
3031
		__sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3920
		__sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3032
		__sip_xmit(p, req->data, req->len);
3921
		__sip_xmit(p, req->data, req->len);
3033
	if (req->data) {
3922
	deinit_req(req);
3034
		ast_free(req->data);
Moved to 9333

   
3035
		req->data = NULL;
Moved to 9334

   
3036
	}

   
3037
	return res;
3923
	return res;
3038
}
3924
}
3039

    
   
3925

   
3040
static void enable_dsp_detect(struct sip_pvt *p)
3926
static void enable_dsp_detect(struct sip_pvt *p)
3041
{
3927
{
[+20] [20] 8 lines
[+20] static void enable_dsp_detect(struct sip_pvt *p)
3050
		if (!p->rtp || ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND)) {
3936
		if (!p->rtp || ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND)) {
3051
			features |= DSP_FEATURE_DIGIT_DETECT;
3937
			features |= DSP_FEATURE_DIGIT_DETECT;
3052
                }
3938
                }
3053
	}
3939
	}
3054

    
   
3940

   
3055
	if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) {
3941
	if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
3056
		features |= DSP_FEATURE_FAX_DETECT;
3942
		features |= DSP_FEATURE_FAX_DETECT;
3057
	}
3943
	}
3058

    
   
3944

   
3059
	if (!features) {
3945
	if (!features) {
3060
		return;
3946
		return;
[+20] [20] 45 lines
[+20] [+] static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
3106
				disable_dsp_detect(p);
3992
				disable_dsp_detect(p);
3107
			}
3993
			}
3108
			res = 0;
3994
			res = 0;
3109
		}
3995
		}
3110
		break;
3996
		break;

    
   
3997
	case AST_OPTION_SECURE_SIGNALING:

    
   
3998
		p->req_secure_signaling = *(unsigned int *) data;

    
   
3999
		res = 0;

    
   
4000
		break;

    
   
4001
	case AST_OPTION_SECURE_MEDIA:

    
   
4002
		ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);

    
   
4003
		res = 0;

    
   
4004
		break;
3111
	default:
4005
	default:

    
   
4006
		ast_log(LOG_NOTICE, "Unknown option: %d\n", option);
3112
		break;
4007
		break;
3113
	}
4008
	}
3114

    
   
4009

   
3115
	return res;
4010
	return res;
3116
}
4011
}
[+20] [20] 40 lines
[+20] [+] static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
3157
	case AST_OPTION_DIGIT_DETECT:
4052
	case AST_OPTION_DIGIT_DETECT:
3158
		cp = (char *) data;
4053
		cp = (char *) data;
3159
		*cp = p->dsp ? 1 : 0;
4054
		*cp = p->dsp ? 1 : 0;
3160
		ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
4055
		ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
3161
		break;
4056
		break;

    
   
4057
	case AST_OPTION_SECURE_SIGNALING:

    
   
4058
		*((unsigned int *) data) = p->req_secure_signaling;

    
   
4059
		res = 0;

    
   
4060
		break;

    
   
4061
	case AST_OPTION_SECURE_MEDIA:

    
   
4062
		*((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;

    
   
4063
		res = 0;

    
   
4064
		break;

    
   
4065
	case AST_OPTION_DEVICE_NAME:

    
   
4066
		if (p && p->outgoing_call) {

    
   
4067
			cp = (char *) data;

    
   
4068
			ast_copy_string(cp, p->dialstring, *datalen);

    
   
4069
			res = 0;

    
   
4070
		}

    
   
4071
		/* We purposely break with a return of -1 in the

    
   
4072
		 * implied else case here

    
   
4073
		 */

    
   
4074
		break;
3162
	default:
4075
	default:
3163
		break;
4076
		break;
3164
	}
4077
	}
3165

    
   
4078

   
3166
	return res;
4079
	return res;
[+20] [20] 80 lines
[+20] [+] static int sip_sendtext(struct ast_channel *ast, const char *text)
3247
/*! \brief Update peer object in realtime storage
4160
/*! \brief Update peer object in realtime storage
3248
	If the Asterisk system name is set in asterisk.conf, we will use
4161
	If the Asterisk system name is set in asterisk.conf, we will use
3249
	that name and store that in the "regserver" field in the sippeers
4162
	that name and store that in the "regserver" field in the sippeers
3250
	table to facilitate multi-server setups.
4163
	table to facilitate multi-server setups.
3251
*/
4164
*/
3252
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms)
4165
static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms)
3253
{
4166
{
3254
	char port[10];
4167
	char port[10];
3255
	char ipaddr[INET_ADDRSTRLEN];
4168
	char ipaddr[INET_ADDRSTRLEN];
3256
	char regseconds[20];
4169
	char regseconds[20];
3257
	char *tablename = NULL;
4170
	char *tablename = NULL;
[+20] [20] 10 lines
[+20] static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms) [+] static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms)
3268
	tablename = realtimeregs ? "sipregs" : "sippeers";
4181
	tablename = realtimeregs ? "sipregs" : "sippeers";
3269
	
4182
	
3270

    
   
4183

   
3271
	snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
4184
	snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
3272
	snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);	/* Expiration time */
4185
	snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);	/* Expiration time */
3273
	ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
4186
	ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
3274
	snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
4187
	ast_copy_string(port, ast_sockaddr_stringify_port(addr), sizeof(port));
3275
	
4188

   
3276
	if (ast_strlen_zero(sysname))	/* No system name, disable this */
4189
	if (ast_strlen_zero(sysname))	/* No system name, disable this */
3277
		sysname = NULL;
4190
		sysname = NULL;
3278
	else if (sip_cfg.rtsave_sysname)
4191
	else if (sip_cfg.rtsave_sysname)
3279
		syslabel = "regserver";
4192
		syslabel = "regserver";
3280

    
   
4193

   
[+20] [20] 50 lines
[+20] [+] static void register_peer_exten(struct sip_peer *peer, int onoff)
3331
}
4244
}
3332

    
   
4245

   
3333
/*! Destroy mailbox subscriptions */
4246
/*! Destroy mailbox subscriptions */
3334
static void destroy_mailbox(struct sip_mailbox *mailbox)
4247
static void destroy_mailbox(struct sip_mailbox *mailbox)
3335
{
4248
{
3336
	if (mailbox->mailbox)

   
3337
		ast_free(mailbox->mailbox);

   
3338
	if (mailbox->context)

   
3339
		ast_free(mailbox->context);

   
3340
	if (mailbox->event_sub)
4249
	if (mailbox->event_sub)
3341
		ast_event_unsubscribe(mailbox->event_sub);
4250
		ast_event_unsubscribe(mailbox->event_sub);
3342
	ast_free(mailbox);
4251
	ast_free(mailbox);
3343
}
4252
}
3344

    
   
4253

   
[+20] [20] 36 lines
[+20] [+] static void sip_destroy_peer(struct sip_peer *peer)
3381
		peer->chanvars = NULL;
4290
		peer->chanvars = NULL;
3382
	}
4291
	}
3383
	
4292
	
3384
	register_peer_exten(peer, FALSE);
4293
	register_peer_exten(peer, FALSE);
3385
	ast_free_ha(peer->ha);
4294
	ast_free_ha(peer->ha);

    
   
4295
	ast_free_ha(peer->directmediaha);
3386
	if (peer->selfdestruct)
4296
	if (peer->selfdestruct)
3387
		ast_atomic_fetchadd_int(&apeerobjs, -1);
4297
		ast_atomic_fetchadd_int(&apeerobjs, -1);
3388
	else if (peer->is_realtime) {
4298
	else if (peer->is_realtime) {
3389
		ast_atomic_fetchadd_int(&rpeerobjs, -1);
4299
		ast_atomic_fetchadd_int(&rpeerobjs, -1);
3390
		ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
4300
		ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
[+20] [20] 8 lines
[+20] static void sip_destroy_peer(struct sip_peer *peer)
3399
	if (peer->socket.tcptls_session) {
4309
	if (peer->socket.tcptls_session) {
3400
		ao2_ref(peer->socket.tcptls_session, -1);
4310
		ao2_ref(peer->socket.tcptls_session, -1);
3401
		peer->socket.tcptls_session = NULL;
4311
		peer->socket.tcptls_session = NULL;
3402
	}
4312
	}
3403

    
   
4313

   

    
   
4314
	ast_cc_config_params_destroy(peer->cc_params);

    
   
4315

   
3404
	ast_string_field_free_memory(peer);
4316
	ast_string_field_free_memory(peer);
3405
}
4317
}
3406

    
   
4318

   
3407
/*! \brief Update peer data in database (if used) */
4319
/*! \brief Update peer data in database (if used) */
3408
static void update_peer(struct sip_peer *p, int expire)
4320
static void update_peer(struct sip_peer *p, int expire)
[+20] [20] 36 lines
[+20] [+] static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
3445
 * Checks the "sippeers" realtime family from extconfig.conf
4357
 * Checks the "sippeers" realtime family from extconfig.conf
3446
 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
4358
 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
3447
 * This returns a pointer to a peer and because we use build_peer, we can rest
4359
 * This returns a pointer to a peer and because we use build_peer, we can rest
3448
 * assured that the refcount is bumped.
4360
 * assured that the refcount is bumped.
3449
*/
4361
*/
3450
static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
4362
static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only)
3451
{
4363
{
3452
	struct sip_peer *peer;
4364
	struct sip_peer *peer;
3453
	struct ast_variable *var = NULL;
4365
	struct ast_variable *var = NULL;
3454
	struct ast_variable *varregs = NULL;
4366
	struct ast_variable *varregs = NULL;
3455
	struct ast_variable *tmp;
4367
	struct ast_variable *tmp;
3456
	struct ast_config *peerlist = NULL;
4368
	struct ast_config *peerlist = NULL;
3457
	char ipaddr[INET_ADDRSTRLEN];
4369
	char ipaddr[INET_ADDRSTRLEN];
3458
	char portstring[6]; /*up to 5 digits plus null terminator*/
4370
	char portstring[6]; /*up to 5 digits plus null terminator*/
3459
	char *cat = NULL;
4371
	char *cat = NULL;
3460
	unsigned short portnum;

   
3461
	int realtimeregs = ast_check_realtime("sipregs");
4372
	int realtimeregs = ast_check_realtime("sipregs");
3462

    
   
4373

   
3463
	/* First check on peer name */
4374
	/* First check on peer name */
3464
	if (newpeername) {
4375
	if (newpeername) {
3465
		if (realtimeregs)
4376
		if (realtimeregs)
3466
			varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
4377
			varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
3467

    
   
4378

   
3468
		var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
4379
		var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
3469
		if (!var && sin)
4380
		if (!var && addr) {
3470
			var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
4381
			var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_sockaddr_stringify_addr(addr), SENTINEL);

    
   
4382
		}
3471
		if (!var) {
4383
		if (!var) {
3472
			var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
4384
			var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
3473
			/*!\note
4385
			/*!\note
3474
			 * If this one loaded something, then we need to ensure that the host
4386
			 * If this one loaded something, then we need to ensure that the host
3475
			 * field matched.  The only reason why we can't have this as a criteria
4387
			 * field matched.  The only reason why we can't have this as a criteria
3476
			 * is because we only have the IP address and the host field might be
4388
			 * is because we only have the IP address and the host field might be
3477
			 * set as a name (and the reverse PTR might not match).
4389
			 * set as a name (and the reverse PTR might not match).
3478
			 */
4390
			 */
3479
			if (var && sin) {
4391
			if (var && addr) {
3480
				for (tmp = var; tmp; tmp = tmp->next) {
4392
				for (tmp = var; tmp; tmp = tmp->next) {
3481
					if (!strcasecmp(tmp->name, "host")) {
4393
					if (!strcasecmp(tmp->name, "host")) {
3482
						struct hostent *hp;
4394
						struct ast_sockaddr *addrs = NULL;
3483
						struct ast_hostent ahp;
4395

   
3484
						if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
4396
						if (ast_sockaddr_resolve(&addrs,

    
   
4397
									 tmp->value,

    
   
4398
									 PARSE_PORT_FORBID,

    
   
4399
									 get_address_family_filter(&bindaddr)) <= 0 ||

    
   
4400
						    ast_sockaddr_cmp(&addrs[0], addr)) {
3485
							/* No match */
4401
							/* No match */
3486
							ast_variables_destroy(var);
4402
							ast_variables_destroy(var);
3487
							var = NULL;
4403
							var = NULL;
3488
						}
4404
						}

    
   
4405
						ast_free(addrs);
3489
						break;
4406
						break;
3490
					}
4407
					}
3491
				}
4408
				}
3492
			}
4409
			}
3493
		}
4410
		}
3494
	}
4411
	}
3495

    
   
4412

   
3496
	if (!var && sin) {	/* Then check on IP address for dynamic peers */
4413
	if (!var && addr) {	/* Then check on IP address for dynamic peers */
3497
		ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
4414
		ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
3498
		portnum = ntohs(sin->sin_port);
4415
		ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
3499
		sprintf(portstring, "%u", portnum);

   
3500
		var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);	/* First check for fixed IP hosts */
4416
		var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);	/* First check for fixed IP hosts */
3501
		if (var) {
4417
		if (var) {
3502
			if (realtimeregs) {
4418
			if (realtimeregs) {
3503
				newpeername = get_name_from_variable(var, newpeername);
4419
				newpeername = get_name_from_variable(var, newpeername);
3504
				varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
4420
				varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
[+20] [20] 60 lines
[+20] static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only) [+] static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only)
3565
			ast_config_destroy(peerlist);
4481
			ast_config_destroy(peerlist);
3566
		return NULL;
4482
		return NULL;
3567
	}
4483
	}
3568

    
   
4484

   
3569
	for (tmp = var; tmp; tmp = tmp->next) {
4485
	for (tmp = var; tmp; tmp = tmp->next) {
3570
		/* If this is type=user, then skip this object. */
4486
		if (!newpeername && !strcasecmp(tmp->name, "name")) {
3571
		if (!strcasecmp(tmp->name, "type") &&

   
3572
		    !strcasecmp(tmp->value, "user")) {

   
3573
			if(peerlist)

   
3574
				ast_config_destroy(peerlist);

   
3575
			else {

   
3576
				ast_variables_destroy(var);

   
3577
				ast_variables_destroy(varregs);

   
3578
			}

   
3579
			return NULL;

   
3580
		} else if (!newpeername && !strcasecmp(tmp->name, "name")) {

   
3581
			newpeername = tmp->value;
4487
			newpeername = tmp->value;
3582
		}
4488
		}
3583
	}
4489
	}
3584
	
4490
	
3585
	if (!newpeername) {	/* Did not find peer in realtime */
4491
	if (!newpeername) {	/* Did not find peer in realtime */
[+20] [20] 28 lines
[+20] static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only) [+] static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only)
3614
					unref_peer(_data, "remove registration ref"),
4520
					unref_peer(_data, "remove registration ref"),
3615
					unref_peer(peer, "remove registration ref"),
4521
					unref_peer(peer, "remove registration ref"),
3616
					ref_peer(peer, "add registration ref"));
4522
					ref_peer(peer, "add registration ref"));
3617
		}
4523
		}
3618
		ao2_t_link(peers, peer, "link peer into peers table");
4524
		ao2_t_link(peers, peer, "link peer into peers table");
3619
		if (peer->addr.sin_addr.s_addr) {
4525
		if (!ast_sockaddr_isnull(&peer->addr)) {
3620
			ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
4526
			ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
3621
		}
4527
		}
3622
	}
4528
	}
3623
	peer->is_realtime = 1;
4529
	peer->is_realtime = 1;
3624
	if (peerlist)
4530
	if (peerlist)
[+20] [20] 35 lines
[+20] [+] static int find_by_name(void *obj, void *arg, void *data, int flags)
3660
	return CMP_MATCH | CMP_STOP;
4566
	return CMP_MATCH | CMP_STOP;
3661
}
4567
}
3662

    
   
4568

   
3663
/*!
4569
/*!
3664
 * \brief Locate device by name or ip address
4570
 * \brief Locate device by name or ip address
3665
 *
4571
 * \param peer, sin, realtime, devstate_only, transport
3666
 * \param which_objects Define which objects should be matched when doing a lookup
4572
 * \param which_objects Define which objects should be matched when doing a lookup
3667
 *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
4573
 *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
3668
 *        Note that this option is not used at all when doing a lookup by IP.
4574
 *        Note that this option is not used at all when doing a lookup by IP.
3669
 *
4575
 *
3670
 *	This is used on find matching device on name or ip/port.
4576
 *	This is used on find matching device on name or ip/port.
3671
 * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
4577
 * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
3672
 *
4578
 *
3673
 * \note Avoid using this function in new functions if there is a way to avoid it,
4579
 * \note Avoid using this function in new functions if there is a way to avoid it,
3674
 * since it might cause a database lookup.
4580
 * since it might cause a database lookup.
3675
 */
4581
 */
3676
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
4582
static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
3677
{
4583
{
3678
	struct sip_peer *p = NULL;
4584
	struct sip_peer *p = NULL;
3679
	struct sip_peer tmp_peer;
4585
	struct sip_peer tmp_peer;
3680

    
   
4586

   
3681
	if (peer) {
4587
	if (peer) {
3682
		ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
4588
		ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
3683
		p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
4589
		p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
3684
	} else if (sin) { /* search by addr? */
4590
	} else if (addr) { /* search by addr? */
3685
		tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
4591
		ast_sockaddr_copy(&tmp_peer.addr, addr);
3686
		tmp_peer.addr.sin_port = sin->sin_port;

   
3687
		tmp_peer.flags[0].flags = 0;
4592
		tmp_peer.flags[0].flags = 0;
3688
		tmp_peer.transports = transport;
4593
		tmp_peer.transports = transport;
3689
		p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
4594
		p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
3690
		if (!p) {
4595
		if (!p) {
3691
			ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
4596
			ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
3692
			p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
4597
			p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
3693
			if (p) {
4598
			if (p) {
3694
				return p;
4599
				return p;
3695
			}
4600
			}
3696
		}
4601
		}
3697
	}
4602
	}
3698

    
   
4603

   
3699
	if (!p && (realtime || devstate_only)) {
4604
	if (!p && (realtime || devstate_only)) {
3700
		p = realtime_peer(peer, sin, devstate_only);
4605
		p = realtime_peer(peer, addr, devstate_only);

    
   
4606
		if (p) {

    
   
4607
			switch (which_objects) {

    
   
4608
			case FINDUSERS:

    
   
4609
				if (!(p->type & SIP_TYPE_USER)) {

    
   
4610
					unref_peer(p, "Wrong type of realtime SIP endpoint");
Moved from 2075

    
   
4611
					return NULL;
Moved from 2076

    
   
4612
				}

    
   
4613
				break;

    
   
4614
			case FINDPEERS:

    
   
4615
				if (!(p->type & SIP_TYPE_PEER)) {

    
   
4616
					unref_peer(p, "Wrong type of realtime SIP endpoint");
Moved from 2075

    
   
4617
					return NULL;
Moved from 2076

    
   
4618
				}

    
   
4619
				break;

    
   
4620
			case FINDALLDEVICES:

    
   
4621
				break;

    
   
4622
			}

    
   
4623
		}
3701
	}
4624
	}
3702

    
   
4625

   
3703
	return p;
4626
	return p;
3704
}
4627
}
3705

    
   
4628

   
[+20] [20] 104 lines
[+20] [+] static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
3810
/*! \brief Initialize RTP portion of a dialog
4733
/*! \brief Initialize RTP portion of a dialog
3811
 * \return -1 on failure, 0 on success
4734
 * \return -1 on failure, 0 on success
3812
 */
4735
 */
3813
static int dialog_initialize_rtp(struct sip_pvt *dialog)
4736
static int dialog_initialize_rtp(struct sip_pvt *dialog)
3814
{
4737
{

    
   
4738
	struct ast_sockaddr bindaddr_tmp;

    
   
4739

   
3815
	if (!sip_methods[dialog->method].need_rtp) {
4740
	if (!sip_methods[dialog->method].need_rtp) {
3816
		return 0;
4741
		return 0;
3817
	}
4742
	}
3818

    
   
4743

   
3819
	if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr, NULL))) {
4744
	ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);

    
   
4745
	if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
3820
		return -1;
4746
		return -1;
3821
	}
4747
	}
3822

    
   
4748

   
3823
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK)) {
4749
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
3824
		if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr, NULL))) {
4750
			(ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {

    
   
4751
		if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
3825
			return -1;
4752
			return -1;
3826
		}
4753
		}
3827
		ast_rtp_instance_set_timeout(dialog->vrtp, global_rtptimeout);
4754
		ast_rtp_instance_set_timeout(dialog->vrtp, global_rtptimeout);
3828
		ast_rtp_instance_set_hold_timeout(dialog->vrtp, global_rtpholdtimeout);
4755
		ast_rtp_instance_set_hold_timeout(dialog->vrtp, global_rtpholdtimeout);
3829

    
   
4756

   
3830
		ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
4757
		ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
3831
	}
4758
	}
3832

    
   
4759

   
3833
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
4760
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
3834
		if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr, NULL))) {
4761
		if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
3835
			return -1;
4762
			return -1;
3836
		}
4763
		}
3837
		ast_rtp_instance_set_timeout(dialog->trtp, global_rtptimeout);
4764
		ast_rtp_instance_set_timeout(dialog->trtp, global_rtptimeout);
3838
		ast_rtp_instance_set_hold_timeout(dialog->trtp, global_rtpholdtimeout);
4765
		ast_rtp_instance_set_hold_timeout(dialog->trtp, global_rtpholdtimeout);
3839

    
   
4766

   
[+20] [20] 21 lines
[+20] static int dialog_initialize_rtp(struct sip_pvt *dialog)
3861
 * \return -1 on error, 0 on success.
4788
 * \return -1 on error, 0 on success.
3862
 *
4789
 *
3863
 */
4790
 */
3864
static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
4791
static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
3865
{
4792
{
3866

    
   

   
3867
	/* this checks that the dialog is contacting the peer on a valid
4793
	/* this checks that the dialog is contacting the peer on a valid
3868
	 * transport type based on the peers transport configuration,
4794
	 * transport type based on the peers transport configuration,
3869
	 * otherwise, this function bails out */
4795
	 * otherwise, this function bails out */
3870
	if (dialog->socket.type && check_request_transport(peer, dialog))
4796
	if (dialog->socket.type && check_request_transport(peer, dialog))
3871
		return -1;
4797
		return -1;
3872
	copy_socket_data(&dialog->socket, &peer->socket);
4798
	copy_socket_data(&dialog->socket, &peer->socket);
3873

    
   
4799

   
3874
	if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
4800
	if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
3875
	    (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
4801
	    (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
3876
		dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
4802
		dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
3877
		dialog->recv = dialog->sa;
4803
		dialog->recv = dialog->sa;
3878
	} else
4804
	} else
3879
		return -1;
4805
		return -1;
3880

    
   
4806

   

    
   
4807
	/* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
3881
	ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
4808
	ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
3882
	ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
4809
	ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);

    
   
4810
	ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
3883
	dialog->capability = peer->capability;
4811
	dialog->capability = peer->capability;
3884
	dialog->prefs = peer->prefs;
4812
	dialog->prefs = peer->prefs;
3885
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
4813
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
3886
		if (!dialog->udptl) {

   
3887
			/* t38pt_udptl was enabled in the peer and not in [general] */
4814
		/* t38pt_udptl was enabled in the peer and not in [general] */
3888
			dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
4815
		if (dialog->udptl || (!dialog->udptl && (dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr)))) {
3889
		}

   
3890
		dialog->t38_maxdatagram = peer->t38_maxdatagram;
4816
			dialog->t38_maxdatagram = peer->t38_maxdatagram;
3891
		set_t38_capabilities(dialog);
4817
			set_t38_capabilities(dialog);

    
   
4818
		} else {

    
   
4819
			/* It is impossible to support T38 without udptl */

    
   
4820
			ast_debug(1, "UDPTL creation failed on dialog.\n");

    
   
4821
			ast_clear_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT);

    
   
4822
		}
3892
	} else if (dialog->udptl) {
4823
	} else if (dialog->udptl) {
3893
		ast_udptl_destroy(dialog->udptl);
4824
		ast_udptl_destroy(dialog->udptl);
3894
		dialog->udptl = NULL;
4825
		dialog->udptl = NULL;
3895
	}
4826
	}
3896

    
   
4827

   
[+20] [20] 19 lines
[+20] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
3916
	if (dialog->trtp) { /* Realtime text */
4847
	if (dialog->trtp) { /* Realtime text */
3917
		ast_rtp_instance_set_timeout(dialog->trtp, peer->rtptimeout);
4848
		ast_rtp_instance_set_timeout(dialog->trtp, peer->rtptimeout);
3918
		ast_rtp_instance_set_hold_timeout(dialog->trtp, peer->rtpholdtimeout);
4849
		ast_rtp_instance_set_hold_timeout(dialog->trtp, peer->rtpholdtimeout);
3919
	}
4850
	}
3920

    
   
4851

   

    
   
4852
	/* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
3921
	ast_string_field_set(dialog, peername, peer->name);
4853
	ast_string_field_set(dialog, peername, peer->name);
3922
	ast_string_field_set(dialog, authname, peer->username);
4854
	ast_string_field_set(dialog, authname, peer->username);
3923
	ast_string_field_set(dialog, username, peer->username);
4855
	ast_string_field_set(dialog, username, peer->username);
3924
	ast_string_field_set(dialog, peersecret, peer->secret);
4856
	ast_string_field_set(dialog, peersecret, peer->secret);
3925
	ast_string_field_set(dialog, peermd5secret, peer->md5secret);
4857
	ast_string_field_set(dialog, peermd5secret, peer->md5secret);
3926
	ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
4858
	ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
3927
	ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
4859
	ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
3928
	ast_string_field_set(dialog, tohost, peer->tohost);
4860
	ast_string_field_set(dialog, tohost, peer->tohost);
3929
	ast_string_field_set(dialog, fullcontact, peer->fullcontact);
4861
	ast_string_field_set(dialog, fullcontact, peer->fullcontact);
3930
	ast_string_field_set(dialog, accountcode, peer->accountcode);
4862
	ast_string_field_set(dialog, accountcode, peer->accountcode);
3931
	ast_string_field_set(dialog, context, peer->context);
4863
	ast_string_field_set(dialog, context, peer->context);
3932
	ast_string_field_set(dialog, cid_num, peer->cid_num);
4864
	ast_string_field_set(dialog, cid_num, peer->cid_num);
3933
	ast_string_field_set(dialog, cid_name, peer->cid_name);
4865
	ast_string_field_set(dialog, cid_name, peer->cid_name);

    
   
4866
	ast_string_field_set(dialog, cid_tag, peer->cid_tag);
3934
	ast_string_field_set(dialog, mwi_from, peer->mwi_from);
4867
	ast_string_field_set(dialog, mwi_from, peer->mwi_from);
3935
	ast_string_field_set(dialog, parkinglot, peer->parkinglot);
4868
	ast_string_field_set(dialog, parkinglot, peer->parkinglot);
3936
	ast_string_field_set(dialog, engine, peer->engine);
4869
	ast_string_field_set(dialog, engine, peer->engine);
3937
	ref_proxy(dialog, obproxy_get(dialog, peer));
4870
	ref_proxy(dialog, obproxy_get(dialog, peer));
3938
	dialog->callgroup = peer->callgroup;
4871
	dialog->callgroup = peer->callgroup;
3939
	dialog->pickupgroup = peer->pickupgroup;
4872
	dialog->pickupgroup = peer->pickupgroup;
3940
	dialog->allowtransfer = peer->allowtransfer;
4873
	dialog->allowtransfer = peer->allowtransfer;
3941
	dialog->jointnoncodeccapability = dialog->noncodeccapability;
4874
	dialog->jointnoncodeccapability = dialog->noncodeccapability;
3942
	dialog->rtptimeout = peer->rtptimeout;
4875
	dialog->rtptimeout = peer->rtptimeout;
3943
	dialog->peerauth = peer->auth;
4876
	dialog->peerauth = peer->auth;
3944
	dialog->maxcallbitrate = peer->maxcallbitrate;
4877
	dialog->maxcallbitrate = peer->maxcallbitrate;
3945
	dialog->disallowed_methods = peer->disallowed_methods;
4878
	dialog->disallowed_methods = peer->disallowed_methods;

    
   
4879
	ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
3946
	if (ast_strlen_zero(dialog->tohost))
4880
	if (ast_strlen_zero(dialog->tohost))
3947
		ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
4881
		ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host(&dialog->sa));
3948
	if (!ast_strlen_zero(peer->fromdomain)) {
4882
	if (!ast_strlen_zero(peer->fromdomain)) {
3949
		ast_string_field_set(dialog, fromdomain, peer->fromdomain);
4883
		ast_string_field_set(dialog, fromdomain, peer->fromdomain);
3950
		if (!dialog->initreq.headers) {
4884
		if (!dialog->initreq.headers) {
3951
			char *c;
4885
			char *c;
3952
			char *tmpcall = ast_strdupa(dialog->callid);
4886
			char *tmpcall = ast_strdupa(dialog->callid);
[+20] [20] 30 lines
[+20] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
3983
	if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
4917
	if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
3984
	    (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
4918
	    (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
3985
		dialog->noncodeccapability |= AST_RTP_DTMF;
4919
		dialog->noncodeccapability |= AST_RTP_DTMF;
3986
	else
4920
	else
3987
		dialog->noncodeccapability &= ~AST_RTP_DTMF;
4921
		dialog->noncodeccapability &= ~AST_RTP_DTMF;

    
   
4922
	dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
3988
	if (peer->call_limit)
4923
	if (peer->call_limit)
3989
		ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
4924
		ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
3990
	if (!dialog->portinuri)
4925
	if (!dialog->portinuri)
3991
		dialog->portinuri = peer->portinuri;
4926
		dialog->portinuri = peer->portinuri;
3992
	

   
3993
	dialog->chanvars = copy_vars(peer->chanvars);
4927
	dialog->chanvars = copy_vars(peer->chanvars);

    
   
4928
	if (peer->fromdomainport)

    
   
4929
		dialog->fromdomainport = peer->fromdomainport;
3994

    
   
4930

   
3995
	return 0;
4931
	return 0;
3996
}
4932
}
3997

    
   
4933

   
3998
/*! \brief create address structure from device name
4934
/*! \brief create address structure from device name
3999
 *      Or, if peer not found, find it in the global DNS
4935
 *      Or, if peer not found, find it in the global DNS
4000
 *      returns TRUE (-1) on failure, FALSE on success */
4936
 *      returns TRUE (-1) on failure, FALSE on success */
4001
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
4937
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address)
4002
{
4938
{
4003
	struct hostent *hp;

   
4004
	struct ast_hostent ahp;

   
4005
	struct sip_peer *peer;
4939
	struct sip_peer *peer;
4006
	char *port;
4940
	char *peername, *peername2, *hostn;
4007
	int portno = 0;
4941
	char host[MAXHOSTNAMELEN];
4008
	char host[MAXHOSTNAMELEN], *hostn;
4942
	char service[MAXHOSTNAMELEN];
4009
	char peername[256];

   
4010
	int srv_ret = 0;
4943
	int srv_ret = 0;

    
   
4944
	int tportno;

    
   
4945

   

    
   
4946
	AST_DECLARE_APP_ARGS(hostport,

    
   
4947
		AST_APP_ARG(host);

    
   
4948
		AST_APP_ARG(port);

    
   
4949
	);
4011

    
   
4950

   
4012
	ast_copy_string(peername, opeer, sizeof(peername));
4951
	peername = ast_strdupa(opeer);
4013
	port = strchr(peername, ':');
4952
	peername2 = ast_strdupa(opeer);
4014
	if (port) {
4953
	AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
4015
		*port++ = '\0';
4954

   

    
   
4955
	if (hostport.port)
4016
		dialog->portinuri = 1;
4956
		dialog->portinuri = 1;
4017
	}
4957

   
4018
	dialog->sa.sin_family = AF_INET;

   
4019
	dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
4958
	dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
4020
	dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
4959
	dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
4021
	peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
4960
	peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
4022

    
   
4961

   
4023
	if (peer) {
4962
	if (peer) {
4024
		int res;
4963
		int res;
4025
		if (newdialog) {
4964
		if (newdialog) {
4026
			set_socket_transport(&dialog->socket, 0);
4965
			set_socket_transport(&dialog->socket, 0);
4027
		}
4966
		}
4028
		res = create_addr_from_peer(dialog, peer);
4967
		res = create_addr_from_peer(dialog, peer);
4029
		if (!ast_strlen_zero(port)) {
4968
		if (!ast_sockaddr_isnull(remote_address)) {
4030
			if ((portno = atoi(port))) {
4969
			ast_sockaddr_copy(&dialog->sa, remote_address);
4031
				dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);

   
4032
			}

   
4033
		}
4970
		}

    
   
4971
		dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
4034
		unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
4972
		unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
4035
		return res;
4973
		return res;
4036
	}
4974
	}
4037

    
   
4975

   
4038
	if (dialog_initialize_rtp(dialog)) {
4976
	if (dialog_initialize_rtp(dialog)) {
4039
		return -1;
4977
		return -1;
4040
	}
4978
	}
4041

    
   
4979

   
4042
	ast_string_field_set(dialog, tohost, peername);
4980
	ast_string_field_set(dialog, tohost, hostport.host);
4043
	dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
4981
	dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
4044

    
   
4982

   
4045
	/* Get the outbound proxy information */
4983
	/* Get the outbound proxy information */
4046
	ref_proxy(dialog, obproxy_get(dialog, NULL));
4984
	ref_proxy(dialog, obproxy_get(dialog, NULL));
4047

    
   
4985

   
4048
	if (sin) {
4986
	if (addr) {
4049
		/* This address should be updated using dnsmgr */
4987
		/* This address should be updated using dnsmgr */
4050
		memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
4988
		ast_sockaddr_copy(&dialog->sa, addr);
4051
		if (!sin->sin_port) {

   
4052
			portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);

   
4053
		} else {

   
4054
			portno = ntohs(sin->sin_port);

   
4055
		}

   
4056
	} else {
4989
	} else {
4057

    
   
4990

   
4058
		/* Let's see if we can find the host in DNS. First try DNS SRV records,
4991
		/* Let's see if we can find the host in DNS. First try DNS SRV records,
4059
		   then hostname lookup */
4992
		   then hostname lookup */
4060
		/*! \todo Fix this function. When we ask for SRV, we should check all transports
4993
		/*! \todo Fix this function. When we ask for SRV, we should check all transports
4061
			  In the future, we should first check NAPTR to find out transport preference
4994
			  In the future, we should first check NAPTR to find out transport preference
4062
		 */
4995
		 */
4063
		hostn = peername;
4996
		hostn = peername;
4064
 		/* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
4997
 		/* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
4065
		 * an A record lookup should be used instead of SRV.
4998
		 * an A record lookup should be used instead of SRV.
4066
		 */
4999
		 */
4067
		if (!port && sip_cfg.srvlookup) {
5000
		if (!hostport.port && sip_cfg.srvlookup) {
4068
			char service[MAXHOSTNAMELEN];
5001
			snprintf(service, sizeof(service), "_%s._%s.%s", 
4069
			int tportno;
5002
				 get_srv_service(dialog->socket.type),
4070
	
5003
				 get_srv_protocol(dialog->socket.type), peername);
4071
			snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
5004
			if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
4072
			srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
5005
						   service)) > 0) {
4073
			if (srv_ret > 0) {

   
4074
				hostn = host;
5006
				hostn = host;
4075
				portno = tportno;

   
4076
			}
5007
			}
4077
		}
5008
		}
4078
	 	if (!portno)
5009

   
4079
			portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
5010
		if (ast_sockaddr_resolve_first(&dialog->sa, hostn, 0)) {
4080
		hp = ast_gethostbyname(hostn, &ahp);

   
4081
		if (!hp) {

   
4082
			ast_log(LOG_WARNING, "No such host: %s\n", peername);
5011
			ast_log(LOG_WARNING, "No such host: %s\n", peername);
4083
			return -1;

   
4084
		}
5012
		}
4085
		memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
5013

   

    
   
5014
		if (srv_ret > 0) {

    
   
5015
			ast_sockaddr_set_port(&dialog->sa, tportno);

    
   
5016
		}
4086
	}
5017
	}
4087

    
   
5018

   
4088
	if (!dialog->socket.type)
5019
	if (!dialog->socket.type)
4089
		set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
5020
		set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
4090
	if (!dialog->socket.port)
5021
	if (!dialog->socket.port) {
4091
		dialog->socket.port = bindaddr.sin_port;
5022
		dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
4092
	dialog->sa.sin_port = htons(portno);
5023
	}
4093
	dialog->recv = dialog->sa;
5024

   

    
   
5025
	if (!ast_sockaddr_port(&dialog->sa)) {

    
   
5026
		ast_sockaddr_set_port(&dialog->sa,

    
   
5027
				      (dialog->socket.type == SIP_TRANSPORT_TLS) ?

    
   
5028
				      STANDARD_TLS_PORT : STANDARD_SIP_PORT);

    
   
5029
	}

    
   
5030
	ast_sockaddr_copy(&dialog->recv, &dialog->sa);
4094
	return 0;
5031
	return 0;
4095
}
5032
}
4096

    
   
5033

   
4097
/*! \brief Scheduled congestion on a call.
5034
/*! \brief Scheduled congestion on a call.
4098
 * Only called by the scheduler, must return the reference when done.
5035
 * Only called by the scheduler, must return the reference when done.
[+20] [20] 28 lines
[+20] [+] static int sip_call(struct ast_channel *ast, char *dest, int timeout)
4127
	int res;
5064
	int res;
4128
	struct sip_pvt *p = ast->tech_pvt;	/* chan is locked, so the reference cannot go away */
5065
	struct sip_pvt *p = ast->tech_pvt;	/* chan is locked, so the reference cannot go away */
4129
	struct varshead *headp;
5066
	struct varshead *headp;
4130
	struct ast_var_t *current;
5067
	struct ast_var_t *current;
4131
	const char *referer = NULL;   /* SIP referrer */
5068
	const char *referer = NULL;   /* SIP referrer */

    
   
5069
	int cc_core_id;

    
   
5070
	char uri[SIPBUFSIZE] = "";
4132

    
   
5071

   
4133
	if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
5072
	if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
4134
		ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
5073
		ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
4135
		return -1;
5074
		return -1;
4136
	}
5075
	}
4137

    
   
5076

   

    
   
5077
	if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {

    
   
5078
		char device_name[AST_CHANNEL_NAME];

    
   
5079
		struct ast_cc_monitor *recall_monitor;

    
   
5080
		struct sip_monitor_instance *monitor_instance;

    
   
5081
		ast_channel_get_device_name(ast, device_name, sizeof(device_name));

    
   
5082
		if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {

    
   
5083
			monitor_instance = recall_monitor->private_data;

    
   
5084
			ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));

    
   
5085
			ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");

    
   
5086
		}

    
   
5087
	}

    
   
5088

   
4138
	/* Check whether there is vxml_url, distinctive ring variables */
5089
	/* Check whether there is vxml_url, distinctive ring variables */
4139
	headp=&ast->varshead;
5090
	headp=&ast->varshead;
4140
	AST_LIST_TRAVERSE(headp, current, entries) {
5091
	AST_LIST_TRAVERSE(headp, current, entries) {
4141
		/* Check whether there is a VXML_URL variable */
5092
		/* Check whether there is a VXML_URL variable */
4142
		if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
5093
		if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
[+20] [20] 15 lines
[+20] static int sip_call(struct ast_channel *ast, char *dest, int timeout)
4158
			/* We're replacing a call. */
5109
			/* We're replacing a call. */
4159
			p->options->replaces = ast_var_value(current);
5110
			p->options->replaces = ast_var_value(current);
4160
		}
5111
		}
4161
	}
5112
	}
4162

    
   
5113

   

    
   
5114
	/* Check to see if we should try to force encryption */

    
   
5115
	if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {

    
   
5116
	   ast_log(LOG_WARNING, "Encrypted signaling is required\n");

    
   
5117
	   ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;

    
   
5118
	   return -1;

    
   
5119
	}

    
   
5120

   

    
   
5121
	if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {

    
   
5122
		if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {

    
   
5123
			ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");

    
   
5124
			ast_clear_flag(&p->flags[0], SIP_REINVITE);

    
   
5125
		}

    
   
5126

   

    
   
5127
		if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {

    
   
5128
			ast_log(LOG_WARNING, "SRTP audio setup failed\n");

    
   
5129
			return -1;

    
   
5130
		}

    
   
5131

   

    
   
5132
		if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {

    
   
5133
			ast_log(LOG_WARNING, "SRTP video setup failed\n");

    
   
5134
			return -1;

    
   
5135
		}

    
   
5136

   

    
   
5137
		if (p->trtp && !p->vsrtp && setup_srtp(&p->tsrtp) < 0) {

    
   
5138
			ast_log(LOG_WARNING, "SRTP text setup failed\n");

    
   
5139
			return -1;

    
   
5140
		}

    
   
5141
	}

    
   
5142

   
4163
	res = 0;
5143
	res = 0;
4164
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
5144
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
4165

    
   
5145

   

    
   
5146
	/* T.38 re-INVITE FAX detection should never be done for outgoing calls,

    
   
5147
	 * so ensure it is disabled.

    
   
5148
	 */

    
   
5149
	ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);

    
   
5150

   
4166
	if (p->options->transfer) {
5151
	if (p->options->transfer) {
4167
		char buf[SIPBUFSIZE/2];
5152
		char buf[SIPBUFSIZE/2];
4168

    
   
5153

   
4169
		if (referer) {
5154
		if (referer) {
4170
			if (sipdebug)
5155
			if (sipdebug)
[+20] [20] 9 lines
[+20] static int sip_call(struct ast_channel *ast, char *dest, int timeout)
4180

    
   
5165

   
4181
	if (res == -1) {
5166
	if (res == -1) {
4182
		ast->hangupcause = AST_CAUSE_USER_BUSY;
5167
		ast->hangupcause = AST_CAUSE_USER_BUSY;
4183
		return res;
5168
		return res;
4184
	}
5169
	}
4185
	p->callingpres = ast->cid.cid_pres;
5170
	p->callingpres = ast_party_id_presentation(&ast->caller.id);
4186
	p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
5171
	p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
4187
	p->jointnoncodeccapability = p->noncodeccapability;
5172
	p->jointnoncodeccapability = p->noncodeccapability;
4188

    
   
5173

   
4189
	/* If there are no audio formats left to offer, punt */
5174
	/* If there are no audio formats left to offer, punt */
4190
	if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
5175
	if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
4191
		ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
5176
		ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
4192
		res = -1;
5177
		res = -1;
4193
	} else {
5178
	} else {
4194
		int xmitres;
5179
		int xmitres;
4195

    
   
5180

   
4196
		sip_pvt_lock(p);
5181
		sip_pvt_lock(p);
4197
		xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
5182
		xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
4198
		sip_pvt_unlock(p);
5183
		sip_pvt_unlock(p);
4199
		if (xmitres == XMIT_ERROR)
5184
		if (xmitres == XMIT_ERROR)
4200
			return -1;
5185
			return -1;
4201
		p->invitestate = INV_CALLING;
5186
		p->invitestate = INV_CALLING;
4202

    
   
5187

   
[+20] [20] 123 lines
[+20] [+] void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
4326
		ast_free(p->refer);
5311
		ast_free(p->refer);
4327
	if (p->route) {
5312
	if (p->route) {
4328
		free_old_route(p->route);
5313
		free_old_route(p->route);
4329
		p->route = NULL;
5314
		p->route = NULL;
4330
	}
5315
	}
4331
	if (p->initreq.data)
5316
	deinit_req(&p->initreq);
4332
		ast_free(p->initreq.data);

   
4333

    
   
5317

   
4334
	/* Destroy Session-Timers if allocated */
5318
	/* Destroy Session-Timers if allocated */
4335
	if (p->stimer) {
5319
	if (p->stimer) {
4336
		p->stimer->quit_flag = 1;
5320
		p->stimer->quit_flag = 1;
4337
		if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
5321
		if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
[+20] [20] 22 lines
[+20] void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
4360
	if (p->chanvars) {
5344
	if (p->chanvars) {
4361
		ast_variables_destroy(p->chanvars);
5345
		ast_variables_destroy(p->chanvars);
4362
		p->chanvars = NULL;
5346
		p->chanvars = NULL;
4363
	}
5347
	}
4364

    
   
5348

   

    
   
5349
	if (p->srtp) {

    
   
5350
		sip_srtp_destroy(p->srtp);

    
   
5351
		p->srtp = NULL;

    
   
5352
	}

    
   
5353

   

    
   
5354
	if (p->vsrtp) {

    
   
5355
		sip_srtp_destroy(p->vsrtp);

    
   
5356
		p->vsrtp = NULL;

    
   
5357
	}

    
   
5358

   

    
   
5359
	if (p->tsrtp) {

    
   
5360
		sip_srtp_destroy(p->tsrtp);

    
   
5361
		p->tsrtp = NULL;

    
   
5362
	}

    
   
5363

   

    
   
5364
	if (p->directmediaha) {

    
   
5365
		ast_free_ha(p->directmediaha);

    
   
5366
		p->directmediaha = NULL;

    
   
5367
	}

    
   
5368

   
4365
	ast_string_field_free_memory(p);
5369
	ast_string_field_free_memory(p);
4366

    
   
5370

   

    
   
5371
	ast_cc_config_params_destroy(p->cc_params);

    
   
5372

   

    
   
5373
	if (p->epa_entry) {

    
   
5374
		ao2_ref(p->epa_entry, -1);

    
   
5375
		p->epa_entry = NULL;

    
   
5376
	}

    
   
5377

   
4367
	if (p->socket.tcptls_session) {
5378
	if (p->socket.tcptls_session) {
4368
		ao2_ref(p->socket.tcptls_session, -1);
5379
		ao2_ref(p->socket.tcptls_session, -1);
4369
		p->socket.tcptls_session = NULL;
5380
		p->socket.tcptls_session = NULL;
4370
	}
5381
	}
4371
}
5382
}
[+20] [20] 28 lines
[+20] [+] static int update_call_counter(struct sip_pvt *fup, int event)
4400
		return 0;
5411
		return 0;
4401

    
   
5412

   
4402
	ast_copy_string(name, fup->username, sizeof(name));
5413
	ast_copy_string(name, fup->username, sizeof(name));
4403

    
   
5414

   
4404
	/* Check the list of devices */
5415
	/* Check the list of devices */
4405
	if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) {
5416
	if (fup->relatedpeer) {

    
   
5417
		p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
4406
		inuse = &p->inUse;
5418
		inuse = &p->inUse;
4407
		call_limit = &p->call_limit;
5419
		call_limit = &p->call_limit;
4408
		inringing = &p->inRinging;
5420
		inringing = &p->inRinging;
4409
		ast_copy_string(name, fup->peername, sizeof(name));
5421
		ast_copy_string(name, fup->peername, sizeof(name));
4410
	}
5422
	}
[+20] [20] 333 lines
[+20] [+] static int sip_hangup(struct ast_channel *ast)
4744
			if (sipdebug)
5756
			if (sipdebug)
4745
				ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
5757
				ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
4746
			update_call_counter(p, DEC_CALL_LIMIT);
5758
			update_call_counter(p, DEC_CALL_LIMIT);
4747
		}
5759
		}
4748
		ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
5760
		ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
4749
		if (p->autokillid > -1 && sip_cancel_destroy(p))

   
4750
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");

   
4751
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
5761
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
4752
		ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Really hang up next time */
5762
		ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Really hang up next time */
4753
		p->needdestroy = 0;
5763
		p->needdestroy = 0;
4754
		p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
5764
		p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
4755
		sip_pvt_lock(p);
5765
		sip_pvt_lock(p);
4756
		p->owner = NULL;  /* Owner will be gone after we return, so take it away */
5766
		p->owner = NULL;  /* Owner will be gone after we return, so take it away */
4757
		sip_pvt_unlock(p);
5767
		sip_pvt_unlock(p);

    
   
5768
		ast_module_unref(ast_module_info->self);
4758
		return 0;
5769
		return 0;
4759
	}
5770
	}
4760

    
   
5771

   
4761
	if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
5772
	if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
4762
		if (p->refer)
5773
		if (p->refer)
[+20] [20] 72 lines
[+20] static int sip_hangup(struct ast_channel *ast)
4835
					needdestroy = 0;
5846
					needdestroy = 0;
4836
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
5847
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
4837
				}
5848
				}
4838
			} else {	/* Incoming call, not up */
5849
			} else {	/* Incoming call, not up */
4839
				const char *res;
5850
				const char *res;
4840
				AST_SCHED_DEL(sched, p->provisional_keepalive_sched_id);
5851
				AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
4841
				if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
5852
				if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
4842
					transmit_response_reliable(p, res, &p->initreq);
5853
					transmit_response_reliable(p, res, &p->initreq);
4843
				else
5854
				else
4844
					transmit_response_reliable(p, "603 Declined", &p->initreq);
5855
					transmit_response_reliable(p, "603 Declined", &p->initreq);
4845
				p->invitestate = INV_TERMINATED;
5856
				p->invitestate = INV_TERMINATED;
[+20] [20] 351 lines
[+20] [+] static int sip_transfer(struct ast_channel *ast, const char *dest)
5197
	sip_pvt_unlock(p);
6208
	sip_pvt_unlock(p);
5198
	return res;
6209
	return res;
5199
}
6210
}
5200

    
   
6211

   
5201
/*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
6212
/*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
5202
static void interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
6213
static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
5203
{
6214
{
5204
	if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
6215
	int res = 0;
5205
		return;
6216

   

    
   
6217
	if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {

    
   
6218
		return -1;
5206
	}
6219
	}
5207
	switch (parameters->request_response) {
6220
	switch (parameters->request_response) {
5208
	case AST_T38_NEGOTIATED:
6221
	case AST_T38_NEGOTIATED:
5209
	case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
6222
	case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
5210
		/* Negotiation can not take place without a valid max_ifp value. */
6223
		/* Negotiation can not take place without a valid max_ifp value. */
[+20] [20] 43 lines
[+20] static void interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters) [+] static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
5254
			change_t38_state(p, T38_DISABLED);
6267
			change_t38_state(p, T38_DISABLED);
5255
			transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
6268
			transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
5256
		} else if (p->t38.state == T38_ENABLED)
6269
		} else if (p->t38.state == T38_ENABLED)
5257
			transmit_reinvite_with_sdp(p, FALSE, FALSE);
6270
			transmit_reinvite_with_sdp(p, FALSE, FALSE);
5258
		break;
6271
		break;

    
   
6272
	case AST_T38_REQUEST_PARMS: {		/* Application wants remote's parameters re-sent */

    
   
6273
		struct ast_control_t38_parameters parameters = p->t38.their_parms;

    
   
6274

   

    
   
6275
		if (p->t38.state == T38_PEER_REINVITE) {

    
   
6276
			AST_SCHED_DEL(sched, p->t38id);

    
   
6277
			parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);

    
   
6278
			parameters.request_response = AST_T38_REQUEST_NEGOTIATE;

    
   
6279
			ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));

    
   
6280
			/* we need to return a positive value here, so that applications that

    
   
6281
			 * send this request can determine conclusively whether it was accepted or not...

    
   
6282
			 * older versions of chan_sip would just silently accept it and return zero.

    
   
6283
			 */

    
   
6284
			res = AST_T38_REQUEST_PARMS;

    
   
6285
		}

    
   
6286
		break;

    
   
6287
	}
5259
	default:
6288
	default:

    
   
6289
		res = -1;
5260
		break;
6290
		break;
5261
	}
6291
	}

    
   
6292

   

    
   
6293
	return res;
5262
}
6294
}
5263

    
   
6295

   
5264
/*! \brief Play indication to user
6296
/*! \brief Play indication to user
5265
 * With SIP a lot of indications is sent as messages, letting the device play
6297
 * With SIP a lot of indications is sent as messages, letting the device play
5266
   the indication - busy signal, congestion etc
6298
   the indication - busy signal, congestion etc
[+20] [20] 79 lines
[+20] [+] static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
5346
			res = -1;
6378
			res = -1;
5347
		break;
6379
		break;
5348
	case AST_CONTROL_T38_PARAMETERS:
6380
	case AST_CONTROL_T38_PARAMETERS:
5349
		if (datalen != sizeof(struct ast_control_t38_parameters)) {
6381
		if (datalen != sizeof(struct ast_control_t38_parameters)) {
5350
			ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);
6382
			ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);

    
   
6383
			res = -1;
5351
		} else {
6384
		} else {
5352
			const struct ast_control_t38_parameters *parameters = data;
6385
			const struct ast_control_t38_parameters *parameters = data;
5353
			interpret_t38_parameters(p, parameters);
6386
			res = interpret_t38_parameters(p, parameters);
5354
		}
6387
		}
5355
		break;
6388
		break;
5356
	case AST_CONTROL_SRCUPDATE:
6389
	case AST_CONTROL_SRCUPDATE:
5357
		ast_rtp_instance_update_source(p->rtp);
6390
		ast_rtp_instance_update_source(p->rtp);
5358
		break;
6391
		break;
[+20] [20] 4 lines
[+20] static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
5363
		update_connectedline(p, data, datalen);
6396
		update_connectedline(p, data, datalen);
5364
		break;
6397
		break;
5365
	case AST_CONTROL_REDIRECTING:
6398
	case AST_CONTROL_REDIRECTING:
5366
		update_redirecting(p, data, datalen);
6399
		update_redirecting(p, data, datalen);
5367
		break;
6400
		break;

    
   
6401
	case AST_CONTROL_AOC:

    
   
6402
		{

    
   
6403
			struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);

    
   
6404
			if (!decoded) {

    
   
6405
				ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");

    
   
6406
				res = -1;
Moved from 2165

    
   
6407
				break;
Moved from 2166

    
   
6408
			}

    
   
6409
			switch (ast_aoc_get_msg_type(decoded)) {

    
   
6410
			case AST_AOC_REQUEST:

    
   
6411
				if (ast_aoc_get_termination_request(decoded)) {

    
   
6412
					/* TODO, once there is a way to get AOC-E on hangup, attempt that here

    
   
6413
					 * before hanging up the channel.*/

    
   
6414

   

    
   
6415
					/* The other side has already initiated the hangup. This frame

    
   
6416
					 * just says they are waiting to get AOC-E before completely tearing

    
   
6417
					 * the call down.  Since SIP does not support this at the moment go

    
   
6418
					 * ahead and terminate the call here to avoid an unnecessary timeout. */

    
   
6419
					ast_log(LOG_DEBUG, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);

    
   
6420
					ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);

    
   
6421
				}

    
   
6422
				break;

    
   
6423
			case AST_AOC_D:

    
   
6424
			case AST_AOC_E:

    
   
6425
				if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {

    
   
6426
					transmit_info_with_aoc(p, decoded);

    
   
6427
				}

    
   
6428
				break;

    
   
6429
			case AST_AOC_S: /* S not supported yet */

    
   
6430
			default:
Moved from 2165

    
   
6431
				break;
Moved from 2166

    
   
6432
			}

    
   
6433
			ast_aoc_destroy_decoded(decoded);

    
   
6434
		}

    
   
6435
		break;
5368
	case -1:
6436
	case -1:
5369
		res = -1;
6437
		res = -1;
5370
		break;
6438
		break;
5371
	default:
6439
	default:
5372
		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
6440
		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
[+20] [20] 26 lines
[+20] [+] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
5399
		const char *my_name;	/* pick a good name */
6467
		const char *my_name;	/* pick a good name */
5400
	
6468
	
5401
		if (title) {
6469
		if (title) {
5402
			my_name = title;
6470
			my_name = title;
5403
		} else {
6471
		} else {
5404
			char *port = NULL;

   
5405
			my_name = ast_strdupa(i->fromdomain);
6472
			my_name = ast_strdupa(i->fromdomain);
5406
			if ((port = strchr(i->fromdomain, ':'))) {

   
5407
				*port = '\0';

   
5408
			}

   
5409
		}
6473
		}
5410

    
   
6474

   
5411
		sip_pvt_unlock(i);
6475
		sip_pvt_unlock(i);
5412
		/* Don't hold a sip pvt lock while we allocate a channel */
6476
		/* Don't hold a sip pvt lock while we allocate a channel */
5413
		tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
6477
		tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
5414
	}
6478
	}
5415
	if (!tmp) {
6479
	if (!tmp) {
5416
		ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
6480
		ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
5417
		sip_pvt_lock(i);
6481
		sip_pvt_lock(i);
5418
		return NULL;
6482
		return NULL;
5419
	}
6483
	}

    
   
6484
	ast_channel_lock(tmp);
5420
	sip_pvt_lock(i);
6485
	sip_pvt_lock(i);

    
   
6486
	ast_channel_cc_params_init(tmp, i->cc_params);

    
   
6487
	tmp->caller.id.tag = ast_strdup(i->cid_tag);

    
   
6488
	ast_channel_unlock(tmp);
5421

    
   
6489

   
5422
	tmp->tech = ( ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ?  &sip_tech_info : &sip_tech;
6490
	tmp->tech = ( ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ?  &sip_tech_info : &sip_tech;
5423

    
   
6491

   
5424
	/* Select our native format based on codec preference until we receive
6492
	/* Select our native format based on codec preference until we receive
5425
	   something from another device to the contrary. */
6493
	   something from another device to the contrary. */
[+20] [20] 77 lines
[+20] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
5503

    
   
6571

   
5504
	if (state == AST_STATE_RING)
6572
	if (state == AST_STATE_RING)
5505
		tmp->rings = 1;
6573
		tmp->rings = 1;
5506
	tmp->adsicpe = AST_ADSI_UNAVAILABLE;
6574
	tmp->adsicpe = AST_ADSI_UNAVAILABLE;
5507

    
   
6575

   
5508
	tmp->writeformat = fmt;
6576
	tmp->writeformat = fmt;
5509
	tmp->rawwriteformat = fmt;
6577
	tmp->rawwriteformat = fmt;
5510
	ast_rtp_instance_set_write_format(i->rtp, fmt);
6578
	ast_rtp_instance_set_write_format(i->rtp, fmt);
5511

    
   
6579

   
5512
	tmp->readformat = fmt;
6580
	tmp->readformat = fmt;
5513
	tmp->rawreadformat = fmt;
6581
	tmp->rawreadformat = fmt;
5514
	ast_rtp_instance_set_read_format(i->rtp, fmt);
6582
	ast_rtp_instance_set_read_format(i->rtp, fmt);
5515

    
   
6583

   
5516
	tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
6584
	tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
5517

    
   
6585

   
5518
	tmp->callgroup = i->callgroup;
6586
	tmp->callgroup = i->callgroup;
5519
	tmp->pickupgroup = i->pickupgroup;
6587
	tmp->pickupgroup = i->pickupgroup;
5520
	tmp->cid.cid_pres = i->callingpres;
6588
	tmp->caller.id.name.presentation = i->callingpres;
5521
	if (!ast_strlen_zero(i->parkinglot))
6589
	tmp->caller.id.number.presentation = i->callingpres;
5522
		ast_string_field_set(tmp, parkinglot, i->parkinglot);
6590
	if (!ast_strlen_zero(i->parkinglot))
5523
	if (!ast_strlen_zero(i->accountcode))
6591
		ast_string_field_set(tmp, parkinglot, i->parkinglot);
5524
		ast_string_field_set(tmp, accountcode, i->accountcode);
6592
	if (!ast_strlen_zero(i->accountcode))
5525
	if (i->amaflags)
6593
		ast_string_field_set(tmp, accountcode, i->accountcode);
5526
		tmp->amaflags = i->amaflags;
6594
	if (i->amaflags)
5527
	if (!ast_strlen_zero(i->language))
6595
		tmp->amaflags = i->amaflags;
5528
		ast_string_field_set(tmp, language, i->language);
6596
	if (!ast_strlen_zero(i->language))
5529
	i->owner = tmp;
6597
		ast_string_field_set(tmp, language, i->language);
5530
	ast_module_ref(ast_module_info->self);
6598
	i->owner = tmp;
5531
	ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
6599
	ast_module_ref(ast_module_info->self);
5532
	/*Since it is valid to have extensions in the dialplan that have unescaped characters in them
6600
	ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
5533
	 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
6601
	/*Since it is valid to have extensions in the dialplan that have unescaped characters in them
5534
	 * structure so that there aren't issues when forming URI's
6602
	 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
5535
	 */
6603
	 * structure so that there aren't issues when forming URI's
5536
	decoded_exten = ast_strdupa(i->exten);
6604
	 */
5537
	ast_uri_decode(decoded_exten);
6605
	decoded_exten = ast_strdupa(i->exten);
5538
	ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
6606
	ast_uri_decode(decoded_exten);
5539

    
   
6607
	ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
5540
	/* Don't use ast_set_callerid() here because it will
6608

   
5541
	 * generate an unnecessary NewCallerID event  */
6609
	/* Don't use ast_set_callerid() here because it will
5542
	tmp->cid.cid_ani = ast_strdup(i->cid_num);
6610
	 * generate an unnecessary NewCallerID event  */
5543
	if (!ast_strlen_zero(i->rdnis))
6611
	if (!ast_strlen_zero(i->cid_num)) {
5544
		tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
6612
		tmp->caller.ani.number.valid = 1;
5545
	
6613
		tmp->caller.ani.number.str = ast_strdup(i->cid_num);
5546
	if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
6614
	}
5547
		tmp->cid.cid_dnid = ast_strdup(i->exten);
6615
	if (!ast_strlen_zero(i->rdnis)) {
5548

    
   
6616
		tmp->redirecting.from.number.valid = 1;

    
   
6617
		tmp->redirecting.from.number.str = ast_strdup(i->rdnis);

    
   
6618
	}

    
   
6619

   

    
   
6620
	if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {

    
   
6621
		tmp->dialed.number.str = ast_strdup(i->exten);

    
   
6622
	}

    
   
6623

   
5549
	tmp->priority = 1;
6624
	tmp->priority = 1;
5550
	if (!ast_strlen_zero(i->uri))
6625
	if (!ast_strlen_zero(i->uri))
5551
		pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
6626
		pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
5552
	if (!ast_strlen_zero(i->domain))
6627
	if (!ast_strlen_zero(i->domain))
5553
		pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
6628
		pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
[+20] [20] 282 lines
[+20] [+] static struct ast_frame *sip_read(struct ast_channel *ast)
5836
	sip_pvt_lock(p);
6911
	sip_pvt_lock(p);
5837
	fr = sip_rtp_read(ast, p, &faxdetected);
6912
	fr = sip_rtp_read(ast, p, &faxdetected);
5838
	p->lastrtprx = time(NULL);
6913
	p->lastrtprx = time(NULL);
5839

    
   
6914

   
5840
	/* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
6915
	/* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
5841
	if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) {
6916
	if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
5842
		ast_channel_lock(ast);
6917
		ast_channel_lock(ast);
5843
		if (strcmp(ast->exten, "fax")) {
6918
		if (strcmp(ast->exten, "fax")) {
5844
			const char *target_context = S_OR(ast->macrocontext, ast->context);
6919
			const char *target_context = S_OR(ast->macrocontext, ast->context);
5845
			ast_channel_unlock(ast);
6920
			ast_channel_unlock(ast);
5846
			if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
6921
			if (ast_exists_extension(ast, target_context, "fax", 1,
5847
				ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension\n", ast->name);
6922
				S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {

    
   
6923
				ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
5848
				pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
6924
				pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
5849
				if (ast_async_goto(ast, target_context, "fax", 1)) {
6925
				if (ast_async_goto(ast, target_context, "fax", 1)) {
5850
					ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
6926
					ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
5851
				}
6927
				}
5852
				fr = &ast_null_frame;
6928
				fr = &ast_null_frame;
5853
			} else {
6929
			} else {
5854
				ast_log(LOG_NOTICE, "Fax detected but no fax extension\n");
6930
				ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
5855
                        }
6931
			}
5856
		} else {
6932
		} else {
5857
			ast_channel_unlock(ast);
6933
			ast_channel_unlock(ast);
5858
                }
6934
		}
5859
        }
6935
	}
[+20] [20] 20 lines
[+20] [+] static char *generate_random_string(char *buf, size_t size)
5880
	snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
6956
	snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
5881

    
   
6957

   
5882
	return buf;
6958
	return buf;
5883
}
6959
}
5884

    
   
6960

   

    
   
6961
static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)

    
   
6962
{

    
   
6963
	struct ast_str *uri = ast_str_alloca(size);

    
   
6964
	ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");

    
   
6965
	/* Here would be a great place to generate a UUID, but for now we'll

    
   
6966
	 * use the handy random string generation function we already have

    
   
6967
	 */

    
   
6968
	ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));

    
   
6969
	ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify(&pvt->ourip));

    
   
6970
	ast_copy_string(buf, ast_str_buffer(uri), size);

    
   
6971
	return buf;

    
   
6972
}

    
   
6973

   
5885
/*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
6974
/*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
5886
static void build_callid_pvt(struct sip_pvt *pvt)
6975
static void build_callid_pvt(struct sip_pvt *pvt)
5887
{
6976
{
5888
	char buf[33];
6977
	char buf[33];
5889

    
   
6978

   
5890
	const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
6979
	const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify(&pvt->ourip));
5891
	
6980
	
5892
	ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
6981
	ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
5893

    
   
6982

   
5894
}
6983
}
5895

    
   
6984

   
5896
/*! \brief Build SIP Call-ID value for a REGISTER transaction */
6985
/*! \brief Build SIP Call-ID value for a REGISTER transaction */
5897
static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
6986
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
5898
{
6987
{
5899
	char buf[33];
6988
	char buf[33];
5900

    
   
6989

   
5901
	const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
6990
	const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host(ourip));
5902

    
   
6991

   
5903
	ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
6992
	ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
5904
}
6993
}
5905

    
   
6994

   
5906
/*! \brief Make our SIP dialog tag */
6995
/*! \brief Make our SIP dialog tag */
[+20] [20] 24 lines
[+20] [+] static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
5931

    
   
7020

   
5932
/*! \brief Allocate sip_pvt structure, set defaults and link in the container.
7021
/*! \brief Allocate sip_pvt structure, set defaults and link in the container.
5933
 * Returns a reference to the object so whoever uses it later must
7022
 * Returns a reference to the object so whoever uses it later must
5934
 * remember to release the reference.
7023
 * remember to release the reference.
5935
 */
7024
 */
5936
struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
7025
struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
5937
				 int useglobal_nat, const int intended_method, struct sip_request *req)
7026
				 int useglobal_nat, const int intended_method, struct sip_request *req)
5938
{
7027
{
5939
	struct sip_pvt *p;
7028
	struct sip_pvt *p;
5940

    
   
7029

   
5941
	if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
7030
	if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
5942
		return NULL;
7031
		return NULL;
5943

    
   
7032

   
5944
	if (ast_string_field_init(p, 512)) {
7033
	if (ast_string_field_init(p, 512)) {
5945
		ao2_t_ref(p, -1, "failed to string_field_init, drop p");
7034
		ao2_t_ref(p, -1, "failed to string_field_init, drop p");
5946
		return NULL;
7035
		return NULL;
5947
	}
7036
	}
5948

    
   
7037

   

    
   
7038
	if (!(p->cc_params = ast_cc_config_params_init())) {

    
   
7039
		ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
Moved from 2075

    
   
7040
		return NULL;
Moved from 2076

    
   
7041
	}

    
   
7042

   

    
   
7043
	/* If this dialog is created as the result of an incoming Request. Lets store

    
   
7044
	 * some information about that request */
5949
	if (req) {
7045
	if (req) {

    
   
7046
		char *sent_by, *branch;

    
   
7047
		const char *cseq = get_header(req, "Cseq");

    
   
7048
		unsigned int seqno;

    
   
7049
		/* get branch parameter from initial Request that started this dialog */

    
   
7050
		get_viabranch(ast_strdupa(get_header(req, "Via")), &sent_by, &branch);

    
   
7051
		/* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise

    
   
7052
		 * it is not useful to us to have it */

    
   
7053
		if (!ast_strlen_zero(branch) && !strncasecmp(branch, "z9hG4bK", 7)) {

    
   
7054
			ast_string_field_set(p, initviabranch, branch);

    
   
7055
			ast_string_field_set(p, initviasentby, sent_by);

    
   
7056
		}

    
   
7057

   

    
   
7058
		/* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate

    
   
7059
		 * except not storing the number.  CSeq validation must take place before dialog creation in find_call */

    
   
7060
		if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {

    
   
7061
			p->init_icseq = seqno;

    
   
7062
		}
5950
		set_socket_transport(&p->socket, req->socket.type); /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
7063
		set_socket_transport(&p->socket, req->socket.type); /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
5951
	} else {
7064
	} else {
5952
		set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
7065
		set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
5953
	}
7066
	}
5954

    
   
7067

   
[+20] [20] 9 lines
[+20] struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin, [+] struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
5964
	p->stateid = -1;
7077
	p->stateid = -1;
5965
	p->sessionversion_remote = -1;
7078
	p->sessionversion_remote = -1;
5966
	p->session_modify = TRUE;
7079
	p->session_modify = TRUE;
5967
	p->stimer = NULL;
7080
	p->stimer = NULL;
5968
	p->prefs = default_prefs;		/* Set default codecs for this call */
7081
	p->prefs = default_prefs;		/* Set default codecs for this call */

    
   
7082
	p->maxforwards = sip_cfg.default_max_forwards;
5969

    
   
7083

   
5970
	if (intended_method != SIP_OPTIONS) {	/* Peerpoke has it's own system */
7084
	if (intended_method != SIP_OPTIONS) {	/* Peerpoke has it's own system */
5971
		p->timer_t1 = global_t1;	/* Default SIP retransmission timer T1 (RFC 3261) */
7085
		p->timer_t1 = global_t1;	/* Default SIP retransmission timer T1 (RFC 3261) */
5972
		p->timer_b = global_timer_b;	/* Default SIP transaction timer B (RFC 3261) */
7086
		p->timer_b = global_timer_b;	/* Default SIP transaction timer B (RFC 3261) */
5973
	}
7087
	}
5974

    
   
7088

   
5975
	if (!sin)
7089
	if (!addr) {
5976
		p->ourip = internip;
7090
		p->ourip = internip;
5977
	else {
7091
	} else {
5978
		p->sa = *sin;
7092
		ast_sockaddr_copy(&p->sa, addr);
5979
		ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
7093
		ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
5980
	}
7094
	}
5981

    
   
7095

   
5982
	/* Copy global flags to this PVT at setup. */
7096
	/* Copy global flags to this PVT at setup. */
5983
	ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
7097
	ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
5984
	ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
7098
	ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);

    
   
7099
	ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
5985

    
   
7100

   
5986
	p->do_history = recordhistory;
7101
	p->do_history = recordhistory;
5987

    
   
7102

   
5988
	p->branch = ast_random();	
7103
	p->branch = ast_random();	
5989
	make_our_tag(p->tag, sizeof(p->tag));
7104
	make_our_tag(p->tag, sizeof(p->tag));
5990
	p->ocseq = INITIAL_CSEQ;
7105
	p->ocseq = INITIAL_CSEQ;
5991
	p->allowed_methods = UINT_MAX;
7106
	p->allowed_methods = UINT_MAX;
5992

    
   
7107

   
5993
	if (sip_methods[intended_method].need_rtp) {
7108
	if (sip_methods[intended_method].need_rtp) {
5994
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && (p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
7109
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {

    
   
7110
			if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
5995
			ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
7111
				ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
5996
			p->t38_maxdatagram = global_t38_maxdatagram;
7112
				p->t38_maxdatagram = global_t38_maxdatagram;

    
   
7113
			} else {

    
   
7114
				/* udptl creation failed, T38 can not be supported on this dialog */

    
   
7115
				ast_log(LOG_ERROR, "UDPTL creation failed\n");

    
   
7116
				ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);

    
   
7117
			}
5997
		}
7118
		}
5998
		p->maxcallbitrate = default_maxcallbitrate;
7119
		p->maxcallbitrate = default_maxcallbitrate;
5999
		p->autoframing = global_autoframing;
7120
		p->autoframing = global_autoframing;
6000
	}
7121
	}
6001

    
   
7122

   
6002
	if (useglobal_nat && sin) {
7123
	if (useglobal_nat && addr) {
6003
		/* Setup NAT structure according to global settings if we have an address */
7124
		/* Setup NAT structure according to global settings if we have an address */
6004
		ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
7125
		ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
6005
		p->recv = *sin;
7126
		ast_sockaddr_copy(&p->recv, addr);

    
   
7127

   
6006
		do_setnat(p);
7128
		do_setnat(p);
6007
	}
7129
	}
6008

    
   
7130

   
6009
	if (p->method != SIP_REGISTER)
7131
	if (p->method != SIP_REGISTER) {
6010
		ast_string_field_set(p, fromdomain, default_fromdomain);
7132
		ast_string_field_set(p, fromdomain, default_fromdomain);

    
   
7133
		p->fromdomainport = default_fromdomainport;

    
   
7134
	}
6011
	build_via(p);
7135
	build_via(p);
6012
	if (!callid)
7136
	if (!callid)
6013
		build_callid_pvt(p);
7137
		build_callid_pvt(p);
6014
	else
7138
	else
6015
		ast_string_field_set(p, callid, callid);
7139
		ast_string_field_set(p, callid, callid);
[+20] [20] 21 lines
[+20] struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin, [+] struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
6037
	
7161
	
6038
	ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
7162
	ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
6039
	return p;
7163
	return p;
6040
}
7164
}
6041

    
   
7165

   

    
   
7166
/* \brief arguments used for Request/Response to matching */

    
   
7167
struct match_req_args {

    
   
7168
	int method;

    
   
7169
	const char *callid;

    
   
7170
	const char *totag;

    
   
7171
	const char *fromtag;

    
   
7172
	unsigned int seqno;

    
   
7173

   

    
   
7174
	/* Set if the method is a Request */

    
   
7175
	const char *ruri;

    
   
7176
	const char *viabranch;

    
   
7177
	const char *viasentby;

    
   
7178

   

    
   
7179
	/* Set this if the Authentication header is present in the Request. */

    
   
7180
	int authentication_present;

    
   
7181
};

    
   
7182

   

    
   
7183
enum match_req_res {

    
   
7184
	SIP_REQ_MATCH,

    
   
7185
	SIP_REQ_NOT_MATCH,

    
   
7186
	SIP_REQ_LOOP_DETECTED,

    
   
7187
};

    
   
7188

   

    
   
7189
/*

    
   
7190
 * \brief Match a incoming Request/Response to a dialog

    
   
7191
 *

    
   
7192
 * \retval enum match_req_res indicating if the dialog matches the arg

    
   
7193
 */

    
   
7194
static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)

    
   
7195
{

    
   
7196
	const char *init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);

    
   
7197

   

    
   
7198
	/*

    
   
7199
	 * Match Tags and call-id to Dialog

    
   
7200
	 */

    
   
7201
	if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {

    
   
7202
		/* call-id does not match. */

    
   
7203
		return SIP_REQ_NOT_MATCH;

    
   
7204
	}

    
   
7205
	if (arg->method == SIP_RESPONSE) {

    
   
7206
		/* Verify totag if we have one stored for this dialog, but never be strict about this for

    
   
7207
		 * a response until the dialog is established */

    
   
7208
		if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {

    
   
7209
			if (ast_strlen_zero(arg->totag)) {

    
   
7210
				/* missing totag when they already gave us one earlier */

    
   
7211
				return SIP_REQ_NOT_MATCH;

    
   
7212
			}

    
   
7213
			if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {

    
   
7214
				/* The totag of the response does not match the one we have stored */

    
   
7215
				return SIP_REQ_NOT_MATCH;

    
   
7216
			}

    
   
7217
		}

    
   
7218
		/* Verify fromtag of response matches the tag we gave them. */

    
   
7219
		if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {

    
   
7220
			/* fromtag from response does not match our tag */

    
   
7221
			return SIP_REQ_NOT_MATCH;

    
   
7222
		}

    
   
7223
	} else {

    
   
7224
		/* Verify the fromtag of Request matches the tag they provided earlier. */

    
   
7225
		if (strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {

    
   
7226
			/* their tag does not match the one was have stored for them */

    
   
7227
			return SIP_REQ_NOT_MATCH;

    
   
7228
		}

    
   
7229
		/* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */

    
   
7230
		if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {

    
   
7231
			/* totag from Request does not match our tag */

    
   
7232
			return SIP_REQ_NOT_MATCH;

    
   
7233
		}

    
   
7234
	}

    
   
7235

   

    
   
7236
	/*

    
   
7237
	 * Compare incoming request against initial transaction.

    
   
7238
	 * 

    
   
7239
	 * This is a best effort attempt at distinguishing forked requests from

    
   
7240
	 * our initial transaction.  If all the elements are NOT in place to evaluate

    
   
7241
	 * this, this block is ignored and the dialog match is made regardless.

    
   
7242
	 * Once the totag is established after the dialog is confirmed, this is not necessary.

    
   
7243
	 *

    
   
7244
	 * CRITERIA required for initial transaction matching.

    
   
7245
	 * 

    
   
7246
	 * 1. Is a Request

    
   
7247
	 * 2. Callid and theirtag match (this is done in the dialog matching block)

    
   
7248
	 * 3. totag is NOT present

    
   
7249
	 * 4. CSeq matchs our initial transaction's cseq number

    
   
7250
	 * 5. pvt has init via branch parameter stored

    
   
7251
	 */

    
   
7252
	if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */

    
   
7253
		ast_strlen_zero(arg->totag) &&                   /* must not have a totag */

    
   
7254
		(sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */

    
   
7255
		!ast_strlen_zero(sip_pvt_ptr->initviabranch)) {  /* The dialog must have started with a RFC3261 compliant branch tag */

    
   
7256

   

    
   
7257
		/* This Request matches all the criteria required for Loop/Merge detection.

    
   
7258
		 * Now we must go down the path of comparing VIA's and RURIs. */

    
   
7259
		if (ast_strlen_zero(arg->viabranch) ||

    
   
7260
			strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||

    
   
7261
			ast_strlen_zero(arg->viasentby) ||

    
   
7262
			strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {

    
   
7263
			/* At this point, this request does not match this Dialog.*/

    
   
7264

   

    
   
7265
			/* if methods are different this is just a mismatch */

    
   
7266
			if ((sip_pvt_ptr->method != arg->method)) {

    
   
7267
				return SIP_REQ_NOT_MATCH;

    
   
7268
			}

    
   
7269

   

    
   
7270
			/* If RUIs are different, this is a forked request to a separate URI.

    
   
7271
			 * Returning a mismatch allows this Request to be processed separately. */

    
   
7272
			if (sip_uri_cmp(init_ruri, arg->ruri)) {

    
   
7273
				/* not a match, request uris are different */

    
   
7274
				return SIP_REQ_NOT_MATCH;

    
   
7275
			}

    
   
7276

   

    
   
7277
			/* Loop/Merge Detected

    
   
7278
			 *

    
   
7279
			 * ---Current Matches to Initial Request---

    
   
7280
			 * request uri

    
   
7281
			 * Call-id

    
   
7282
			 * their-tag

    
   
7283
			 * no totag present

    
   
7284
			 * method

    
   
7285
			 * cseq

    
   
7286
			 *

    
   
7287
			 * --- Does not Match Initial Request ---

    
   
7288
			 * Top Via

    
   
7289
			 *

    
   
7290
			 * Without the same Via, this can not match our initial transaction for this dialog,

    
   
7291
			 * but given that this Request matches everything else associated with that initial

    
   
7292
			 * Request this is most certainly a Forked request in which we have already received

    
   
7293
			 * part of the fork.

    
   
7294
			 */

    
   
7295
			return SIP_REQ_LOOP_DETECTED;

    
   
7296
		}

    
   
7297
	} /* end of Request Via check */

    
   
7298

   

    
   
7299
	/* Match Authentication Request.

    
   
7300
	 *

    
   
7301
	 * A Request with an Authentication header must come back with the

    
   
7302
	 * same Request URI.  Otherwise it is not a match.

    
   
7303
	 */

    
   
7304
	if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */

    
   
7305
		ast_strlen_zero(arg->totag) &&        /* no totag is present to match */

    
   
7306
		arg->authentication_present &&        /* Authentication header is present in Request */

    
   
7307
		sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */

    
   
7308

   

    
   
7309
		/* Authentication was provided, but the Request URI did not match the last one on this dialog. */

    
   
7310
		return SIP_REQ_NOT_MATCH;

    
   
7311
	}

    
   
7312

   

    
   
7313
	return SIP_REQ_MATCH;

    
   
7314
}

    
   
7315

   
6042
/*! \brief find or create a dialog structure for an incoming SIP message.
7316
/*! \brief find or create a dialog structure for an incoming SIP message.
6043
 * Connect incoming SIP message to current dialog or create new dialog structure
7317
 * Connect incoming SIP message to current dialog or create new dialog structure
6044
 * Returns a reference to the sip_pvt object, remember to give it back once done.
7318
 * Returns a reference to the sip_pvt object, remember to give it back once done.
6045
 *     Called by handle_incoming(), sipsock_read
7319
 *     Called by handle_incoming(), sipsock_read
6046
 */
7320
 */
6047
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
7321
static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
6048
{
7322
{
6049
	struct sip_pvt *p = NULL;
7323
	struct sip_pvt *p = NULL;
6050
	char *tag = "";	/* note, tag is never NULL */

   
6051