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 2 and 3

1 2 3 4
1 2 3 4

  1. /trunk/channels/chan_sip.c: Loading...
/trunk/channels/chan_sip.c
Diff Revision 2 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"
264
#include "asterisk/aoc.h"
265
#include "asterisk/aoc.h"
265
#include "sip/include/sip.h"
266
#include "sip/include/sip.h"
266
#include "sip/include/globals.h"
267
#include "sip/include/globals.h"
267
#include "sip/include/config_parser.h"
268
#include "sip/include/config_parser.h"
268
#include "sip/include/reqresp_parser.h"
269
#include "sip/include/reqresp_parser.h"
269
#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"
270
#include "asterisk/ccss.h"
273
#include "asterisk/ccss.h"
271
#include "asterisk/xml.h"
274
#include "asterisk/xml.h"
272
#include "sip/include/dialog.h"
275
#include "sip/include/dialog.h"
273
#include "sip/include/dialplan_functions.h"
276
#include "sip/include/dialplan_functions.h"
274

    
   
277

   

    
   
278

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

    
   
420
					<enum name="maxforwards">

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

    
   
422
					</enum>
416
					<enum name="chanvar[name]">
423
					<enum name="chanvar[name]">
417
						<para>A channel variable configured with setvar for this peer.</para>
424
						<para>A channel variable configured with setvar for this peer.</para>
418
					</enum>
425
					</enum>
419
					<enum name="codec[x]">
426
					<enum name="codec[x]">
420
						<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] 209 lines
[+20] [+] static const struct cfsip_methods {
630
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
637
	{ SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
631
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
638
	{ SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
632
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
639
	{ SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
633
};
640
};
634

    
   
641

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

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

   
637
static const struct cfsip_options {

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

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

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

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

   
642
	/* RFC3262: PRACK 100% reliability */

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

   
644
	/* RFC3959: SIP Early session support */

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

   
646
	/* SIMPLE events:  RFC4662 */

   
647
	{ SIP_OPT_EVENTLIST,	NOT_SUPPORTED,	"eventlist" },

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

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

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

   
651
	{ SIP_OPT_GRUU,		NOT_SUPPORTED,	"gruu" },

   
652
	/* RFC4244 History info */

   
653
	{ SIP_OPT_HISTINFO,	NOT_SUPPORTED,	"histinfo" },

   
654
	/* RFC3911: SIP Join header support */

   
655
	{ SIP_OPT_JOIN,		NOT_SUPPORTED,	"join" },

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

   
657
	{ SIP_OPT_NOREFERSUB,	NOT_SUPPORTED,	"norefersub" },

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

   
659
	{ SIP_OPT_OUTBOUND,	NOT_SUPPORTED,	"outbound" },

   
660
	/* RFC3327: Path support */

   
661
	{ SIP_OPT_PATH,		NOT_SUPPORTED,	"path" },

   
662
	/* RFC3840: Callee preferences */

   
663
	{ SIP_OPT_PREF,		NOT_SUPPORTED,	"pref" },

   
664
	/* RFC3312: Precondition support */

   
665
	{ SIP_OPT_PRECONDITION,	NOT_SUPPORTED,	"precondition" },

   
666
	/* RFC3323: Privacy with proxies*/

   
667
	{ SIP_OPT_PRIVACY,	NOT_SUPPORTED,	"privacy" },

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

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

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

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

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

   
673
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replaces" },

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

   
675
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replace" },

   
676
	/* RFC4412 Resource priorities */

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

   
678
	/* RFC3329: Security agreement mechanism */

   
679
	{ SIP_OPT_SEC_AGREE,	NOT_SUPPORTED,	"sec_agree" },

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

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

   
682
	/* RFC4028: SIP Session-Timers */

   
683
	{ SIP_OPT_TIMER,	SUPPORTED,	"timer" },

   
684
	/* RFC4538: Target-dialog */

   
685
	{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,	"tdialog" },

   
686
};

   
687

    
   

   
688
/*! \brief Diversion header reasons
642
/*! \brief Diversion header reasons
689
 *
643
 *
690
 * The core defines a bunch of constants used to define
644
 * The core defines a bunch of constants used to define
691
 * redirecting reasons. This provides a translation table
645
 * redirecting reasons. This provides a translation table
692
 * between those and the strings which may be present in
646
 * between those and the strings which may be present in
[+20] [20] 471 lines
[+20] [+] static struct sip_auth *authl = NULL;
1164
 * 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
1165
 * the protocol handle this above us.
1119
 * the protocol handle this above us.
1166
 */
1120
 */
1167
static int sipsock  = -1;
1121
static int sipsock  = -1;
1168

    
   
1122

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

    
   
1124

   
1171
/*! \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
1172
 *  internip is initialized picking a suitable address from one of the
1126
 *  internip is initialized picking a suitable address from one of the
1173
 * 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
1174
 * default address/port in SIP messages, and as the default address
1128
 * default address/port in SIP messages, and as the default address
1175
 * (but not port) in SDP messages.
1129
 * (but not port) in SDP messages.
1176
 */
1130
 */
1177
static struct sockaddr_in internip;
1131
static struct ast_sockaddr internip;
1178

    
   
1132

   
1179
/*! \brief our external IP address/port for SIP sessions.
1133
/*! \brief our external IP address/port for SIP sessions.
1180
 * 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
1181
 * 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)
1182
 * ways from the config file:
1136
 * ways from the config file:
1183
 *
1137
 *
1184
 * + with "externip = host[:port]" we specify the address/port explicitly.
1138
 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1185
 *   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;
1186
 *
1140
 *
1187
 * + with "externhost = host[:port]" we do a similar thing, but the
1141
 * + with "externhost = host[:port]" we do a similar thing, but the
1188
 *   hostname is stored in externhost, and the hostname->IP mapping
1142
 *   hostname is stored in externhost, and the hostname->IP mapping
1189
 *   is refreshed every 'externrefresh' seconds;
1143
 *   is refreshed every 'externrefresh' seconds;
1190
 *
1144
 *
1191
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1145
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1192
 *   to the specified server, and store the result in externip.
1146
 *   to the specified server, and store the result in externaddr.
1193
 *
1147
 *
1194
 * Other variables (externhost, externexpire, externrefresh) are used
1148
 * Other variables (externhost, externexpire, externrefresh) are used
1195
 * to support the above functions.
1149
 * to support the above functions.
1196
 */
1150
 */
1197
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 */
1198
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 */
1199

    
   
1153

   
1200
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1154
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1201
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 */
1202
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) */
1203
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 */
1212
 */
1166
 */
1213
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 */
1214

    
   
1168

   
1215
static int ourport_tcp;             /*!< The port used for TCP connections */
1169
static int ourport_tcp;             /*!< The port used for TCP connections */
1216
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1170
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1217
static struct sockaddr_in debugaddr;
1171
static struct ast_sockaddr debugaddr;
1218

    
   
1172

   
1219
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 */
1220

    
   
1174

   
1221
/*! some list management macros. */
1175
/*! some list management macros. */
1222

    
   
1176

   
[+20] [20] 25 lines
[+20] [+] static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1248
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);
1249
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);
1250
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);
1251
static const char *sip_get_callid(struct ast_channel *chan);
1205
static const char *sip_get_callid(struct ast_channel *chan);
1252

    
   
1206

   
1253
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);
1254
static int sip_standard_port(enum sip_transport type, int port);
1208
static int sip_standard_port(enum sip_transport type, int port);
1255
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);
1256

    
   
1211

   
1257
/*--- Transmitting responses and requests */
1212
/*--- Transmitting responses and requests */
1258
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);
1259
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);
1260
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);
1261
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1216
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1262
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);
1263
static int retrans_pkt(const void *data);
1218
static int retrans_pkt(const void *data);
1264
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);
1265
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);
1266
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);
1267
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);
1268
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);
1269
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);
[+20] [20] 25 lines
[+20] [+] static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1295
/* Misc dialog routines */
1250
/* Misc dialog routines */
1296
static int __sip_autodestruct(const void *data);
1251
static int __sip_autodestruct(const void *data);
1297
static void *registry_unref(struct sip_registry *reg, char *tag);
1252
static void *registry_unref(struct sip_registry *reg, char *tag);
1298
static int update_call_counter(struct sip_pvt *fup, int event);
1253
static int update_call_counter(struct sip_pvt *fup, int event);
1299
static int auto_congest(const void *arg);
1254
static int auto_congest(const void *arg);
1300
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);
1301
static void free_old_route(struct sip_route *route);
1256
static void free_old_route(struct sip_route *route);
1302
static void list_route(struct sip_route *route);
1257
static void list_route(struct sip_route *route);
1303
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);
1304
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,
1305
					      struct sip_request *req, const char *uri);
1260
					      struct sip_request *req, const char *uri);
1306
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);
1307
static void check_pendings(struct sip_pvt *p);
1262
static void check_pendings(struct sip_pvt *p);
1308
static void *sip_park_thread(void *stuff);
1263
static void *sip_park_thread(void *stuff);
1309
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);
1315
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);
1316
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);
1317
static int find_sdp(struct sip_request *req);
1272
static int find_sdp(struct sip_request *req);
1318
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);
1319
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);
1320
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);
1321
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1276
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1322
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);
1323
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);
1324
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);
1325
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);
1339
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,
1340
					 const char *secret, const char *md5secret, int sipmethod,
1295
					 const char *secret, const char *md5secret, int sipmethod,
1341
					 const char *uri, enum xmittype reliable, int ignore);
1296
					 const char *uri, enum xmittype reliable, int ignore);
1342
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,
1343
					      int sipmethod, const char *uri, enum xmittype reliable,
1298
					      int sipmethod, const char *uri, enum xmittype reliable,
1344
					      struct sockaddr_in *sin, struct sip_peer **authpeer);
1299
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1345
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);
1346

    
   
1301

   
1347
/*--- Domain handling */
1302
/*--- Domain handling */
1348
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 */
1349
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);
1350
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);
1361
static int expire_register(const void *data);
1316
static int expire_register(const void *data);
1362
static void *do_monitor(void *data);
1317
static void *do_monitor(void *data);
1363
static int restart_monitor(void);
1318
static int restart_monitor(void);
1364
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);
1365
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);
1366
/* 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 */
1367
static int sip_refer_allocate(struct sip_pvt *p);
1323
static int sip_refer_allocate(struct sip_pvt *p);
1368
static int sip_notify_allocate(struct sip_pvt *p);
1324
static int sip_notify_allocate(struct sip_pvt *p);
1369
static void ast_quiet_chan(struct ast_channel *chan);
1325
static void ast_quiet_chan(struct ast_channel *chan);
1370
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);
1422
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);
1423
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1379
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1424
static int sip_addheader(struct ast_channel *chan, const char *data);
1380
static int sip_addheader(struct ast_channel *chan, const char *data);
1425
static int sip_do_reload(enum channelreloadreason reason);
1381
static int sip_do_reload(enum channelreloadreason reason);
1426
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);
1427

    
   
1387

   
1428
/*--- Debugging
1388
/*--- Debugging
1429
	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
1430
	a SIP dialog
1390
	a SIP dialog
1431
*/
1391
*/
1432
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 */
1433
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);
1434
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1394
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1435
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, ...);
1436
static void sip_dump_history(struct sip_pvt *dialog);
1396
static void sip_dump_history(struct sip_pvt *dialog);
1437

    
   
1397

   
1438
/*--- Device object handling */
1398
/*--- Device object handling */
1439
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);
1440
static int update_call_counter(struct sip_pvt *fup, int event);
1400
static int update_call_counter(struct sip_pvt *fup, int event);
1441
static void sip_destroy_peer(struct sip_peer *peer);
1401
static void sip_destroy_peer(struct sip_peer *peer);
1442
static void sip_destroy_peer_fn(void *peer);
1402
static void sip_destroy_peer_fn(void *peer);
1443
static void set_peer_defaults(struct sip_peer *peer);
1403
static void set_peer_defaults(struct sip_peer *peer);
1444
static struct sip_peer *temp_peer(const char *name);
1404
static struct sip_peer *temp_peer(const char *name);
1445
static void register_peer_exten(struct sip_peer *peer, int onoff);
1405
static void register_peer_exten(struct sip_peer *peer, int onoff);
1446
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);
1447
static int sip_poke_peer_s(const void *data);
1407
static int sip_poke_peer_s(const void *data);
1448
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);
1449
static void reg_source_db(struct sip_peer *peer);
1409
static void reg_source_db(struct sip_peer *peer);
1450
static void destroy_association(struct sip_peer *peer);
1410
static void destroy_association(struct sip_peer *peer);
1451
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);
1452
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);
1453
static void set_socket_transport(struct sip_socket *socket, int transport);
1413
static void set_socket_transport(struct sip_socket *socket, int transport);
1454

    
   
1414

   
1455
/* Realtime device support */
1415
/* Realtime device support */
1456
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);
1457
static void update_peer(struct sip_peer *p, int expire);
1417
static void update_peer(struct sip_peer *p, int expire);
1458
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);
1459
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);
1460
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);
1461
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);
1462

    
   
1422

   
1463
/*--- Internal UA client handling (outbound registrations) */
1423
/*--- Internal UA client handling (outbound registrations) */
1464
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);
1465
static void sip_registry_destroy(struct sip_registry *reg);
1425
static void sip_registry_destroy(struct sip_registry *reg);
1466
static int sip_register(const char *value, int lineno);
1426
static int sip_register(const char *value, int lineno);
1467
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1427
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1468
static int sip_reregister(const void *data);
1428
static int sip_reregister(const void *data);
1469
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);
1475
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 */
1476
static int determine_firstline_parts(struct sip_request *req);
1436
static int determine_firstline_parts(struct sip_request *req);
1477
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1437
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1478
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);
1479
static int find_sip_method(const char *msg);
1439
static int find_sip_method(const char *msg);
1480
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);

   
1481
static unsigned int parse_allowed_methods(struct sip_request *req);
1440
static unsigned int parse_allowed_methods(struct sip_request *req);
1482
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);
1483
static int parse_request(struct sip_request *req);
1442
static int parse_request(struct sip_request *req);
1484
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);
1485
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);
1495
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);
1496
static int set_address_from_contact(struct sip_pvt *pvt);
1455
static int set_address_from_contact(struct sip_pvt *pvt);
1497
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);
1498
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);
1499
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);
1500
static int get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1459
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1501
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);
1502
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);
1503
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);
1504
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);
1505
static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req, struct ast_party_redirecting *redirecting, int set_call_forward);

   
1506
static int get_domain(const char *str, char *domain, int len);
1464
static int get_domain(const char *str, char *domain, int len);
1507
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);
1508

    
   
1466

   
1509
/*-- TCP connection handling ---*/
1467
/*-- TCP connection handling ---*/
1510
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);
1511
static void *sip_tcp_worker_fn(void *);
1469
static void *sip_tcp_worker_fn(void *);
1512

    
   
1470

   
1513
/*--- Constructing requests and responses */
1471
/*--- Constructing requests and responses */
1514
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);
1515
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);
1516
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);
1517
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1476
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1518
static int init_resp(struct sip_request *resp, const char *msg);
1477
static int init_resp(struct sip_request *resp, const char *msg);
1519
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);
1520
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);
1521
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);
1522
static void build_via(struct sip_pvt *p);
1481
static void build_via(struct sip_pvt *p);
1523
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);
1524
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog, struct sockaddr_in *remote_address);
1483
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1525
static char *generate_random_string(char *buf, size_t size);
1484
static char *generate_random_string(char *buf, size_t size);
1526
static void build_callid_pvt(struct sip_pvt *pvt);
1485
static void build_callid_pvt(struct sip_pvt *pvt);
1527
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);
1528
static void make_our_tag(char *tagbuf, size_t len);
1487
static void make_our_tag(char *tagbuf, size_t len);
1529
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);
1530
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);
1531
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);
1532
static int add_text(struct sip_request *req, const char *text);
1492
static int add_text(struct sip_request *req, const char *text);
1533
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);
1534
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);
1535
static int add_vidupdate(struct sip_request *req);
1495
static int add_vidupdate(struct sip_request *req);
1536
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);
1537
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);
1538
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);
1539
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);
1540
static void set_destination(struct sip_pvt *p, char *uri);
1500
static void set_destination(struct sip_pvt *p, char *uri);
1541
static void append_date(struct sip_request *req);
1501
static void append_date(struct sip_request *req);
1542
static void build_contact(struct sip_pvt *p);
1502
static void build_contact(struct sip_pvt *p);
1543

    
   
1503

   
1544
/*------Request handling functions */
1504
/*------Request handling functions */
1545
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);
1546
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);
1547
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);
1548
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);
1549
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);
1550
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);
1551
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);
1552
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);
1553
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);
1554
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);
1555
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);
1556
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);
1557
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);
1558
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);
1559

    
   
1519

   
1560
/*------Response handling functions */
1520
/*------Response handling functions */
1561
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1521
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1562
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);
1563
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);
1564
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);
1565
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);
1566
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);
1567
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);
1568

    
   
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

   
1569
/*------ T38 Support --------- */
1533
/*------ T38 Support --------- */
1570
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);
1571
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);
1572
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);
1573
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] 346 lines
[+20] [+] static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1920
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1884
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1921
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1885
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1922

    
   
1886

   
1923
	sip_pvt_lock(monitor_instance->subscription_pvt);
1887
	sip_pvt_lock(monitor_instance->subscription_pvt);
1924
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1888
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1925
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa.sin_addr, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1889
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1926
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1890
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1927
	monitor_instance->subscription_pvt->expiry = when;
1891
	monitor_instance->subscription_pvt->expiry = when;
1928

    
   
1892

   
1929
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1893
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1930
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1894
	sip_pvt_unlock(monitor_instance->subscription_pvt);
[+20] [20] 572 lines
[+20] [+] static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2503
	/* 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 */
2504
	fds[0].fd = tcptls_session->fd;
2468
	fds[0].fd = tcptls_session->fd;
2505
	fds[1].fd = me->alert_pipe[0];
2469
	fds[1].fd = me->alert_pipe[0];
2506
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2470
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
2507

    
   
2471

   
2508
	if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2472
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2509
		goto cleanup;
2473
		goto cleanup;
2510
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2474
	}

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

    
   
2477
	}
2512

    
   
2478

   
2513
	for (;;) {
2479
	for (;;) {
2514
		struct ast_str *str_save;
2480
		struct ast_str *str_save;
2515

    
   
2481

   
2516
		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)
2553
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2519
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2554
					ast_mutex_unlock(&tcptls_session->lock);
2520
					ast_mutex_unlock(&tcptls_session->lock);
2555
					goto cleanup;
2521
					goto cleanup;
2556
				}
2522
				}
2557
				ast_mutex_unlock(&tcptls_session->lock);
2523
				ast_mutex_unlock(&tcptls_session->lock);
2558
				if (me->stop)
2524
				if (me->stop) {
2559
					 goto cleanup;
2525
					 goto cleanup;

    
   
2526
				}
2560
				ast_str_append(&req.data, 0, "%s", buf);
2527
				ast_str_append(&req.data, 0, "%s", buf);
2561
				req.len = req.data->used;
2528
				req.len = req.data->used;
2562
			}
2529
			}
2563
			copy_request(&reqcpy, &req);
2530
			copy_request(&reqcpy, &req);
2564
			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)
2571
						ast_mutex_unlock(&tcptls_session->lock);
2538
						ast_mutex_unlock(&tcptls_session->lock);
2572
						goto cleanup;
2539
						goto cleanup;
2573
					}
2540
					}
2574
					buf[bytes_read] = '\0';
2541
					buf[bytes_read] = '\0';
2575
					ast_mutex_unlock(&tcptls_session->lock);
2542
					ast_mutex_unlock(&tcptls_session->lock);
2576
					if (me->stop)
2543
					if (me->stop) {
2577
						goto cleanup;
2544
						goto cleanup;

    
   
2545
					}
2578
					cl -= strlen(buf);
2546
					cl -= strlen(buf);
2579
					ast_str_append(&req.data, 0, "%s", buf);
2547
					ast_str_append(&req.data, 0, "%s", buf);
2580
					req.len = req.data->used;
2548
					req.len = req.data->used;
2581
				}
2549
				}
2582
			}
2550
			}
[+20] [20] 42 lines
[+20] static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
2625
cleanup:
2593
cleanup:
2626
	if (me) {
2594
	if (me) {
2627
		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");
2628
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2596
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2629
	}
2597
	}
2630
	if (reqcpy.data) {
2598
	deinit_req(&reqcpy);
2631
		ast_free(reqcpy.data);
2599
	deinit_req(&req);
2632
	}

   
2633

    
   

   
2634
	if (req.data) {

   
2635
		ast_free(req.data);

   
2636
		req.data = NULL;

   
2637
	}

   
2638

    
   
2600

   
2639
	/* 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 */
2640
	if (ca) {
2602
	if (ca) {
2641
		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");
2642
	}
2604
	}
[+20] [20] 80 lines
[+20] [+] void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2723
	if (dialog->owner) {
2685
	if (dialog->owner) {
2724
		if (lockowner)
2686
		if (lockowner)
2725
			ast_channel_lock(dialog->owner);
2687
			ast_channel_lock(dialog->owner);
2726
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2688
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2727
		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");
2728
		if (lockowner)
2690
		if (lockowner) {
2729
			ast_channel_unlock(dialog->owner);
2691
			ast_channel_unlock(dialog->owner);
2730
	}
2692
		}

    
   
2693
	}
2731
	if (dialog->registry) {
2694
	if (dialog->registry) {
2732
		if (dialog->registry->call == dialog)
2695
		if (dialog->registry->call == dialog) {
2733
			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
		}
2734
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2698
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2735
	}
2699
	}
2736
	if (dialog->stateid > -1) {
2700
	if (dialog->stateid > -1) {
2737
		ast_extension_state_del(dialog->stateid, NULL);
2701
		ast_extension_state_del(dialog->stateid, NULL);
2738
		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.");
2739
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2703
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2740
	}
2704
	}
2741
	/* Remove link from peer to subscription of MWI */
2705
	/* Remove link from peer to subscription of MWI */
2742
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2706
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
2743
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2707
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2744
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2708
	}

    
   
2709
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
2745
		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
	}
2746

    
   
2712

   
2747
	/* remove all current packets in this dialog */
2713
	/* remove all current packets in this dialog */
2748
	while((cp = dialog->packets)) {
2714
	while((cp = dialog->packets)) {
2749
		dialog->packets = dialog->packets->next;
2715
		dialog->packets = dialog->packets->next;
2750
		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)
2757

    
   
2723

   
2758
	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"));
2759

    
   
2725

   
2760
	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"));
2761
	
2727
	
2762
	if (dialog->autokillid > -1)
2728
	if (dialog->autokillid > -1) {
2763
		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
	}
2764

    
   
2731

   
2765
	if (dialog->request_queue_sched_id > -1) {
2732
	if (dialog->request_queue_sched_id > -1) {
2766
		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"));
2767
	}
2734
	}
2768

    
   
2735

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

    
   
2776

   
2810
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)
2811
{
2778
{

    
   
2779
	if (pvt->final_destruction_scheduled) {

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

    
   
2781
	}
2812
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2782
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2813
	pvt->needdestroy = 1;
2783
	pvt->needdestroy = 1;
2814
}
2784
}
2815

    
   
2785

   
2816
/*! \brief Initialize the initital request packet in the pvt structure.
2786
/*! \brief Initialize the initital request packet in the pvt structure.
2817
 	This packet is used for creating replies and future requests in
2787
 	This packet is used for creating replies and future requests in
2818
	a dialog */
2788
	a dialog */
2819
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)
2820
{
2790
{
2821
	if (p->initreq.headers)
2791
	if (p->initreq.headers) {
2822
		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);
2823
	else
2793
	} else {
2824
		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
	}
2825
	/* Use this as the basis */
2796
	/* Use this as the basis */
2826
	copy_request(&p->initreq, req);
2797
	copy_request(&p->initreq, req);
2827
	parse_request(&p->initreq);
2798
	parse_request(&p->initreq);
2828
	if (req->debug)
2799
	if (req->debug) {
2829
		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);
2830
}
2801
	}

    
   
2802
}
2831

    
   
2803

   
2832
/*! \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 */
2833
static void sip_alreadygone(struct sip_pvt *dialog)
2805
static void sip_alreadygone(struct sip_pvt *dialog)
2834
{
2806
{
2835
	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);
2836
	dialog->alreadygone = 1;
2808
	dialog->alreadygone = 1;
2837
}
2809
}
2838

    
   
2810

   
2839
/*! 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 */
2840
static int proxy_update(struct sip_proxy *proxy)
2812
static int proxy_update(struct sip_proxy *proxy)
2841
{
2813
{
2842
	/* if it's actually an IP address and not a name,
2814
	/* if it's actually an IP address and not a name,
2843
           there's no need for a managed lookup */
2815
           there's no need for a managed lookup */
2844
	if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2816
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
2845
		/* 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 */
2846
		/* 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 */
2847
		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) {
2848
			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);
2849
			return FALSE;
2822
				return FALSE;
2850
		}
2823
		}

    
   
2824

   
2851
	}
2825
	}

    
   
2826

   

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

    
   
2828

   
2852
	proxy->last_dnsupdate = time(NULL);
2829
	proxy->last_dnsupdate = time(NULL);
2853
	return TRUE;
2830
	return TRUE;
2854
}
2831
}
2855

    
   
2832

   
2856
/*! \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)
2865
	}
2842
	}
2866

    
   
2843

   
2867
	return port;
2844
	return port;
2868
}
2845
}
2869

    
   
2846

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

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

   
2872
{

   
2873
	struct sip_proxy *proxy;

   
2874

    
   

   
2875
	if (ast_strlen_zero(name)) {

   
2876
		return NULL;

   
2877
	}

   
2878

    
   

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

   
2880
	if (!proxy)

   
2881
		return NULL;

   
2882
	proxy->force = force;

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

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

   
2885
	proxy->ip.sin_family = AF_INET;

   
2886
	proxy_update(proxy);

   
2887
	return proxy;

   
2888
}

   
2889

    
   

   
2890
/*! \brief Get default outbound proxy or global proxy */
2847
/*! \brief Get default outbound proxy or global proxy */
2891
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)
2892
{
2849
{
2893
	if (peer && peer->outboundproxy) {
2850
	if (peer && peer->outboundproxy) {
2894
		if (sipdebug)
2851
		if (sipdebug) {
2895
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2852
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");

    
   
2853
		}
2896
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2854
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2897
		return peer->outboundproxy;
2855
		return peer->outboundproxy;
2898
	}
2856
	}
2899
	if (sip_cfg.outboundproxy.name[0]) {
2857
	if (sip_cfg.outboundproxy.name[0]) {
2900
		if (sipdebug)
2858
		if (sipdebug) {
2901
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2859
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");

    
   
2860
		}
2902
		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);
2903
		return &sip_cfg.outboundproxy;
2862
		return &sip_cfg.outboundproxy;
2904
	}
2863
	}
2905
	if (sipdebug)
2864
	if (sipdebug) {
2906
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2865
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");

    
   
2866
	}
2907
	return NULL;
2867
	return NULL;
2908
}
2868
}
2909

    
   
2869

   
2910
/*! \brief returns true if 'name' (with optional trailing whitespace)
2870
/*! \brief returns true if 'name' (with optional trailing whitespace)
2911
 * 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)
2925
/*! \brief  find_sip_method: Find SIP method from header */
2885
/*! \brief  find_sip_method: Find SIP method from header */
2926
static int find_sip_method(const char *msg)
2886
static int find_sip_method(const char *msg)
2927
{
2887
{
2928
	int i, res = 0;
2888
	int i, res = 0;
2929
	
2889
	
2930
	if (ast_strlen_zero(msg))
2890
	if (ast_strlen_zero(msg)) {
2931
		return 0;
2891
		return 0;

    
   
2892
	}
2932
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2893
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2933
		if (method_match(i, msg))
2894
		if (method_match(i, msg)) {
2934
			res = sip_methods[i].id;
2895
			res = sip_methods[i].id;
2935
	}
2896
		}

    
   
2897
	}
2936
	return res;
2898
	return res;
2937
}
2899
}
2938

    
   
2900

   
2939
/*! \brief Parse supported header in incoming packet */
2901
/*! \brief See if we pass debug IP filter */
2940
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)
2941
{
2903
{
2942
	char *next, *sep;
2904
	/* Can't debug if sipdebug is not enabled */
2943
	char *temp;
2905
	if (!sipdebug) {
2944
	unsigned int profile = 0;

   
2945
	int i, found;

   
2946

    
   

   
2947
	if (ast_strlen_zero(supported) )

   
2948
		return 0;
2906
		return 0;
2949
	temp = ast_strdupa(supported);

   
2950

    
   

   
2951
	if (sipdebug)

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

   
2953

    
   

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

   
2955
		found = FALSE;

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

   
2957
			*sep++ = '\0';

   
2958
		next = ast_skip_blanks(next);

   
2959
		if (sipdebug)

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

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

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

   
2963
				profile |= sip_options[i].id;

   
2964
				found = TRUE;

   
2965
				if (sipdebug)

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

   
2967
				break;

   
2968
			}

   
2969
		}

   
2970

    
   

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

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

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

   
2974
		rejected with a 420 response. */

   
2975
		if (!found)

   
2976
			profile |= SIP_OPT_UNKNOWN;

   
2977

    
   

   
2978
		if (!found && sipdebug) {

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

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

   
2981
			else

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

   
2983
		}

   
2984
	}
2907
	}
2985

    
   
2908

   
2986
	if (pvt)
2909
	/* A null debug_addr means we'll debug any address */
2987
		pvt->sipoptions = profile;
2910
	if (ast_sockaddr_isnull(&debugaddr)) {
2988
	return profile;
2911
		return 1;
2989
}
2912
	}
2990

    
   
2913

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

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

   
3000
			return 0;

   
3001
	}
2921
	}
3002
	return 1;

   
3003
}
2922
}
3004

    
   
2923

   
3005
/*! \brief The real destination address for a write */
2924
/*! \brief The real destination address for a write */
3006
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)
3007
{
2926
{
3008
	if (p->outboundproxy)
2927
	if (p->outboundproxy) {
3009
		return &p->outboundproxy->ip;
2928
		return &p->outboundproxy->ip;

    
   
2929
	}
3010

    
   
2930

   
3011
	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;
3012
}
2932
}
3013

    
   
2933

   
3014
/*! \brief Display SIP nat mode */
2934
/*! \brief Display SIP nat mode */
3015
static const char *sip_nat_mode(const struct sip_pvt *p)
2935
static const char *sip_nat_mode(const struct sip_pvt *p)
3016
{
2936
{
3017
	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";
3018
}
2938
}
3019

    
   
2939

   
3020
/*! \brief Test PVT for debugging output */
2940
/*! \brief Test PVT for debugging output */
3021
static inline int sip_debug_test_pvt(struct sip_pvt *p)
2941
static inline int sip_debug_test_pvt(struct sip_pvt *p)
3022
{
2942
{
3023
	if (!sipdebug)
2943
	if (!sipdebug) {
3024
		return 0;
2944
		return 0;

    
   
2945
	}
3025
	return sip_debug_test_addr(sip_real_dst(p));
2946
	return sip_debug_test_addr(sip_real_dst(p));
3026
}
2947
}
3027

    
   
2948

   
3028
/*! \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 */
3029
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)
3081
	}
3002
	}
3082

    
   
3003

   
3083
	return "UNKNOWN";
3004
	return "UNKNOWN";
3084
}
3005
}
3085

    
   
3006

   
3086
/*! \brief Return transport of dialog.
3007
/*! \brief Return protocol string for srv dns query */
3087
	\note this is based on a false assumption. We don't always use the
3008
static inline const char *get_srv_protocol(enum sip_transport t)
3088
	outbound proxy for all requests in a dialog. It depends on the

   
3089
	"force" parameter. The FIRST request is always sent to the ob proxy.

   
3090
	\todo Fix this function to work correctly

   
3091
*/

   
3092
static inline const char *get_transport_pvt(struct sip_pvt *p)

   
3093
{

   
3094
	if (p->outboundproxy && p->outboundproxy->transport) {

   
3095
		set_socket_transport(&p->socket, p->outboundproxy->transport);

   
3096
	}

   
3097

    
   

   
3098
	return get_transport(p->socket.type);

   
3099
}

   
3100

    
   

   
3101
/*! \brief Transmit SIP message

   
3102
	Sends a SIP request or response on a given socket (in the pvt)

   
3103
	Called by retrans_pkt, send_request, send_response and

   
3104
	__sip_reliable_xmit

   
3105
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.

   
3106
*/

   
3107
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)

   
3108
{
3009
{
3109
	int res = 0;
3010
	switch (t) {
3110
	const struct sockaddr_in *dst = sip_real_dst(p);
3011
	case SIP_TRANSPORT_UDP:
3111

    
   
3012
		return "udp";
3112
	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));
3013
	case SIP_TRANSPORT_TLS:
3113

    
   
3014
	case SIP_TRANSPORT_TCP:
3114
	if (sip_prepare_socket(p) < 0)
3015
		return "tcp";
3115
		return XMIT_ERROR;

   
3116

    
   

   
3117
	if (p->socket.type == SIP_TRANSPORT_UDP) {

   
3118
		res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));

   
3119
	} else if (p->socket.tcptls_session) {

   
3120
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);

   
3121
	} else {

   
3122
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");

   
3123
		return XMIT_ERROR;

   
3124
	}

   
3125

    
   

   
3126
	if (res == -1) {

   
3127
		switch (errno) {

   
3128
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */

   
3129
		case EHOSTUNREACH: 	/* Host can't be reached */

   
3130
		case ENETDOWN: 		/* Interface down */

   
3131
		case ENETUNREACH:	/* Network failure */

   
3132
		case ECONNREFUSED:      /* ICMP port unreachable */

   
3133
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */

   
3134
		}

   
3135
	}

   
3136
	if (res != len)

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

   
3138

    
   

   
3139
	return res;

   
3140
}
3016
	}
3141

    
   
3017

   
3142
/*! \brief Build a Via header for a request */
3018
	return "udp";
3143
static void build_via(struct sip_pvt *p)
Moved to 3093

   
3144
{
Moved to 3094

   
3145
	/* Work around buggy UNIDEN UIP200 firmware */
Moved to 3095

   
3146
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
Moved to 3096

   
3147

    
   

   
3148
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */

   
3149
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",

   
3150
		 get_transport_pvt(p),

   
3151
		 ast_inet_ntoa(p->ourip.sin_addr),

   
3152
		 ntohs(p->ourip.sin_port), (int) p->branch, rport);

   
3153
}
3019
}
3154

    
   
3020

   
3155
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3021
/*! \brief Return service string for srv dns query */
3156
 *
3022
static inline const char *get_srv_service(enum sip_transport t)
3157
 * Using the localaddr structure built up with localnet statements in sip.conf

   
3158
 * apply it to their address to see if we need to substitute our

   
3159
 * externip or can get away with our internal bindaddr

   
3160
 * 'us' is always overwritten.

   
3161
 */

   
3162
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)

   
3163
{
3023
{
3164
	struct sockaddr_in theirs;
3024
	switch (t) {
3165
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
Moved to 3117

   
3166
	 * reachable IP address and port. This is done if:
Moved to 3118

   
3167
	 * 1. we have a localaddr list (containing 'internal' addresses marked
Moved to 3119

   
3168
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
Moved to 3120

   
3169
	 *    and AST_SENSE_ALLOW on 'external' ones);
Moved to 3121

   
3170
	 * 2. either stunaddr or externip is set, so we know what to use as the

   
3171
	 *    externally visible address;

   
3172
	 * 3. the remote address, 'them', is external;

   
3173
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY

   
3174
	 *    when passed to ast_apply_ha() so it does need to be remapped.

   
3175
	 *    This fourth condition is checked later.

   
3176
	 */

   
3177
	int want_remap;

   
3178

    
   

   
3179
	*us = internip;		/* starting guess for the internal address */

   
3180
	/* now ask the system what would it use to talk to 'them' */

   
3181
	ast_ouraddrfor(them, &us->sin_addr);

   
3182
	theirs.sin_addr = *them;

   
3183

    
   

   
3184
	want_remap = localaddr &&

   
3185
		(externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&

   
3186
		ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;

   
3187

    
   

   
3188
	if (want_remap &&

   
3189
	    (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {

   
3190
		/* if we used externhost or stun, see if it is time to refresh the info */
Moved to 3150

   
3191
		if (externexpire && time(NULL) >= externexpire) {
Moved to 3151

   
3192
			if (stunaddr.sin_addr.s_addr) {
Moved to 3152

   
3193
				ast_stun_request(sipsock, &stunaddr, NULL, &externip);

   
3194
			} else {

   
3195
				if (ast_parse_arg(externhost, PARSE_INADDR, &externip))

   
3196
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);

   
3197
			}

   
3198
			externexpire = time(NULL) + externrefresh;

   
3199
		}

   
3200
		if (externip.sin_addr.s_addr) {

   
3201
			*us = externip;

   
3202
			switch (p->socket.type) {

   
3203
			case SIP_TRANSPORT_TCP:
3025
	case SIP_TRANSPORT_TCP:
3204
				us->sin_port = htons(externtcpport);

   
3205
				break;

   
3206
			case SIP_TRANSPORT_TLS:

   
3207
				us->sin_port = htons(externtlsport);

   
3208
				break;

   
3209
			case SIP_TRANSPORT_UDP:
3026
	case SIP_TRANSPORT_UDP:
3210
				break; /* fall through */
3027
		return "sip";
3211
			default:

   
3212
				us->sin_port = htons(STANDARD_SIP_PORT); /* we should never get here */

   
3213
			}

   
3214
		}

   
3215
		else

   
3216
			ast_log(LOG_WARNING, "stun failed\n");

   
3217
		ast_debug(1, "Target address %s is not local, substituting externip\n",

   
3218
			ast_inet_ntoa(*(struct in_addr *)&them->s_addr));

   
3219
	} else if (p) {
Moved to 3190

   
3220
		/* no remapping, but we bind to a specific address, so use it. */
Moved to 3191

   
3221
		switch (p->socket.type) {
Moved to 3192

   
3222
		case SIP_TRANSPORT_TCP:
Moved to 3193

   
3223
			if (sip_tcp_desc.local_address.sin_addr.s_addr) {

   
3224
				*us = sip_tcp_desc.local_address;

   
3225
			} else {

   
3226
				us->sin_port = sip_tcp_desc.local_address.sin_port;

   
3227
			}

   
3228
			break;

   
3229
		case SIP_TRANSPORT_TLS:
3028
	case SIP_TRANSPORT_TLS:
3230
			if (sip_tls_desc.local_address.sin_addr.s_addr) {
3029
		return "sips";
3231
				*us = sip_tls_desc.local_address;

   
3232
			} else {

   
3233
				us->sin_port = sip_tls_desc.local_address.sin_port;

   
3234
			}

   
3235
				break;

   
3236
		case SIP_TRANSPORT_UDP:

   
3237
			/* fall through on purpose */

   
3238
		default:

   
3239
			if (bindaddr.sin_addr.s_addr) {

   
3240
				*us = bindaddr;

   
3241
			}
3030
	}

    
   
3031
	return "sip";
3242
		}
3032
}
3243
	} else if (bindaddr.sin_addr.s_addr) {
3033

   
3244
		*us = bindaddr;
3034
/*! \brief Return transport of dialog.
3245
	}
3035
	\note this is based on a false assumption. We don't always use the
3246
	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));
3036
	outbound proxy for all requests in a dialog. It depends on the
Moved from 3089

    
   
3037
	"force" parameter. The FIRST request is always sent to the ob proxy.
Moved from 3090

    
   
3038
	\todo Fix this function to work correctly
Moved from 3091

    
   
3039
*/
Moved from 3092

    
   
3040
static inline const char *get_transport_pvt(struct sip_pvt *p)
Moved from 3093

    
   
3041
{
Moved from 3094

    
   
3042
	if (p->outboundproxy && p->outboundproxy->transport) {
Moved from 3095

    
   
3043
		set_socket_transport(&p->socket, p->outboundproxy->transport);
Moved from 3096

    
   
3044
	}

    
   
3045

   
Moved from 3098

    
   
3046
	return get_transport(p->socket.type);
Moved from 3099

    
   
3047
}

    
   
3048

   
Moved from 3101

    
   
3049
/*! \brief Transmit SIP message
Moved from 3102

    
   
3050
	Sends a SIP request or response on a given socket (in the pvt)
Moved from 3103

    
   
3051
	Called by retrans_pkt, send_request, send_response and
Moved from 3104

    
   
3052
	__sip_reliable_xmit
Moved from 3105

    
   
3053
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
Moved from 3106

    
   
3054
*/
Moved from 3107

    
   
3055
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)

    
   
3056
{

    
   
3057
	int res = 0;

    
   
3058
	const struct ast_sockaddr *dst = sip_real_dst(p);

    
   
3059

   

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

    
   
3061

   

    
   
3062
	if (sip_prepare_socket(p) < 0) {

    
   
3063
		return XMIT_ERROR;

    
   
3064
	}

    
   
3065

   

    
   
3066
	if (p->socket.type == SIP_TRANSPORT_UDP) {

    
   
3067
		res = ast_sendto(p->socket.fd, data->str, len, 0, dst);
Moved from 3119

    
   
3068
	} else if (p->socket.tcptls_session) {
Moved from 3120

    
   
3069
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
Moved from 3121

    
   
3070
	} else {
Moved from 3122

    
   
3071
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
Moved from 3123

    
   
3072
		return XMIT_ERROR;
Moved from 3124

    
   
3073
	}

    
   
3074

   
Moved from 3126

    
   
3075
	if (res == -1) {
Moved from 3127

    
   
3076
		switch (errno) {
Moved from 3128

    
   
3077
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
Moved from 3129

    
   
3078
		case EHOSTUNREACH: 	/* Host can't be reached */
Moved from 3130

    
   
3079
		case ENETDOWN: 		/* Interface down */
Moved from 3131

    
   
3080
		case ENETUNREACH:	/* Network failure */
Moved from 3132

    
   
3081
		case ECONNREFUSED:      /* ICMP port unreachable */
Moved from 3133

    
   
3082
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
Moved from 3134

    
   
3083
		}
Moved from 3135

    
   
3084
	}

    
   
3085
	if (res != len) {

    
   
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
	}

    
   
3088

   

    
   
3089
	return res;

    
   
3090
}

    
   
3091

   

    
   
3092
/*! \brief Build a Via header for a request */
Moved from 3143

    
   
3093
static void build_via(struct sip_pvt *p)
Moved from 3144

    
   
3094
{
Moved from 3145

    
   
3095
	/* Work around buggy UNIDEN UIP200 firmware */
Moved from 3146

    
   
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" : "";

    
   
3097

   

    
   
3098
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */

    
   
3099
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",

    
   
3100
		 get_transport_pvt(p),

    
   
3101
		 ast_sockaddr_stringify(&p->ourip),

    
   
3102
		 (int) p->branch, rport);

    
   
3103
}

    
   
3104

   

    
   
3105
/*! \brief NAT fix - decide which IP address to use for Asterisk server?

    
   
3106
 *

    
   
3107
 * Using the localaddr structure built up with localnet statements in sip.conf

    
   
3108
 * apply it to their address to see if we need to substitute our

    
   
3109
 * externaddr or can get away with our internal bindaddr
Moved from 3160

    
   
3110
 * 'us' is always overwritten.
Moved from 3161

    
   
3111
 */

    
   
3112
static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)

    
   
3113
{

    
   
3114
	struct ast_sockaddr theirs;

    
   
3115
	struct sockaddr_in externaddr_sin;

    
   
3116

   
Moved from 3165

    
   
3117
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
Moved from 3166

    
   
3118
	 * reachable IP address and port. This is done if:
Moved from 3167

    
   
3119
	 * 1. we have a localaddr list (containing 'internal' addresses marked
Moved from 3168

    
   
3120
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
Moved from 3169

    
   
3121
	 *    and AST_SENSE_ALLOW on 'external' ones);

    
   
3122
	 * 2. either stunaddr or externaddr is set, so we know what to use as the
Moved from 3171

    
   
3123
	 *    externally visible address;
Moved from 3172

    
   
3124
	 * 3. the remote address, 'them', is external;
Moved from 3173

    
   
3125
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
Moved from 3174

    
   
3126
	 *    when passed to ast_apply_ha() so it does need to be remapped.
Moved from 3175

    
   
3127
	 *    This fourth condition is checked later.
Moved from 3176

    
   
3128
	 */

    
   
3129
	int want_remap = 0;

    
   
3130

   

    
   
3131
	ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */

    
   
3132
	/* now ask the system what would it use to talk to 'them' */

    
   
3133
	ast_ouraddrfor(them, us);

    
   
3134
	ast_sockaddr_copy(&theirs, them);

    
   
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 {

    
   
3143
		want_remap = localaddr &&

    
   
3144
			!(ast_sockaddr_isnull(&externaddr) && stunaddr.sin_addr.s_addr) &&

    
   
3145
			ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;

    
   
3146
	}

    
   
3147

   

    
   
3148
	if (want_remap &&

    
   
3149
	    (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
Moved from 3190

    
   
3150
		/* if we used externhost or stun, see if it is time to refresh the info */
Moved from 3191

    
   
3151
		if (externexpire && time(NULL) >= externexpire) {
Moved from 3192

    
   
3152
			if (stunaddr.sin_addr.s_addr) {

    
   
3153
				ast_sockaddr_to_sin(&externaddr, &externaddr_sin);

    
   
3154
				ast_stun_request(sipsock, &stunaddr, NULL, &externaddr_sin);

    
   
3155
			} else {

    
   
3156
				if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
Moved from 3196

    
   
3157
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
Moved from 3197

    
   
3158
				}

    
   
3159
				externexpire = time(NULL);

    
   
3160
			}

    
   
3161
			externexpire = time(NULL) + externrefresh;

    
   
3162
		}

    
   
3163
		if (!ast_sockaddr_isnull(&externaddr)) {

    
   
3164
			ast_sockaddr_copy(us, &externaddr);

    
   
3165
			switch (p->socket.type) {

    
   
3166
			case SIP_TRANSPORT_TCP:

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

    
   
3172
				break;

    
   
3173
			case SIP_TRANSPORT_TLS:

    
   
3174
				ast_sockaddr_set_port(us, externtlsport);

    
   
3175
				break;

    
   
3176
			case SIP_TRANSPORT_UDP:

    
   
3177
				if (!ast_sockaddr_port(&externaddr)) {

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

    
   
3179
				}

    
   
3180
				break;

    
   
3181
			default:

    
   
3182
				break;

    
   
3183
			}

    
   
3184
		}

    
   
3185
		else {

    
   
3186
			ast_log(LOG_WARNING, "stun failed\n");

    
   
3187
		}

    
   
3188
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",

    
   
3189
			  ast_sockaddr_stringify(them));
Moved from 3219

    
   
3190
	} else if (p) {
Moved from 3220

    
   
3191
		/* no remapping, but we bind to a specific address, so use it. */
Moved from 3221

    
   
3192
		switch (p->socket.type) {
Moved from 3222

    
   
3193
		case SIP_TRANSPORT_TCP:

    
   
3194
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {

    
   
3195
				ast_sockaddr_copy(us,

    
   
3196
						  &sip_tcp_desc.local_address);

    
   
3197
			} else {

    
   
3198
				ast_sockaddr_set_port(us,

    
   
3199
						      ast_sockaddr_port(&sip_tcp_desc.local_address));

    
   
3200
			}

    
   
3201
			break;

    
   
3202
		case SIP_TRANSPORT_TLS:

    
   
3203
			if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {

    
   
3204
				ast_sockaddr_copy(us,

    
   
3205
						  &sip_tls_desc.local_address);

    
   
3206
			} else {

    
   
3207
				ast_sockaddr_set_port(us,

    
   
3208
						      ast_sockaddr_port(&sip_tls_desc.local_address));

    
   
3209
			}

    
   
3210
			break;

    
   
3211
		case SIP_TRANSPORT_UDP:

    
   
3212
			/* fall through on purpose */

    
   
3213
		default:

    
   
3214
			if (!ast_sockaddr_is_any(&bindaddr)) {

    
   
3215
				ast_sockaddr_copy(us, &bindaddr);

    
   
3216
			}

    
   
3217
			if (!ast_sockaddr_port(us)) {

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

    
   
3219
			}

    
   
3220
		}

    
   
3221
	} else if (!ast_sockaddr_is_any(&bindaddr)) {

    
   
3222
		ast_sockaddr_copy(us, &bindaddr);

    
   
3223
	}

    
   
3224
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
3247
}
3225
}
3248

    
   
3226

   
3249
/*! \brief Append to SIP dialog history with arg list  */
3227
/*! \brief Append to SIP dialog history with arg list  */
3250
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)
3251
{
3229
{
3252
	char buf[80], *c = buf; /* max history length */
3230
	char buf[80], *c = buf; /* max history length */
3253
	struct sip_history *hist;
3231
	struct sip_history *hist;
3254
	int l;
3232
	int l;
3255

    
   
3233

   
3256
	vsnprintf(buf, sizeof(buf), fmt, ap);
3234
	vsnprintf(buf, sizeof(buf), fmt, ap);
3257
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3235
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3258
	l = strlen(buf) + 1;
3236
	l = strlen(buf) + 1;
3259
	if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
3237
	if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3260
		return;
3238
		return;

    
   
3239
	}
3261
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3240
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3262
		ast_free(hist);
3241
		ast_free(hist);
3263
		return;
3242
		return;
3264
	}
3243
	}
3265
	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)
3276
/*! \brief Append to SIP dialog history with arg list  */
3255
/*! \brief Append to SIP dialog history with arg list  */
3277
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, ...)
3278
{
3257
{
3279
	va_list ap;
3258
	va_list ap;
3280

    
   
3259

   
3281
	if (!p)
3260
	if (!p) {
3282
		return;
3261
		return;

    
   
3262
	}
3283

    
   
3263

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

    
   
3266
	}
3286

    
   
3267

   
3287
	va_start(ap, fmt);
3268
	va_start(ap, fmt);
3288
	append_history_va(p, fmt, ap);
3269
	append_history_va(p, fmt, ap);
3289
	va_end(ap);
3270
	va_end(ap);
3290

    
   
3271

   
[+20] [20] 4 lines
[+20] static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3295
static int retrans_pkt(const void *data)
3276
static int retrans_pkt(const void *data)
3296
{
3277
{
3297
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3278
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3298
	int reschedule = DEFAULT_RETRANS;
3279
	int reschedule = DEFAULT_RETRANS;
3299
	int xmitres = 0;
3280
	int xmitres = 0;
3300
	
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

   
3301
	/* Lock channel PVT */
3291
	/* Lock channel PVT */
3302
	sip_pvt_lock(pkt->owner);
3292
	sip_pvt_lock(pkt->owner);
3303

    
   
3293

   
3304
	if (pkt->retrans < MAX_RETRANS) {
3294
	if (!pkt->retrans_stop) {
3305
		pkt->retrans++;
3295
		pkt->retrans++;
3306
 		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 */
3307
			if (sipdebug)
3297
			if (sipdebug) {
3308
 				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
			}
3309
		} else {
3303
		} else {
3310
 			int siptimer_a;
3304
			int siptimer_a;
3311

    
   
3305

   
3312
 			if (sipdebug)
3306
			if (sipdebug) {
3313
 				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",
3314
 			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) {
3315
 				pkt->timer_a = 2 ;
3314
				pkt->timer_a = 2 ;
3316
 			else
3315
			} else {
3317
 				pkt->timer_a = 2 * pkt->timer_a;
3316
				pkt->timer_a = 2 * pkt->timer_a;

    
   
3317
			}
3318

    
   
3318

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

    
   
3324

   
3324
 			/* Reschedule re-transmit */
3325
			/* Reschedule re-transmit */
3325
			reschedule = siptimer_a;
3326
			reschedule = siptimer_a;
3326
 			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);
3327
 		}
3332
		}
3328

    
   
3333

   
3329
		if (sip_debug_test_pvt(pkt->owner)) {
3334
		if (sip_debug_test_pvt(pkt->owner)) {
3330
			const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
3335
			const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
3331
			ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
3336
			ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
3332
				pkt->retrans, sip_nat_mode(pkt->owner),
3337
				pkt->retrans, sip_nat_mode(pkt->owner),
3333
				ast_inet_ntoa(dst->sin_addr),
3338
				ast_sockaddr_stringify(dst),
3334
				ntohs(dst->sin_port), pkt->data->str);
3339
				pkt->data->str);
3335
		}
3340
		}
3336

    
   
3341

   
3337
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3342
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3338
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3343
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3339
		sip_pvt_unlock(pkt->owner);
3344
		sip_pvt_unlock(pkt->owner);
3340
		if (xmitres == XMIT_ERROR)
3345

   
3341
			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,
3342
		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
			}
3343
			return  reschedule;
3356
			return  reschedule;
3344
	}
3357
		}
3345
	/* 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

   
3346
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3365
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3347
		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 */
3348
			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"
3349
				pkt->owner->callid, pkt->seqno,
3368
				"Packet timed out after %dms with no response\n",
3350
				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
		}
3351
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3375
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3352
			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);
3353

    
   

   
3354
	}
3377
	}

    
   
3378

   
3355
	if (xmitres == XMIT_ERROR) {
3379
	if (xmitres == XMIT_ERROR) {
3356
		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);
3357
		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)");
3358
	} else
3382
	} else {
3359
		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)");
3360
 		
3384
	}
3361
	pkt->retransid = -1;

   
3362

    
   
3385

   
3363
	if (pkt->is_fatal) {
3386
	if (pkt->is_fatal) {
3364
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3387
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3365
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3388
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3366
			usleep(1);
3389
			usleep(1);
3367
			sip_pvt_lock(pkt->owner);
3390
			sip_pvt_lock(pkt->owner);
3368
		}
3391
		}
3369

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

   
3371
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3393
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3372
		
3394
		}
3373
		if (pkt->owner->owner) {
3395
		if (pkt->owner->owner) {
3374
			sip_alreadygone(pkt->owner);

   
3375
			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
			}
3376
			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);
3377
			ast_channel_unlock(pkt->owner->owner);
3417
			ast_channel_unlock(pkt->owner->owner);
3378
		} else {
3418
		} else {
3379
			/* If no channel owner, destroy now */
3419
			/* If no channel owner, destroy now */
3380

    
   
3420

   
[+20] [20] 6 lines
[+20] static int retrans_pkt(const void *data)
3387
		}
3427
		}
3388
	}
3428
	}
3389

    
   
3429

   
3390
	if (pkt->method == SIP_BYE) {
3430
	if (pkt->method == SIP_BYE) {
3391
		/* 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. */
3392
		if (pkt->owner->owner)
3432
		if (pkt->owner->owner) {
3393
			ast_channel_unlock(pkt->owner->owner);
3433
			ast_channel_unlock(pkt->owner->owner);

    
   
3434
		}
3394
		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.");
3395
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3436
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3396
	}
3437
	}
3397

    
   
3438

   
3398
	/* Remove the packet */
3439
	/* Remove the packet */
3399
	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) {
3400
		if (cur == pkt) {
3441
		if (cur == pkt) {
3401
			UNLINK(cur, pkt->owner->packets, prev);
3442
			UNLINK(cur, pkt->owner->packets, prev);
3402
			sip_pvt_unlock(pkt->owner);
3443
			sip_pvt_unlock(pkt->owner);
3403
			if (pkt->owner)
3444
			if (pkt->owner) {
3404
				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");
3405
			if (pkt->data)
3446
			}

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

    
   
3449
			}
3407
			pkt->data = NULL;
3450
			pkt->data = NULL;
3408
			ast_free(pkt);
3451
			ast_free(pkt);
3409
			return 0;
3452
			return 0;
3410
		}
3453
		}
3411
	}
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)
3441
		} else {
3484
		} else {
3442
			return AST_SUCCESS;
3485
			return AST_SUCCESS;
3443
		}
3486
		}
3444
	}
3487
	}
3445

    
   
3488

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

    
   
3491
	}
3448
	/* copy data, add a terminator and save length */
3492
	/* copy data, add a terminator and save length */
3449
	if (!(pkt->data = ast_str_create(len))) {
3493
	if (!(pkt->data = ast_str_create(len))) {
3450
		ast_free(pkt);
3494
		ast_free(pkt);
3451
		return AST_FAILURE;
3495
		return AST_FAILURE;
3452
	}
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)
3466
			pkt->response_code = respid;
3510
			pkt->response_code = respid;
3467
		}
3511
		}
3468
	}
3512
	}
3469
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3513
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3470
	pkt->retransid = -1;
3514
	pkt->retransid = -1;
3471
	if (pkt->timer_t1)
3515
	if (pkt->timer_t1) {
3472
		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 */
3473

    
   
3521

   
3474
	/* Schedule retransmission */
3522
	/* Schedule retransmission */
3475
	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);
3476
	if (sipdebug)
3524
	if (sipdebug) {
3477
		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
	}
3478

    
   
3527

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

    
   
3529

   
3481
	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 */
3482
		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)");
3483
		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");
3484
		AST_SCHED_DEL(sched, pkt->retransid);
3533
		AST_SCHED_DEL(sched, pkt->retransid);
3485
		p->packets = pkt->next;
3534
		p->packets = pkt->next;
3486
		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");
3487
		ast_free(pkt->data);
3536
		ast_free(pkt->data);
3488
		ast_free(pkt);
3537
		ast_free(pkt);
3489
		return AST_FAILURE;
3538
		return AST_FAILURE;
3490
	} 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
		}
3491
		return AST_SUCCESS;
3547
		return AST_SUCCESS;
3492
	}
3548
	}
3493
}
3549
}
3494

    
   
3550

   
3495
/*! \brief Kill a SIP dialog (called only by the scheduler)
3551
/*! \brief Kill a SIP dialog (called only by the scheduler)
[+20] [20] 30 lines
[+20] [+] static int __sip_autodestruct(const void *data)
3526
			/* They've had their chance to respond. Time to bail */
3582
			/* They've had their chance to respond. Time to bail */
3527
			__sip_pretend_ack(p);
3583
			__sip_pretend_ack(p);
3528
		}
3584
		}
3529
	}
3585
	}
3530

    
   
3586

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

   
3532
		if (p->relatedpeer) {
3587
	if (p->relatedpeer) {
3533
			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) */
3534
		}
3589
	}
3535
	}

   
3536

    
   
3590

   
3537
	/* Reset schedule ID */
3591
	/* Reset schedule ID */
3538
	p->autokillid = -1;
3592
	p->autokillid = -1;
3539

    
   
3593

   
3540
	if (p->owner) {
3594
	if (p->owner) {
[+20] [20] 14 lines
[+20] static int __sip_autodestruct(const void *data)
3555
	}
3609
	}
3556
	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.");
3557
	return 0;
3611
	return 0;
3558
}
3612
}
3559

    
   
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

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

    
   
3632
	if (p->final_destruction_scheduled) {

    
   
3633
		return; /* already set final destruction */

    
   
3634
	}

    
   
3635

   
3563
	if (ms < 0) {
3636
	if (ms < 0) {
3564
		if (p->timer_t1 == 0) {
3637
		if (p->timer_t1 == 0) {
3565
			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) */
3566
		}
3639
		}
3567
		if (p->timer_b == 0) {
3640
		if (p->timer_b == 0) {
3568
			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) */
3569
		}
3642
		}
3570
		ms = p->timer_t1 * 64;
3643
		ms = p->timer_t1 * 64;
3571
	}
3644
	}
3572
	if (sip_debug_test_pvt(p))
3645
	if (sip_debug_test_pvt(p)) {
3573
		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);
3574
	if (sip_cancel_destroy(p))
3647
	}

    
   
3648
	if (sip_cancel_destroy(p)) {
3575
		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
	}
3576

    
   
3651

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

    
   
3654
	}
3579
	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"));
3580

    
   
3656

   
3581
	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) {
3582
		stop_session_timer(p);
3658
		stop_session_timer(p);
3583
}
3659
	}

    
   
3660
}
3584

    
   
3661

   
3585
/*! \brief Cancel destruction of SIP dialog.
3662
/*! \brief Cancel destruction of SIP dialog.
3586
 * 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
3587
 * from within the scheduler, this might be the last reference.
3664
 * from within the scheduler, this might be the last reference.
3588
 */
3665
 */
3589
int sip_cancel_destroy(struct sip_pvt *p)
3666
int sip_cancel_destroy(struct sip_pvt *p)
3590
{
3667
{
3591
	int res = 0;
3668
	int res = 0;

    
   
3669

   

    
   
3670
	if (p->final_destruction_scheduled) {

    
   
3671
		return res;

    
   
3672
	}

    
   
3673

   
3592
	if (p->autokillid > -1) {
3674
	if (p->autokillid > -1) {
3593
		int res3;
3675
		int res3;
3594

    
   
3676

   
3595
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3677
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3596
			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)
3617
	if (p->outboundproxy && !p->outboundproxy->force){
3699
	if (p->outboundproxy && !p->outboundproxy->force){
3618
		ref_proxy(p, NULL);
3700
		ref_proxy(p, NULL);
3619
	}
3701
	}
3620

    
   
3702

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

    
   
3706
		}
3624
		if (cur->is_resp || cur->method == sipmethod) {
3707
		if (cur->is_resp || cur->method == sipmethod) {
3625
			res = TRUE;
3708
			res = TRUE;
3626
			msg = "Found";
3709
			msg = "Found";
3627
			if (!resp && (seqno == p->pendinginvite)) {
3710
			if (!resp && (seqno == p->pendinginvite)) {
3628
				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)
3653
				usleep(1);
3736
				usleep(1);
3654
				sip_pvt_lock(p);
3737
				sip_pvt_lock(p);
3655
			}
3738
			}
3656
			UNLINK(cur, p->packets, prev);
3739
			UNLINK(cur, p->packets, prev);
3657
			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");
3658
			if (cur->data)
3741
			if (cur->data) {
3659
				ast_free(cur->data);
3742
				ast_free(cur->data);

    
   
3743
			}
3660
			ast_free(cur);
3744
			ast_free(cur);
3661
			break;
3745
			break;
3662
		}
3746
		}
3663
	}
3747
	}
3664
	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] 103 lines
[+20] [+] static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
3768
/*! \brief Transmit response on SIP request*/
3852
/*! \brief Transmit response on SIP request*/
3769
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)
3770
{
3854
{
3771
	int res;
3855
	int res;
3772

    
   
3856

   

    
   
3857
	finalize_content(req);
3773
	add_blank(req);
3858
	add_blank(req);
3774
	if (sip_debug_test_pvt(p)) {
3859
	if (sip_debug_test_pvt(p)) {
3775
		const struct sockaddr_in *dst = sip_real_dst(p);
3860
		const struct ast_sockaddr *dst = sip_real_dst(p);
3776

    
   
3861

   
3777
		ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
3862
		ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
3778
			reliable ? "Reliably " : "", sip_nat_mode(p),
3863
			reliable ? "Reliably " : "", sip_nat_mode(p),
3779
			ast_inet_ntoa(dst->sin_addr),
3864
			ast_sockaddr_stringify(dst),
3780
			ntohs(dst->sin_port), req->data->str);
3865
			req->data->str);
3781
	}
3866
	}
3782
	if (p->do_history) {
3867
	if (p->do_history) {
3783
		struct sip_request tmp = { .rlPart1 = 0, };
3868
		struct sip_request tmp = { .rlPart1 = 0, };
3784
		parse_copy(&tmp, req);
3869
		parse_copy(&tmp, req);
3785
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
3870
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
3786
			(tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
3871
			(tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
3787
		ast_free(tmp.data);
3872
		deinit_req(&tmp);
3788
	}
3873
	}
3789

    
   
3874

   
3790
	/* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
3875
	/* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
3791
	if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
3876
	if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
3792
		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"));
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"));
3793
	}
3878
	}
3794

    
   
3879

   
3795
	res = (reliable) ?
3880
	res = (reliable) ?
3796
		 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3881
		 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3797
		__sip_xmit(p, req->data, req->len);
3882
		__sip_xmit(p, req->data, req->len);
3798
	ast_free(req->data);
3883
	deinit_req(req);
3799
	req->data = NULL;
3884
	if (res > 0) {
3800
	if (res > 0)

   
3801
		return 0;
3885
		return 0;

    
   
3886
	}
3802
	return res;
3887
	return res;
3803
}
3888
}
3804

    
   
3889

   
3805
/*! \brief Send SIP Request to the other part of the dialogue 
3890
/*! \brief Send SIP Request to the other part of the dialogue 
3806
	\return see \ref __sip_xmit
3891
	\return see \ref __sip_xmit
[+20] [20] 7 lines
[+20] [+] static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3814
	*/
3899
	*/
3815
	if (p->outboundproxy) {
3900
	if (p->outboundproxy) {
3816
		p->sa = p->outboundproxy->ip;
3901
		p->sa = p->outboundproxy->ip;
3817
	}
3902
	}
3818

    
   
3903

   

    
   
3904
	finalize_content(req);
3819
	add_blank(req);
3905
	add_blank(req);
3820
	if (sip_debug_test_pvt(p)) {
3906
	if (sip_debug_test_pvt(p)) {
3821
		if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT))
3907
		if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
3822
			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);
3908
			ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
3823
		else
3909
		} else {
3824
			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);
3910
			ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);

    
   
3911
		}
3825
	}
3912
	}
3826
	if (p->do_history) {
3913
	if (p->do_history) {
3827
		struct sip_request tmp = { .rlPart1 = 0, };
3914
		struct sip_request tmp = { .rlPart1 = 0, };
3828
		parse_copy(&tmp, req);
3915
		parse_copy(&tmp, req);
3829
		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);
3830
		ast_free(tmp.data);
3917
		deinit_req(&tmp);
3831
	}
3918
	}
3832
	res = (reliable) ?
3919
	res = (reliable) ?
3833
		__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) :
3834
		__sip_xmit(p, req->data, req->len);
3921
		__sip_xmit(p, req->data, req->len);
3835
	if (req->data) {
3922
	deinit_req(req);
3836
		ast_free(req->data);
Moved to 9333

   
3837
		req->data = NULL;
Moved to 9334

   
3838
	}

   
3839
	return res;
3923
	return res;
3840
}
3924
}
3841

    
   
3925

   
3842
static void enable_dsp_detect(struct sip_pvt *p)
3926
static void enable_dsp_detect(struct sip_pvt *p)
3843
{
3927
{
[+20] [20] 64 lines
[+20] [+] static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
3908
				disable_dsp_detect(p);
3992
				disable_dsp_detect(p);
3909
			}
3993
			}
3910
			res = 0;
3994
			res = 0;
3911
		}
3995
		}
3912
		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;
3913
	default:
4005
	default:

    
   
4006
		ast_log(LOG_NOTICE, "Unknown option: %d\n", option);
3914
		break;
4007
		break;
3915
	}
4008
	}
3916

    
   
4009

   
3917
	return res;
4010
	return res;
3918
}
4011
}
[+20] [20] 40 lines
[+20] [+] static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
3959
	case AST_OPTION_DIGIT_DETECT:
4052
	case AST_OPTION_DIGIT_DETECT:
3960
		cp = (char *) data;
4053
		cp = (char *) data;
3961
		*cp = p->dsp ? 1 : 0;
4054
		*cp = p->dsp ? 1 : 0;
3962
		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);
3963
		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;
3964
	case AST_OPTION_DEVICE_NAME:
4065
	case AST_OPTION_DEVICE_NAME:
3965
		if (p && p->outgoing_call) {
4066
		if (p && p->outgoing_call) {
3966
			cp = (char *) data;
4067
			cp = (char *) data;
3967
			ast_copy_string(cp, p->dialstring, *datalen);
4068
			ast_copy_string(cp, p->dialstring, *datalen);
3968
			res = 0;
4069
			res = 0;
[+20] [20] 90 lines
[+20] [+] static int sip_sendtext(struct ast_channel *ast, const char *text)
4059
/*! \brief Update peer object in realtime storage
4160
/*! \brief Update peer object in realtime storage
4060
	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
4061
	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
4062
	table to facilitate multi-server setups.
4163
	table to facilitate multi-server setups.
4063
*/
4164
*/
4064
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)
4065
{
4166
{
4066
	char port[10];
4167
	char port[10];
4067
	char ipaddr[INET_ADDRSTRLEN];
4168
	char ipaddr[INET_ADDRSTRLEN];
4068
	char regseconds[20];
4169
	char regseconds[20];
4069
	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)
4080
	tablename = realtimeregs ? "sipregs" : "sippeers";
4181
	tablename = realtimeregs ? "sipregs" : "sippeers";
4081
	
4182
	
4082

    
   
4183

   
4083
	snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
4184
	snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
4084
	snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);	/* Expiration time */
4185
	snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);	/* Expiration time */
4085
	ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
4186
	ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
4086
	snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
4187
	ast_copy_string(port, ast_sockaddr_stringify_port(addr), sizeof(port));
4087
	
4188

   
4088
	if (ast_strlen_zero(sysname))	/* No system name, disable this */
4189
	if (ast_strlen_zero(sysname))	/* No system name, disable this */
4089
		sysname = NULL;
4190
		sysname = NULL;
4090
	else if (sip_cfg.rtsave_sysname)
4191
	else if (sip_cfg.rtsave_sysname)
4091
		syslabel = "regserver";
4192
		syslabel = "regserver";
4092

    
   
4193

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

    
   
4245

   
4145
/*! Destroy mailbox subscriptions */
4246
/*! Destroy mailbox subscriptions */
4146
static void destroy_mailbox(struct sip_mailbox *mailbox)
4247
static void destroy_mailbox(struct sip_mailbox *mailbox)
4147
{
4248
{
4148
	if (mailbox->mailbox)

   
4149
		ast_free(mailbox->mailbox);

   
4150
	if (mailbox->context)

   
4151
		ast_free(mailbox->context);

   
4152
	if (mailbox->event_sub)
4249
	if (mailbox->event_sub)
4153
		ast_event_unsubscribe(mailbox->event_sub);
4250
		ast_event_unsubscribe(mailbox->event_sub);
4154
	ast_free(mailbox);
4251
	ast_free(mailbox);
4155
}
4252
}
4156

    
   
4253

   
[+20] [20] 103 lines
[+20] [+] static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
4260
 * Checks the "sippeers" realtime family from extconfig.conf
4357
 * Checks the "sippeers" realtime family from extconfig.conf
4261
 * 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.
4262
 * 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
4263
 * assured that the refcount is bumped.
4360
 * assured that the refcount is bumped.
4264
*/
4361
*/
4265
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)
4266
{
4363
{
4267
	struct sip_peer *peer;
4364
	struct sip_peer *peer;
4268
	struct ast_variable *var = NULL;
4365
	struct ast_variable *var = NULL;
4269
	struct ast_variable *varregs = NULL;
4366
	struct ast_variable *varregs = NULL;
4270
	struct ast_variable *tmp;
4367
	struct ast_variable *tmp;
4271
	struct ast_config *peerlist = NULL;
4368
	struct ast_config *peerlist = NULL;
4272
	char ipaddr[INET_ADDRSTRLEN];
4369
	char ipaddr[INET_ADDRSTRLEN];
4273
	char portstring[6]; /*up to 5 digits plus null terminator*/
4370
	char portstring[6]; /*up to 5 digits plus null terminator*/
4274
	char *cat = NULL;
4371
	char *cat = NULL;
4275
	unsigned short portnum;

   
4276
	int realtimeregs = ast_check_realtime("sipregs");
4372
	int realtimeregs = ast_check_realtime("sipregs");
4277

    
   
4373

   
4278
	/* First check on peer name */
4374
	/* First check on peer name */
4279
	if (newpeername) {
4375
	if (newpeername) {
4280
		if (realtimeregs)
4376
		if (realtimeregs)
4281
			varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
4377
			varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
4282

    
   
4378

   
4283
		var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
4379
		var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
4284
		if (!var && sin)
4380
		if (!var && addr) {
4285
			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
		}
4286
		if (!var) {
4383
		if (!var) {
4287
			var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
4384
			var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
4288
			/*!\note
4385
			/*!\note
4289
			 * 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
4290
			 * 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
4291
			 * 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
4292
			 * set as a name (and the reverse PTR might not match).
4389
			 * set as a name (and the reverse PTR might not match).
4293
			 */
4390
			 */
4294
			if (var && sin) {
4391
			if (var && addr) {
4295
				for (tmp = var; tmp; tmp = tmp->next) {
4392
				for (tmp = var; tmp; tmp = tmp->next) {
4296
					if (!strcasecmp(tmp->name, "host")) {
4393
					if (!strcasecmp(tmp->name, "host")) {
4297
						struct hostent *hp;
4394
						struct ast_sockaddr *addrs = NULL;
4298
						struct ast_hostent ahp;
4395

   
4299
						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)) {
4300
							/* No match */
4401
							/* No match */
4301
							ast_variables_destroy(var);
4402
							ast_variables_destroy(var);
4302
							var = NULL;
4403
							var = NULL;
4303
						}
4404
						}

    
   
4405
						ast_free(addrs);
4304
						break;
4406
						break;
4305
					}
4407
					}
4306
				}
4408
				}
4307
			}
4409
			}
4308
		}
4410
		}
4309
	}
4411
	}
4310

    
   
4412

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

   
4315
		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 */
4316
		if (var) {
4417
		if (var) {
4317
			if (realtimeregs) {
4418
			if (realtimeregs) {
4318
				newpeername = get_name_from_variable(var, newpeername);
4419
				newpeername = get_name_from_variable(var, newpeername);
4319
				varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
4420
				varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
[+20] [20] 99 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)
4419
					unref_peer(_data, "remove registration ref"),
4520
					unref_peer(_data, "remove registration ref"),
4420
					unref_peer(peer, "remove registration ref"),
4521
					unref_peer(peer, "remove registration ref"),
4421
					ref_peer(peer, "add registration ref"));
4522
					ref_peer(peer, "add registration ref"));
4422
		}
4523
		}
4423
		ao2_t_link(peers, peer, "link peer into peers table");
4524
		ao2_t_link(peers, peer, "link peer into peers table");
4424
		if (peer->addr.sin_addr.s_addr) {
4525
		if (!ast_sockaddr_isnull(&peer->addr)) {
4425
			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");
4426
		}
4527
		}
4427
	}
4528
	}
4428
	peer->is_realtime = 1;
4529
	peer->is_realtime = 1;
4429
	if (peerlist)
4530
	if (peerlist)
[+20] [20] 35 lines
[+20] [+] static int find_by_name(void *obj, void *arg, void *data, int flags)
4465
	return CMP_MATCH | CMP_STOP;
4566
	return CMP_MATCH | CMP_STOP;
4466
}
4567
}
4467

    
   
4568

   
4468
/*!
4569
/*!
4469
 * \brief Locate device by name or ip address
4570
 * \brief Locate device by name or ip address
4470
 *
4571
 * \param peer, sin, realtime, devstate_only, transport
4471
 * \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
4472
 *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
4573
 *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
4473
 *        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.
4474
 *
4575
 *
4475
 *	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.
4476
 * 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.
4477
 *
4578
 *
4478
 * \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,
4479
 * since it might cause a database lookup.
4580
 * since it might cause a database lookup.
4480
 */
4581
 */
4481
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)
4482
{
4583
{
4483
	struct sip_peer *p = NULL;
4584
	struct sip_peer *p = NULL;
4484
	struct sip_peer tmp_peer;
4585
	struct sip_peer tmp_peer;
4485

    
   
4586

   
4486
	if (peer) {
4587
	if (peer) {
4487
		ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
4588
		ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
4488
		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");
4489
	} else if (sin) { /* search by addr? */
4590
	} else if (addr) { /* search by addr? */
4490
		tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
4591
		ast_sockaddr_copy(&tmp_peer.addr, addr);
4491
		tmp_peer.addr.sin_port = sin->sin_port;

   
4492
		tmp_peer.flags[0].flags = 0;
4592
		tmp_peer.flags[0].flags = 0;
4493
		tmp_peer.transports = transport;
4593
		tmp_peer.transports = transport;
4494
		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); */
4495
		if (!p) {
4595
		if (!p) {
4496
			ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
4596
			ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
4497
			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); */
4498
			if (p) {
4598
			if (p) {
4499
				return p;
4599
				return p;
4500
			}
4600
			}
4501
		}
4601
		}
4502
	}
4602
	}
4503

    
   
4603

   
4504
	if (!p && (realtime || devstate_only)) {
4604
	if (!p && (realtime || devstate_only)) {
4505
		p = realtime_peer(peer, sin, devstate_only);
4605
		p = realtime_peer(peer, addr, devstate_only);
4506
		if (p) {
4606
		if (p) {
4507
			switch (which_objects) {
4607
			switch (which_objects) {
4508
			case FINDUSERS:
4608
			case FINDUSERS:
4509
				if (!(p->type & SIP_TYPE_USER)) {
4609
				if (!(p->type & SIP_TYPE_USER)) {
4510
					unref_peer(p, "Wrong type of realtime SIP endpoint");
4610
					unref_peer(p, "Wrong type of realtime SIP endpoint");
[+20] [20] 122 lines
[+20] [+] static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
4633
/*! \brief Initialize RTP portion of a dialog
4733
/*! \brief Initialize RTP portion of a dialog
4634
 * \return -1 on failure, 0 on success
4734
 * \return -1 on failure, 0 on success
4635
 */
4735
 */
4636
static int dialog_initialize_rtp(struct sip_pvt *dialog)
4736
static int dialog_initialize_rtp(struct sip_pvt *dialog)
4637
{
4737
{

    
   
4738
	struct ast_sockaddr bindaddr_tmp;

    
   
4739

   
4638
	if (!sip_methods[dialog->method].need_rtp) {
4740
	if (!sip_methods[dialog->method].need_rtp) {
4639
		return 0;
4741
		return 0;
4640
	}
4742
	}
4641

    
   
4743

   
4642
	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))) {
4643
		return -1;
4746
		return -1;
4644
	}
4747
	}
4645

    
   
4748

   
4646
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
4749
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
4647
			(ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
4750
			(ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
4648
		if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr, NULL))) {
4751
		if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
4649
			return -1;
4752
			return -1;
4650
		}
4753
		}
4651
		ast_rtp_instance_set_timeout(dialog->vrtp, global_rtptimeout);
4754
		ast_rtp_instance_set_timeout(dialog->vrtp, global_rtptimeout);
4652
		ast_rtp_instance_set_hold_timeout(dialog->vrtp, global_rtpholdtimeout);
4755
		ast_rtp_instance_set_hold_timeout(dialog->vrtp, global_rtpholdtimeout);
4653

    
   
4756

   
4654
		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);
4655
	}
4758
	}
4656

    
   
4759

   
4657
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
4760
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
4658
		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))) {
4659
			return -1;
4762
			return -1;
4660
		}
4763
		}
4661
		ast_rtp_instance_set_timeout(dialog->trtp, global_rtptimeout);
4764
		ast_rtp_instance_set_timeout(dialog->trtp, global_rtptimeout);
4662
		ast_rtp_instance_set_hold_timeout(dialog->trtp, global_rtpholdtimeout);
4765
		ast_rtp_instance_set_hold_timeout(dialog->trtp, global_rtpholdtimeout);
4663

    
   
4766

   
[+20] [20] 21 lines
[+20] static int dialog_initialize_rtp(struct sip_pvt *dialog)
4685
 * \return -1 on error, 0 on success.
4788
 * \return -1 on error, 0 on success.
4686
 *
4789
 *
4687
 */
4790
 */
4688
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)
4689
{
4792
{
4690

    
   

   
4691
	/* 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
4692
	 * transport type based on the peers transport configuration,
4794
	 * transport type based on the peers transport configuration,
4693
	 * otherwise, this function bails out */
4795
	 * otherwise, this function bails out */
4694
	if (dialog->socket.type && check_request_transport(peer, dialog))
4796
	if (dialog->socket.type && check_request_transport(peer, dialog))
4695
		return -1;
4797
		return -1;
4696
	copy_socket_data(&dialog->socket, &peer->socket);
4798
	copy_socket_data(&dialog->socket, &peer->socket);
4697

    
   
4799

   
4698
	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)) &&
4699
	    (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
4801
	    (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
4700
		dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
4802
		dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
4701
		dialog->recv = dialog->sa;
4803
		dialog->recv = dialog->sa;
4702
	} else
4804
	} else
4703
		return -1;
4805
		return -1;
4704

    
   
4806

   

    
   
4807
	/* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
4705
	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);
4706
	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);
4707
	ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
4810
	ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
4708
	dialog->capability = peer->capability;
4811
	dialog->capability = peer->capability;
4709
	dialog->prefs = peer->prefs;
4812
	dialog->prefs = peer->prefs;
4710
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
4813
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
4711
		/* t38pt_udptl was enabled in the peer and not in [general] */
4814
		/* t38pt_udptl was enabled in the peer and not in [general] */
4712
		if (dialog->udptl || (!dialog->udptl && (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)))) {
4713
			dialog->t38_maxdatagram = peer->t38_maxdatagram;
4816
			dialog->t38_maxdatagram = peer->t38_maxdatagram;
4714
			set_t38_capabilities(dialog);
4817
			set_t38_capabilities(dialog);
4715
		} else {
4818
		} else {
4716
			/* It is impossible to support T38 without udptl */
4819
			/* It is impossible to support T38 without udptl */
4717
			ast_debug(1, "UDPTL creation failed on dialog.\n");
4820
			ast_debug(1, "UDPTL creation failed on dialog.\n");
[+20] [20] 26 lines
[+20] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
4744
	if (dialog->trtp) { /* Realtime text */
4847
	if (dialog->trtp) { /* Realtime text */
4745
		ast_rtp_instance_set_timeout(dialog->trtp, peer->rtptimeout);
4848
		ast_rtp_instance_set_timeout(dialog->trtp, peer->rtptimeout);
4746
		ast_rtp_instance_set_hold_timeout(dialog->trtp, peer->rtpholdtimeout);
4849
		ast_rtp_instance_set_hold_timeout(dialog->trtp, peer->rtpholdtimeout);
4747
	}
4850
	}
4748

    
   
4851

   

    
   
4852
	/* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
4749
	ast_string_field_set(dialog, peername, peer->name);
4853
	ast_string_field_set(dialog, peername, peer->name);
4750
	ast_string_field_set(dialog, authname, peer->username);
4854
	ast_string_field_set(dialog, authname, peer->username);
4751
	ast_string_field_set(dialog, username, peer->username);
4855
	ast_string_field_set(dialog, username, peer->username);
4752
	ast_string_field_set(dialog, peersecret, peer->secret);
4856
	ast_string_field_set(dialog, peersecret, peer->secret);
4753
	ast_string_field_set(dialog, peermd5secret, peer->md5secret);
4857
	ast_string_field_set(dialog, peermd5secret, peer->md5secret);
[+20] [20] 18 lines
[+20] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
4772
	dialog->peerauth = peer->auth;
4876
	dialog->peerauth = peer->auth;
4773
	dialog->maxcallbitrate = peer->maxcallbitrate;
4877
	dialog->maxcallbitrate = peer->maxcallbitrate;
4774
	dialog->disallowed_methods = peer->disallowed_methods;
4878
	dialog->disallowed_methods = peer->disallowed_methods;
4775
	ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
4879
	ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
4776
	if (ast_strlen_zero(dialog->tohost))
4880
	if (ast_strlen_zero(dialog->tohost))
4777
		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));
4778
	if (!ast_strlen_zero(peer->fromdomain)) {
4882
	if (!ast_strlen_zero(peer->fromdomain)) {
4779
		ast_string_field_set(dialog, fromdomain, peer->fromdomain);
4883
		ast_string_field_set(dialog, fromdomain, peer->fromdomain);
4780
		if (!dialog->initreq.headers) {
4884
		if (!dialog->initreq.headers) {
4781
			char *c;
4885
			char *c;
4782
			char *tmpcall = ast_strdupa(dialog->callid);
4886
			char *tmpcall = ast_strdupa(dialog->callid);
[+20] [20] 45 lines
[+20] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
4828
}
4932
}
4829

    
   
4933

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

   
4836
	struct ast_hostent ahp;

   
4837
	struct sip_peer *peer;
4939
	struct sip_peer *peer;
4838
	char *port;
4940
	char *peername, *peername2, *hostn;
4839
	int portno = 0;
4941
	char host[MAXHOSTNAMELEN];
4840
	char host[MAXHOSTNAMELEN], *hostn;
4942
	char service[MAXHOSTNAMELEN];
4841
	char peername[256];

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

    
   
4950

   
4844
	ast_copy_string(peername, opeer, sizeof(peername));
4951
	peername = ast_strdupa(opeer);
4845
	port = strchr(peername, ':');
4952
	peername2 = ast_strdupa(opeer);
4846
	if (port) {
4953
	AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
4847
		*port++ = '\0';
4954

   

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

   
4850
	dialog->sa.sin_family = AF_INET;

   
4851
	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) */
4852
	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) */
4853
	peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
4960
	peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
4854

    
   
4961

   
4855
	if (peer) {
4962
	if (peer) {
4856
		int res;
4963
		int res;
4857
		if (newdialog) {
4964
		if (newdialog) {
4858
			set_socket_transport(&dialog->socket, 0);
4965
			set_socket_transport(&dialog->socket, 0);
4859
		}
4966
		}
4860
		res = create_addr_from_peer(dialog, peer);
4967
		res = create_addr_from_peer(dialog, peer);
4861
		if (remote_address && remote_address->sin_addr.s_addr) {
4968
		if (!ast_sockaddr_isnull(remote_address)) {
4862
			dialog->sa = dialog->recv = *remote_address;
4969
			ast_sockaddr_copy(&dialog->sa, remote_address);
4863
		} else if (!ast_strlen_zero(port)) {

   
4864
			if ((portno = atoi(port))) {

   
4865
				dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);

   
4866
			}

   
4867
		}
4970
		}

    
   
4971
		dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
4868
		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");
4869
		return res;
4973
		return res;
4870
	}
4974
	}
4871

    
   
4975

   
4872
	if (dialog_initialize_rtp(dialog)) {
4976
	if (dialog_initialize_rtp(dialog)) {
4873
		return -1;
4977
		return -1;
4874
	}
4978
	}
4875

    
   
4979

   
4876
	ast_string_field_set(dialog, tohost, peername);
4980
	ast_string_field_set(dialog, tohost, hostport.host);
4877
	dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
4981
	dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
4878

    
   
4982

   
4879
	/* Get the outbound proxy information */
4983
	/* Get the outbound proxy information */
4880
	ref_proxy(dialog, obproxy_get(dialog, NULL));
4984
	ref_proxy(dialog, obproxy_get(dialog, NULL));
4881

    
   
4985

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

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

   
4887
		} else {

   
4888
			portno = ntohs(sin->sin_port);

   
4889
		}

   
4890
	} else {
4989
	} else {
4891

    
   
4990

   
4892
		/* 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,
4893
		   then hostname lookup */
4992
		   then hostname lookup */
4894
		/*! \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
4895
			  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
4896
		 */
4995
		 */
4897
		hostn = peername;
4996
		hostn = peername;
4898
 		/* 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
4899
		 * an A record lookup should be used instead of SRV.
4998
		 * an A record lookup should be used instead of SRV.
4900
		 */
4999
		 */
4901
		if (!port && sip_cfg.srvlookup) {
5000
		if (!hostport.port && sip_cfg.srvlookup) {
4902
			char service[MAXHOSTNAMELEN];
5001
			snprintf(service, sizeof(service), "_%s._%s.%s", 
4903
			int tportno;
5002
				 get_srv_service(dialog->socket.type),
4904
	
5003
				 get_srv_protocol(dialog->socket.type), peername);
4905
			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,
4906
			srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
5005
						   service)) > 0) {
4907
			if (srv_ret > 0) {

   
4908
				hostn = host;
5006
				hostn = host;
4909
				portno = tportno;

   
4910
			}
5007
			}
4911
		}
5008
		}
4912
	 	if (!portno)
5009

   
4913
			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)) {
4914
		hp = ast_gethostbyname(hostn, &ahp);

   
4915
		if (!hp) {

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

   
4918
		}
5012
		}
4919
		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
		}
4920
	}
5017
	}
4921

    
   
5018

   
4922
	if (!dialog->socket.type)
5019
	if (!dialog->socket.type)
4923
		set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
5020
		set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
4924
	if (!dialog->socket.port)
5021
	if (!dialog->socket.port) {
4925
		dialog->socket.port = bindaddr.sin_port;
5022
		dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
4926
	dialog->sa.sin_port = htons(portno);
5023
	}
4927
	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);
4928
	return 0;
5031
	return 0;
4929
}
5032
}
4930

    
   
5033

   
4931
/*! \brief Scheduled congestion on a call.
5034
/*! \brief Scheduled congestion on a call.
4932
 * 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] 73 lines
[+20] [+] static int sip_call(struct ast_channel *ast, char *dest, int timeout)
5006
			/* We're replacing a call. */
5109
			/* We're replacing a call. */
5007
			p->options->replaces = ast_var_value(current);
5110
			p->options->replaces = ast_var_value(current);
5008
		}
5111
		}
5009
	}
5112
	}
5010

    
   
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

   
5011
	res = 0;
5143
	res = 0;
5012
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
5144
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
5013

    
   
5145

   
5014
	/* T.38 re-INVITE FAX detection should never be done for outgoing calls,
5146
	/* T.38 re-INVITE FAX detection should never be done for outgoing calls,
5015
	 * so ensure it is disabled.
5147
	 * so ensure it is disabled.
[+20] [20] 17 lines
[+20] static int sip_call(struct ast_channel *ast, char *dest, int timeout)
5033

    
   
5165

   
5034
	if (res == -1) {
5166
	if (res == -1) {
5035
		ast->hangupcause = AST_CAUSE_USER_BUSY;
5167
		ast->hangupcause = AST_CAUSE_USER_BUSY;
5036
		return res;
5168
		return res;
5037
	}
5169
	}
5038
	p->callingpres = ast->cid.cid_pres;
5170
	p->callingpres = ast_party_id_presentation(&ast->caller.id);
5039
	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);
5040
	p->jointnoncodeccapability = p->noncodeccapability;
5172
	p->jointnoncodeccapability = p->noncodeccapability;
5041

    
   
5173

   
5042
	/* If there are no audio formats left to offer, punt */
5174
	/* If there are no audio formats left to offer, punt */
5043
	if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
5175
	if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
[+20] [20] 135 lines
[+20] [+] void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
5179
		ast_free(p->refer);
5311
		ast_free(p->refer);
5180
	if (p->route) {
5312
	if (p->route) {
5181
		free_old_route(p->route);
5313
		free_old_route(p->route);
5182
		p->route = NULL;
5314
		p->route = NULL;
5183
	}
5315
	}
5184
	if (p->initreq.data)
5316
	deinit_req(&p->initreq);
5185
		ast_free(p->initreq.data);

   
5186

    
   
5317

   
5187
	/* Destroy Session-Timers if allocated */
5318
	/* Destroy Session-Timers if allocated */
5188
	if (p->stimer) {
5319
	if (p->stimer) {
5189
		p->stimer->quit_flag = 1;
5320
		p->stimer->quit_flag = 1;
5190
		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)
5213
	if (p->chanvars) {
5344
	if (p->chanvars) {
5214
		ast_variables_destroy(p->chanvars);
5345
		ast_variables_destroy(p->chanvars);
5215
		p->chanvars = NULL;
5346
		p->chanvars = NULL;
5216
	}
5347
	}
5217

    
   
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

   
5218
	if (p->directmediaha) {
5364
	if (p->directmediaha) {
5219
		ast_free_ha(p->directmediaha);
5365
		ast_free_ha(p->directmediaha);
5220
		p->directmediaha = NULL;
5366
		p->directmediaha = NULL;
5221
	}
5367
	}
5222

    
   
5368

   
[+20] [20] 42 lines
[+20] [+] static int update_call_counter(struct sip_pvt *fup, int event)
5265
		return 0;
5411
		return 0;
5266

    
   
5412

   
5267
	ast_copy_string(name, fup->username, sizeof(name));
5413
	ast_copy_string(name, fup->username, sizeof(name));
5268

    
   
5414

   
5269
	/* Check the list of devices */
5415
	/* Check the list of devices */
5270
	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");
5271
		inuse = &p->inUse;
5418
		inuse = &p->inUse;
5272
		call_limit = &p->call_limit;
5419
		call_limit = &p->call_limit;
5273
		inringing = &p->inRinging;
5420
		inringing = &p->inRinging;
5274
		ast_copy_string(name, fup->peername, sizeof(name));
5421
		ast_copy_string(name, fup->peername, sizeof(name));
5275
	}
5422
	}
[+20] [20] 333 lines
[+20] [+] static int sip_hangup(struct ast_channel *ast)
5609
			if (sipdebug)
5756
			if (sipdebug)
5610
				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);
5611
			update_call_counter(p, DEC_CALL_LIMIT);
5758
			update_call_counter(p, DEC_CALL_LIMIT);
5612
		}
5759
		}
5613
		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);
5614
		if (p->autokillid > -1 && sip_cancel_destroy(p))

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

   
5616
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
5761
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
5617
		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 */
5618
		p->needdestroy = 0;
5763
		p->needdestroy = 0;
5619
		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");
5620
		sip_pvt_lock(p);
5765
		sip_pvt_lock(p);
5621
		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 */
5622
		sip_pvt_unlock(p);
5767
		sip_pvt_unlock(p);

    
   
5768
		ast_module_unref(ast_module_info->self);
5623
		return 0;
5769
		return 0;
5624
	}
5770
	}
5625

    
   
5771

   
5626
	if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
5772
	if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
5627
		if (p->refer)
5773
		if (p->refer)
[+20] [20] 708 lines
[+20] [+] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
6336
		return NULL;
6482
		return NULL;
6337
	}
6483
	}
6338
	ast_channel_lock(tmp);
6484
	ast_channel_lock(tmp);
6339
	sip_pvt_lock(i);
6485
	sip_pvt_lock(i);
6340
	ast_channel_cc_params_init(tmp, i->cc_params);
6486
	ast_channel_cc_params_init(tmp, i->cc_params);
6341
	tmp->cid.cid_tag = ast_strdup(i->cid_tag);
6487
	tmp->caller.id.tag = ast_strdup(i->cid_tag);
6342
	ast_channel_unlock(tmp);
6488
	ast_channel_unlock(tmp);
6343

    
   
6489

   
6344
	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;
6345

    
   
6491

   
6346
	/* Select our native format based on codec preference until we receive
6492
	/* Select our native format based on codec preference until we receive
[+20] [20] 90 lines
[+20] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
6437

    
   
6583

   
6438
	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");
6439

    
   
6585

   
6440
	tmp->callgroup = i->callgroup;
6586
	tmp->callgroup = i->callgroup;
6441
	tmp->pickupgroup = i->pickupgroup;
6587
	tmp->pickupgroup = i->pickupgroup;
6442
	tmp->cid.cid_pres = i->callingpres;
6588
	tmp->caller.id.name.presentation = i->callingpres;

    
   
6589
	tmp->caller.id.number.presentation = i->callingpres;
6443
	if (!ast_strlen_zero(i->parkinglot))
6590
	if (!ast_strlen_zero(i->parkinglot))
6444
		ast_string_field_set(tmp, parkinglot, i->parkinglot);
6591
		ast_string_field_set(tmp, parkinglot, i->parkinglot);
6445
	if (!ast_strlen_zero(i->accountcode))
6592
	if (!ast_strlen_zero(i->accountcode))
6446
		ast_string_field_set(tmp, accountcode, i->accountcode);
6593
		ast_string_field_set(tmp, accountcode, i->accountcode);
6447
	if (i->amaflags)
6594
	if (i->amaflags)
[+20] [20] 11 lines
[+20] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
6459
	ast_uri_decode(decoded_exten);
6606
	ast_uri_decode(decoded_exten);
6460
	ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
6607
	ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
6461

    
   
6608

   
6462
	/* Don't use ast_set_callerid() here because it will
6609
	/* Don't use ast_set_callerid() here because it will
6463
	 * generate an unnecessary NewCallerID event  */
6610
	 * generate an unnecessary NewCallerID event  */
6464
	tmp->cid.cid_ani = ast_strdup(i->cid_num);
6611
	if (!ast_strlen_zero(i->cid_num)) {
6465
	if (!ast_strlen_zero(i->rdnis))
6612
		tmp->caller.ani.number.valid = 1;
6466
		tmp->redirecting.from.number = ast_strdup(i->rdnis);
6613
		tmp->caller.ani.number.str = ast_strdup(i->cid_num);
6467
	
6614
	}
6468
	if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
6615
	if (!ast_strlen_zero(i->rdnis)) {
6469
		tmp->cid.cid_dnid = ast_strdup(i->exten);
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
	}
6470

    
   
6623

   
6471
	tmp->priority = 1;
6624
	tmp->priority = 1;
6472
	if (!ast_strlen_zero(i->uri))
6625
	if (!ast_strlen_zero(i->uri))
6473
		pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
6626
		pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
6474
	if (!ast_strlen_zero(i->domain))
6627
	if (!ast_strlen_zero(i->domain))
[+20] [20] 288 lines
[+20] [+] static struct ast_frame *sip_read(struct ast_channel *ast)
6763
	if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
6916
	if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
6764
		ast_channel_lock(ast);
6917
		ast_channel_lock(ast);
6765
		if (strcmp(ast->exten, "fax")) {
6918
		if (strcmp(ast->exten, "fax")) {
6766
			const char *target_context = S_OR(ast->macrocontext, ast->context);
6919
			const char *target_context = S_OR(ast->macrocontext, ast->context);
6767
			ast_channel_unlock(ast);
6920
			ast_channel_unlock(ast);
6768
			if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
6921
			if (ast_exists_extension(ast, target_context, "fax", 1,

    
   
6922
				S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
6769
				ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
6923
				ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
6770
				pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
6924
				pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
6771
				if (ast_async_goto(ast, target_context, "fax", 1)) {
6925
				if (ast_async_goto(ast, target_context, "fax", 1)) {
6772
					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);
6773
				}
6927
				}
[+20] [20] 31 lines
[+20] [+] static char *generate_random_string(char *buf, size_t size)
6805
}
6959
}
6806

    
   
6960

   
6807
static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
6961
static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
6808
{
6962
{
6809
	struct ast_str *uri = ast_str_alloca(size);
6963
	struct ast_str *uri = ast_str_alloca(size);
6810
	int ourport = ntohs(pvt->ourip.sin_port);

   
6811
	ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
6964
	ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
6812
	/* Here would be a great place to generate a UUID, but for now we'll
6965
	/* Here would be a great place to generate a UUID, but for now we'll
6813
	 * use the handy random string generation function we already have
6966
	 * use the handy random string generation function we already have
6814
	 */
6967
	 */
6815
	ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
6968
	ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
6816
	ast_str_append(&uri, 0, "@%s", ast_inet_ntoa(pvt->ourip.sin_addr));
6969
	ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify(&pvt->ourip));
6817
	if (!sip_standard_port(pvt->socket.type, ourport)) {

   
6818
		ast_str_append(&uri, 0, ":%d", ourport);

   
6819
	}

   
6820
	ast_copy_string(buf, ast_str_buffer(uri), size);
6970
	ast_copy_string(buf, ast_str_buffer(uri), size);
6821
	return buf;
6971
	return buf;
6822
}
6972
}
6823

    
   
6973

   
6824
/*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
6974
/*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
6825
static void build_callid_pvt(struct sip_pvt *pvt)
6975
static void build_callid_pvt(struct sip_pvt *pvt)
6826
{
6976
{
6827
	char buf[33];
6977
	char buf[33];
6828

    
   
6978

   
6829
	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));
6830
	
6980
	
6831
	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);
6832

    
   
6982

   
6833
}
6983
}
6834

    
   
6984

   
6835
/*! \brief Build SIP Call-ID value for a REGISTER transaction */
6985
/*! \brief Build SIP Call-ID value for a REGISTER transaction */
6836
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)
6837
{
6987
{
6838
	char buf[33];
6988
	char buf[33];
6839

    
   
6989

   
6840
	const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
6990
	const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host(ourip));
6841

    
   
6991

   
6842
	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);
6843
}
6993
}
6844

    
   
6994

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

    
   
7020

   
6871
/*! \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.
6872
 * 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
6873
 * remember to release the reference.
7023
 * remember to release the reference.
6874
 */
7024
 */
6875
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,
6876
				 int useglobal_nat, const int intended_method, struct sip_request *req)
7026
				 int useglobal_nat, const int intended_method, struct sip_request *req)
6877
{
7027
{
6878
	struct sip_pvt *p;
7028
	struct sip_pvt *p;
6879

    
   
7029

   
6880
	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")))
[+20] [20] 7 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,
6888
	if (!(p->cc_params = ast_cc_config_params_init())) {
7038
	if (!(p->cc_params = ast_cc_config_params_init())) {
6889
		ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
7039
		ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
6890
		return NULL;
7040
		return NULL;
6891
	}
7041
	}
6892

    
   
7042

   

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

    
   
7044
	 * some information about that request */
6893
	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
		}
6894
		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 */
6895
	} else {
7064
	} else {
6896
		set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
7065
		set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
6897
	}
7066
	}
6898

    
   
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,
6908
	p->stateid = -1;
7077
	p->stateid = -1;
6909
	p->sessionversion_remote = -1;
7078
	p->sessionversion_remote = -1;
6910
	p->session_modify = TRUE;
7079
	p->session_modify = TRUE;
6911
	p->stimer = NULL;
7080
	p->stimer = NULL;
6912
	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;
6913

    
   
7083

   
6914
	if (intended_method != SIP_OPTIONS) {	/* Peerpoke has it's own system */
7084
	if (intended_method != SIP_OPTIONS) {	/* Peerpoke has it's own system */
6915
		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) */
6916
		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) */
6917
	}
7087
	}
6918

    
   
7088

   
6919
	if (!sin)
7089
	if (!addr) {
6920
		p->ourip = internip;
7090
		p->ourip = internip;
6921
	else {
7091
	} else {
6922
		p->sa = *sin;
7092
		ast_sockaddr_copy(&p->sa, addr);
6923
		ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
7093
		ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
6924
	}
7094
	}
6925

    
   
7095

   
6926
	/* Copy global flags to this PVT at setup. */
7096
	/* Copy global flags to this PVT at setup. */
6927
	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);
6928
	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);
[+20] [20] 6 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,
6935
	p->ocseq = INITIAL_CSEQ;
7105
	p->ocseq = INITIAL_CSEQ;
6936
	p->allowed_methods = UINT_MAX;
7106
	p->allowed_methods = UINT_MAX;
6937

    
   
7107

   
6938
	if (sip_methods[intended_method].need_rtp) {
7108
	if (sip_methods[intended_method].need_rtp) {
6939
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
7109
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
6940
			if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
7110
			if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
6941
				ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
7111
				ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
6942
				p->t38_maxdatagram = global_t38_maxdatagram;
7112
				p->t38_maxdatagram = global_t38_maxdatagram;
6943
			} else {
7113
			} else {
6944
				/* udptl creation failed, T38 can not be supported on this dialog */
7114
				/* udptl creation failed, T38 can not be supported on this dialog */
6945
				ast_log(LOG_ERROR, "UDPTL creation failed\n");
7115
				ast_log(LOG_ERROR, "UDPTL creation failed\n");
6946
				ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
7116
				ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
6947
			}
7117
			}
6948
		}
7118
		}
6949
		p->maxcallbitrate = default_maxcallbitrate;
7119
		p->maxcallbitrate = default_maxcallbitrate;
6950
		p->autoframing = global_autoframing;
7120
		p->autoframing = global_autoframing;
6951
	}
7121
	}
6952

    
   
7122

   
6953
	if (useglobal_nat && sin) {
7123
	if (useglobal_nat && addr) {
6954
		/* 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 */
6955
		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);
6956
		p->recv = *sin;
7126
		ast_sockaddr_copy(&p->recv, addr);

    
   
7127

   
6957
		do_setnat(p);
7128
		do_setnat(p);
6958
	}
7129
	}
6959

    
   
7130

   
6960
	if (p->method != SIP_REGISTER) {
7131
	if (p->method != SIP_REGISTER) {
6961
		ast_string_field_set(p, fromdomain, default_fromdomain);
7132
		ast_string_field_set(p, fromdomain, default_fromdomain);
[+20] [20] 28 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,
6990
	
7161
	
6991
	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");
6992
	return p;
7163
	return p;
6993
}
7164
}
6994

    
   
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

   
6995
/*! \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.
6996
 * 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
6997
 * 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.
6998
 *     Called by handle_incoming(), sipsock_read
7319
 *     Called by handle_incoming(), sipsock_read
6999
 */
7320
 */
7000
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)
7001
{
7322
{
7002
	struct sip_pvt *p = NULL;
7323
	struct sip_pvt *p = NULL;
7003
	char *tag = "";	/* note, tag is never NULL */

   
7004
	char totag[128];
7324
	char totag[128];
7005
	char fromtag[128];
7325
	char fromtag[128];
7006
	const char *callid = get_header(req, "Call-ID");
7326
	const char *callid = get_header(req, "Call-ID");
7007
	const char *from = get_header(req, "From");
7327
	const char *from = get_header(req, "From");
7008
	const char *to = get_header(req, "To");
7328
	const char *to = get_header(req, "To");
7009
	const char *cseq = get_header(req, "Cseq");
7329
	const char *cseq = get_header(req, "Cseq");
7010
	struct sip_pvt *sip_pvt_ptr;
7330
	struct sip_pvt *sip_pvt_ptr;
7011

    
   
7331
	unsigned int seqno;
7012
	/* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
7332
	/* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
7013
	/* get_header always returns non-NULL so we must use ast_strlen_zero() */
7333
	/* get_header always returns non-NULL so we must use ast_strlen_zero() */
7014
	if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
7334
	if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
7015
			ast_strlen_zero(from) || ast_strlen_zero(cseq))
7335
			ast_strlen_zero(from) || ast_strlen_zero(cseq) ||

    
   
7336
			(sscanf(cseq, "%30u", &seqno) != 1)) {

    
   
7337

   

    
   
7338
		/* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */

    
   
7339
		if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {

    
   
7340
			transmit_response_using_temp(callid, addr, 1, intended_method,

    
   
7341
						     req, "400 Bad Request");

    
   
7342
		}
7016
		return NULL;	/* Invalid packet */
7343
		return NULL;	/* Invalid packet */

    
   
7344
	}
7017

    
   
7345

   
7018
	if (sip_cfg.pedanticsipchecking) {
7346
	if (sip_cfg.pedanticsipchecking) {
7019
		/* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
7347
		/* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
7020
		   we need more to identify a branch - so we have to check branch, from
7348
		   we need more to identify a branch - so we have to check branch, from
7021
		   and to tags to identify a call leg.
7349
		   and to tags to identify a call leg.
7022
		   For Asterisk to behave correctly, you need to turn on pedanticsipchecking
7350
		   For Asterisk to behave correctly, you need to turn on pedanticsipchecking
7023
		   in sip.conf
7351
		   in sip.conf
7024
		   */
7352
		   */
7025
		if (gettag(req, "To", totag, sizeof(totag)))
7353
		if (gettag(req, "To", totag, sizeof(totag)))
7026
			req->has_to_tag = 1;	/* Used in handle_request/response */
7354
			req->has_to_tag = 1;	/* Used in handle_request/response */
7027
		gettag(req, "From", fromtag, sizeof(fromtag));
7355
		gettag(req, "From", fromtag, sizeof(fromtag));
7028

    
   
7356

   
7029
		tag = (req->method == SIP_RESPONSE) ? totag : fromtag;

   
7030

    
   

   
7031
		ast_debug(5, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
7357
		ast_debug(5, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
7032

    
   
7358

   
7033
		/* All messages must always have From: tag */
7359
		/* All messages must always have From: tag */
7034
		if (ast_strlen_zero(fromtag)) {
7360
		if (ast_strlen_zero(fromtag)) {
7035
			ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
7361
			ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
7036
			return NULL;
7362
			return NULL;
7037
		}
7363
		}
7038
		/* reject requests that must always have a To: tag */
7364
		/* reject requests that must always have a To: tag */
7039
		if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
7365
		if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {

    
   
7366
			if (req->method != SIP_ACK) {

    
   
7367
				transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");

    
   
7368
			}
7040
			ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
7369
			ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
7041
			return NULL;
7370
			return NULL;
7042
		}
7371
		}
7043
	}
7372
	}
7044

    
   
7373

   
[+20] [20] 5 lines
[+20] static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method) [+] static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
7050
		if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
7379
		if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
7051
			/* Found the call */
7380
			/* Found the call */
7052
			sip_pvt_lock(sip_pvt_ptr);
7381
			sip_pvt_lock(sip_pvt_ptr);
7053
			return sip_pvt_ptr;
7382
			return sip_pvt_ptr;
7054
		}
7383
		}
7055
	} else { /* in pedantic mode! -- do the fancy linear search */
7384
	} else { /* in pedantic mode! -- do the fancy search */
7056
		struct sip_pvt tmp_dialog = {
7385
		struct sip_pvt tmp_dialog = {
7057
			.callid = callid,
7386
			.callid = callid,
7058
		};
7387
		};
7059
		struct ao2_iterator *iterator = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER | OBJ_MULTIPLE,
7388
		struct match_req_args args = { 0, };

    
   
7389
		int found;

    
   
7390
		struct ao2_iterator *iterator = ao2_t_callback(dialogs,

    
   
7391
			OBJ_POINTER | OBJ_MULTIPLE,

    
   
7392
			dialog_find_multiple,

    
   
7393
			&tmp_dialog,
7060
							   "pedantic ao2_find in dialogs");
7394
			"pedantic ao2_find in dialogs");
7061
		if (iterator) {

   
7062
			int found = TRUE;

   
7063

    
   
7395

   
7064
			while ((sip_pvt_ptr = ao2_iterator_next(iterator))) {
7396
		args.method = req->method;
7065
				if (req->method != SIP_REGISTER) {
7397
		args.callid = NULL; /* we already matched this. */
7066
					found = ast_strlen_zero(tag) || ast_strlen_zero(sip_pvt_ptr->theirtag) ||
7398
		args.totag = totag;
7067
						!ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) ||
7399
		args.fromtag = fromtag;
7068
						!strcmp(sip_pvt_ptr->theirtag, tag);
7400
		args.seqno = seqno;
7069
				}
7401

   
7070
				ast_debug(5, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match",
7402
		/* If this is a Request, set the Via and Authorization header arguments */
7071
					  sip_pvt_ptr->callid, sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
7403
		if (req->method != SIP_RESPONSE) {
7072
				/* If we get a new request within an existing to-tag - check the to tag as well */
7404
			args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
7073
				if (found && req->method != SIP_RESPONSE) { /* SIP Request */
7405
			get_viabranch(ast_strdupa(get_header(req, "Via")), (char **) &args.viasentby, (char **) &args.viabranch);
7074
					if (sip_pvt_ptr->tag[0] == '\0' && totag[0]) {
7406
			if (!ast_strlen_zero(get_header(req, "Authorization")) ||
7075
						/* We have no to tag, but they have. Wrong dialog */
7407
				!ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
7076
						found = FALSE;
7408
				args.authentication_present = 1;
7077
					} else if (totag[0]) { /* Both have tags, compare them */
7409
			}
7078
						if (strcmp(totag, sip_pvt_ptr->tag)) {

   
7079
							found = FALSE; /* This is not our packet */

   
7080
						}

   
7081
					}

   
7082
					if (!found)

   
7083
						ast_debug(5, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n",

   
7084
							  sip_pvt_ptr->callid, totag, sip_methods[req->method].text);

   
7085
				}
7410
		}
7086
				if (found) {
7411

   

    
   
7412
		/* Iterate a list of dialogs already matched by Call-id */

    
   
7413
		while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {

    
   
7414
			found = match_req_to_dialog(sip_pvt_ptr, &args);

    
   
7415

   

    
   
7416
			switch (found) {

    
   
7417
			case SIP_REQ_MATCH:
7087
					sip_pvt_lock(sip_pvt_ptr);
7418
				sip_pvt_lock(sip_pvt_ptr);
7088
					ao2_iterator_destroy(iterator);
7419
				ao2_iterator_destroy(iterator);
7089
					return sip_pvt_ptr;
7420
				return sip_pvt_ptr; /* return pvt with ref */

    
   
7421
			case SIP_REQ_LOOP_DETECTED:

    
   
7422
				/* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.

    
   
7423
			 	* RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */

    
   
7424
				transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");

    
   
7425
				dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");

    
   
7426
				ao2_iterator_destroy(iterator);

    
   
7427
				return NULL;

    
   
7428
			case SIP_REQ_NOT_MATCH:

    
   
7429
			default:

    
   
7430
				dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
7090
				}
7431
			}
7091
			}
7432
		}

    
   
7433
		if (iterator) {
7092
			ao2_iterator_destroy(iterator);
7434
			ao2_iterator_destroy(iterator);
7093
		}
7435
		}
7094
	}
7436
	} /* end of pedantic mode Request/Reponse to Dialog matching */
7095

    
   
7437

   
7096
	/* See if the method is capable of creating a dialog */
7438
	/* See if the method is capable of creating a dialog */
7097
	if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
7439
	if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
7098
		if (intended_method == SIP_REFER) {
7440
		if (intended_method == SIP_REFER) {
7099
			/* We do support REFER, but not outside of a dialog yet */
7441
			/* We do support REFER, but not outside of a dialog yet */
7100
			transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
7442
			transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
7101
		} else {
7443
		} else {
7102
			/* Ok, time to create a new SIP dialog object, a pvt */
7444
			/* Ok, time to create a new SIP dialog object, a pvt */
7103
			if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
7445
			if ((p = sip_alloc(callid, addr, 1, intended_method, req)))  {
7104
				/* Ok, we've created a dialog, let's go and process it */
7446
				/* Ok, we've created a dialog, let's go and process it */
7105
				sip_pvt_lock(p);
7447
				sip_pvt_lock(p);
7106
			} else {
7448
			} else {
7107
				/* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
7449
				/* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
7108
					getting a dialog from sip_alloc.
7450
					getting a dialog from sip_alloc.
7109
	
7451
	
7110
					Without a dialog we can't retransmit and handle ACKs and all that, but at least
7452
					Without a dialog we can't retransmit and handle ACKs and all that, but at least
7111
					send an error message.
7453
					send an error message.
7112
	
7454
	
7113
					Sorry, we apologize for the inconvienience
7455
					Sorry, we apologize for the inconvienience
7114
				*/
7456
				*/
7115
				transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
7457
				transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
7116
				ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
7458
				ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
7117
			}
7459
			}
7118
		}
7460
		}
7119
		return p; /* can be NULL */
7461
		return p; /* can be NULL */
7120
	} else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
7462
	} else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
7121
		/* A method we do not support, let's take it on the volley */
7463
		/* A method we do not support, let's take it on the volley */
7122
		transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
7464
		transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
7123
		ast_debug(2, "Got a request with unsupported SIP method.\n");
7465
		ast_debug(2, "Got a request with unsupported SIP method.\n");
7124
	} else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
7466
	} else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
7125
		/* This is a request outside of a dialog that we don't know about */
7467
		/* This is a request outside of a dialog that we don't know about */
7126
		transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
7468
		transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
7127
		ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
7469
		ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
7128
	}
7470
	}
7129
	/* We do not respond to responses for dialogs that we don't know about, we just drop
7471
	/* We do not respond to responses for dialogs that we don't know about, we just drop
7130
	   the session quickly */
7472
	   the session quickly */
7131
	if (intended_method == SIP_RESPONSE)
7473
	if (intended_method == SIP_RESPONSE)
7132
		ast_debug(2, "That's odd...  Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
7474
		ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
7133

    
   
7475

   
7134
	return NULL;
7476
	return NULL;
7135
}
7477
}
7136

    
   
7478

   
7137
/*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
7479
/*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
[+20] [20] 433 lines
[+20] [+] static int find_sdp(struct sip_request *req)
7571
	}
7913
	}
7572
	return FALSE;
7914
	return FALSE;
7573
}
7915
}
7574

    
   
7916

   
7575

    
   
7917

   
7576
static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
7918
static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
7577
{
7919
{
7578
	const char *m;
7920
	const char *m;
7579
	const char *c;
7921
	const char *c;
7580
	int miterator = req->sdp_start;
7922
	int miterator = req->sdp_start;
7581
	int citerator = req->sdp_start;
7923
	int citerator = req->sdp_start;
7582
	int x = 0;
7924
	int x = 0;
7583
	int numberofports;
7925
	int numberofports;
7584
	int len;
7926
	int len;
7585
	char host[258] = ""; /*Initialize to empty so we will know if we have any input */
7927
	int af;
7586
	struct ast_hostent audiohp;
7928
	char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
7587
	struct hostent *hp;

   
7588

    
   
7929

   
7589
	c = get_sdp_iterate(&citerator, req, "c");
7930
	c = get_sdp_iterate(&citerator, req, "c");
7590
	if (sscanf(c, "IN IP4 %256s", host) != 1) {
7931
	if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
7591
		ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
7932
			ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
7592
		/* Continue since there may be a valid host in a c= line specific to the audio stream */
7933
			/* Continue since there may be a valid host in a c= line specific to the audio stream */
7593
	}
7934
	}
7594
	/* We only want the m and c lines for audio */
7935
	/* We only want the m and c lines for audio */
7595
	for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
7936
	for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
[+20] [20] 5 lines
[+20] static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin) [+] static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
7601
			 * XXX There is no guarantee that we'll be grabbing the c= line for this
7942
			 * XXX There is no guarantee that we'll be grabbing the c= line for this
7602
			 * particular media stream here. However, this is the same logic used in process_sdp.
7943
			 * particular media stream here. However, this is the same logic used in process_sdp.
7603
			 */
7944
			 */
7604
			c = get_sdp_iterate(&citerator, req, "c");
7945
			c = get_sdp_iterate(&citerator, req, "c");
7605
			if (!ast_strlen_zero(c)) {
7946
			if (!ast_strlen_zero(c)) {
7606
				sscanf(c, "IN IP4 %256s", host);
7947
				sscanf(c, "IN %3s %256s", proto, host);
7607
			}
7948
			}
7608
			break;
7949
			break;
7609
		}
7950
		}
7610
	}
7951
	}
7611

    
   
7952

   

    
   
7953
	if (!strcmp("IP4", proto)) {

    
   
7954
		af = AF_INET;

    
   
7955
	} else if (!strcmp("IP6", proto)) {

    
   
7956
		af = AF_INET6;

    
   
7957
	} else {

    
   
7958
		ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);

    
   
7959
		return -1;

    
   
7960
	}

    
   
7961

   
7612
	if (ast_strlen_zero(host) || x == 0) {
7962
	if (ast_strlen_zero(host) || x == 0) {
7613
		ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
7963
		ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
7614
		return -1;
7964
		return -1;
7615
	}
7965
	}
7616

    
   
7966

   
7617
	hp = ast_gethostbyname(host, &audiohp);
7967
	if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
7618
	if (!hp) {

   
7619
		ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
7968
		ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
7620
		return -1;
7969
		return -1;
7621
	}
7970
	}
7622

    
   
7971

   
7623
	memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));

   
7624
	sin->sin_port = htons(x);

   
7625
	return 0;
7972
	return 0;
7626
}
7973
}
7627

    
   
7974

   
7628
/*! \brief Process SIP SDP offer, select formats and activate RTP channels
7975
/*! \brief Process SIP SDP offer, select formats and activate RTP channels
7629
	If offer is rejected, we will not change any properties of the call
7976
	If offer is rejected, we will not change any properties of the call
[+20] [20] 13 lines
[+20] [+] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
7643
	const char *m = NULL;           /* SDP media offer */
7990
	const char *m = NULL;           /* SDP media offer */
7644
	const char *nextm = NULL;
7991
	const char *nextm = NULL;
7645
	int len = -1;
7992
	int len = -1;
7646

    
   
7993

   
7647
	/* Host information */
7994
	/* Host information */
7648
	struct ast_hostent sessionhp;
7995
	struct ast_sockaddr sessionsa;
7649
	struct ast_hostent audiohp;
7996
	struct ast_sockaddr audiosa;
7650
	struct ast_hostent videohp;
7997
	struct ast_sockaddr videosa;
7651
	struct ast_hostent texthp;
7998
	struct ast_sockaddr textsa;
7652
	struct ast_hostent imagehp;
7999
	struct ast_sockaddr imagesa;
7653
	struct hostent *hp = NULL;	/*!< RTP Audio host IP */
8000
	struct ast_sockaddr *sa = NULL;	/*!< RTP Audio host IP */
7654
	struct hostent *vhp = NULL;	/*!< RTP video host IP */
8001
	struct ast_sockaddr *vsa = NULL;	/*!< RTP video host IP */
7655
	struct hostent *thp = NULL;	/*!< RTP text host IP */
8002
	struct ast_sockaddr *tsa = NULL;	/*!< RTP text host IP */
7656
	struct hostent *ihp = NULL;     /*!< UDPTL host ip */
8003
	struct ast_sockaddr *isa = NULL;     /*!< UDPTL host ip */
7657
 	int portno = -1;		/*!< RTP Audio port number */
8004
 	int portno = -1;		/*!< RTP Audio port number */
7658
 	int vportno = -1;		/*!< RTP Video port number */
8005
 	int vportno = -1;		/*!< RTP Video port number */
7659
	int tportno = -1;		/*!< RTP Text port number */
8006
	int tportno = -1;		/*!< RTP Text port number */
7660
	int udptlportno = -1;		/*!< UDPTL Image port number */
8007
	int udptlportno = -1;		/*!< UDPTL Image port number */
7661
	struct sockaddr_in sin;		/*!< media socket address */

   
7662
	struct sockaddr_in vsin;	/*!< video socket address */

   
7663
	struct sockaddr_in isin;	/*!< image socket address */

   
7664
	struct sockaddr_in tsin;	/*!< text socket address */

   
7665

    
   
8008

   
7666
	/* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */	
8009
	/* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */	
7667
	format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
8010
	format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
7668
	int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
8011
	int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
7669

    
   
8012

   
7670
	struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
8013
	struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
7671
	format_t newjointcapability;				/* Negotiated capability */
8014
	format_t newjointcapability;				/* Negotiated capability */
7672
	format_t newpeercapability;
8015
	format_t newpeercapability;
7673
	int newnoncodeccapability;
8016
	int newnoncodeccapability;
7674

    
   
8017

   
7675
	const char *codecs;
8018
	const char *codecs;
7676
	int codec;
8019
	int codec;
7677

    
   
8020

   

    
   
8021
	/* SRTP */

    
   
8022
	int secure_audio = FALSE;

    
   
8023
	int secure_video = FALSE;

    
   
8024

   
7678
	/* Others */
8025
	/* Others */
7679
	int sendonly = -1;
8026
	int sendonly = -1;
7680
	int vsendonly = -1;
8027
	int vsendonly = -1;
7681
	int numberofports;
8028
	int numberofports;
7682
	int numberofmediastreams = 0;
8029
	int numberofmediastreams = 0;
[+20] [20] 53 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
7736
			 */
8083
			 */
7737
			if (!process_sdp_o(value, p))
8084
			if (!process_sdp_o(value, p))
7738
				return (p->session_modify == FALSE) ? 0 : -1;
8085
				return (p->session_modify == FALSE) ? 0 : -1;
7739
			break;
8086
			break;
7740
		case 'c':
8087
		case 'c':
7741
			if (process_sdp_c(value, &sessionhp)) {
8088
			if (process_sdp_c(value, &sessionsa)) {
7742
				processed = TRUE;
8089
				processed = TRUE;
7743
				hp = &sessionhp.hp;
8090
				sa = &sessionsa;
7744
				vhp = hp;
8091
				vsa = sa;
7745
				thp = hp;
8092
				tsa = sa;
7746
				ihp = hp;
8093
				isa = sa;
7747
			}
8094
			}
7748
			break;
8095
			break;
7749
		case 'a':
8096
		case 'a':
7750
			if (process_sdp_a_sendonly(value, &sendonly)) {
8097
			if (process_sdp_a_sendonly(value, &sendonly)) {
7751
				processed = TRUE;
8098
				processed = TRUE;
[+20] [20] 20 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
7772
	while (!ast_strlen_zero(nextm)) {
8119
	while (!ast_strlen_zero(nextm)) {
7773
		int audio = FALSE;
8120
		int audio = FALSE;
7774
		int video = FALSE;
8121
		int video = FALSE;
7775
		int image = FALSE;
8122
		int image = FALSE;
7776
		int text = FALSE;
8123
		int text = FALSE;

    
   
8124
		char protocol[5] = {0,};
7777
		int x;
8125
		int x;
7778

    
   
8126

   
7779
		numberofports = 1;
8127
		numberofports = 1;
7780
		len = -1;
8128
		len = -1;
7781
		start = next;
8129
		start = next;
7782
		m = nextm;
8130
		m = nextm;
7783
		iterator = next;
8131
		iterator = next;
7784
		nextm = get_sdp_iterate(&next, req, "m");
8132
		nextm = get_sdp_iterate(&next, req, "m");
7785

    
   
8133

   
7786
		/* Search for audio media definition */
8134
		/* Search for audio media definition */
7787
		if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
8135
		if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
7788
		    (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
8136
		    (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {

    
   
8137
			if (!strcmp(protocol, "SAVP")) {

    
   
8138
				secure_audio = 1;

    
   
8139
			} else if (strcmp(protocol, "AVP")) {

    
   
8140
				ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);

    
   
8141
				continue;

    
   
8142
			}
7789
			audio = TRUE;
8143
			audio = TRUE;
7790
			p->offered_media[SDP_AUDIO].offered = TRUE;
8144
			p->offered_media[SDP_AUDIO].offered = TRUE;
7791
			numberofmediastreams++;
8145
			numberofmediastreams++;
7792
			portno = x;
8146
			portno = x;
7793

    
   
8147

   
[+20] [20] 9 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
7803
					ast_verbose("Found RTP audio format %d\n", codec);
8157
					ast_verbose("Found RTP audio format %d\n", codec);
7804
				
8158
				
7805
				ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
8159
				ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
7806
			}
8160
			}
7807
		/* Search for video media definition */
8161
		/* Search for video media definition */
7808
		} else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
8162
		} else if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
7809
			   (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
8163
			   (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len >= 0)) {

    
   
8164
			if (!strcmp(protocol, "SAVP")) {

    
   
8165
				secure_video = 1;

    
   
8166
			} else if (strcmp(protocol, "AVP")) {

    
   
8167
				ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);

    
   
8168
				continue;

    
   
8169
			}
7810
			video = TRUE;
8170
			video = TRUE;
7811
			p->novideo = FALSE;
8171
			p->novideo = FALSE;
7812
			p->offered_media[SDP_VIDEO].offered = TRUE;
8172
			p->offered_media[SDP_VIDEO].offered = TRUE;
7813
			numberofmediastreams++;
8173
			numberofmediastreams++;
7814
			vportno = x;
8174
			vportno = x;
[+20] [20] 41 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
7856
			udptlportno = x;
8216
			udptlportno = x;
7857
			numberofmediastreams++;
8217
			numberofmediastreams++;
7858

    
   
8218

   
7859
			if (p->t38.state != T38_ENABLED) {
8219
			if (p->t38.state != T38_ENABLED) {
7860
				memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
8220
				memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));

    
   
8221

   

    
   
8222
				/* default EC to none, the remote end should

    
   
8223
				 * respond with the EC they want to use */

    
   
8224
				ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
7861
			}
8225
			}
7862
		} else {
8226
		} else {
7863
			ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
8227
			ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
7864
			continue;
8228
			continue;
7865
		}
8229
		}
7866

    
   
8230

   
7867
		/* Check for number of ports */
8231
		/* Check for number of ports */
7868
		if (numberofports > 1)
8232
		if (numberofports > 1)
7869
			ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
8233
			ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
7870
		
8234
		
7871

    
   

   
7872

    
   

   
7873
		/* Media stream specific parameters */
8235
		/* Media stream specific parameters */
7874
		while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
8236
		while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
7875
			int processed = FALSE;
8237
			int processed = FALSE;
7876

    
   
8238

   
7877
			switch (type) {
8239
			switch (type) {
7878
			case 'c':
8240
			case 'c':
7879
				if (audio) {
8241
				if (audio) {
7880
					if (process_sdp_c(value, &audiohp)) {
8242
					if (process_sdp_c(value, &audiosa)) {
7881
						processed = TRUE;
8243
						processed = TRUE;
7882
						hp = &audiohp.hp;
8244
						sa = &audiosa;
7883
					}
8245
					}
7884
				} else if (video) {
8246
				} else if (video) {
7885
					if (process_sdp_c(value, &videohp)) {
8247
					if (process_sdp_c(value, &videosa)) {
7886
						processed = TRUE;
8248
						processed = TRUE;
7887
						vhp = &videohp.hp;
8249
						vsa = &videosa;
7888
					}
8250
					}
7889
				} else if (text) {
8251
				} else if (text) {
7890
					if (process_sdp_c(value, &texthp)) {
8252
					if (process_sdp_c(value, &textsa)) {
7891
						processed = TRUE;
8253
						processed = TRUE;
7892
						thp = &texthp.hp;
8254
						tsa = &textsa;
7893
					}
8255
					}
7894
				} else if (image) {
8256
				} else if (image) {
7895
					if (process_sdp_c(value, &imagehp)) {
8257
					if (process_sdp_c(value, &imagesa)) {
7896
						processed = TRUE;
8258
						processed = TRUE;
7897
						ihp = &imagehp.hp;
8259
						isa = &imagesa;
7898
					}
8260
					}
7899
				}
8261
				}
7900
				break;
8262
				break;
7901
			case 'a':
8263
			case 'a':
7902
				/* Audio specific scanning */
8264
				/* Audio specific scanning */
7903
				if (audio) {
8265
				if (audio) {
7904
					if (process_sdp_a_sendonly(value, &sendonly))
8266
					if (process_sdp_a_sendonly(value, &sendonly))
7905
						processed = TRUE;
8267
						processed = TRUE;

    
   
8268
					else if (process_crypto(p, p->rtp, &p->srtp, value))

    
   
8269
						processed = TRUE;
7906
					else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
8270
					else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
7907
						processed = TRUE;
8271
						processed = TRUE;
7908
				}
8272
				}
7909
				/* Video specific scanning */
8273
				/* Video specific scanning */
7910
				else if (video) {
8274
				else if (video) {
7911
					if (process_sdp_a_sendonly(value, &vsendonly))
8275
					if (process_sdp_a_sendonly(value, &vsendonly))
7912
						processed = TRUE;
8276
						processed = TRUE;

    
   
8277
					else if (process_crypto(p, p->vrtp, &p->vsrtp, value))

    
   
8278
						processed = TRUE;
7913
					else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
8279
					else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
7914
						processed = TRUE;
8280
						processed = TRUE;
7915
				}
8281
				}
7916
				/* Text (T.140) specific scanning */
8282
				/* Text (T.140) specific scanning */
7917
				else if (text) {
8283
				else if (text) {
7918
					if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
8284
					if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
7919
						processed = TRUE;
8285
						processed = TRUE;

    
   
8286
					else if (process_crypto(p, p->trtp, &p->tsrtp, value))

    
   
8287
						processed = TRUE;
7920
				}
8288
				}
7921
				/* Image (T.38 FAX) specific scanning */
8289
				/* Image (T.38 FAX) specific scanning */
7922
				else if (image) {
8290
				else if (image) {
7923
					if (process_sdp_a_image(value, p))
8291
					if (process_sdp_a_image(value, p))
7924
						processed = TRUE;
8292
						processed = TRUE;
[+20] [20] 9 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
7934
		}
8302
		}
7935
	}
8303
	}
7936

    
   
8304

   
7937

    
   
8305

   
7938
	/* Sanity checks */
8306
	/* Sanity checks */
7939
	if (!hp && !vhp && !thp && !ihp) {
8307
	if (!sa && !vsa && !tsa && !isa) {
7940
		ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
8308
		ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
7941
		return -1;
8309
		return -1;
7942
	}
8310
	}
7943

    
   
8311

   
7944
	if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
8312
	if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1) {
7945
		/* No acceptable offer found in SDP  - we have no ports */
8313
		/* No acceptable offer found in SDP  - we have no ports */
7946
		/* Do not change RTP or VRTP if this is a re-invite */
8314
		/* Do not change RTP or VRTP if this is a re-invite */

    
   
8315
		ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
7947
		return -2;
8316
		return -2;

    
   
8317
	}
7948

    
   
8318

   
7949
	if (numberofmediastreams > 3)
8319
	if (numberofmediastreams > 3) {
7950
		/* We have too many fax, audio and/or video and/or text media streams, fail this offer */
8320
		/* We have too many fax, audio and/or video and/or text media streams, fail this offer */

    
   
8321
		ast_log(LOG_WARNING, "Faling due to too many media streams\n");
7951
		return -3;
8322
		return -3;

    
   
8323
	}

    
   
8324

   

    
   
8325
	if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {

    
   
8326
		ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");

    
   
8327
		return -4;

    
   
8328
	}

    
   
8329

   

    
   
8330
	if (!secure_audio && p->srtp) {

    
   
8331
		ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");

    
   
8332
		return -4;

    
   
8333
	}

    
   
8334

   

    
   
8335
	if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {

    
   
8336
		ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");

    
   
8337
		return -4;

    
   
8338
	}

    
   
8339

   

    
   
8340
	if (!p->novideo && !secure_video && p->vsrtp) {

    
   
8341
		ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");

    
   
8342
		return -4;

    
   
8343
	}

    
   
8344

   

    
   
8345
	if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {

    
   
8346
		ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");

    
   
8347
		return -4;

    
   
8348
	}
7952

    
   
8349

   
7953
	if (udptlportno == -1) {
8350
	if (udptlportno == -1) {
7954
		change_t38_state(p, T38_DISABLED);
8351
		change_t38_state(p, T38_DISABLED);
7955
	}
8352
	}
7956

    
   
8353

   
7957

    
   

   
7958
	/* Now gather all of the codecs that we are asked for: */
8354
	/* Now gather all of the codecs that we are asked for: */
7959
	ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
8355
	ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
7960
	ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
8356
	ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
7961
	ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
8357
	ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
7962

    
   
8358

   
[+20] [20] 29 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
7992
	}
8388
	}
7993

    
   
8389

   
7994
	/* Setup audio address and port */
8390
	/* Setup audio address and port */
7995
	if (p->rtp) {
8391
	if (p->rtp) {
7996
		if (portno > 0) {
8392
		if (portno > 0) {
7997
			sin.sin_family = AF_INET;
8393
			ast_sockaddr_set_port(sa, portno);
7998
			sin.sin_port = htons(portno);
8394
			ast_rtp_instance_set_remote_address(p->rtp, sa);
7999
			memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
8395
			if (debug) {
8000
			ast_rtp_instance_set_remote_address(p->rtp, &sin);
8396
				ast_verbose("Peer audio RTP is at port %s\n",
8001
			if (debug)
8397
					    ast_sockaddr_stringify(sa));
8002
				ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
8398
			}
8003
			/* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
8399
			/* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since
8004
			   they are acceptable */
8400
			   they are acceptable */
8005
			p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
8401
			p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
8006
			p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
8402
			p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
8007
			p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
8403
			p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
8008

    
   
8404

   
[+20] [20] 26 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
8035
	}
8431
	}
8036

    
   
8432

   
8037
	/* Setup video address and port */
8433
	/* Setup video address and port */
8038
	if (p->vrtp) {
8434
	if (p->vrtp) {
8039
		if (vportno > 0) {
8435
		if (vportno > 0) {
8040
			vsin.sin_family = AF_INET;
8436
			ast_sockaddr_set_port(vsa, vportno);
8041
			vsin.sin_port = htons(vportno);
8437
			ast_rtp_instance_set_remote_address(p->vrtp, vsa);
8042
			memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
8438
			if (debug) {
8043
			ast_rtp_instance_set_remote_address(p->vrtp, &vsin);
8439
				ast_verbose("Peer video RTP is at port %s\n",
8044
			if (debug) 
8440
					    ast_sockaddr_stringify(vsa));
8045
				ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
8441
			}
8046
			ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
8442
			ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
8047
		} else {
8443
		} else {
8048
			ast_rtp_instance_stop(p->vrtp);
8444
			ast_rtp_instance_stop(p->vrtp);
8049
			if (debug)
8445
			if (debug)
8050
				ast_verbose("Peer doesn't provide video\n");
8446
				ast_verbose("Peer doesn't provide video\n");
8051
		}
8447
		}
8052
	}
8448
	}
8053

    
   
8449

   
8054
	/* Setup text address and port */
8450
	/* Setup text address and port */
8055
	if (p->trtp) {
8451
	if (p->trtp) {
8056
		if (tportno > 0) {
8452
		if (tportno > 0) {
8057
			tsin.sin_family = AF_INET;
8453
			ast_sockaddr_set_port(tsa, tportno);
8058
			tsin.sin_port = htons(tportno);
8454
			ast_rtp_instance_set_remote_address(p->trtp, tsa);
8059
			memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
8455
			if (debug) {
8060
			ast_rtp_instance_set_remote_address(p->trtp, &tsin);
8456
				ast_verbose("Peer T.140 RTP is at port %s\n",
8061
			if (debug) 
8457
					    ast_sockaddr_stringify(tsa));
8062
				ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
8458
			}
8063
			if ((p->jointcapability & AST_FORMAT_T140RED)) {
8459
			if ((p->jointcapability & AST_FORMAT_T140RED)) {
8064
				p->red = 1;
8460
				p->red = 1;
8065
				ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
8461
				ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
8066
			} else {
8462
			} else {
8067
				p->red = 0;
8463
				p->red = 0;
[+20] [20] 6 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
8074
		}
8470
		}
8075
	}
8471
	}
8076
	/* Setup image address and port */
8472
	/* Setup image address and port */
8077
	if (p->udptl) {
8473
	if (p->udptl) {
8078
		if (udptlportno > 0) {
8474
		if (udptlportno > 0) {
8079
			isin.sin_family = AF_INET;

   
8080
			isin.sin_port = htons(udptlportno);

   
8081
			if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
8475
			if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
8082
				struct sockaddr_in remote_address = { 0, };
8476
				ast_rtp_instance_get_remote_address(p->rtp, isa);
8083
				ast_rtp_instance_get_remote_address(p->rtp, &remote_address);
8477
				if (!ast_sockaddr_isnull(isa)) {
8084
				if (remote_address.sin_addr.s_addr) {

   
8085
					memcpy(&isin, &remote_address, sizeof(isin));

   
8086
					if (debug) {
8478
					if (debug) {
8087
						ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(isin.sin_addr));
8479
						ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
8088
					}
8480
					}
8089
				}
8481
				}
8090
			} else {

   
8091
				memcpy(&isin.sin_addr, ihp->h_addr, sizeof(isin.sin_addr));

   
8092
			}
8482
			}
8093
			ast_udptl_set_peer(p->udptl, &isin);
8483
			ast_sockaddr_set_port(isa, udptlportno);

    
   
8484
			ast_udptl_set_peer(p->udptl, isa);
8094
			if (debug)
8485
			if (debug)
8095
				ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
8486
				ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
8096

    
   
8487

   
8097
			/* verify the far max ifp can be calculated. this requires far max datagram to be set. */
8488
			/* verify the far max ifp can be calculated. this requires far max datagram to be set. */
8098
			if (!ast_udptl_get_far_max_datagram(p->udptl)) {
8489
			if (!ast_udptl_get_far_max_datagram(p->udptl)) {
8099
				/* setting to zero will force a default if none was provided by the SDP */
8490
				/* setting to zero will force a default if none was provided by the SDP */
8100
				ast_udptl_set_far_max_datagram(p->udptl, 0);
8491
				ast_udptl_set_far_max_datagram(p->udptl, 0);
[+20] [20] 10 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
8111
				if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
8502
				if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
8112
					ast_channel_lock(p->owner);
8503
					ast_channel_lock(p->owner);
8113
					if (strcmp(p->owner->exten, "fax")) {
8504
					if (strcmp(p->owner->exten, "fax")) {
8114
						const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
8505
						const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
8115
						ast_channel_unlock(p->owner);
8506
						ast_channel_unlock(p->owner);
8116
						if (ast_exists_extension(p->owner, target_context, "fax", 1, p->owner->cid.cid_num)) {
8507
						if (ast_exists_extension(p->owner, target_context, "fax", 1,

    
   
8508
							S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
8117
							ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
8509
							ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
8118
							pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
8510
							pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
8119
							if (ast_async_goto(p->owner, target_context, "fax", 1)) {
8511
							if (ast_async_goto(p->owner, target_context, "fax", 1)) {
8120
								ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
8512
								ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
8121
							}
8513
							}
[+20] [20] 35 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
8157
		p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
8549
		p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
8158
		ast_set_read_format(p->owner, p->owner->readformat);
8550
		ast_set_read_format(p->owner, p->owner->readformat);
8159
		ast_set_write_format(p->owner, p->owner->writeformat);
8551
		ast_set_write_format(p->owner, p->owner->writeformat);
8160
	}
8552
	}
8161
	
8553
	
8162
	if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
8554
	if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && !ast_sockaddr_isnull(sa) && (!sendonly || sendonly == -1)) {
8163
		ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
8555
		ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
8164
		/* Activate a re-invite */
8556
		/* Activate a re-invite */
8165
		ast_queue_frame(p->owner, &ast_null_frame);
8557
		ast_queue_frame(p->owner, &ast_null_frame);
8166
		/* Queue Manager Unhold event */
8558
		/* Queue Manager Unhold event */
8167
		append_history(p, "Unhold", "%s", req->data->str);
8559
		append_history(p, "Unhold", "%s", req->data->str);
[+20] [20] 5 lines
[+20] static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
8173
				      p->owner->name,
8565
				      p->owner->name,
8174
				      p->owner->uniqueid);
8566
				      p->owner->uniqueid);
8175
		if (sip_cfg.notifyhold)
8567
		if (sip_cfg.notifyhold)
8176
			sip_peer_hold(p, FALSE);
8568
			sip_peer_hold(p, FALSE);
8177
		ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
8569
		ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
8178
	} else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
8570
	} else if (ast_sockaddr_isnull(sa) || (sendonly && sendonly != -1)) {
8179
		int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
8571
		int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
8180
		ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
8572
		ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
8181
				       S_OR(p->mohsuggest, NULL),
8573
				       S_OR(p->mohsuggest, NULL),
8182
				       !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
8574
				       !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
8183
		if (sendonly)
8575
		if (sendonly)
[+20] [20] 101 lines
[+20] [+] static int process_sdp_o(const char *o, struct sip_pvt *p)
8285
	}
8677
	}
8286

    
   
8678

   
8287
	return TRUE;
8679
	return TRUE;
8288
}
8680
}
8289

    
   
8681

   
8290
static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
8682
static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
8291
{
8683
{
8292
	char host[258];
8684
	char proto[4], host[258];
8293
	struct hostent *hp;
8685
	int af;
8294

    
   
8686

   
8295
	/* Check for Media-description-level-address */
8687
	/* Check for Media-description-level-address */
8296
	if (sscanf(c, "IN IP4 %255s", host) != 1) {
8688
	if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
8297
		ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
8689
		if (!strcmp("IP4", proto)) {
8298
		return FALSE;
8690
			af = AF_INET;

    
   
8691
		} else if (!strcmp("IP6", proto)) {

    
   
8692
			af = AF_INET6;
8299
	} else {
8693
		} else {
8300
		if (!(hp = ast_gethostbyname(host, ast_hp))) {
8694
			ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);

    
   
8695
			return FALSE;

    
   
8696
		}

    
   
8697
		if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
8301
			ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
8698
			ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
8302
			return FALSE;
8699
			return FALSE;
8303
		}
8700
		}
8304
		return TRUE;
8701
		return TRUE;

    
   
8702
	} else {

    
   
8703
		ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);

    
   
8704
		return FALSE;
8305
	}
8705
	}
8306
	return FALSE;
8706
	return FALSE;
8307
}
8707
}
8308

    
   
8708

   
8309
static int process_sdp_a_sendonly(const char *a, int *sendonly)
8709
static int process_sdp_a_sendonly(const char *a, int *sendonly)
[+20] [20] 95 lines
[+20] [+] static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
8405
					} else {
8805
					} else {
8406
						found = TRUE;
8806
						found = TRUE;
8407
					}
8807
					}
8408
				}
8808
				}
8409
				break;
8809
				break;

    
   
8810
			case AST_FORMAT_G719:

    
   
8811
				if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {

    
   
8812
					if (bit_rate != 64000) {

    
   
8813
						ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);

    
   
8814
						ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);

    
   
8815
					} else {

    
   
8816
						found = TRUE;

    
   
8817
					}

    
   
8818
				}
8410
			}
8819
			}
8411
		}
8820
		}
8412
	}
8821
	}
8413

    
   
8822

   
8414
	return found;
8823
	return found;
[+20] [20] 206 lines
[+20] [+] static int add_header(struct sip_request *req, const char *var, const char *value)
8621
	req->headers++;
9030
	req->headers++;
8622

    
   
9031

   
8623
	return 0;	
9032
	return 0;	
8624
}
9033
}
8625

    
   
9034

   
8626
/*! \brief Add 'Content-Length' header to SIP message */
9035
/*! \brief Add 'Max-Forwards' header to SIP message */
8627
static int add_header_contentLength(struct sip_request *req, int len)
9036
static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
8628
{
9037
{
8629
	char clen[10];
9038
	char clen[10];

    
   
9039
	const char *max = NULL;

    
   
9040

   

    
   
9041
	if (dialog->owner) {

    
   
9042
 		max = pbx_builtin_getvar_helper(dialog->owner, "SIP_MAX_FORWARDS");

    
   
9043
	}

    
   
9044

   

    
   
9045
	/* The channel variable overrides the peer/channel value */

    
   
9046
	if (max == NULL) {

    
   
9047
		snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);

    
   
9048
	}

    
   
9049
	return add_header(req, "Max-Forwards", max != NULL ? max : clen);

    
   
9050
}

    
   
9051

   

    
   
9052
/*! \brief Add 'Content-Length' header and content to SIP message */

    
   
9053
static int finalize_content(struct sip_request *req)

    
   
9054
{

    
   
9055
	char clen[10];

    
   
9056

   

    
   
9057
	if (req->lines) {

    
   
9058
		ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");

    
   
9059
		return -1;

    
   
9060
	}

    
   
9061

   

    
   
9062
	snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));

    
   
9063
	add_header(req, "Content-Length", clen);

    
   
9064

   

    
   
9065
	if (ast_str_strlen(req->content)) {

    
   
9066
		ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));

    
   
9067
		req->len = ast_str_strlen(req->data);

    
   
9068
	}

    
   
9069
	req->lines = ast_str_strlen(req->content) ? 1 : 0;

    
   
9070
	return 0;

    
   
9071
}

    
   
9072

   

    
   
9073
/*! \brief Add content (not header) to SIP message */

    
   
9074
static int add_content(struct sip_request *req, const char *line)

    
   
9075
{

    
   
9076
	if (req->lines) {

    
   
9077
		ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");

    
   
9078
		return -1;

    
   
9079
	}

    
   
9080

   

    
   
9081
	ast_str_append(&req->content, 0, "%s", line);

    
   
9082
	return 0;

    
   
9083
}

    
   
9084

   
Moved from 8652

    
   
9085
/*! \brief Copy one header field from one request to another */
Moved from 8653

    
   
9086
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
Moved from 8654

    
   
9087
{
Moved from 8655

    
   
9088
	const char *tmp = get_header(orig, field);

    
   
9089

   
Moved from 8657

    
   
9090
	if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
Moved from 8658

    
   
9091
		return add_header(req, field, tmp);
Moved from 8659

    
   
9092
	ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
Moved from 8660

    
   
9093
	return -1;
Moved from 8661

    
   
9094
}

    
   
9095

   
Moved from 8663

    
   
9096
/*! \brief Copy all headers from one request to another */
Moved from 8664

    
   
9097
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
Moved from 8665

    
   
9098
{
Moved from 8666

    
   
9099
	int start = 0;
Moved from 8667

    
   
9100
	int copied = 0;
Moved from 8668

    
   
9101
	for (;;) {
Moved from 8669

    
   
9102
		const char *tmp = __get_header(orig, field, &start);

    
   
9103

   
Moved from 8671

    
   
9104
		if (ast_strlen_zero(tmp))
Moved from 8672

    
   
9105
			break;
Moved from 8673

    
   
9106
		/* Add what we're responding to */
Moved from 8674

    
   
9107
		add_header(req, field, tmp);
Moved from 8675

    
   
9108
		copied++;
Moved from 8676

    
   
9109
	}
Moved from 8677

    
   
9110
	return copied ? 0 : -1;
Moved from 8678

    
   
9111
}

    
   
9112

   
Moved from 8680

    
   
9113
/*! \brief Copy SIP VIA Headers from the request to the response
Moved from 8681

    
   
9114
\note	If the client indicates that it wishes to know the port we received from,
Moved from 8682

    
   
9115
	it adds ;rport without an argument to the topmost via header. We need to
Moved from 8683

    
   
9116
	add the port number (from our point of view) to that parameter.
Moved from 8684

    
   
9117
\verbatim
Moved from 8685

    
   
9118
	We always add ;received=<ip address> to the topmost via header.
Moved from 8686

    
   
9119
\endverbatim
Moved from 8687

    
   
9120
	Received: RFC 3261, rport RFC 3581 */
Moved from 8688

    
   
9121
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
Moved from 8689

    
   
9122
{
Moved from 8690

    
   
9123
	int copied = 0;
Moved from 8691

    
   
9124
	int start = 0;

    
   
9125

   

    
   
9126
	for (;;) {

    
   
9127
		char new[512];

    
   
9128
		const char *oh = __get_header(orig, field, &start);

    
   
9129

   
Moved from 8697

    
   
9130
		if (ast_strlen_zero(oh))
Moved from 8698

    
   
9131
			break;

    
   
9132

   
Moved from 8700

    
   
9133
		if (!copied) {	/* Only check for empty rport in topmost via header */
Moved from 8701

    
   
9134
			char leftmost[512], *others, *rport;

    
   
9135

   
Moved from 8703

    
   
9136
			/* Only work on leftmost value */
Moved from 8704

    
   
9137
			ast_copy_string(leftmost, oh, sizeof(leftmost));
Moved from 8705

    
   
9138
			others = strchr(leftmost, ',');
Moved from 8706

    
   
9139
			if (others)
Moved from 8707

    
   
9140
			    *others++ = '\0';

    
   
9141

   
Moved from 8709

    
   
9142
			/* Find ;rport;  (empty request) */
Moved from 8710

    
   
9143
			rport = strstr(leftmost, ";rport");
Moved from 8711

    
   
9144
			if (rport && *(rport+6) == '=')
Moved from 8712

    
   
9145
				rport = NULL;		/* We already have a parameter to rport */

    
   
9146

   
Moved from 8714

    
   
9147
			if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
Moved from 8715

    
   
9148
				/* We need to add received port - rport */
Moved from 8716

    
   
9149
				char *end;

    
   
9150

   

    
   
9151
				rport = strstr(leftmost, ";rport");

    
   
9152

   
Moved from 8720

    
   
9153
				if (rport) {
Moved from 8721

    
   
9154
					end = strchr(rport + 1, ';');
Moved from 8722

    
   
9155
					if (end)
Moved from 8723

    
   
9156
						memmove(rport, end, strlen(end) + 1);
Moved from 8724

    
   
9157
					else
Moved from 8725

    
   
9158
						*rport = '\0';
Moved from 8726

    
   
9159
				}
8630

    
   
9160

   
8631
	snprintf(clen, sizeof(clen), "%d", len);

   
8632
	return add_header(req, "Content-Length", clen);

   
8633
}

   
8634

    
   

   
8635
/*! \brief Add content (not header) to SIP message */

   
8636
static int add_line(struct sip_request *req, const char *line)

   
8637
{

   
8638
	if (req->lines == SIP_MAX_LINES)  {

   
8639
		ast_log(LOG_WARNING, "Out of SIP line space\n");

   
8640
		return -1;

   
8641
	}

   
8642
	if (!req->lines)

   
8643
		/* Add extra empty return */

   
8644
		req->len += ast_str_append(&req->data, 0, "\r\n");

   
8645
	req->line[req->lines] = req->len;

   
8646
	ast_str_append(&req->data, 0, "%s", line);

   
8647
	req->len = ast_str_strlen(req->data);

   
8648
	req->lines++;

   
8649
	return 0;	

   
8650
}

   
8651

    
   

   
8652
/*! \brief Copy one header field from one request to another */
Moved to 9085

   
8653
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
Moved to 9086

   
8654
{
Moved to 9087

   
8655
	const char *tmp = get_header(orig, field);
Moved to 9088

   
8656

    
   

   
8657
	if (!ast_strlen_zero(tmp)) /* Add what we're responding to */

   
8658
		return add_header(req, field, tmp);

   
8659
	ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);

   
8660
	return -1;

   
8661
}

   
8662

    
   

   
8663
/*! \brief Copy all headers from one request to another */
Moved to 9096

   
8664
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
Moved to 9097

   
8665
{
Moved to 9098

   
8666
	int start = 0;
Moved to 9099

   
8667
	int copied = 0;
Moved to 9100

   
8668
	for (;;) {
Moved to 9101

   
8669
		const char *tmp = __get_header(orig, field, &start);
Moved to 9102

   
8670

    
   

   
8671
		if (ast_strlen_zero(tmp))

   
8672
			break;

   
8673
		/* Add what we're responding to */

   
8674
		add_header(req, field, tmp);

   
8675
		copied++;

   
8676
	}

   
8677
	return copied ? 0 : -1;

   
8678
}

   
8679

    
   

   
8680
/*! \brief Copy SIP VIA Headers from the request to the response
Moved to 9113

   
8681
\note	If the client indicates that it wishes to know the port we received from,
Moved to 9114

   
8682
	it adds ;rport without an argument to the topmost via header. We need to
Moved to 9115

   
8683
	add the port number (from our point of view) to that parameter.
Moved to 9116

   
8684
\verbatim
Moved to 9117

   
8685
	We always add ;received=<ip address> to the topmost via header.
Moved to 9118

   
8686
\endverbatim
Moved to 9119