Review Board 1.7.16


DIALOG_INFO_XML stale (and timeout) notifiy subscriptions stop BLF's working on Grandstream GXP20xx phones.

Review Request #1813 - Created March 12, 2012 and updated

Alec Davis
1.8 and above
Reviewers
asterisk-dev
Asterisk
This issue is caused by review "handle_request_subscribe is too slow cause of iterating through all sip dialogs" https://reviewboard.asterisk.org/r/901/
commit http://svnview.digium.com/svn/asterisk?view=revision&revision=289623



Some phones (Grandstream GXP20XX series 1.2.5.3 firmware) if rebooted, loose the BLF lights due to the new subscription's "version" being less than the previous subscription's "version".
This happens the instant that asterisk timeouts the previous subscription - which has the much larger "version" sequence number.

The only way for the lights to start working again, is for the current subscription's "version" number to increment past the previous old "version" number.
That period of time could be huge, if the phone isn't rebooted for days.

The workaround has been to reboot the phone twice, within a few minutes of each reboot.
  1st time wait for the BLF's to fail (then reboot again) - which is the timeout period - a few minutes.
  2nd time the lights will work, then fail, then after a few minutes start working again.

This fix prevents the old subscription timeout from updating the phones "version" number. 

This issue doesn't affect the GXP21XX series.

Attempt to show issue byway of example below with some debug output showing call-id and version number.

astrid-test*CLI> core show hints

    -= Registered Asterisk Dial Plan Hints =-
            8601GXP0001@trusted             : Custom:q8601_a8612    State:InUse           Watchers  1
Debug output:

===Set the BLF state to InUse
- Executing [s@macro-custom-agent-inout:13] Set("SIP/GXP0001-00000005", "DEVICE_STATE(Custom:q8601_a8612)=INUSE") in new stack
...
[Mar 14 11:01:39] NOTICE[10819]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="3c65aed02ae1d5df@192.168.5.141"> version=5

=============
Reboot the phone, it gets a new BLF subscription.
=============
[Mar 14 11:02:30] NOTICE[10826]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="79956c0168125400@192.168.5.141"> version=0
===The BLF has correct state of InUse.

...
[Mar 14 11:05:00] NOTICE[10826]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="79956c0168125400@192.168.5.141"> version=1
===The BLF still has correct state of InUse.

...
The timeout 'last notification'
[Mar 14 11:05:09] NOTICE[10826]: chan_sip.c:13131 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="3c65aed02ae1d5df@192.168.5.141" direction="recipient"> version=6
[Mar 14 11:05:09] NOTICE[10826]: chan_sip.c:3868 __sip_autodestruct: ALEC TIMEOUT of SIP subscription 3c65aed02ae1d5df@192.168.5.141
===The BLF has incorrectly gone Idle.

...
[Mar 14 11:15:01] NOTICE[10826]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="79956c0168125400@192.168.5.141"> version=5
===The BLF is still incorrect at Idle.

    -- Registered SIP 'GXP0001' at 192.168.5.141:5066
[Mar 14 11:17:31] NOTICE[10826]: chan_sip.c:13136 state_notify_build_xml: ALEC <dialog id="8601GXP0001" call-id="79956c0168125400@192.168.5.141"> version=6
===The BLF now has correct state of InUse.
In place on a 1.8 deployment for months, our production box with ~80 GXP phones, half of which are the older GXP20XX series.

Changes between revision 1 and 2

1 2
1 2

  1. trunk/channels/chan_sip.c: Loading...
trunk/channels/chan_sip.c
Diff Revision 1 Diff Revision 2
1
/*
1
/*
2
 * Asterisk -- An open source telephony toolkit.
2
 * Asterisk -- An open source telephony toolkit.
3
 *
3
 *
4
 * Copyright (C) 1999 - 2006, Digium, Inc.
4
 * Copyright (C) 1999 - 2012, Digium, Inc.
5
 *
5
 *
6
 * Mark Spencer <markster@digium.com>
6
 * Mark Spencer <markster@digium.com>
7
 *
7
 *
8
 * See http://www.asterisk.org for more information about
8
 * See http://www.asterisk.org for more information about
9
 * the Asterisk project. Please do not directly contact
9
 * the Asterisk project. Please do not directly contact
[+20] [20] 28 lines
[+20]
38
 * \todo Better support of forking
38
 * \todo Better support of forking
39
 * \todo VIA branch tag transaction checking
39
 * \todo VIA branch tag transaction checking
40
 * \todo Transaction support
40
 * \todo Transaction support
41
 *
41
 *
42
 * ******** Wishlist: Improvements
42
 * ******** Wishlist: Improvements
43
 * - Support of SIP domains for devices, so that we match on username@domain in the From: header
43
 * - Support of SIP domains for devices, so that we match on username\@domain in the From: header
44
 * - Connect registrations with a specific device on the incoming call. It's not done
44
 * - Connect registrations with a specific device on the incoming call. It's not done
45
 *   automatically in Asterisk
45
 *   automatically in Asterisk
46
 *
46
 *
47
 * \ingroup channel_drivers
47
 * \ingroup channel_drivers
48
 *
48
 *
[+20] [20] 41 lines
[+20]
90
 * \par Hanging up
90
 * \par Hanging up
91
 * The PBX issues a hangup on both incoming and outgoing calls through
91
 * The PBX issues a hangup on both incoming and outgoing calls through
92
 * the sip_hangup() function
92
 * the sip_hangup() function
93
 */
93
 */
94

    
   
94

   

    
   
95
/*! \li \ref chan_sip.c uses configuration files \ref sip.conf and \ref sip_notify.conf

    
   
96
 * \addtogroup configuration_file

    
   
97
 */

    
   
98

   

    
   
99
/*! \page sip.conf sip.conf

    
   
100
 * \verbinclude sip.conf.sample

    
   
101
 */

    
   
102

   

    
   
103
/*! \page sip_notify.conf sip_notify.conf

    
   
104
 * \verbinclude sip_notify.conf.sample

    
   
105
 */

    
   
106

   
95
/*!
107
/*!
96
 * \page sip_tcp_tls SIP TCP and TLS support
108
 * \page sip_tcp_tls SIP TCP and TLS support
97
 *
109
 *
98
 * \par tcpfixes TCP implementation changes needed
110
 * \par tcpfixes TCP implementation changes needed
99
 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
111
 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
[+20] [20] 61 lines
[+20]
161
 *	- Does not check transport in refer_to uri.
173
 *	- Does not check transport in refer_to uri.
162
 */
174
 */
163

    
   
175

   
164
/*** MODULEINFO
176
/*** MODULEINFO
165
	<use type="module">res_crypto</use>
177
	<use type="module">res_crypto</use>

    
   
178
	<use type="module">res_http_websocket</use>
166
	<depend>chan_local</depend>
179
	<depend>chan_local</depend>
167
	<support_level>core</support_level>
180
	<support_level>core</support_level>
168
 ***/
181
 ***/
169

    
   
182

   
170
/*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
183
/*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
[+20] [20] 57 lines
[+20] [+] ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
228
   balanced, along with the complete history for that object.
241
   balanced, along with the complete history for that object.
229
   In normal operation, the macros defined will throw away the tags, so they do not
242
   In normal operation, the macros defined will throw away the tags, so they do not
230
   affect the speed of the program at all. They can be considered to be documentation.
243
   affect the speed of the program at all. They can be considered to be documentation.
231
*/
244
*/
232
/* #define  REF_DEBUG 1 */
245
/* #define  REF_DEBUG 1 */

    
   
246

   
233
#include "asterisk/lock.h"
247
#include "asterisk/lock.h"
234
#include "asterisk/config.h"
248
#include "asterisk/config.h"
235
#include "asterisk/module.h"
249
#include "asterisk/module.h"
236
#include "asterisk/pbx.h"
250
#include "asterisk/pbx.h"
237
#include "asterisk/sched.h"
251
#include "asterisk/sched.h"
[+20] [20] 37 lines
[+20] ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
275
#include "asterisk/ccss.h"
289
#include "asterisk/ccss.h"
276
#include "asterisk/xml.h"
290
#include "asterisk/xml.h"
277
#include "sip/include/dialog.h"
291
#include "sip/include/dialog.h"
278
#include "sip/include/dialplan_functions.h"
292
#include "sip/include/dialplan_functions.h"
279
#include "sip/include/security_events.h"
293
#include "sip/include/security_events.h"

    
   
294
#include "asterisk/sip_api.h"
280

    
   
295

   
281

    
   

   
282
/*** DOCUMENTATION
296
/*** DOCUMENTATION
283
	<application name="SIPDtmfMode" language="en_US">
297
	<application name="SIPDtmfMode" language="en_US">
284
		<synopsis>
298
		<synopsis>
285
			Change the dtmfmode for a SIP call.
299
			Change the dtmfmode for a SIP call.
286
		</synopsis>
300
		</synopsis>
[+20] [20] 50 lines
[+20] ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
337
			<para>SIPRemoveHeader(P-Asserted-Identity:);</para>
351
			<para>SIPRemoveHeader(P-Asserted-Identity:);</para>
338
			<para></para>
352
			<para></para>
339
			<para>Always returns <literal>0</literal>.</para>
353
			<para>Always returns <literal>0</literal>.</para>
340
		</description>
354
		</description>
341
	</application>
355
	</application>

    
   
356
	<application name="SIPSendCustomINFO" language="en_US">

    
   
357
		<synopsis>

    
   
358
			Send a custom INFO frame on specified channels.

    
   
359
		</synopsis>

    
   
360
		<syntax>

    
   
361
			<parameter name="Data" required="true" />

    
   
362
			<parameter name="UserAgent" required="false" />

    
   
363
		</syntax>

    
   
364
		<description>

    
   
365
			<para>SIPSendCustomINFO() allows you to send a custom INFO message on all

    
   
366
			active SIP channels or on channels with the specified User Agent. This

    
   
367
			application is only available if TEST_FRAMEWORK is defined.</para>

    
   
368
		</description>

    
   
369
	</application>
342
	<function name="SIP_HEADER" language="en_US">
370
	<function name="SIP_HEADER" language="en_US">
343
		<synopsis>
371
		<synopsis>
344
			Gets the specified SIP header from an incoming INVITE message.
372
			Gets the specified SIP header from an incoming INVITE message.
345
		</synopsis>
373
		</synopsis>
346
		<syntax>
374
		<syntax>
[+20] [20] 46 lines
[+20] ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
393
						<para>The configured Callgroup.</para>
421
						<para>The configured Callgroup.</para>
394
					</enum>
422
					</enum>
395
					<enum name="pickupgroup">
423
					<enum name="pickupgroup">
396
						<para>The configured Pickupgroup.</para>
424
						<para>The configured Pickupgroup.</para>
397
					</enum>
425
					</enum>

    
   
426
					<enum name="namedcallgroup">

    
   
427
						<para>The configured Named Callgroup.</para>

    
   
428
					</enum>

    
   
429
					<enum name="namedpickupgroup">

    
   
430
						<para>The configured Named Pickupgroup.</para>

    
   
431
					</enum>
398
					<enum name="codecs">
432
					<enum name="codecs">
399
						<para>The configured codecs.</para>
433
						<para>The configured codecs.</para>
400
					</enum>
434
					</enum>
401
					<enum name="status">
435
					<enum name="status">
402
						<para>Status (if qualify=yes).</para>
436
						<para>Status (if qualify=yes).</para>
[+20] [20] 119 lines
[+20] ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
522
			</parameter>
556
			</parameter>
523
		</syntax>
557
		</syntax>
524
		<description>
558
		<description>
525
			<para>Qualify a SIP peer.</para>
559
			<para>Qualify a SIP peer.</para>
526
		</description>
560
		</description>

    
   
561
		<see-also>

    
   
562
			<ref type="managerEvent">SIPqualifypeerdone</ref>

    
   
563
		</see-also>
527
	</manager>
564
	</manager>
528
	<manager name="SIPshowregistry" language="en_US">
565
	<manager name="SIPshowregistry" language="en_US">
529
		<synopsis>
566
		<synopsis>
530
			Show SIP registrations (text format).
567
			Show SIP registrations (text format).
531
		</synopsis>
568
		</synopsis>
[+20] [20] 23 lines
[+20] ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
555
			<para>Sends a SIP Notify event.</para>
592
			<para>Sends a SIP Notify event.</para>
556
			<para>All parameters for this event must be specified in the body of this request
593
			<para>All parameters for this event must be specified in the body of this request
557
			via multiple <literal>Variable: name=value</literal> sequences.</para>
594
			via multiple <literal>Variable: name=value</literal> sequences.</para>
558
		</description>
595
		</description>
559
	</manager>
596
	</manager>

    
   
597
	<manager name="SIPpeerstatus" language="en_US">

    
   
598
		<synopsis>

    
   
599
			Show the status of one or all of the sip peers.

    
   
600
		</synopsis>

    
   
601
		<syntax>

    
   
602
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />

    
   
603
			<parameter name="Peer" required="false">

    
   
604
				<para>The peer name you want to check.</para>

    
   
605
			</parameter>

    
   
606
		</syntax>

    
   
607
		<description>

    
   
608
			<para>Retrieves the status of one or all of the sip peers.  If no peer name is specified, status

    
   
609
			for all of the sip peers will be retrieved.</para>

    
   
610
		</description>

    
   
611
	</manager>

    
   
612
	<info name="SIPMessageFromInfo" language="en_US" tech="SIP">

    
   
613
		<para>The <literal>from</literal> parameter can be a configured peer name

    
   
614
		or in the form of "display-name" &lt;URI&gt;.</para>

    
   
615
	</info>

    
   
616
	<info name="SIPMessageToInfo" language="en_US" tech="SIP">

    
   
617
		<para>Specifying a prefix of <literal>sip:</literal> will send the

    
   
618
		message as a SIP MESSAGE request.</para>

    
   
619
	</info>
560
 ***/
620
 ***/
561

    
   
621

   
562
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
622
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
563
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
623
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
564
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
624
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;

    
   
625
static int min_subexpiry = DEFAULT_MIN_EXPIRY;     /*!< Minimum accepted subscription time */

    
   
626
static int max_subexpiry = DEFAULT_MAX_EXPIRY;     /*!< Maximum accepted subscription time */
565
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
627
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
566

    
   
628

   
567
static int unauth_sessions = 0;
629
static int unauth_sessions = 0;
568
static int authlimit = DEFAULT_AUTHLIMIT;
630
static int authlimit = DEFAULT_AUTHLIMIT;
569
static int authtimeout = DEFAULT_AUTHTIMEOUT;
631
static int authtimeout = DEFAULT_AUTHTIMEOUT;
[+20] [20] 99 lines
[+20] [+] static const struct sip_reasons {
669
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
731
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
670
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
732
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
671
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
733
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
672
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
734
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
673
	{ AST_REDIRECTING_REASON_AWAY, "away" },
735
	{ AST_REDIRECTING_REASON_AWAY, "away" },
674
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
736
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},

    
   
737
	{ AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
675
};
738
};
676

    
   
739

   
677

    
   
740

   
678
/*! \name DefaultSettings
741
/*! \name DefaultSettings
679
	Default setttings are used as a channel setting and as a default when
742
	Default setttings are used as a channel setting and as a default when
680
	configuring devices
743
	configuring devices
681
*/
744
*/
682
/*@{*/

   
683
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
745
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
684
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
746
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
685
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
747
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
686
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
748
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
687
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
749
static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
688
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
750
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
689
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
751
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
690
static int default_qualify;                        /*!< Default Qualify= setting */
752
static int default_qualify;                        /*!< Default Qualify= setting */

    
   
753
static int default_keepalive;                      /*!< Default keepalive= setting */
691
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
754
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
692
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
755
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
693
                                                    *   a bridged channel on hold */
756
                                                    *   a bridged channel on hold */
694
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
757
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
695
static char default_engine[256];                   /*!< Default RTP engine */
758
static char default_engine[256];                   /*!< Default RTP engine */
696
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
759
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
697
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
760
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
698
static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
761
static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
699
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
762
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
700
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
763
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
701
/*@}*/

   
702

    
   
764

   
703
static struct sip_settings sip_cfg;		/*!< SIP configuration data.
765
static struct sip_settings sip_cfg;		/*!< SIP configuration data.
704
					\note in the future we could have multiple of these (per domain, per device group etc) */
766
					\note in the future we could have multiple of these (per domain, per device group etc) */
705

    
   
767

   
706
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
768
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
[+20] [20] 37 lines
[+20] [+] static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
744
static int global_qualifyfreq;          /*!< Qualify frequency */
806
static int global_qualifyfreq;          /*!< Qualify frequency */
745
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
807
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
746
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
808
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
747

    
   
809

   
748
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
810
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
749
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
811
static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher                        */
750
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
812
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
751
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
813
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
752

    
   
814

   
753
static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
815
static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
754

    
   
816

   
755
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
817
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */

    
   
818
static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
756
/*@}*/
819
/*@}*/
757

    
   
820

   
758
/*!
821
/*!
759
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
822
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
760
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
823
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
761
 * event package. This variable is set at module load time and may be checked at runtime to determine
824
 * event package. This variable is set at module load time and may be checked at runtime to determine
762
 * if XML parsing support was found.
825
 * if XML parsing support was found.
763
 */
826
 */
764
static int can_parse_xml;
827
static int can_parse_xml;
765

    
   
828

   
766
/*! \name Object counters @{
829
/*! \name Object counters @{
767
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
830
 *
768
 *  should be used to modify these values. */
831
 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()

    
   
832
 * should be used to modify these values.

    
   
833
 */
769
static int speerobjs = 0;     /*!< Static peers */
834
static int speerobjs = 0;     /*!< Static peers */
770
static int rpeerobjs = 0;     /*!< Realtime peers */
835
static int rpeerobjs = 0;     /*!< Realtime peers */
771
static int apeerobjs = 0;     /*!< Autocreated peer objects */
836
static int apeerobjs = 0;     /*!< Autocreated peer objects */
772
static int regobjs = 0;       /*!< Registry objects */
837
static int regobjs = 0;       /*!< Registry objects */
773
/* }@ */
838
/*! @} */
774

    
   
839

   
775
static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
840
static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
776
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
841
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
777

    
   
842

   
778
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
843
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */

    
   
844
static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for named ACL system change events */
779
static int network_change_event_sched_id = -1;
845
static int network_change_event_sched_id = -1;
780

    
   
846

   
781
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
847
static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
782

    
   
848

   
783
AST_MUTEX_DEFINE_STATIC(netlock);
849
AST_MUTEX_DEFINE_STATIC(netlock);
[+20] [20] 303 lines
[+20] [+] static void destroy_escs(void)
1087
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1153
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1088
		ao2_ref(event_state_compositors[i].compositor, -1);
1154
		ao2_ref(event_state_compositors[i].compositor, -1);
1089
	}
1155
	}
1090
}
1156
}
1091

    
   
1157

   

    
   
1158
struct state_notify_data {

    
   
1159
	int state;

    
   
1160
	struct ao2_container *device_state_info;

    
   
1161
	int presence_state;

    
   
1162
	const char *presence_subtype;

    
   
1163
	const char *presence_message;

    
   
1164
};

    
   
1165

   
1092
/*!
1166
/*!
1093
 * \details
1167
 * \details
1094
 * Here we implement the container for dialogs which are in the
1168
 * Here we implement the container for dialogs which are in the
1095
 * dialog_needdestroy state to iterate only through the dialogs
1169
 * dialog_needdestroy state to iterate only through the dialogs
1096
 * unlink them instead of iterate through all dialogs
1170
 * unlink them instead of iterate through all dialogs
[+20] [20] 43 lines
[+20] [+] static struct ast_subscription_mwi_list {
1140
static void temp_pvt_cleanup(void *);
1214
static void temp_pvt_cleanup(void *);
1141

    
   
1215

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

    
   
1218

   

    
   
1219
/*! \brief A per-thread buffer for transport to string conversion */

    
   
1220
AST_THREADSTORAGE(sip_transport_str_buf);

    
   
1221

   

    
   
1222
/*! \brief Size of the SIP transport buffer */

    
   
1223
#define SIP_TRANSPORT_STR_BUFSIZE 128

    
   
1224

   
1145
/*! \brief Authentication container for realm authentication */
1225
/*! \brief Authentication container for realm authentication */
1146
static struct sip_auth_container *authl = NULL;
1226
static struct sip_auth_container *authl = NULL;
1147
/*! \brief Global authentication container protection while adjusting the references. */
1227
/*! \brief Global authentication container protection while adjusting the references. */
1148
AST_MUTEX_DEFINE_STATIC(authl_lock);
1228
AST_MUTEX_DEFINE_STATIC(authl_lock);
1149

    
   
1229

   
[+20] [20] 96 lines
[+20] [+] static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1246
static const char *sip_get_callid(struct ast_channel *chan);
1326
static const char *sip_get_callid(struct ast_channel *chan);
1247

    
   
1327

   
1248
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1328
static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1249
static int sip_standard_port(enum sip_transport type, int port);
1329
static int sip_standard_port(enum sip_transport type, int port);
1250
static int sip_prepare_socket(struct sip_pvt *p);
1330
static int sip_prepare_socket(struct sip_pvt *p);
1251
static int get_address_family_filter(const struct ast_sockaddr *addr);
1331
static int get_address_family_filter(unsigned int transport);
1252

    
   
1332

   
1253
/*--- Transmitting responses and requests */
1333
/*--- Transmitting responses and requests */
1254
static int sipsock_read(int *id, int fd, short events, void *ignore);
1334
static int sipsock_read(int *id, int fd, short events, void *ignore);
1255
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1335
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1256
static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1336
static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
[+20] [20] 60 lines
[+20] [+] static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1317
static int find_sdp(struct sip_request *req);
1397
static int find_sdp(struct sip_request *req);
1318
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1398
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);
1399
static int process_sdp_o(const char *o, struct sip_pvt *p);
1320
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1400
static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1321
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1401
static int process_sdp_a_sendonly(const char *a, int *sendonly);

    
   
1402
static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);

    
   
1403
static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1322
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1404
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);
1405
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);
1406
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);
1407
static int process_sdp_a_image(const char *a, struct sip_pvt *p);

    
   
1408
static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);

    
   
1409
static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);

    
   
1410
static void start_ice(struct ast_rtp_instance *instance);
1326
static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1411
static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1327
			     struct ast_str **m_buf, struct ast_str **a_buf,
1412
			     struct ast_str **m_buf, struct ast_str **a_buf,
1328
			     int debug, int *min_packet_size);
1413
			     int debug, int *min_packet_size);
1329
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1414
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1330
				struct ast_str **m_buf, struct ast_str **a_buf,
1415
				struct ast_str **m_buf, struct ast_str **a_buf,
[+20] [20] 5 lines
[+20] [+] static void stop_media_flows(struct sip_pvt *p);
1336
/*--- Authentication stuff */
1421
/*--- Authentication stuff */
1337
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1422
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1338
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1423
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1339
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1424
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,
1425
					 const char *secret, const char *md5secret, int sipmethod,
1341
					 const char *uri, enum xmittype reliable, int ignore);
1426
					 const char *uri, enum xmittype reliable);
1342
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1427
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,
1428
					      int sipmethod, const char *uri, enum xmittype reliable,
1344
					      struct ast_sockaddr *addr, struct sip_peer **authpeer);
1429
					      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 ast_sockaddr *addr);
1430
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

    
   
1431

   
[+20] [20] 7 lines
[+20] [+] static void clear_sip_domains(void);
1354
static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1439
static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1355

    
   
1440

   
1356
/*--- Misc functions */
1441
/*--- Misc functions */
1357
static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1442
static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1358
static int reload_config(enum channelreloadreason reason);
1443
static int reload_config(enum channelreloadreason reason);
1359
static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
1444
static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
1360
static int expire_register(const void *data);
1445
static int expire_register(const void *data);
1361
static void *do_monitor(void *data);
1446
static void *do_monitor(void *data);
1362
static int restart_monitor(void);
1447
static int restart_monitor(void);
1363
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1448
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1364
static struct ast_variable *copy_vars(struct ast_variable *src);
1449
static struct ast_variable *copy_vars(struct ast_variable *src);
1365
static int dialog_find_multiple(void *obj, void *arg, int flags);
1450
static int dialog_find_multiple(void *obj, void *arg, int flags);
1366
static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1451
static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1367
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1452
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1368
static int sip_refer_allocate(struct sip_pvt *p);
1453
static int sip_refer_alloc(struct sip_pvt *p);
1369
static int sip_notify_allocate(struct sip_pvt *p);
1454
static int sip_notify_alloc(struct sip_pvt *p);
1370
static void ast_quiet_chan(struct ast_channel *chan);
1455
static void ast_quiet_chan(struct ast_channel *chan);
1371
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1456
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1372
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1457
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1373

    
   
1458

   
1374
/*--- Device monitoring and Device/extension state/event handling */
1459
/*--- Device monitoring and Device/extension state/event handling */
1375
static int cb_extensionstate(const char *context, const char *exten, enum ast_extension_states state, void *data);
1460
static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);

    
   
1461
static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
1376
static int sip_poke_noanswer(const void *data);
1462
static int sip_poke_noanswer(const void *data);
1377
static int sip_poke_peer(struct sip_peer *peer, int force);
1463
static int sip_poke_peer(struct sip_peer *peer, int force);
1378
static void sip_poke_all_peers(void);
1464
static void sip_poke_all_peers(void);
1379
static void sip_peer_hold(struct sip_pvt *p, int hold);
1465
static void sip_peer_hold(struct sip_pvt *p, int hold);
1380
static void mwi_event_cb(const struct ast_event *, void *);
1466
static void mwi_event_cb(const struct ast_event *, void *);
1381
static void network_change_event_cb(const struct ast_event *, void *);
1467
static void network_change_event_cb(const struct ast_event *, void *);

    
   
1468
static void acl_change_event_cb(const struct ast_event *event, void *userdata);

    
   
1469
static void sip_keepalive_all_peers(void);
1382

    
   
1470

   
1383
/*--- Applications, functions, CLI and manager command helpers */
1471
/*--- Applications, functions, CLI and manager command helpers */
1384
static const char *sip_nat_mode(const struct sip_pvt *p);
1472
static const char *sip_nat_mode(const struct sip_pvt *p);
1385
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1473
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386
static char *transfermode2str(enum transfermodes mode) attribute_const;
1474
static char *transfermode2str(enum transfermodes mode) attribute_const;
1387
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1475
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1388
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1476
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1389
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1477
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1390
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1478
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1391
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1479
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1392
static void  print_group(int fd, ast_group_t group, int crlf);
1480
static void  print_group(int fd, ast_group_t group, int crlf);

    
   
1481
static void  print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
1393
static const char *dtmfmode2str(int mode) attribute_const;
1482
static const char *dtmfmode2str(int mode) attribute_const;
1394
static int str2dtmfmode(const char *str) attribute_unused;
1483
static int str2dtmfmode(const char *str) attribute_unused;
1395
static const char *insecure2str(int mode) attribute_const;
1484
static const char *insecure2str(int mode) attribute_const;
1396
static const char *allowoverlap2str(int mode) attribute_const;
1485
static const char *allowoverlap2str(int mode) attribute_const;
1397
static void cleanup_stale_contexts(char *new, char *old);
1486
static void cleanup_stale_contexts(char *new, char *old);
[+20] [20] 13 lines
[+20] [+] static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1411
static char *complete_sip_peer(const char *word, int state, int flags2);
1500
static char *complete_sip_peer(const char *word, int state, int flags2);
1412
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1501
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1413
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1502
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1414
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1503
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1415
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1504
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1416
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1505
static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
1417
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1506
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1418
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1507
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1419
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1508
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1420
static char *sip_do_debug_ip(int fd, const char *arg);
1509
static char *sip_do_debug_ip(int fd, const char *arg);
1421
static char *sip_do_debug_peer(int fd, const char *arg);
1510
static char *sip_do_debug_peer(int fd, const char *arg);
[+20] [20] 6 lines
[+20] [+] static int sip_addheader(struct ast_channel *chan, const char *data);
1428
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1517
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1429
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1518
static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1430
				      const char *name, int flag, int family);
1519
				      const char *name, int flag, int family);
1431
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1520
static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1432
				      const char *name, int flag);
1521
				      const char *name, int flag);

    
   
1522
static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,

    
   
1523
						const char *name, int flag, unsigned int transport);
1433

    
   
1524

   
1434
/*--- Debugging
1525
/*--- Debugging
1435
	Functions for enabling debug per IP or fully, or enabling history logging for
1526
	Functions for enabling debug per IP or fully, or enabling history logging for
1436
	a SIP dialog
1527
	a SIP dialog
1437
*/
1528
*/
[+20] [20] 38 lines
[+20] [+] static int sip_reregister(const void *data);
1476
static int sip_reg_timeout(const void *data);
1567
static int sip_reg_timeout(const void *data);
1477
static void sip_send_all_registers(void);
1568
static void sip_send_all_registers(void);
1478
static int sip_reinvite_retry(const void *data);
1569
static int sip_reinvite_retry(const void *data);
1479

    
   
1570

   
1480
/*--- Parsing SIP requests and responses */
1571
/*--- Parsing SIP requests and responses */
1481
static void append_date(struct sip_request *req);	/* Append date to SIP packet */

   
1482
static int determine_firstline_parts(struct sip_request *req);
1572
static int determine_firstline_parts(struct sip_request *req);
1483
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1573
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1484
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1574
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1485
static int find_sip_method(const char *msg);
1575
static int find_sip_method(const char *msg);
1486
static unsigned int parse_allowed_methods(struct sip_request *req);
1576
static unsigned int parse_allowed_methods(struct sip_request *req);
1487
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1577
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1488
static int parse_request(struct sip_request *req);
1578
static int parse_request(struct sip_request *req);
1489
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1579
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1490
static int method_match(enum sipmethod id, const char *name);
1580
static int method_match(enum sipmethod id, const char *name);
1491
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1581
static void parse_copy(struct sip_request *dst, const struct sip_request *src);

    
   
1582
static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1492
static const char *find_alias(const char *name, const char *_default);
1583
static const char *find_alias(const char *name, const char *_default);
1493
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1584
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1494
static void lws2sws(struct ast_str *msgbuf);
1585
static void lws2sws(struct ast_str *msgbuf);
1495
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1586
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1496
static char *remove_uri_parameters(char *uri);
1587
static char *remove_uri_parameters(char *uri);
1497
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1588
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1498
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1589
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1499
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1590
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1500
static int set_address_from_contact(struct sip_pvt *pvt);
1591
static int set_address_from_contact(struct sip_pvt *pvt);
1501
static void check_via(struct sip_pvt *p, struct sip_request *req);
1592
static void check_via(struct sip_pvt *p, struct sip_request *req);
1502
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1593
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1503
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1594
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
1504
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1595
static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1505
static int get_msg_text(char *buf, int len, struct sip_request *req);
1596
static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1506
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);

   
1507
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1597
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1508
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1598
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1509
static int get_domain(const char *str, char *domain, int len);
1599
static int get_domain(const char *str, char *domain, int len);
1510
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1600
static void get_realm(struct sip_pvt *p, const struct sip_request *req);

    
   
1601
static char *get_content(struct sip_request *req);
1511

    
   
1602

   
1512
/*-- TCP connection handling ---*/
1603
/*-- TCP connection handling ---*/
1513
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1604
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1514
static void *sip_tcp_worker_fn(void *);
1605
static void *sip_tcp_worker_fn(void *);
1515

    
   
1606

   
[+20] [20] 7 lines
[+20] [+] static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1523
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1614
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1524
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1615
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1525
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1616
static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1526
static void build_via(struct sip_pvt *p);
1617
static void build_via(struct sip_pvt *p);
1527
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1618
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1528
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
1619
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
1529
static char *generate_random_string(char *buf, size_t size);
1620
static char *generate_random_string(char *buf, size_t size);
1530
static void build_callid_pvt(struct sip_pvt *pvt);
1621
static void build_callid_pvt(struct sip_pvt *pvt);
1531
static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1622
static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1532
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1623
static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1533
static void make_our_tag(char *tagbuf, size_t len);
1624
static void make_our_tag(struct sip_pvt *pvt);
1534
static int add_header(struct sip_request *req, const char *var, const char *value);
1625
static int add_header(struct sip_request *req, const char *var, const char *value);
1535
static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1626
static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1536
static int add_content(struct sip_request *req, const char *line);
1627
static int add_content(struct sip_request *req, const char *line);
1537
static int finalize_content(struct sip_request *req);
1628
static int finalize_content(struct sip_request *req);
1538
static void destroy_msg_headers(struct sip_pvt *pvt);
1629
static void destroy_msg_headers(struct sip_pvt *pvt);
1539
static int add_text(struct sip_request *req, struct sip_pvt *p);
1630
static int add_text(struct sip_request *req, struct sip_pvt *p);
1540
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1631
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1541
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1632
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1542
static int add_vidupdate(struct sip_request *req);
1633
static int add_vidupdate(struct sip_request *req);
1543
static void add_route(struct sip_request *req, struct sip_route *route);
1634
static void add_route(struct sip_request *req, struct sip_route *route);
1544
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1635
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1545
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1636
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1546
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1637
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1547
static void set_destination(struct sip_pvt *p, char *uri);
1638
static void set_destination(struct sip_pvt *p, char *uri);
1548
static void append_date(struct sip_request *req);
1639
static void add_date(struct sip_request *req);

    
   
1640
static void add_expires(struct sip_request *req, int expires);
1549
static void build_contact(struct sip_pvt *p);
1641
static void build_contact(struct sip_pvt *p);
1550

    
   
1642

   
1551
/*------Request handling functions */
1643
/*------Request handling functions */
1552
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1644
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1553
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1645
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1554
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
1646
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *recount, const char *e, int *nounlock);
1555
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
1647
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
1556
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1648
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1557
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1649
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1558
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1650
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1559
static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1651
static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1560
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1652
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1561
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1653
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1562
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1654
static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1563
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
1655
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *nounlock);
1564
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1656
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1565
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
1657
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
1566

    
   
1658

   
1567
/*------Response handling functions */
1659
/*------Response handling functions */
1568
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1660
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
[+20] [20] 18 lines
[+20] [+] static void change_t38_state(struct sip_pvt *p, int state);
1587
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1679
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1588
static int  proc_session_timer(const void *vp);
1680
static int  proc_session_timer(const void *vp);
1589
static void stop_session_timer(struct sip_pvt *p);
1681
static void stop_session_timer(struct sip_pvt *p);
1590
static void start_session_timer(struct sip_pvt *p);
1682
static void start_session_timer(struct sip_pvt *p);
1591
static void restart_session_timer(struct sip_pvt *p);
1683
static void restart_session_timer(struct sip_pvt *p);
1592
static const char *strefresher2str(enum st_refresher r);
1684
static const char *strefresherparam2str(enum st_refresher r);
1593
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1685
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
1594
static int parse_minse(const char *p_hdrval, int *const p_interval);
1686
static int parse_minse(const char *p_hdrval, int *const p_interval);
1595
static int st_get_se(struct sip_pvt *, int max);
1687
static int st_get_se(struct sip_pvt *, int max);
1596
static enum st_refresher st_get_refresher(struct sip_pvt *);
1688
static enum st_refresher st_get_refresher(struct sip_pvt *);
1597
static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1689
static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1598
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1690
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
[+20] [20] 339 lines
[+20] [+] static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1938

    
   
2030

   
1939
	if (!monitor_instance) {
2031
	if (!monitor_instance) {
1940
		return -1;
2032
		return -1;
1941
	}
2033
	}
1942

    
   
2034

   
1943
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
2035
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
1944
		return -1;
2036
		return -1;
1945
	}
2037
	}
1946

    
   
2038

   
1947
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
2039
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1948
		ast_get_ccnr_available_timer(monitor->interface->config_params);
2040
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1949

    
   
2041

   
1950
	sip_pvt_lock(monitor_instance->subscription_pvt);
2042
	sip_pvt_lock(monitor_instance->subscription_pvt);
1951
	ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
2043
	ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
1952
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
2044
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
1953
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
2045
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1954
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
2046
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1955
	monitor_instance->subscription_pvt->expiry = when;
2047
	monitor_instance->subscription_pvt->expiry = when;
1956

    
   
2048

   
1957
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
2049
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
[+20] [20] 342 lines
[+20] [+] static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2300
	}
2392
	}
2301

    
   
2393

   
2302
	return ast;
2394
	return ast;
2303
}
2395
}
2304

    
   
2396

   
2305
static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
2397
static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason, int *table_lookup)
2306
{
2398
{

    
   
2399
	int code = reason->code;

    
   
2400

   

    
   
2401
	/* If there's a specific string set, then we just

    
   
2402
	 * use it.

    
   
2403
	 */

    
   
2404
	if (!ast_strlen_zero(reason->str)) {

    
   
2405
		/* If we care about whether this can be found in

    
   
2406
		 * the table, then we need to check about that.

    
   
2407
		 */

    
   
2408
		if (table_lookup) {

    
   
2409
			/* If the string is literally "unknown" then don't bother with the lookup

    
   
2410
			 * because it can lead to a false negative.

    
   
2411
			 */

    
   
2412
			if (!strcasecmp(reason->str, "unknown") ||

    
   
2413
					sip_reason_str_to_code(reason->str) != AST_REDIRECTING_REASON_UNKNOWN) {

    
   
2414
				*table_lookup = TRUE;

    
   
2415
			} else {

    
   
2416
				*table_lookup = FALSE;

    
   
2417
			}

    
   
2418
		}

    
   
2419
		return reason->str;

    
   
2420
	}

    
   
2421

   

    
   
2422
	if (table_lookup) {

    
   
2423
		*table_lookup = TRUE;

    
   
2424
	}

    
   
2425

   
2307
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2426
	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2308
		return sip_reason_table[code].text;
2427
		return sip_reason_table[code].text;
2309
	}
2428
	}
2310

    
   
2429

   
2311
	return "unknown";
2430
	return "unknown";
[+20] [20] 60 lines
[+20] [+] static void sip_tcptls_client_args_destructor(void *obj)
2372
		ast_free(args->tls_cfg->certfile);
2491
		ast_free(args->tls_cfg->certfile);
2373
		ast_free(args->tls_cfg->pvtfile);
2492
		ast_free(args->tls_cfg->pvtfile);
2374
		ast_free(args->tls_cfg->cipher);
2493
		ast_free(args->tls_cfg->cipher);
2375
		ast_free(args->tls_cfg->cafile);
2494
		ast_free(args->tls_cfg->cafile);
2376
		ast_free(args->tls_cfg->capath);
2495
		ast_free(args->tls_cfg->capath);

    
   
2496

   

    
   
2497
		ast_ssl_teardown(args->tls_cfg);
2377
	}
2498
	}
2378
	ast_free(args->tls_cfg);
2499
	ast_free(args->tls_cfg);
2379
	ast_free((char *) args->name);
2500
	ast_free((char *) args->name);
2380
}
2501
}
2381

    
   
2502

   
[+20] [20] 107 lines
[+20] [+] static void *sip_tcp_worker_fn(void *data)
2489
	struct ast_tcptls_session_instance *tcptls_session = data;
2610
	struct ast_tcptls_session_instance *tcptls_session = data;
2490

    
   
2611

   
2491
	return _sip_tcp_helper_thread(tcptls_session);
2612
	return _sip_tcp_helper_thread(tcptls_session);
2492
}
2613
}
2493

    
   
2614

   
2494
/*! \brief Check if the authtimeout has expired.
2615
/*! \brief SIP WebSocket connection handler */
2495
 * \param start the time when the session started
2616
static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2496
 *

   
2497
 * \retval 0 the timeout has expired

   
2498
 * \retval -1 error

   
2499
 * \return the number of milliseconds until the timeout will expire

   
2500
 */

   
2501
static int sip_check_authtimeout(time_t start)

   
2502
{
2617
{
2503
	int timeout;
2618
	int res;
2504
	time_t now;

   
2505
	if(time(&now) == -1) {

   
2506
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));

   
2507
		return -1;

   
2508
	}

   
2509

    
   

   
2510
	timeout = (authtimeout - (now - start)) * 1000;

   
2511
	if (timeout < 0) {

   
2512
		/* we have timed out */

   
2513
		return 0;

   
2514
	}

   
2515

    
   

   
2516
	return timeout;

   
2517
}

   
2518

    
   

   
2519
/*! \brief SIP TCP thread management function

   
2520
	This function reads from the socket, parses the packet into a request

   
2521
*/

   
2522
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)

   
2523
{

   
2524
	int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;

   
2525
	time_t start;
Moved to 3041

   
2526
	struct sip_request req = { 0, } , reqcpy = { 0, };
Moved to 3042

   
2527
	struct sip_threadinfo *me = NULL;
Moved to 3043

   
2528
	char buf[1024] = "";
Moved to 3044

   
2529
	struct pollfd fds[2] = { { 0 }, { 0 }, };
Moved to 3045

   
2530
	struct ast_tcptls_session_args *ca = NULL;
Moved to 3046

   
2531

    
   

   
2532
	/* If this is a server session, then the connection has already been

   
2533
	 * setup. Check if the authlimit has been reached and if not create the

   
2534
	 * threadinfo object so we can access this thread for writing.

   
2535
	 *

   
2536
	 * if this is a client connection more work must be done.

   
2537
	 * 1. We own the parent session args for a client connection.  This pointer needs

   
2538
	 *    to be held on to so we can decrement it's ref count on thread destruction.

   
2539
	 * 2. The threadinfo object was created before this thread was launched, however

   
2540
	 *    it must be found within the threadt table.

   
2541
	 * 3. Last, the tcptls_session must be started.

   
2542
	 */

   
2543
	if (!tcptls_session->client) {

   
2544
		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {

   
2545
			/* unauth_sessions is decremented in the cleanup code */

   
2546
			goto cleanup;

   
2547
		}

   
2548

    
   

   
2549
		if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {

   
2550
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));

   
2551
			goto cleanup;

   
2552
		}

   
2553

    
   

   
2554
		flags |= O_NONBLOCK;

   
2555
		if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {

   
2556
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));

   
2557
			goto cleanup;

   
2558
		}

   
2559

    
   

   
2560
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {

   
2561
			goto cleanup;

   
2562
		}

   
2563
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");

   
2564
	} else {

   
2565
		struct sip_threadinfo tmp = {

   
2566
			.tcptls_session = tcptls_session,

   
2567
		};

   
2568

    
   

   
2569
		if ((!(ca = tcptls_session->parent)) ||

   
2570
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||

   
2571
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {

   
2572
			goto cleanup;

   
2573
		}

   
2574
	}

   
2575

    
   

   
2576
	flags = 1;

   
2577
	if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {

   
2578
		ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));

   
2579
		goto cleanup;

   
2580
	}

   
2581

    
   

   
2582
	me->threadid = pthread_self();
Moved to 3098

   
2583
	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
Moved to 3099

   
2584

    
   

   
2585
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
Moved to 3101

   
2586
	fds[0].fd = tcptls_session->fd;
Moved to 3102

   
2587
	fds[1].fd = me->alert_pipe[0];
Moved to 3103

   
2588
	fds[0].events = fds[1].events = POLLIN | POLLPRI;
Moved to 3104

   
2589

    
   

   
2590
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {

   
2591
		goto cleanup;

   
2592
	}

   
2593
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {

   
2594
		goto cleanup;

   
2595
	}

   
2596

    
   

   
2597
	if(time(&start) == -1) {

   
2598
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));

   
2599
		goto cleanup;

   
2600
	}

   
2601

    
   

   
2602
	for (;;) {
Moved to 3118

   
2603
		struct ast_str *str_save;
Moved to 3119

   
2604

    
   

   
2605
		if (!tcptls_session->client && req.authenticated && !authenticated) {

   
2606
			authenticated = 1;

   
2607
			ast_atomic_fetchadd_int(&unauth_sessions, -1);

   
2608
		}

   
2609

    
   

   
2610
		/* calculate the timeout for unauthenticated server sessions */

   
2611
		if (!tcptls_session->client && !authenticated ) {

   
2612
			if ((timeout = sip_check_authtimeout(start)) < 0) {

   
2613
				goto cleanup;

   
2614
			}

   
2615

    
   
2619

   
2616
			if (timeout == 0) {
2620
	if (ast_websocket_set_nonblock(session)) {
2617
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2621
		goto end;
2618
				goto cleanup;

   
2619
			}

   
2620
		} else {

   
2621
			timeout = -1;

   
2622
		}
2622
	}
2623

    
   
2623

   
2624
		res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
2624
	while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2625
		if (res < 0) {
2625
		char *payload;
2626
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
2626
		uint64_t payload_len;
2627
			goto cleanup;
2627
		enum ast_websocket_opcode opcode;
2628
		} else if (res == 0) {
2628
		int fragmented;
2629
			/* timeout */

   
2630
			ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");

   
2631
			goto cleanup;

   
2632
		}

   
2633

    
   

   
2634
		/* handle the socket event, check for both reads from the socket fd,

   
2635
		 * and writes from alert_pipe fd */

   
2636
		if (fds[0].revents) { /* there is data on the socket to be read */

   
2637
			after_poll = 1;

   
2638

    
   

   
2639
			fds[0].revents = 0;

   
2640

    
   

   
2641
			/* clear request structure */
Moved to 3159

   
2642
			str_save = req.data;
Moved to 3160

   
2643
			memset(&req, 0, sizeof(req));
Moved to 3161

   
2644
			req.data = str_save;
Moved to 3162

   
2645
			ast_str_reset(req.data);
Moved to 3163

   
2646

    
   

   
2647
			str_save = reqcpy.data;
Moved to 3165

   
2648
			memset(&reqcpy, 0, sizeof(reqcpy));
Moved to 3166

   
2649
			reqcpy.data = str_save;
Moved to 3167

   
2650
			ast_str_reset(reqcpy.data);
Moved to 3168

   
2651

    
   

   
2652
			memset(buf, 0, sizeof(buf));

   
2653

    
   
2629

   
2654
			if (tcptls_session->ssl) {
2630
		if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2655
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
2631
			/* We err on the side of caution and terminate the session if any error occurs */
2656
				req.socket.port = htons(ourport_tls);
2632
			break;
2657
			} else {

   
2658
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);

   
2659
				req.socket.port = htons(ourport_tcp);

   
2660
			}
2633
		}
2661
			req.socket.fd = tcptls_session->fd;

   
2662

    
   
2634

   
2663
			/* Read in headers one line at a time */
2635
		if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2664
			while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
2636
			struct sip_request req = { 0, };
2665
				if (!tcptls_session->client && !authenticated ) {

   
2666
					if ((timeout = sip_check_authtimeout(start)) < 0) {

   
2667
						goto cleanup;

   
2668
					}

   
2669

    
   
2637

   
2670
					if (timeout == 0) {
2638
			if (!(req.data = ast_str_create(payload_len))) {
2671
						ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2639
				goto end;
2672
						goto cleanup;
2640
			}
2673
					}
2641

   
2674
				} else {
2642
			if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
2675
					timeout = -1;
2643
				deinit_req(&req);

    
   
2644
				goto end;

    
   
2645
			}

    
   
2646

   

    
   
2647
			req.socket.fd = ast_websocket_fd(session);

    
   
2648
			set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? SIP_TRANSPORT_WSS : SIP_TRANSPORT_WS);

    
   
2649
			req.socket.ws_session = session;

    
   
2650

   

    
   
2651
			handle_request_do(&req, ast_websocket_remote_address(session));

    
   
2652
			deinit_req(&req);

    
   
2653

   

    
   
2654
		} else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {

    
   
2655
			break;

    
   
2656
		}

    
   
2657
	}

    
   
2658

   

    
   
2659
end:

    
   
2660
	ast_websocket_unref(session);

    
   
2661
}

    
   
2662

   

    
   
2663
/*! \brief Check if the authtimeout has expired.

    
   
2664
 * \param start the time when the session started
Moved from 2496

    
   
2665
 *
Moved from 2497

    
   
2666
 * \retval 0 the timeout has expired
Moved from 2498

    
   
2667
 * \retval -1 error
Moved from 2499

    
   
2668
 * \return the number of milliseconds until the timeout will expire
Moved from 2500

    
   
2669
 */
Moved from 2501

    
   
2670
static int sip_check_authtimeout(time_t start)

    
   
2671
{

    
   
2672
	int timeout;
Moved from 2504

    
   
2673
	time_t now;
Moved from 2505

    
   
2674
	if(time(&now) == -1) {
Moved from 2506

    
   
2675
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
Moved from 2507

    
   
2676
		return -1;
Moved from 2508

    
   
2677
	}

    
   
2678

   
Moved from 2510

    
   
2679
	timeout = (authtimeout - (now - start)) * 1000;
Moved from 2511

    
   
2680
	if (timeout < 0) {
Moved from 2512

    
   
2681
		/* we have timed out */
Moved from 2513

    
   
2682
		return 0;
Moved from 2514

    
   
2683
	}

    
   
2684

   
Moved from 2516

    
   
2685
	return timeout;
Moved from 2517

    
   
2686
}

    
   
2687

   

    
   
2688
/*!

    
   
2689
 * \brief Read a SIP request or response from a TLS connection

    
   
2690
 *

    
   
2691
 * Because TLS operations are hidden from view via a FILE handle, the

    
   
2692
 * logic for reading data is a bit complex, and we have to make periodic

    
   
2693
 * checks to be sure we aren't taking too long to perform the necessary

    
   
2694
 * action.

    
   
2695
 *

    
   
2696
 * \todo XXX This should be altered in the future not to use a FILE pointer

    
   
2697
 *

    
   
2698
 * \param req The request structure to fill in

    
   
2699
 * \param tcptls_session The TLS connection on which the data is being received

    
   
2700
 * \param authenticated A flag indicating whether authentication has occurred yet.

    
   
2701
 *        This is only relevant in a server role.

    
   
2702
 * \param start The time at which we started attempting to read data. Used in

    
   
2703
 *        determining if there has been a timeout.

    
   
2704
 * \param me Thread info. Used as a means of determining if the session needs to be stoppped.

    
   
2705
 * \retval -1 Failed to read data

    
   
2706
 * \retval 0 Succeeded in reading data

    
   
2707
 */

    
   
2708
static int sip_tls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session, int authenticated, time_t start, struct sip_threadinfo *me)

    
   
2709
{

    
   
2710
	int res, content_length, after_poll = 1, need_poll = 1;

    
   
2711
	struct sip_request reqcpy = { 0, };

    
   
2712
	char buf[1024] = "";

    
   
2713
	int timeout = -1;

    
   
2714

   

    
   
2715
	/* Read in headers one line at a time */

    
   
2716
	while (ast_str_strlen(req->data) < 4 || strncmp(REQ_OFFSET_TO_STR(req, data->used - 4), "\r\n\r\n", 4)) {

    
   
2717
		if (!tcptls_session->client && !authenticated) {

    
   
2718
			if ((timeout = sip_check_authtimeout(start)) < 0) {

    
   
2719
				ast_debug(2, "SIP SSL server failed to determine authentication timeout\n");
Moved from 2507

    
   
2720
				return -1;
Moved from 2508

    
   
2721
			}

    
   
2722

   

    
   
2723
			if (timeout == 0) {

    
   
2724
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");

    
   
2725
				return -1;

    
   
2726
			}

    
   
2727
		} else {

    
   
2728
			timeout = -1;
2676
				}
2729
		}
2677

    
   
2730

   
2678
				/* special polling behavior is required for TLS
2731
		/* special polling behavior is required for TLS
2679
				 * sockets because of the buffering done in the
2732
		 * sockets because of the buffering done in the
2680
				 * TLS layer */
2733
		 * TLS layer */
2681
				if (!tcptls_session->ssl || need_poll) {
2734
		if (need_poll) {
2682
					need_poll = 0;
2735
			need_poll = 0;
2683
					after_poll = 1;
2736
			after_poll = 1;
2684
					res = ast_wait_for_input(tcptls_session->fd, timeout);
2737
			res = ast_wait_for_input(tcptls_session->fd, timeout);
2685
					if (res < 0) {
2738
			if (res < 0) {
2686
						ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2739
				ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2687
						goto cleanup;
2740
				return -1;
2688
					} else if (res == 0) {
2741
			} else if (res == 0) {
2689
						/* timeout */
2742
				/* timeout */
2690
						ast_debug(2, "SIP TCP server timed out\n");
2743
				ast_debug(2, "SIP TCP server timed out\n");
2691
						goto cleanup;
2744
				return -1;
2692
					}
2745
			}
2693
				}
2746
		}
2694

    
   
2747

   
2695
				ao2_lock(tcptls_session);
2748
		ao2_lock(tcptls_session);
2696
				if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2749
		if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2697
					ao2_unlock(tcptls_session);
2750
			ao2_unlock(tcptls_session);
2698
					if (after_poll) {
2751
			if (after_poll) {
2699
						goto cleanup;
2752
				return -1;
2700
					} else {
2753
			} else {
2701
						need_poll = 1;
2754
				need_poll = 1;
2702
						continue;
2755
				continue;
2703
					}
2756
			}
2704
				}
2757
		}
2705
				ao2_unlock(tcptls_session);
2758
		ao2_unlock(tcptls_session);
2706
				after_poll = 0;
2759
		after_poll = 0;
2707
				if (me->stop) {
2760
		if (me->stop) {
2708
					 goto cleanup;
2761
			return -1;
2709
				}
2762
		}
2710
				ast_str_append(&req.data, 0, "%s", buf);
2763
		ast_str_append(&req->data, 0, "%s", buf);
2711
			}
2764
	}
2712
			copy_request(&reqcpy, &req);
2765
	copy_request(&reqcpy, req);
2713
			parse_request(&reqcpy);
2766
	parse_request(&reqcpy);
2714
			/* In order to know how much to read, we need the content-length header */
2767
	/* In order to know how much to read, we need the content-length header */
2715
			if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
2768
	if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &content_length)) {
2716
				while (cl > 0) {
2769
		while (content_length > 0) {
2717
					size_t bytes_read;
2770
			size_t bytes_read;
2718
					if (!tcptls_session->client && !authenticated ) {
2771
			if (!tcptls_session->client && !authenticated) {
2719
						if ((timeout = sip_check_authtimeout(start)) < 0) {
2772
				if ((timeout = sip_check_authtimeout(start)) < 0) {
2720
							goto cleanup;
2773
					return -1;
2721
						}
2774
				}
2722

    
   
2775

   
2723
						if (timeout == 0) {
2776
				if (timeout == 0) {
2724
							ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
2777
					ast_debug(2, "SIP SSL server timed out\n");
2725
							goto cleanup;
2778
					return -1;
2726
						}
2779
				}
2727
					} else {
2780
			} else {
2728
						timeout = -1;
2781
				timeout = -1;
2729
					}
2782
			}
2730

    
   
2783

   
2731
					if (!tcptls_session->ssl || need_poll) {
2784
			if (need_poll) {
2732
						need_poll = 0;
2785
				need_poll = 0;
2733
						after_poll = 1;
2786
				after_poll = 1;
2734
						res = ast_wait_for_input(tcptls_session->fd, timeout);
2787
				res = ast_wait_for_input(tcptls_session->fd, timeout);
2735
						if (res < 0) {
2788
				if (res < 0) {
2736
							ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2789
					ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
2737
							goto cleanup;
2790
					return -1;
2738
						} else if (res == 0) {
2791
				} else if (res == 0) {
2739
							/* timeout */
2792
					/* timeout */
2740
							ast_debug(2, "SIP TCP server timed out\n");
2793
					ast_debug(2, "SIP TCP server timed out\n");
2741
							goto cleanup;
2794
					return -1;
2742
						}
2795
				}
2743
					}
2796
			}
2744

    
   
2797

   
2745
					ao2_lock(tcptls_session);
2798
			ao2_lock(tcptls_session);
2746
					if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
2799
			if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, content_length), tcptls_session->f))) {
2747
						ao2_unlock(tcptls_session);
2800
				ao2_unlock(tcptls_session);
2748
						if (after_poll) {
2801
				if (after_poll) {
2749
							goto cleanup;
2802
					return -1;
2750
						} else {
2803
				} else {
2751
							need_poll = 1;
2804
					need_poll = 1;
2752
							continue;
2805
					continue;
2753
						}
2806
				}
2754
					}
2807
			}
2755
					buf[bytes_read] = '\0';
2808
			buf[bytes_read] = '\0';
2756
					ao2_unlock(tcptls_session);
2809
			ao2_unlock(tcptls_session);
2757
					after_poll = 0;
2810
			after_poll = 0;
2758
					if (me->stop) {
2811
			if (me->stop) {
2759
						goto cleanup;
2812
				return -1;
2760
					}
2813
			}
2761
					cl -= strlen(buf);
2814
			content_length -= strlen(buf);
2762
					ast_str_append(&req.data, 0, "%s", buf);
2815
			ast_str_append(&req->data, 0, "%s", buf);
2763
				}
2816
		}
2764
			}
2817
	}
2765
			/*! \todo XXX If there's no Content-Length or if the content-length and what
2818
	/*! \todo XXX If there's no Content-Length or if the content-length and what
2766
					we receive is not the same - we should generate an error */
2819
					we receive is not the same - we should generate an error */
Moved from 2513

    
   
2820
	return 0;
Moved from 2514

    
   
2821
}

    
   
2822

   

    
   
2823
/*!

    
   
2824
 * \brief Indication of a TCP message's integrity

    
   
2825
 */

    
   
2826
enum message_integrity {

    
   
2827
	/*!

    
   
2828
	 * The message has an error in it with

    
   
2829
	 * regards to its Content-Length header

    
   
2830
	 */

    
   
2831
	MESSAGE_INVALID,

    
   
2832
	/*!

    
   
2833
	 * The message is incomplete

    
   
2834
	 */

    
   
2835
	MESSAGE_FRAGMENT,

    
   
2836
	/*!

    
   
2837
	 * The data contains a complete message

    
   
2838
	 * plus a fragment of another.

    
   
2839
	 */

    
   
2840
	MESSAGE_FRAGMENT_COMPLETE,

    
   
2841
	/*!

    
   
2842
	 * The message is complete

    
   
2843
	 */

    
   
2844
	MESSAGE_COMPLETE,

    
   
2845
};

    
   
2846

   

    
   
2847
/*!

    
   
2848
 * \brief

    
   
2849
 * Get the content length from an unparsed SIP message

    
   
2850
 *

    
   
2851
 * \param message The unparsed SIP message headers

    
   
2852
 * \return The value of the Content-Length header or -1 if message is invalid

    
   
2853
 */

    
   
2854
static int read_raw_content_length(const char *message)

    
   
2855
{

    
   
2856
	char *content_length_str;

    
   
2857
	int content_length = -1;

    
   
2858

   

    
   
2859
	struct ast_str *msg_copy;

    
   
2860
	char *msg;

    
   
2861

   

    
   
2862
	/* Using a ast_str because lws2sws takes one of those */

    
   
2863
	if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
Moved from 2507

    
   
2864
		return -1;
Moved from 2508

    
   
2865
	}

    
   
2866
	ast_str_set(&msg_copy, 0, "%s", message);

    
   
2867

   

    
   
2868
	if (sip_cfg.pedanticsipchecking) {

    
   
2869
		lws2sws(msg_copy);

    
   
2870
	}

    
   
2871

   

    
   
2872
	msg = ast_str_buffer(msg_copy);

    
   
2873

   

    
   
2874
	/* Let's find a Content-Length header */

    
   
2875
	if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {

    
   
2876
		content_length_str += sizeof("\nContent-Length:") - 1;

    
   
2877
	} else if ((content_length_str = strcasestr(msg, "\nl:"))) {

    
   
2878
		content_length_str += sizeof("\nl:") - 1;

    
   
2879
	} else {

    
   
2880
		/* RFC 3261 18.3

    
   
2881
		 * "In the case of stream-oriented transports such as TCP, the Content-

    
   
2882
		 *  Length header field indicates the size of the body.  The Content-

    
   
2883
		 *  Length header field MUST be used with stream oriented transports."

    
   
2884
		 */

    
   
2885
		goto done;

    
   
2886
	}

    
   
2887

   

    
   
2888
	/* Double-check that this is a complete header */

    
   
2889
	if (!strchr(content_length_str, '\n')) {

    
   
2890
		goto done;

    
   
2891
	}

    
   
2892

   

    
   
2893
	if (sscanf(content_length_str, "%30d", &content_length) != 1) {

    
   
2894
		content_length = -1;

    
   
2895
	}

    
   
2896

   

    
   
2897
done:

    
   
2898
	ast_free(msg_copy);

    
   
2899
	return content_length;

    
   
2900
}

    
   
2901

   

    
   
2902
/*!

    
   
2903
 * \brief Check that a message received over TCP is a full message

    
   
2904
 *

    
   
2905
 * This will take the information read in and then determine if

    
   
2906
 * 1) The message is a full SIP request

    
   
2907
 * 2) The message is a partial SIP request

    
   
2908
 * 3) The message contains a full SIP request along with another partial request

    
   
2909
 * \param data The unparsed incoming SIP message.

    
   
2910
 * \param request The resulting request with extra fragments removed.

    
   
2911
 * \param overflow If the message contains more than a full request, this is the remainder of the message

    
   
2912
 * \return The resulting integrity of the message

    
   
2913
 */

    
   
2914
static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)

    
   
2915
{

    
   
2916
	char *message = ast_str_buffer(*request);

    
   
2917
	char *body;

    
   
2918
	int content_length;

    
   
2919
	int message_len = ast_str_strlen(*request);

    
   
2920
	int body_len;

    
   
2921

   

    
   
2922
	/* Important pieces to search for in a SIP request are \r\n\r\n. This

    
   
2923
	 * marks either

    
   
2924
	 * 1) The division between the headers and body

    
   
2925
	 * 2) The end of the SIP request

    
   
2926
	 */

    
   
2927
	body = strstr(message, "\r\n\r\n");

    
   
2928
	if (!body) {

    
   
2929
		/* This is clearly a partial message since we haven't reached an end

    
   
2930
		 * yet.

    
   
2931
		 */

    
   
2932
		return MESSAGE_FRAGMENT;

    
   
2933
	}

    
   
2934
	body += sizeof("\r\n\r\n") - 1;

    
   
2935
	body_len = message_len - (body - message);

    
   
2936

   

    
   
2937
	body[-1] = '\0';

    
   
2938
	content_length = read_raw_content_length(message);

    
   
2939
	body[-1] = '\n';

    
   
2940

   

    
   
2941
	if (content_length < 0) {

    
   
2942
		return MESSAGE_INVALID;

    
   
2943
	} else if (content_length == 0) {

    
   
2944
		/* We've definitely received an entire message. We need

    
   
2945
		 * to check if there's also a fragment of another message

    
   
2946
		 * in addition.

    
   
2947
		 */

    
   
2948
		if (body_len == 0) {

    
   
2949
			return MESSAGE_COMPLETE;

    
   
2950
		} else {

    
   
2951
			ast_str_append(overflow, 0, "%s", body);

    
   
2952
			ast_str_truncate(*request, message_len - body_len);

    
   
2953
			return MESSAGE_FRAGMENT_COMPLETE;

    
   
2954
		}

    
   
2955
	}

    
   
2956
	/* Positive content length. Let's see what sort of

    
   
2957
	 * message body we're dealing with.

    
   
2958
	 */

    
   
2959
	if (body_len < content_length) {

    
   
2960
		/* We don't have the full message body yet */

    
   
2961
		return MESSAGE_FRAGMENT;

    
   
2962
	} else if (body_len > content_length) {

    
   
2963
		/* We have the full message plus a fragment of a further

    
   
2964
		 * message

    
   
2965
		 */

    
   
2966
		ast_str_append(overflow, 0, "%s", body + content_length);

    
   
2967
		ast_str_truncate(*request, message_len - (body_len - content_length));

    
   
2968
		return MESSAGE_FRAGMENT_COMPLETE;

    
   
2969
	} else {

    
   
2970
		/* Yay! Full message with no extra content */

    
   
2971
		return MESSAGE_COMPLETE;

    
   
2972
	}

    
   
2973
}

    
   
2974

   

    
   
2975
/*!

    
   
2976
 * \brief Read SIP request or response from a TCP connection

    
   
2977
 *

    
   
2978
 * \param req The request structure to be filled in

    
   
2979
 * \param tcptls_session The TCP connection from which to read

    
   
2980
 * \retval -1 Failed to read data

    
   
2981
 * \retval 0 Successfully read data

    
   
2982
 */

    
   
2983
static int sip_tcp_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,

    
   
2984
		int authenticated, time_t start)

    
   
2985
{

    
   
2986
	enum message_integrity message_integrity = MESSAGE_FRAGMENT;

    
   
2987

   

    
   
2988
	while (message_integrity == MESSAGE_FRAGMENT) {

    
   
2989
		if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {

    
   
2990
			char readbuf[4097];

    
   
2991
			int timeout;

    
   
2992
			int res;

    
   
2993
			if (!tcptls_session->client && !authenticated) {

    
   
2994
				if ((timeout = sip_check_authtimeout(start)) < 0) {

    
   
2995
					return -1;

    
   
2996
				}

    
   
2997

   

    
   
2998
				if (timeout == 0) {

    
   
2999
					ast_debug(2, "SIP TCP server timed out\n");
Moved from 2507

    
   
3000
					return -1;
Moved from 2508

    
   
3001
				}

    
   
3002
			} else {

    
   
3003
				timeout = -1;

    
   
3004
			}

    
   
3005
			res = ast_wait_for_input(tcptls_session->fd, timeout);

    
   
3006
			if (res < 0) {

    
   
3007
				ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);

    
   
3008
				return -1;

    
   
3009
			} else if (res == 0) {

    
   
3010
				ast_debug(2, "SIP TCP server timed out\n");
Moved from 2507

    
   
3011
				return -1;
Moved from 2508

    
   
3012
			}

    
   
3013

   

    
   
3014
			res = recv(tcptls_session->fd, readbuf, sizeof(readbuf) - 1, 0);

    
   
3015
			if (res < 0) {

    
   
3016
				ast_debug(2, "SIP TCP server error when receiving data\n");

    
   
3017
				return -1;

    
   
3018
			} else if (res == 0) {

    
   
3019
				ast_debug(2, "SIP TCP server has shut down\n");
Moved from 2507

    
   
3020
				return -1;
Moved from 2508

    
   
3021
			}

    
   
3022
			readbuf[res] = '\0';

    
   
3023
			ast_str_append(&req->data, 0, "%s", readbuf);

    
   
3024
		} else {

    
   
3025
			ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));

    
   
3026
			ast_str_reset(tcptls_session->overflow_buf);

    
   
3027
		}

    
   
3028

   

    
   
3029
		message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);

    
   
3030
	}

    
   
3031

   
Moved from 2513

    
   
3032
	return 0;
Moved from 2514

    
   
3033
}

    
   
3034

   
Moved from 2519

    
   
3035
/*! \brief SIP TCP thread management function
Moved from 2520

    
   
3036
	This function reads from the socket, parses the packet into a request
Moved from 2521

    
   
3037
*/
Moved from 2522

    
   
3038
static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
Moved from 2523

    
   
3039
{

    
   
3040
	int res, timeout = -1, authenticated = 0, flags;
Moved from 2525

    
   
3041
	time_t start;
Moved from 2526

    
   
3042
	struct sip_request req = { 0, } , reqcpy = { 0, };
Moved from 2527

    
   
3043
	struct sip_threadinfo *me = NULL;
Moved from 2528

    
   
3044
	char buf[1024] = "";
Moved from 2529

    
   
3045
	struct pollfd fds[2] = { { 0 }, { 0 }, };
Moved from 2530

    
   
3046
	struct ast_tcptls_session_args *ca = NULL;

    
   
3047

   
Moved from 2532

    
   
3048
	/* If this is a server session, then the connection has already been
Moved from 2533

    
   
3049
	 * setup. Check if the authlimit has been reached and if not create the
Moved from 2534

    
   
3050
	 * threadinfo object so we can access this thread for writing.
Moved from 2535

    
   
3051
	 *
Moved from 2536

    
   
3052
	 * if this is a client connection more work must be done.
Moved from 2537

    
   
3053
	 * 1. We own the parent session args for a client connection.  This pointer needs
Moved from 2538

    
   
3054
	 *    to be held on to so we can decrement it's ref count on thread destruction.
Moved from 2539

    
   
3055
	 * 2. The threadinfo object was created before this thread was launched, however
Moved from 2540

    
   
3056
	 *    it must be found within the threadt table.
Moved from 2541

    
   
3057
	 * 3. Last, the tcptls_session must be started.
Moved from 2542

    
   
3058
	 */
Moved from 2543

    
   
3059
	if (!tcptls_session->client) {
Moved from 2544

    
   
3060
		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
Moved from 2545

    
   
3061
			/* unauth_sessions is decremented in the cleanup code */
Moved from 2546

    
   
3062
			goto cleanup;
Moved from 2547

    
   
3063
		}

    
   
3064

   
Moved from 2549

    
   
3065
		if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
Moved from 2550

    
   
3066
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
Moved from 2551

    
   
3067
			goto cleanup;
Moved from 2552

    
   
3068
		}

    
   
3069

   
Moved from 2554

    
   
3070
		flags |= O_NONBLOCK;
Moved from 2555

    
   
3071
		if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
Moved from 2556

    
   
3072
			ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
Moved from 2557

    
   
3073
			goto cleanup;
Moved from 2558

    
   
3074
		}

    
   
3075

   
Moved from 2560

    
   
3076
		if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
Moved from 2561

    
   
3077
			goto cleanup;
Moved from 2562

    
   
3078
		}
Moved from 2563

    
   
3079
		ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
Moved from 2564

    
   
3080
	} else {
Moved from 2565

    
   
3081
		struct sip_threadinfo tmp = {
Moved from 2566

    
   
3082
			.tcptls_session = tcptls_session,
Moved from 2567

    
   
3083
		};

    
   
3084

   
Moved from 2569

    
   
3085
		if ((!(ca = tcptls_session->parent)) ||
Moved from 2570

    
   
3086
			(!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
Moved from 2571

    
   
3087
			(!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
Moved from 2572

    
   
3088
			goto cleanup;
Moved from 2573

    
   
3089
		}
Moved from 2574

    
   
3090
	}

    
   
3091

   
Moved from 2576

    
   
3092
	flags = 1;
Moved from 2577

    
   
3093
	if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
Moved from 2578

    
   
3094
		ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
Moved from 2579

    
   
3095
		goto cleanup;
Moved from 2580

    
   
3096
	}

    
   
3097

   
Moved from 2582

    
   
3098
	me->threadid = pthread_self();
Moved from 2583

    
   
3099
	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");

    
   
3100

   
Moved from 2585

    
   
3101
	/* set up pollfd to watch for reads on both the socket and the alert_pipe */
Moved from 2586

    
   
3102
	fds[0].fd = tcptls_session->fd;
Moved from 2587

    
   
3103
	fds[1].fd = me->alert_pipe[0];
Moved from 2588

    
   
3104
	fds[0].events = fds[1].events = POLLIN | POLLPRI;

    
   
3105

   
Moved from 2590

    
   
3106
	if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
Moved from 2591

    
   
3107
		goto cleanup;
Moved from 2592

    
   
3108
	}
Moved from 2593

    
   
3109
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
Moved from 2594

    
   
3110
		goto cleanup;
Moved from 2595

    
   
3111
	}

    
   
3112

   
Moved from 2597

    
   
3113
	if(time(&start) == -1) {
Moved from 2598

    
   
3114
		ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
Moved from 2599

    
   
3115
		goto cleanup;
Moved from 2600

    
   
3116
	}

    
   
3117

   
Moved from 2602

    
   
3118
	for (;;) {
Moved from 2603

    
   
3119
		struct ast_str *str_save;

    
   
3120

   
Moved from 2605

    
   
3121
		if (!tcptls_session->client && req.authenticated && !authenticated) {
Moved from 2606

    
   
3122
			authenticated = 1;
Moved from 2607

    
   
3123
			ast_atomic_fetchadd_int(&unauth_sessions, -1);
Moved from 2608

    
   
3124
		}

    
   
3125

   
Moved from 2610

    
   
3126
		/* calculate the timeout for unauthenticated server sessions */
Moved from 2611

    
   
3127
		if (!tcptls_session->client && !authenticated ) {
Moved from 2612

    
   
3128
			if ((timeout = sip_check_authtimeout(start)) < 0) {
Moved from 2613

    
   
3129
				goto cleanup;
Moved from 2614

    
   
3130
			}

    
   
3131

   

    
   
3132
			if (timeout == 0) {
Moved from 2630

    
   
3133
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
Moved from 2631

    
   
3134
				goto cleanup;
Moved from 2632

    
   
3135
			}

    
   
3136
		} else {

    
   
3137
			timeout = -1;

    
   
3138
		}

    
   
3139

   

    
   
3140
		if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {

    
   
3141
			res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */

    
   
3142
			if (res < 0) {

    
   
3143
				ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);

    
   
3144
				goto cleanup;

    
   
3145
			} else if (res == 0) {
Moved from 2629

    
   
3146
				/* timeout */
Moved from 2630

    
   
3147
				ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
Moved from 2631

    
   
3148
				goto cleanup;
Moved from 2632

    
   
3149
			}

    
   
3150
		}

    
   
3151

   

    
   
3152
		/* 

    
   
3153
		 * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,

    
   
3154
		 * and writes from alert_pipe fd.

    
   
3155
		 */

    
   
3156
		if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */

    
   
3157
			fds[0].revents = 0;

    
   
3158

   
Moved from 2641

    
   
3159
			/* clear request structure */
Moved from 2642

    
   
3160
			str_save = req.data;
Moved from 2643

    
   
3161
			memset(&req, 0, sizeof(req));
Moved from 2644

    
   
3162
			req.data = str_save;
Moved from 2645

    
   
3163
			ast_str_reset(req.data);

    
   
3164

   
Moved from 2647

    
   
3165
			str_save = reqcpy.data;
Moved from 2648

    
   
3166
			memset(&reqcpy, 0, sizeof(reqcpy));
Moved from 2649

    
   
3167
			reqcpy.data = str_save;
Moved from 2650

    
   
3168
			ast_str_reset(reqcpy.data);

    
   
3169

   

    
   
3170
			memset(buf, 0, sizeof(buf));

    
   
3171

   

    
   
3172
			if (tcptls_session->ssl) {

    
   
3173
				set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);

    
   
3174
				req.socket.port = htons(ourport_tls);

    
   
3175
			} else {

    
   
3176
				set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);

    
   
3177
				req.socket.port = htons(ourport_tcp);

    
   
3178
			}

    
   
3179
			req.socket.fd = tcptls_session->fd;

    
   
3180
			if (tcptls_session->ssl) {

    
   
3181
				res = sip_tls_read(&req, tcptls_session, authenticated, start, me);

    
   
3182
			} else {

    
   
3183
				res = sip_tcp_read(&req, tcptls_session, authenticated, start);

    
   
3184
			}

    
   
3185

   

    
   
3186
			if (res < 0) {
Moved from 2546

    
   
3187
				goto cleanup;
Moved from 2547

    
   
3188
			}
2767

    
   
3189

   
2768
			req.socket.tcptls_session = tcptls_session;
3190
			req.socket.tcptls_session = tcptls_session;

    
   
3191
			req.socket.ws_session = NULL;
2769
			handle_request_do(&req, &tcptls_session->remote_address);
3192
			handle_request_do(&req, &tcptls_session->remote_address);
2770
		}
3193
		}
2771

    
   
3194

   
2772
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
3195
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2773
			enum sip_tcptls_alert alert;
3196
			enum sip_tcptls_alert alert;
[+20] [20] 10 lines
[+20] static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
2784
			case TCPTLS_ALERT_STOP:
3207
			case TCPTLS_ALERT_STOP:
2785
				goto cleanup;
3208
				goto cleanup;
2786
			case TCPTLS_ALERT_DATA:
3209
			case TCPTLS_ALERT_DATA:
2787
				ao2_lock(me);
3210
				ao2_lock(me);
2788
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
3211
				if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
2789
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
3212
					ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
2790
				}
3213
				}
2791
				ao2_unlock(me);
3214
				ao2_unlock(me);
2792

    
   
3215

   
2793
				if (packet) {
3216
				if (packet) {
2794
					if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
3217
					if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
[+20] [20] 83 lines
[+20] [+] static void peer_sched_cleanup(struct sip_peer *peer)
2878
				sip_unref_peer(peer, "removing poke peer ref"));
3301
				sip_unref_peer(peer, "removing poke peer ref"));
2879
	}
3302
	}
2880
	if (peer->expire != -1) {
3303
	if (peer->expire != -1) {
2881
		AST_SCHED_DEL_UNREF(sched, peer->expire,
3304
		AST_SCHED_DEL_UNREF(sched, peer->expire,
2882
				sip_unref_peer(peer, "remove register expire ref"));
3305
				sip_unref_peer(peer, "remove register expire ref"));

    
   
3306
	}

    
   
3307
	if (peer->keepalivesend != -1) {

    
   
3308
		AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,

    
   
3309
				    sip_unref_peer(peer, "remove keepalive peer ref"));
2883
	}
3310
	}
2884
}
3311
}
2885

    
   
3312

   
2886
typedef enum {
3313
typedef enum {
2887
	SIP_PEERS_MARKED,
3314
	SIP_PEERS_MARKED,
[+20] [20] 170 lines
[+20] [+] static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
3058
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
3485
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
3059
}
3486
}
3060

    
   
3487

   
3061
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
3488
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
3062
static struct ast_udptl_protocol sip_udptl = {
3489
static struct ast_udptl_protocol sip_udptl = {
3063
	type: "SIP",
3490
	.type = "SIP",
3064
	get_udptl_info: sip_get_udptl_peer,
3491
	.get_udptl_info = sip_get_udptl_peer,
3065
	set_udptl_peer: sip_set_udptl_peer,
3492
	.set_udptl_peer = sip_set_udptl_peer,
3066
};
3493
};
3067

    
   
3494

   
3068
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3495
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3069
	__attribute__((format(printf, 2, 3)));
3496
	__attribute__((format(printf, 2, 3)));
3070

    
   
3497

   
[+20] [20] 47 lines
[+20] [+] static int proxy_update(struct sip_proxy *proxy)
3118
	/* if it's actually an IP address and not a name,
3545
	/* if it's actually an IP address and not a name,
3119
           there's no need for a managed lookup */
3546
           there's no need for a managed lookup */
3120
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3547
	if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3121
		/* Ok, not an IP address, then let's check if it's a domain or host */
3548
		/* Ok, not an IP address, then let's check if it's a domain or host */
3122
		/* XXX Todo - if we have proxy port, don't do SRV */
3549
		/* XXX Todo - if we have proxy port, don't do SRV */
3123
		proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr); /* Filter address family */
3550
		proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
3124
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
3551
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
3125
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
3552
				ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
3126
				return FALSE;
3553
				return FALSE;
3127
		}
3554
		}
3128

    
   
3555

   
3129
	}
3556
	}
3130

    
   
3557

   
3131
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
3558
	ast_sockaddr_set_port(&proxy->ip, proxy->port);
3132

    
   
3559

   
3133
	proxy->last_dnsupdate = time(NULL);
3560
	proxy->last_dnsupdate = time(NULL);
3134
	return TRUE;
3561
	return TRUE;

    
   
3562
}

    
   
3563

   

    
   
3564
/*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is

    
   
3565
 *         non-NULL, no allocation is performed and dest is used instead.

    
   
3566
 *         On error NULL is returned. */

    
   
3567
static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)

    
   
3568
{

    
   
3569
	char *mutable_proxy, *sep, *name;

    
   
3570
	int allocated = 0;

    
   
3571

   

    
   
3572
	if (!dest) {

    
   
3573
		dest = ao2_alloc(sizeof(struct sip_proxy), NULL);

    
   
3574
		if (!dest) {

    
   
3575
			ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");

    
   
3576
			return NULL;

    
   
3577
		}

    
   
3578
		allocated = 1;

    
   
3579
	}

    
   
3580

   

    
   
3581
	/* Format is: [transport://]name[:port][,force] */

    
   
3582
	mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));

    
   
3583
	sep = strchr(mutable_proxy, ',');

    
   
3584
	if (sep) {

    
   
3585
		*sep++ = '\0';

    
   
3586
		dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);

    
   
3587
	} else {

    
   
3588
		dest->force = FALSE;

    
   
3589
	}

    
   
3590

   

    
   
3591
	sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);

    
   
3592

   

    
   
3593
	/* Check that there is a name at all */

    
   
3594
	if (ast_strlen_zero(name)) {

    
   
3595
		if (allocated) {

    
   
3596
			ao2_ref(dest, -1);

    
   
3597
		} else {

    
   
3598
			dest->name[0] = '\0';

    
   
3599
		}

    
   
3600
		return NULL;

    
   
3601
	}

    
   
3602
	ast_copy_string(dest->name, name, sizeof(dest->name));

    
   
3603

   

    
   
3604
	/* Resolve host immediately */

    
   
3605
	proxy_update(dest);

    
   
3606

   

    
   
3607
	return dest;
3135
}
3608
}
3136

    
   
3609

   
3137
/*! \brief converts ascii port to int representation. If no
3610
/*! \brief converts ascii port to int representation. If no
3138
 *  pt buffer is provided or the pt has errors when being converted
3611
 *  pt buffer is provided or the pt has errors when being converted
3139
 *  to an int value, the port provided as the standard is used.
3612
 *  to an int value, the port provided as the standard is used.
[+20] [20] 9 lines
[+20] [+] unsigned int port_str2int(const char *pt, unsigned int standard)
3149
}
3622
}
3150

    
   
3623

   
3151
/*! \brief Get default outbound proxy or global proxy */
3624
/*! \brief Get default outbound proxy or global proxy */
3152
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3625
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3153
{
3626
{

    
   
3627
	if (dialog && dialog->options && dialog->options->outboundproxy) {

    
   
3628
		if (sipdebug) {

    
   
3629
			ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");

    
   
3630
		}

    
   
3631
		append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);

    
   
3632
		return dialog->options->outboundproxy;

    
   
3633
	}
3154
	if (peer && peer->outboundproxy) {
3634
	if (peer && peer->outboundproxy) {
3155
		if (sipdebug) {
3635
		if (sipdebug) {
3156
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3636
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3157
		}
3637
		}
3158
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3638
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
[+20] [20] 21 lines
[+20] static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3180
static int method_match(enum sipmethod id, const char *name)
3660
static int method_match(enum sipmethod id, const char *name)
3181
{
3661
{
3182
	int len = strlen(sip_methods[id].text);
3662
	int len = strlen(sip_methods[id].text);
3183
	int l_name = name ? strlen(name) : 0;
3663
	int l_name = name ? strlen(name) : 0;
3184
	/* true if the string is long enough, and ends with whitespace, and matches */
3664
	/* true if the string is long enough, and ends with whitespace, and matches */
3185
	return (l_name >= len && name[len] < 33 &&
3665
	return (l_name >= len && name && name[len] < 33 &&
3186
		!strncasecmp(sip_methods[id].text, name, len));
3666
		!strncasecmp(sip_methods[id].text, name, len));
3187
}
3667
}
3188

    
   
3668

   
3189
/*! \brief  find_sip_method: Find SIP method from header */
3669
/*! \brief  find_sip_method: Find SIP method from header */
3190
static int find_sip_method(const char *msg)
3670
static int find_sip_method(const char *msg)
[+20] [20] 75 lines
[+20] [+] static int get_transport_str2enum(const char *transport)
3266
		res |= SIP_TRANSPORT_TCP;
3746
		res |= SIP_TRANSPORT_TCP;
3267
	}
3747
	}
3268
	if (!strcasecmp(transport, "tls")) {
3748
	if (!strcasecmp(transport, "tls")) {
3269
		res |= SIP_TRANSPORT_TLS;
3749
		res |= SIP_TRANSPORT_TLS;
3270
	}
3750
	}

    
   
3751
	if (!strcasecmp(transport, "ws")) {

    
   
3752
		res |= SIP_TRANSPORT_WS;

    
   
3753
	}

    
   
3754
	if (!strcasecmp(transport, "wss")) {

    
   
3755
		res |= SIP_TRANSPORT_WSS;

    
   
3756
	}
3271

    
   
3757

   
3272
	return res;
3758
	return res;
3273
}
3759
}
3274

    
   
3760

   
3275
/*! \brief Return configuration of transports for a device */
3761
/*! \brief Return configuration of transports for a device */
3276
static inline const char *get_transport_list(unsigned int transports) {
3762
static inline const char *get_transport_list(unsigned int transports)
3277
	switch (transports) {
3763
{
3278
		case SIP_TRANSPORT_UDP:
3764
	char *buf;
3279
			return "UDP";
3765

   
3280
		case SIP_TRANSPORT_TCP:
3766
	if (!transports) {
3281
			return "TCP";
3767
		return "UNKNOWN";
3282
		case SIP_TRANSPORT_TLS:

   
3283
			return "TLS";

   
3284
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:

   
3285
			return "TCP,UDP";

   
3286
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:

   
3287
			return "TLS,UDP";

   
3288
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:

   
3289
			return "TLS,TCP";

   
3290
		default:

   
3291
			return transports ?

   
3292
				"TLS,TCP,UDP" : "UNKNOWN";	

   
3293
	}
3768
	}

    
   
3769

   

    
   
3770
	if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {

    
   
3771
		return "";

    
   
3772
	}

    
   
3773

   

    
   
3774
	memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);

    
   
3775

   

    
   
3776
	if (transports & SIP_TRANSPORT_UDP) {

    
   
3777
		strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));

    
   
3778
	}

    
   
3779
	if (transports & SIP_TRANSPORT_TCP) {

    
   
3780
		strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));

    
   
3781
	}

    
   
3782
	if (transports & SIP_TRANSPORT_TLS) {

    
   
3783
		strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));

    
   
3784
	}

    
   
3785
	if (transports & SIP_TRANSPORT_WS) {

    
   
3786
		strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));

    
   
3787
	}

    
   
3788
	if (transports & SIP_TRANSPORT_WSS) {

    
   
3789
		strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));

    
   
3790
	}

    
   
3791

   

    
   
3792
	/* Remove the trailing ',' if present */

    
   
3793
	if (strlen(buf)) {

    
   
3794
		buf[strlen(buf) - 1] = 0;

    
   
3795
	}

    
   
3796

   

    
   
3797
	return buf;
3294
}
3798
}
3295

    
   
3799

   
3296
/*! \brief Return transport as string */
3800
/*! \brief Return transport as string */
3297
const char *sip_get_transport(enum sip_transport t)
3801
const char *sip_get_transport(enum sip_transport t)
3298
{
3802
{
3299
	switch (t) {
3803
	switch (t) {
3300
	case SIP_TRANSPORT_UDP:
3804
	case SIP_TRANSPORT_UDP:
3301
		return "UDP";
3805
		return "UDP";
3302
	case SIP_TRANSPORT_TCP:
3806
	case SIP_TRANSPORT_TCP:
3303
		return "TCP";
3807
		return "TCP";
3304
	case SIP_TRANSPORT_TLS:
3808
	case SIP_TRANSPORT_TLS:
3305
		return "TLS";
3809
		return "TLS";

    
   
3810
	case SIP_TRANSPORT_WS:

    
   
3811
	case SIP_TRANSPORT_WSS:

    
   
3812
		return "WS";
3306
	}
3813
	}
3307

    
   
3814

   
3308
	return "UNKNOWN";
3815
	return "UNKNOWN";
3309
}
3816
}
3310

    
   
3817

   
3311
/*! \brief Return protocol string for srv dns query */
3818
/*! \brief Return protocol string for srv dns query */
3312
static inline const char *get_srv_protocol(enum sip_transport t)
3819
static inline const char *get_srv_protocol(enum sip_transport t)
3313
{
3820
{
3314
	switch (t) {
3821
	switch (t) {
3315
	case SIP_TRANSPORT_UDP:
3822
	case SIP_TRANSPORT_UDP:
3316
		return "udp";
3823
		return "udp";

    
   
3824
	case SIP_TRANSPORT_WS:

    
   
3825
		return "ws";
3317
	case SIP_TRANSPORT_TLS:
3826
	case SIP_TRANSPORT_TLS:
3318
	case SIP_TRANSPORT_TCP:
3827
	case SIP_TRANSPORT_TCP:
3319
		return "tcp";
3828
		return "tcp";

    
   
3829
	case SIP_TRANSPORT_WSS:

    
   
3830
		return "wss";
3320
	}
3831
	}
3321

    
   
3832

   
3322
	return "udp";
3833
	return "udp";
3323
}
3834
}
3324

    
   
3835

   
3325
/*! \brief Return service string for srv dns query */
3836
/*! \brief Return service string for srv dns query */
3326
static inline const char *get_srv_service(enum sip_transport t)
3837
static inline const char *get_srv_service(enum sip_transport t)
3327
{
3838
{
3328
	switch (t) {
3839
	switch (t) {
3329
	case SIP_TRANSPORT_TCP:
3840
	case SIP_TRANSPORT_TCP:
3330
	case SIP_TRANSPORT_UDP:
3841
	case SIP_TRANSPORT_UDP:

    
   
3842
	case SIP_TRANSPORT_WS:
3331
		return "sip";
3843
		return "sip";
3332
	case SIP_TRANSPORT_TLS:
3844
	case SIP_TRANSPORT_TLS:

    
   
3845
	case SIP_TRANSPORT_WSS:
3333
		return "sips";
3846
		return "sips";
3334
	}
3847
	}
3335
	return "sip";
3848
	return "sip";
3336
}
3849
}
3337

    
   
3850

   
[+20] [20] 36 lines
[+20] [+] static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
3374

    
   
3887

   
3375
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3888
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3376
		res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
3889
		res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
3377
	} else if (p->socket.tcptls_session) {
3890
	} else if (p->socket.tcptls_session) {
3378
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
3891
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));

    
   
3892
	} else if (p->socket.ws_session) {

    
   
3893
		if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, data->str, ast_str_strlen(data)))) {

    
   
3894
			/* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */

    
   
3895
			res = ast_str_strlen(data);

    
   
3896
		}
3379
	} else {
3897
	} else {
3380
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3898
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3381
		return XMIT_ERROR;
3899
		return XMIT_ERROR;
3382
	}
3900
	}
3383

    
   
3901

   
[+20] [20] 56 lines
[+20] [+] static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3440
	/* now ask the system what would it use to talk to 'them' */
3958
	/* now ask the system what would it use to talk to 'them' */
3441
	ast_ouraddrfor(them, us);
3959
	ast_ouraddrfor(them, us);
3442
	ast_sockaddr_copy(&theirs, them);
3960
	ast_sockaddr_copy(&theirs, them);
3443

    
   
3961

   
3444
	if (ast_sockaddr_is_ipv6(&theirs)) {
3962
	if (ast_sockaddr_is_ipv6(&theirs)) {
3445
		if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
3963
		if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
3446
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3964
			ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3447
				"but we're using IPv6, which doesn't need it. Please "
3965
				"but we're using IPv6, which doesn't need it. Please "
3448
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3966
				"remove \"localnet\" and/or \"externaddr\" settings.\n");
3449
		}
3967
		}
3450
	} else {
3968
	} else {
[+20] [20] 33 lines
[+20] static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3484
				break;
4002
				break;
3485
			}
4003
			}
3486
		}
4004
		}
3487
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",
4005
		ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3488
			  ast_sockaddr_stringify(them));
4006
			  ast_sockaddr_stringify(them));
3489
	} else if (p) {
4007
	} else {
3490
		/* no remapping, but we bind to a specific address, so use it. */
4008
		/* no remapping, but we bind to a specific address, so use it. */
3491
		switch (p->socket.type) {
4009
		switch (p->socket.type) {
3492
		case SIP_TRANSPORT_TCP:
4010
		case SIP_TRANSPORT_TCP:
3493
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
4011
			if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3494
				ast_sockaddr_copy(us,
4012
				ast_sockaddr_copy(us,
[+20] [20] 20 lines
[+20] static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3515
			}
4033
			}
3516
			if (!ast_sockaddr_port(us)) {
4034
			if (!ast_sockaddr_port(us)) {
3517
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
4035
				ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
3518
			}
4036
			}
3519
		}
4037
		}
3520
	} else if (!ast_sockaddr_is_any(&bindaddr)) {

   
3521
		ast_sockaddr_copy(us, &bindaddr);

   
3522
	}
4038
	}
3523
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
4039
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
3524
}
4040
}
3525

    
   
4041

   
3526
/*! \brief Append to SIP dialog history with arg list  */
4042
/*! \brief Append to SIP dialog history with arg list  */
[+20] [20] 132 lines
[+20] [+] static int retrans_pkt(const void *data)
3659
	/* At this point, either the packet's retransmission timed out, or there was a
4175
	/* At this point, either the packet's retransmission timed out, or there was a
3660
	 * transmission error, either way destroy the scheduler item and this packet. */
4176
	 * transmission error, either way destroy the scheduler item and this packet. */
3661

    
   
4177

   
3662
	pkt->retransid = -1; /* Kill this scheduler item */
4178
	pkt->retransid = -1; /* Kill this scheduler item */
3663

    
   
4179

   
3664
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
4180
	if (pkt->method != SIP_OPTIONS && xmitres == 0) {
3665
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
4181
		if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
3666
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
4182
			ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
3667
				"Packet timed out after %dms with no response\n",
4183
				"Packet timed out after %dms with no response\n",
3668
				pkt->owner->callid,
4184
				pkt->owner->callid,
3669
				pkt->seqno,
4185
				pkt->seqno,
[+20] [20] 40 lines
[+20] static int retrans_pkt(const void *data)
3710
				pkt->owner->pendinginvite = 0;
4226
				pkt->owner->pendinginvite = 0;
3711
			} else {
4227
			} else {
3712
				/* there is nothing left to do, mark the dialog as gone */
4228
				/* there is nothing left to do, mark the dialog as gone */
3713
				sip_alreadygone(pkt->owner);
4229
				sip_alreadygone(pkt->owner);
3714
			}
4230
			}
3715
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
4231
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
3716
			ast_channel_unlock(pkt->owner->owner);
4232
			ast_channel_unlock(pkt->owner->owner);
3717
		} else {
4233
		} else {
3718
			/* If no channel owner, destroy now */
4234
			/* If no channel owner, destroy now */
3719

    
   
4235

   
3720
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
4236
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
[+20] [20] 138 lines
[+20] [+] static int __sip_autodestruct(const void *data)
3859
	struct sip_pvt *p = (struct sip_pvt *)data;
4375
	struct sip_pvt *p = (struct sip_pvt *)data;
3860
	struct ast_channel *owner;
4376
	struct ast_channel *owner;
3861

    
   
4377

   
3862
	/* If this is a subscription, tell the phone that we got a timeout */
4378
	/* If this is a subscription, tell the phone that we got a timeout */
3863
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION && p->subscribed != DIALOG_INFO_XML) {
4379
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION && p->subscribed != DIALOG_INFO_XML) {
3864
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
4380
		struct state_notify_data data = { 0, };

    
   
4381
		data.state = AST_EXTENSION_DEACTIVATED;

    
   
4382

   

    
   
4383
		transmit_state_notify(p, &data, 1, TRUE);	/* Send last notification */
3865
		p->subscribed = NONE;
4384
		p->subscribed = NONE;
3866
		append_history(p, "Subscribestatus", "timeout");
4385
		append_history(p, "Subscribestatus", "timeout");
3867
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
4386
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3868
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
4387
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3869
	}
4388
	}
3870

    
   
4389

   
3871
	/* If there are packets still waiting for delivery, delay the destruction */
4390
	/* If there are packets still waiting for delivery, delay the destruction */
3872
	if (p->packets) {
4391
	if (p->packets) {
3873
		if (!p->needdestroy) {
4392
		if (!p->needdestroy) {
3874
			char method_str[31];
4393
			char method_str[31];
3875
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
4394
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3876
			append_history(p, "ReliableXmit", "timeout");
4395
			append_history(p, "ReliableXmit", "timeout");
3877
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
4396
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3878
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
4397
				if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3879
					pvt_set_needdestroy(p, "autodestruct");
4398
					pvt_set_needdestroy(p, "autodestruct");
3880
				}
4399
				}
3881
			}
4400
			}
3882
			return 10000;
4401
			return 10000;
3883
		} else {
4402
		} else {
3884
			/* They've had their chance to respond. Time to bail */
4403
			/* They've had their chance to respond. Time to bail */
3885
			__sip_pretend_ack(p);
4404
			__sip_pretend_ack(p);
3886
		}
4405
		}
3887
	}
4406
	}
3888

    
   
4407

   
3889
	/* Reset schedule ID */
4408
	/* Reset schedule ID */
3890
	p->autokillid = -1;
4409
	p->autokillid = -1;
3891

    
   
4410

   
3892

    
   

   
3893
	/*
4411
	/*
3894
	 * Lock both the pvt and the channel safely so that we can queue up a frame.
4412
	 * Lock both the pvt and the channel safely so that we can queue up a frame.
3895
	 */
4413
	 */
3896
	owner = sip_pvt_lock_full(p);
4414
	owner = sip_pvt_lock_full(p);
3897
	if (owner) {
4415
	if (owner) {
3898
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
4416
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n", p->callid, ast_channel_name(owner), sip_methods[p->method].text);
3899
		ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
4417
		ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
3900
		ast_channel_unlock(owner);
4418
		ast_channel_unlock(owner);
3901
		ast_channel_unref(owner);
4419
		ast_channel_unref(owner);

    
   
4420
		sip_pvt_unlock(p);

    
   
4421
		return 10000;
3902
	} else if (p->refer && !p->alreadygone) {
4422
	} else if (p->refer && !p->alreadygone) {
3903
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
4423
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3904
		stop_media_flows(p);
4424
		stop_media_flows(p);
3905
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
4425
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3906
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
4426
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
[+20] [20] 291 lines
[+20] [+] static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
4198
			reliable ? "Reliably " : "", sip_nat_mode(p),
4718
			reliable ? "Reliably " : "", sip_nat_mode(p),
4199
			ast_sockaddr_stringify(dst),
4719
			ast_sockaddr_stringify(dst),
4200
			req->data->str);
4720
			req->data->str);
4201
	}
4721
	}
4202
	if (p->do_history) {
4722
	if (p->do_history) {
4203
		struct sip_request tmp = { .rlPart1 = 0, };
4723
		struct sip_request tmp = { .rlpart1 = 0, };
4204
		parse_copy(&tmp, req);
4724
		parse_copy(&tmp, req);
4205
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, sip_get_header(&tmp, "CSeq"),
4725
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, sip_get_header(&tmp, "CSeq"),
4206
			(tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
4726
			(tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlpart2) : sip_methods[tmp.method].text);
4207
		deinit_req(&tmp);
4727
		deinit_req(&tmp);
4208
	}
4728
	}
4209

    
   
4729

   
4210
	/* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
4730
	/* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
4211
	if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
4731
	if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
[+20] [20] 34 lines
[+20] [+] static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
4246
		} else {
4766
		} else {
4247
			ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
4767
			ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
4248
		}
4768
		}
4249
	}
4769
	}
4250
	if (p->do_history) {
4770
	if (p->do_history) {
4251
		struct sip_request tmp = { .rlPart1 = 0, };
4771
		struct sip_request tmp = { .rlpart1 = 0, };
4252
		parse_copy(&tmp, req);
4772
		parse_copy(&tmp, req);
4253
		append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
4773
		append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
4254
		deinit_req(&tmp);
4774
		deinit_req(&tmp);
4255
	}
4775
	}
4256
	res = (reliable) ?
4776
	res = (reliable) ?
[+20] [20] 250 lines
[+20] [+] static int sip_sendtext(struct ast_channel *ast, const char *text)
4507
	if (!text) {
5027
	if (!text) {
4508
		return 0;
5028
		return 0;
4509
	}
5029
	}
4510
	if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
5030
	if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
4511
		ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
5031
		ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
4512
		return(0);
5032
		return 0;
4513
	}
5033
	}
4514

    
   
5034

   
4515
	debug = sip_debug_test_pvt(dialog);
5035
	debug = sip_debug_test_pvt(dialog);
4516
	if (debug) {
5036
	if (debug) {
4517
		ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
5037
		ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
[+20] [20] 153 lines
[+20] [+] static void sip_destroy_peer(struct sip_peer *peer)
4671
		ast_variables_destroy(peer->chanvars);
5191
		ast_variables_destroy(peer->chanvars);
4672
		peer->chanvars = NULL;
5192
		peer->chanvars = NULL;
4673
	}
5193
	}
4674

    
   
5194

   
4675
	register_peer_exten(peer, FALSE);
5195
	register_peer_exten(peer, FALSE);
4676
	ast_free_ha(peer->ha);
5196
	ast_free_acl_list(peer->acl);
4677
	ast_free_ha(peer->directmediaha);
5197
	ast_free_acl_list(peer->directmediaacl);
4678
	if (peer->selfdestruct)
5198
	if (peer->selfdestruct)
4679
		ast_atomic_fetchadd_int(&apeerobjs, -1);
5199
		ast_atomic_fetchadd_int(&apeerobjs, -1);
4680
	else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
5200
	else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
4681
		ast_atomic_fetchadd_int(&rpeerobjs, -1);
5201
		ast_atomic_fetchadd_int(&rpeerobjs, -1);
4682
		ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
5202
		ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
[+20] [20] 5 lines
[+20] static void sip_destroy_peer(struct sip_peer *peer)
4688
	}
5208
	}
4689

    
   
5209

   
4690
	if (peer->socket.tcptls_session) {
5210
	if (peer->socket.tcptls_session) {
4691
		ao2_ref(peer->socket.tcptls_session, -1);
5211
		ao2_ref(peer->socket.tcptls_session, -1);
4692
		peer->socket.tcptls_session = NULL;
5212
		peer->socket.tcptls_session = NULL;

    
   
5213
	} else if (peer->socket.ws_session) {

    
   
5214
		ast_websocket_unref(peer->socket.ws_session);

    
   
5215
		peer->socket.ws_session = NULL;
4693
	}
5216
	}
4694

    
   
5217

   

    
   
5218
	peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);

    
   
5219
	peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);

    
   
5220

   
4695
	ast_cc_config_params_destroy(peer->cc_params);
5221
	ast_cc_config_params_destroy(peer->cc_params);
4696

    
   
5222

   
4697
	ast_string_field_free_memory(peer);
5223
	ast_string_field_free_memory(peer);
4698

    
   
5224

   
4699
	peer->caps = ast_format_cap_destroy(peer->caps);
5225
	peer->caps = ast_format_cap_destroy(peer->caps);

    
   
5226

   

    
   
5227
	ast_rtp_dtls_cfg_free(&peer->dtls_cfg);
4700
}
5228
}
4701

    
   
5229

   
4702
/*! \brief Update peer data in database (if used) */
5230
/*! \brief Update peer data in database (if used) */
4703
static void update_peer(struct sip_peer *p, int expire)
5231
static void update_peer(struct sip_peer *p, int expire)
4704
{
5232
{
[+20] [20] 140 lines
[+20] [+] static int realtime_peer_by_name(const char *const *name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
4845
					struct ast_sockaddr *addrs = NULL;
5373
					struct ast_sockaddr *addrs = NULL;
4846

    
   
5374

   
4847
					if (ast_sockaddr_resolve(&addrs,
5375
					if (ast_sockaddr_resolve(&addrs,
4848
								 tmp->value,
5376
								 tmp->value,
4849
								 PARSE_PORT_FORBID,
5377
								 PARSE_PORT_FORBID,
4850
								 get_address_family_filter(&bindaddr)) <= 0 ||
5378
								 get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
4851
								 ast_sockaddr_cmp(&addrs[0], addr)) {
5379
								 ast_sockaddr_cmp(&addrs[0], addr)) {
4852
						/* No match */
5380
						/* No match */
4853
						ast_variables_destroy(*var);
5381
						ast_variables_destroy(*var);
4854
						*var = NULL;
5382
						*var = NULL;
4855
					}
5383
					}
[+20] [20] 179 lines
[+20] [+] static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
5035
	peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
5563
	peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
5036
	if (!peer) {
5564
	if (!peer) {
5037
		goto cleanup;
5565
		goto cleanup;
5038
	}
5566
	}
5039

    
   
5567

   

    
   
5568
	/* Previous versions of Asterisk did not require the type field to be

    
   
5569
	 * set for real time peers.  This statement preserves that behavior. */

    
   
5570
	if  (peer->type == 0) {

    
   
5571
		if (which_objects == FINDUSERS) {

    
   
5572
			peer->type = SIP_TYPE_USER;

    
   
5573
		} else if (which_objects == FINDPEERS) {

    
   
5574
			peer->type = SIP_TYPE_PEER;

    
   
5575
		} else {

    
   
5576
			peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;

    
   
5577
		}

    
   
5578
	}

    
   
5579

   
5040
	ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
5580
	ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
5041

    
   
5581

   
5042
	if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
5582
	if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
5043
		/* Cache peer */
5583
		/* Cache peer */
5044
		ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
5584
		ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
[+20] [20] 94 lines
[+20] [+] static struct sip_peer *sip_find_peer_full(const char *peer, struct ast_sockaddr *addr, char *callbackexten, int realtime, int which_objects, int devstate_only, int transport)
5139
	return p;
5679
	return p;
5140
}
5680
}
5141

    
   
5681

   
5142
/*!
5682
/*!
5143
 * \brief Locate device by name or ip address
5683
 * \brief Locate device by name or ip address
5144
 * \param peer, sin, realtime, devstate_only, transport
5684
 * \param peer, addr, realtime, devstate_only, transport
5145
 * \param which_objects Define which objects should be matched when doing a lookup
5685
 * \param which_objects Define which objects should be matched when doing a lookup
5146
 *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
5686
 *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
5147
 *        Note that this option is not used at all when doing a lookup by IP.
5687
 *        Note that this option is not used at all when doing a lookup by IP.
5148
 *
5688
 *
5149
 *	This is used on find matching device on name or ip/port.
5689
 *	This is used on find matching device on name or ip/port.
[+20] [20] 106 lines
[+20] [+] static void set_t38_capabilities(struct sip_pvt *p)
5256
static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
5796
static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
5257
{
5797
{
5258
	if (to_sock->tcptls_session) {
5798
	if (to_sock->tcptls_session) {
5259
		ao2_ref(to_sock->tcptls_session, -1);
5799
		ao2_ref(to_sock->tcptls_session, -1);
5260
		to_sock->tcptls_session = NULL;
5800
		to_sock->tcptls_session = NULL;

    
   
5801
	} else if (to_sock->ws_session) {

    
   
5802
		ast_websocket_unref(to_sock->ws_session);

    
   
5803
		to_sock->ws_session = NULL;
5261
	}
5804
	}
5262

    
   
5805

   
5263
	if (from_sock->tcptls_session) {
5806
	if (from_sock->tcptls_session) {
5264
		ao2_ref(from_sock->tcptls_session, +1);
5807
		ao2_ref(from_sock->tcptls_session, +1);

    
   
5808
	} else if (from_sock->ws_session) {

    
   
5809
		ast_websocket_ref(from_sock->ws_session);
5265
	}
5810
	}
5266

    
   
5811

   
5267
	*to_sock = *from_sock;
5812
	*to_sock = *from_sock;

    
   
5813
}

    
   
5814

   

    
   
5815
/*! \brief Initialize DTLS-SRTP support on an RTP instance */

    
   
5816
static int dialog_initialize_dtls_srtp(const struct sip_pvt *dialog, struct ast_rtp_instance *rtp, struct sip_srtp **srtp)

    
   
5817
{

    
   
5818
	struct ast_rtp_engine_dtls *dtls;

    
   
5819

   

    
   
5820
	if (!dialog->dtls_cfg.enabled) {
Moved from 2513

    
   
5821
		return 0;
Moved from 2514

    
   
5822
	}

    
   
5823

   

    
   
5824
	if (!ast_rtp_engine_srtp_is_registered()) {

    
   
5825
		ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
Moved from 2507

    
   
5826
		return -1;
Moved from 2508

    
   
5827
	}

    
   
5828

   

    
   
5829
	if (!(dtls = ast_rtp_instance_get_dtls(rtp))) {

    
   
5830
		ast_log(LOG_ERROR, "No DTLS-SRTP support present on engine for RTP instance '%p', was it compiled with support for it?\n",

    
   
5831
			rtp);
Moved from 2507

    
   
5832
		return -1;
Moved from 2508

    
   
5833
	}

    
   
5834

   

    
   
5835
	if (dtls->set_configuration(rtp, &dialog->dtls_cfg)) {

    
   
5836
		ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",

    
   
5837
			rtp);
Moved from 2507

    
   
5838
		return -1;
Moved from 2508

    
   
5839
	}

    
   
5840

   

    
   
5841
	if (!(*srtp = sip_srtp_alloc())) {

    
   
5842
		ast_log(LOG_ERROR, "Failed to create required SRTP structure on RTP instance '%p'\n",

    
   
5843
			rtp);
Moved from 2507

    
   
5844
		return -1;
Moved from 2508

    
   
5845
	}

    
   
5846

   

    
   
5847
	return 0;
5268
}
5848
}
5269

    
   
5849

   
5270
/*! \brief Initialize RTP portion of a dialog
5850
/*! \brief Initialize RTP portion of a dialog
5271
 * \return -1 on failure, 0 on success
5851
 * \return -1 on failure, 0 on success
5272
 */
5852
 */
5273
static int dialog_initialize_rtp(struct sip_pvt *dialog)
5853
static int dialog_initialize_rtp(struct sip_pvt *dialog)
5274
{
5854
{
5275
	struct ast_sockaddr bindaddr_tmp;
5855
	struct ast_sockaddr bindaddr_tmp;

    
   
5856
	struct ast_rtp_engine_ice *ice;
5276

    
   
5857

   
5277
	if (!sip_methods[dialog->method].need_rtp) {
5858
	if (!sip_methods[dialog->method].need_rtp) {
5278
		return 0;
5859
		return 0;
5279
	}
5860
	}
5280

    
   
5861

   
5281
	ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
5862
	ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
5282
	if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
5863
	if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
5283
		return -1;
5864
		return -1;

    
   
5865
	}

    
   
5866

   

    
   
5867
	if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->rtp))) {

    
   
5868
		ice->stop(dialog->rtp);

    
   
5869
	}

    
   
5870

   

    
   
5871
	if (dialog_initialize_dtls_srtp(dialog, dialog->rtp, &dialog->srtp)) {

    
   
5872
		return -1;
5284
	}
5873
	}
5285

    
   
5874

   
5286
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
5875
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
5287
			(ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_FORMAT_TYPE_VIDEO)))) {
5876
			(ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_FORMAT_TYPE_VIDEO)))) {
5288
		if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
5877
		if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
5289
			return -1;
5878
			return -1;
5290
		}
5879
		}

    
   
5880

   

    
   
5881
		if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->vrtp))) {

    
   
5882
			ice->stop(dialog->vrtp);

    
   
5883
		}

    
   
5884

   

    
   
5885
		if (dialog_initialize_dtls_srtp(dialog, dialog->vrtp, &dialog->vsrtp)) {
Moved from 2507

    
   
5886
			return -1;
Moved from 2508

    
   
5887
		}

    
   
5888

   
5291
		ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
5889
		ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
5292
		ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
5890
		ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
5293
		ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
5891
		ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
5294

    
   
5892

   
5295
		ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
5893
		ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);

    
   
5894
		ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
5296
	}
5895
	}
5297

    
   
5896

   
5298
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
5897
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
5299
		if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
5898
		if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
5300
			return -1;
5899
			return -1;
5301
		}
5900
		}

    
   
5901

   

    
   
5902
		if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->trtp))) {

    
   
5903
			ice->stop(dialog->trtp);

    
   
5904
		}

    
   
5905

   

    
   
5906
		if (dialog_initialize_dtls_srtp(dialog, dialog->trtp, &dialog->tsrtp)) {
Moved from 2507

    
   
5907
			return -1;
Moved from 2508

    
   
5908
		}

    
   
5909

   
5302
		/* Do not timeout text as its not constant*/
5910
		/* Do not timeout text as its not constant*/
5303
		ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
5911
		ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
5304

    
   
5912

   
5305
		ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
5913
		ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
5306
	}
5914
	}
[+20] [20] 45 lines
[+20] [+] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
5352
	ast_format_cap_copy(dialog->caps, peer->caps);
5960
	ast_format_cap_copy(dialog->caps, peer->caps);
5353
	dialog->prefs = peer->prefs;
5961
	dialog->prefs = peer->prefs;
5354
	dialog->amaflags = peer->amaflags;
5962
	dialog->amaflags = peer->amaflags;
5355

    
   
5963

   
5356
	ast_string_field_set(dialog, engine, peer->engine);
5964
	ast_string_field_set(dialog, engine, peer->engine);

    
   
5965

   

    
   
5966
	ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &dialog->dtls_cfg);
5357

    
   
5967

   
5358
	dialog->rtptimeout = peer->rtptimeout;
5968
	dialog->rtptimeout = peer->rtptimeout;
5359
	dialog->rtpholdtimeout = peer->rtpholdtimeout;
5969
	dialog->rtpholdtimeout = peer->rtpholdtimeout;
5360
	dialog->rtpkeepalive = peer->rtpkeepalive;
5970
	dialog->rtpkeepalive = peer->rtpkeepalive;
5361
	if (dialog_initialize_rtp(dialog)) {
5971
	if (dialog_initialize_rtp(dialog)) {
[+20] [20] 29 lines
[+20] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
5391
	}
6001
	}
5392
	ast_string_field_set(dialog, engine, peer->engine);
6002
	ast_string_field_set(dialog, engine, peer->engine);
5393
	ref_proxy(dialog, obproxy_get(dialog, peer));
6003
	ref_proxy(dialog, obproxy_get(dialog, peer));
5394
	dialog->callgroup = peer->callgroup;
6004
	dialog->callgroup = peer->callgroup;
5395
	dialog->pickupgroup = peer->pickupgroup;
6005
	dialog->pickupgroup = peer->pickupgroup;

    
   
6006
	ast_unref_namedgroups(dialog->named_callgroups);

    
   
6007
	dialog->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);

    
   
6008
	ast_unref_namedgroups(dialog->named_pickupgroups);

    
   
6009
	dialog->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
5396
	ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
6010
	ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
5397
	dialog->allowtransfer = peer->allowtransfer;
6011
	dialog->allowtransfer = peer->allowtransfer;
5398
	dialog->jointnoncodeccapability = dialog->noncodeccapability;
6012
	dialog->jointnoncodeccapability = dialog->noncodeccapability;
5399

    
   
6013

   
5400
	/* Update dialog authorization credentials */
6014
	/* Update dialog authorization credentials */
[+20] [20] 27 lines
[+20] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
5428

    
   
6042

   
5429
				*new_callid = '\0';
6043
				*new_callid = '\0';
5430

    
   
6044

   
5431
				/* Change the dialog callid. */
6045
				/* Change the dialog callid. */
5432
				callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
6046
				callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
5433
				new_callid = alloca(callid_size);
6047
				new_callid = ast_alloca(callid_size);
5434
				snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
6048
				snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
5435
				change_callid_pvt(dialog, new_callid);
6049
				change_callid_pvt(dialog, new_callid);
5436
			}
6050
			}
5437
		}
6051
		}
5438
	}
6052
	}
[+20] [20] 20 lines
[+20] static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
5459
	if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
6073
	if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
5460
	    (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
6074
	    (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
5461
		dialog->noncodeccapability |= AST_RTP_DTMF;
6075
		dialog->noncodeccapability |= AST_RTP_DTMF;
5462
	else
6076
	else
5463
		dialog->noncodeccapability &= ~AST_RTP_DTMF;
6077
		dialog->noncodeccapability &= ~AST_RTP_DTMF;
5464
	dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
6078

   

    
   
6079
	dialog->directmediaacl = ast_duplicate_acl_list(peer->directmediaacl);

    
   
6080

   
5465
	if (peer->call_limit)
6081
	if (peer->call_limit)
5466
		ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
6082
		ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
5467
	if (!dialog->portinuri)
6083
	if (!dialog->portinuri)
5468
		dialog->portinuri = peer->portinuri;
6084
		dialog->portinuri = peer->portinuri;
5469
	dialog->chanvars = copy_vars(peer->chanvars);
6085
	dialog->chanvars = copy_vars(peer->chanvars);
[+20] [20] 10 lines
[+20] [+] static inline int default_sip_port(enum sip_transport type)
5480
}
6096
}
5481

    
   
6097

   
5482
/*! \brief create address structure from device name
6098
/*! \brief create address structure from device name
5483
 *      Or, if peer not found, find it in the global DNS
6099
 *      Or, if peer not found, find it in the global DNS
5484
 *      returns TRUE (-1) on failure, FALSE on success */
6100
 *      returns TRUE (-1) on failure, FALSE on success */
5485
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address)
6101
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
5486
{
6102
{
5487
	struct sip_peer *peer;
6103
	struct sip_peer *peer;
5488
	char *peername, *peername2, *hostn;
6104
	char *peername, *peername2, *hostn;
5489
	char host[MAXHOSTNAMELEN];
6105
	char host[MAXHOSTNAMELEN];
5490
	char service[MAXHOSTNAMELEN];
6106
	char service[MAXHOSTNAMELEN];
[+20] [20] 20 lines
[+20] static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address) [+] static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
5511
		int res;
6127
		int res;
5512
		if (newdialog) {
6128
		if (newdialog) {
5513
			set_socket_transport(&dialog->socket, 0);
6129
			set_socket_transport(&dialog->socket, 0);
5514
		}
6130
		}
5515
		res = create_addr_from_peer(dialog, peer);
6131
		res = create_addr_from_peer(dialog, peer);
5516
		if (!ast_sockaddr_isnull(remote_address)) {

   
5517
			ast_sockaddr_copy(&dialog->sa, remote_address);

   
5518
		}

   
5519
		dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
6132
		dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
5520
		sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
6133
		sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
5521
		return res;
6134
		return res;
5522
	} else if (ast_check_digits(peername)) {
6135
	} else if (ast_check_digits(peername)) {
5523
		/* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
6136
		/* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
[+20] [20] 38 lines
[+20] static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address) [+] static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
5562
						   service)) > 0) {
6175
						   service)) > 0) {
5563
				hostn = host;
6176
				hostn = host;
5564
			}
6177
			}
5565
		}
6178
		}
5566

    
   
6179

   
5567
		if (ast_sockaddr_resolve_first(&dialog->sa, hostn, 0)) {
6180
		if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
5568
			ast_log(LOG_WARNING, "No such host: %s\n", peername);
6181
			ast_log(LOG_WARNING, "No such host: %s\n", peername);
5569
			return -1;
6182
			return -1;
5570
		}
6183
		}
5571

    
   
6184

   
5572
		if (srv_ret > 0) {
6185
		if (srv_ret > 0) {
[+20] [20] 68 lines
[+20] [+] static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
5641
			ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
6254
			ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
5642
		}
6255
		}
5643
	}
6256
	}
5644

    
   
6257

   
5645
	/* Check whether there is vxml_url, distinctive ring variables */
6258
	/* Check whether there is vxml_url, distinctive ring variables */
5646
	headp=ast_channel_varshead(ast);
6259
	headp = ast_channel_varshead(ast);
5647
	AST_LIST_TRAVERSE(headp, current, entries) {
6260
	AST_LIST_TRAVERSE(headp, current, entries) {
5648
		/* Check whether there is a VXML_URL variable */
6261
		/* Check whether there is a VXML_URL variable */
5649
		if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
6262
		if (!p->options->vxml_url && !strcmp(ast_var_name(current), "VXML_URL")) {
5650
			p->options->vxml_url = ast_var_value(current);
6263
			p->options->vxml_url = ast_var_value(current);
5651
		} else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
6264
		} else if (!p->options->uri_options && !strcmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
5652
			p->options->uri_options = ast_var_value(current);
6265
			p->options->uri_options = ast_var_value(current);
5653
		} else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
6266
		} else if (!p->options->addsipheaders && !strncmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
5654
			/* Check whether there is a variable with a name starting with SIPADDHEADER */
6267
			/* Check whether there is a variable with a name starting with SIPADDHEADER */
5655
			p->options->addsipheaders = 1;
6268
			p->options->addsipheaders = 1;
5656
		} else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
6269
		} else if (!strcmp(ast_var_name(current), "SIPFROMDOMAIN")) {
5657
			ast_string_field_set(p, fromdomain, ast_var_value(current));
6270
			ast_string_field_set(p, fromdomain, ast_var_value(current));
5658
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
6271
		} else if (!strcmp(ast_var_name(current), "SIPTRANSFER")) {
5659
			/* This is a transfered call */
6272
			/* This is a transfered call */
5660
			p->options->transfer = 1;
6273
			p->options->transfer = 1;
5661
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
6274
		} else if (!strcmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
5662
			/* This is the referrer */
6275
			/* This is the referrer */
5663
			referer = ast_var_value(current);
6276
			referer = ast_var_value(current);
5664
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
6277
		} else if (!strcmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
5665
			/* We're replacing a call. */
6278
			/* We're replacing a call. */
5666
			p->options->replaces = ast_var_value(current);
6279
			p->options->replaces = ast_var_value(current);
5667
		} else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
6280
		} else if (!strcmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
5668
			if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
6281
			if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
5669
				ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.");
6282
				ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
5670
			}
6283
			}
5671
		}
6284
		}
5672
	}
6285
	}
5673

    
   
6286

   
5674
	/* Check to see if we should try to force encryption */
6287
	/* Check to see if we should try to force encryption */
[+20] [20] 83 lines
[+20] static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
5758
			connected.id.name.valid = 1;
6371
			connected.id.name.valid = 1;
5759
			connected.id.name.str = (char *) p->cid_name;
6372
			connected.id.name.str = (char *) p->cid_name;
5760
			connected.id.name.presentation = p->callingpres;
6373
			connected.id.name.presentation = p->callingpres;
5761
		}
6374
		}
5762
		if (update_connected.id.number || update_connected.id.name) {
6375
		if (update_connected.id.number || update_connected.id.name) {

    
   
6376
			/* Invalidate any earlier private connected id representation */

    
   
6377
			ast_set_party_id_all(&update_connected.priv);

    
   
6378

   
5763
			connected.id.tag = (char *) p->cid_tag;
6379
			connected.id.tag = (char *) p->cid_tag;
5764
			connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
6380
			connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
5765
			ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
6381
			ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
5766
		}
6382
		}
5767

    
   
6383

   
5768
		xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
6384
		xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);

    
   
6385
		if (xmitres == XMIT_ERROR) {
5769
		sip_pvt_unlock(p);
6386
			sip_pvt_unlock(p);
5770
		if (xmitres == XMIT_ERROR)

   
5771
			return -1;
6387
			return -1;

    
   
6388
		}
5772
		p->invitestate = INV_CALLING;
6389
		p->invitestate = INV_CALLING;
5773

    
   
6390

   
5774
		/* Initialize auto-congest time */
6391
		/* Initialize auto-congest time */
5775
		AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
6392
		AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
5776
								dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
6393
								dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
5777
								dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
6394
								dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
5778
								dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
6395
								dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );

    
   
6396
		sip_pvt_unlock(p);
5779
	}
6397
	}
5780
	return res;
6398
	return res;
5781
}
6399
}
5782

    
   
6400

   
5783
/*! \brief Destroy registry object
6401
/*! \brief Destroy registry object
[+20] [20] 29 lines
[+20] [+] static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
5813
	}
6431
	}
5814
	
6432
	
5815
	AST_SCHED_DEL(sched, mwi->resub);
6433
	AST_SCHED_DEL(sched, mwi->resub);
5816
	ast_string_field_free_memory(mwi);
6434
	ast_string_field_free_memory(mwi);
5817
	ast_free(mwi);
6435
	ast_free(mwi);

    
   
6436
}

    
   
6437

   

    
   
6438
/*! \brief Destroy SDP media offer list */

    
   
6439
static void offered_media_list_destroy(struct sip_pvt *p)

    
   
6440
{

    
   
6441
	struct offered_media *offer;

    
   
6442
	while ((offer = AST_LIST_REMOVE_HEAD(&p->offered_media, next))) {

    
   
6443
		ast_free(offer->decline_m_line);

    
   
6444
		ast_free(offer);

    
   
6445
	}
5818
}
6446
}
5819

    
   
6447

   
5820
/*! \brief Execute destruction of SIP dialog structure, release memory */
6448
/*! \brief Execute destruction of SIP dialog structure, release memory */
5821
void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
6449
void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
5822
{
6450
{
[+20] [20] 28 lines
[+20] void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
5851
		/* Give the channel a chance to react before deallocation */
6479
		/* Give the channel a chance to react before deallocation */
5852
		usleep(1);
6480
		usleep(1);
5853
	}
6481
	}
5854

    
   
6482

   
5855
	/* Remove link from peer to subscription of MWI */
6483
	/* Remove link from peer to subscription of MWI */
5856
	if (p->relatedpeer && p->relatedpeer->mwipvt)
6484
	if (p->relatedpeer && p->relatedpeer->mwipvt == p)
5857
		p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
6485
		p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
5858
	if (p->relatedpeer && p->relatedpeer->call == p)
6486
	if (p->relatedpeer && p->relatedpeer->call == p)
5859
		p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
6487
		p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
5860
	
6488
	
5861
	if (p->relatedpeer)
6489
	if (p->relatedpeer)
[+20] [20] 5 lines
[+20] void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
5867
		p->registry = registry_unref(p->registry, "delete p->registry");
6495
		p->registry = registry_unref(p->registry, "delete p->registry");
5868
	}
6496
	}
5869
	
6497
	
5870
	if (p->mwi) {
6498
	if (p->mwi) {
5871
		p->mwi->call = NULL;
6499
		p->mwi->call = NULL;

    
   
6500
		p->mwi = NULL;
5872
	}
6501
	}
5873

    
   
6502

   
5874
	if (dumphistory)
6503
	if (dumphistory)
5875
		sip_dump_history(p);
6504
		sip_dump_history(p);
5876

    
   
6505

   
5877
	if (p->options)
6506
	if (p->options) {

    
   
6507
		if (p->options->outboundproxy) {

    
   
6508
			ao2_ref(p->options->outboundproxy, -1);

    
   
6509
		}
5878
		ast_free(p->options);
6510
		ast_free(p->options);

    
   
6511
		p->options = NULL;

    
   
6512
	}
5879

    
   
6513

   
5880
	if (p->notify) {
6514
	if (p->notify) {
5881
		ast_variables_destroy(p->notify->headers);
6515
		ast_variables_destroy(p->notify->headers);
5882
		ast_free(p->notify->content);
6516
		ast_free(p->notify->content);
5883
		ast_free(p->notify);
6517
		ast_free(p->notify);

    
   
6518
		p->notify = NULL;
5884
	}
6519
	}
5885
	if (p->rtp) {
6520
	if (p->rtp) {
5886
		ast_rtp_instance_destroy(p->rtp);
6521
		ast_rtp_instance_destroy(p->rtp);

    
   
6522
		p->rtp = NULL;
5887
	}
6523
	}
5888
	if (p->vrtp) {
6524
	if (p->vrtp) {
5889
		ast_rtp_instance_destroy(p->vrtp);
6525
		ast_rtp_instance_destroy(p->vrtp);

    
   
6526
		p->vrtp = NULL;
5890
	}
6527
	}
5891
	if (p->trtp) {
6528
	if (p->trtp) {
5892
		ast_rtp_instance_destroy(p->trtp);
6529
		ast_rtp_instance_destroy(p->trtp);

    
   
6530
		p->trtp = NULL;
5893
	}
6531
	}
5894
	if (p->udptl)
6532
	if (p->udptl) {
5895
		ast_udptl_destroy(p->udptl);
6533
		ast_udptl_destroy(p->udptl);
5896
	if (p->refer)
6534
		p->udptl = NULL;

    
   
6535
	}

    
   
6536
	if (p->refer) {

    
   
6537
		if (p->refer->refer_call) {

    
   
6538
			p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");

    
   
6539
		}

    
   
6540
		ast_string_field_free_memory(p->refer);
5897
		ast_free(p->refer);
6541
		ast_free(p->refer);

    
   
6542
		p->refer = NULL;

    
   
6543
	}
5898
	if (p->route) {
6544
	if (p->route) {
5899
		free_old_route(p->route);
6545
		free_old_route(p->route);
5900
		p->route = NULL;
6546
		p->route = NULL;
5901
	}
6547
	}
5902
	deinit_req(&p->initreq);
6548
	deinit_req(&p->initreq);
[+20] [20] 10 lines
[+20] void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
5913
	}
6559
	}
5914

    
   
6560

   
5915
	while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
6561
	while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
5916
		ast_free(req);
6562
		ast_free(req);
5917
	}
6563
	}

    
   
6564

   

    
   
6565
	offered_media_list_destroy(p);
5918

    
   
6566

   
5919
	if (p->chanvars) {
6567
	if (p->chanvars) {
5920
		ast_variables_destroy(p->chanvars);
6568
		ast_variables_destroy(p->chanvars);
5921
		p->chanvars = NULL;
6569
		p->chanvars = NULL;
5922
	}
6570
	}
[+20] [20] 13 lines
[+20] void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
5936
	if (p->tsrtp) {
6584
	if (p->tsrtp) {
5937
		sip_srtp_destroy(p->tsrtp);
6585
		sip_srtp_destroy(p->tsrtp);
5938
		p->tsrtp = NULL;
6586
		p->tsrtp = NULL;
5939
	}
6587
	}
5940

    
   
6588

   
5941
	if (p->directmediaha) {
6589
	if (p->directmediaacl) {
5942
		ast_free_ha(p->directmediaha);
6590
		p->directmediaacl = ast_free_acl_list(p->directmediaacl);
5943
		p->directmediaha = NULL;

   
5944
	}
6591
	}
5945

    
   
6592

   
5946
	ast_string_field_free_memory(p);
6593
	ast_string_field_free_memory(p);
5947

    
   
6594

   
5948
	ast_cc_config_params_destroy(p->cc_params);
6595
	ast_cc_config_params_destroy(p->cc_params);

    
   
6596
	p->cc_params = NULL;
5949

    
   
6597

   
5950
	if (p->epa_entry) {
6598
	if (p->epa_entry) {
5951
		ao2_ref(p->epa_entry, -1);
6599
		ao2_ref(p->epa_entry, -1);
5952
		p->epa_entry = NULL;
6600
		p->epa_entry = NULL;
5953
	}
6601
	}
5954

    
   
6602

   
5955
	if (p->socket.tcptls_session) {
6603
	if (p->socket.tcptls_session) {
5956
		ao2_ref(p->socket.tcptls_session, -1);
6604
		ao2_ref(p->socket.tcptls_session, -1);
5957
		p->socket.tcptls_session = NULL;
6605
		p->socket.tcptls_session = NULL;

    
   
6606
	} else if (p->socket.ws_session) {

    
   
6607
		ast_websocket_unref(p->socket.ws_session);

    
   
6608
		p->socket.ws_session = NULL;
5958
	}
6609
	}
5959

    
   
6610

   
5960
	if (p->peerauth) {
6611
	if (p->peerauth) {
5961
		ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
6612
		ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
5962
		p->peerauth = NULL;
6613
		p->peerauth = NULL;
5963
	}
6614
	}
5964

    
   
6615

   

    
   
6616
	p->named_callgroups = ast_unref_namedgroups(p->named_callgroups);

    
   
6617
	p->named_pickupgroups = ast_unref_namedgroups(p->named_pickupgroups);

    
   
6618

   
5965
	p->caps = ast_format_cap_destroy(p->caps);
6619
	p->caps = ast_format_cap_destroy(p->caps);
5966
	p->jointcaps = ast_format_cap_destroy(p->jointcaps);
6620
	p->jointcaps = ast_format_cap_destroy(p->jointcaps);
5967
	p->peercaps = ast_format_cap_destroy(p->peercaps);
6621
	p->peercaps = ast_format_cap_destroy(p->peercaps);
5968
	p->redircaps = ast_format_cap_destroy(p->redircaps);
6622
	p->redircaps = ast_format_cap_destroy(p->redircaps);
5969
	p->prefcaps = ast_format_cap_destroy(p->prefcaps);
6623
	p->prefcaps = ast_format_cap_destroy(p->prefcaps);

    
   
6624

   

    
   
6625
	ast_rtp_dtls_cfg_free(&p->dtls_cfg);

    
   
6626

   

    
   
6627
	if (p->last_device_state_info) {

    
   
6628
		ao2_ref(p->last_device_state_info, -1);

    
   
6629
		p->last_device_state_info = NULL;

    
   
6630
	}

    
   
6631

   

    
   
6632
	/* Lastly, kill the callid associated with the pvt */

    
   
6633
	if (p->logger_callid) {

    
   
6634
		ast_callid_unref(p->logger_callid);

    
   
6635
	}
5970
}
6636
}
5971

    
   
6637

   
5972
/*! \brief  update_call_counter: Handle call_limit for SIP devices
6638
/*! \brief  update_call_counter: Handle call_limit for SIP devices
5973
 * Setting a call-limit will cause calls above the limit not to be accepted.
6639
 * Setting a call-limit will cause calls above the limit not to be accepted.
5974
 *
6640
 *
[+20] [20] 9 lines
[+20] void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
5984
 *
6650
 *
5985
 */
6651
 */
5986
static int update_call_counter(struct sip_pvt *fup, int event)
6652
static int update_call_counter(struct sip_pvt *fup, int event)
5987
{
6653
{
5988
	char name[256];
6654
	char name[256];
5989
	int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
6655
	int *inuse = NULL, *call_limit = NULL, *ringing = NULL;
5990
	int outgoing = fup->outgoing_call;
6656
	int outgoing = fup->outgoing_call;
5991
	struct sip_peer *p = NULL;
6657
	struct sip_peer *p = NULL;
5992

    
   
6658

   
5993
	ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
6659
	ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
5994

    
   
6660

   
[+20] [20] 6 lines
[+20] static int update_call_counter(struct sip_pvt *fup, int event)
6001
	ast_copy_string(name, fup->username, sizeof(name));
6667
	ast_copy_string(name, fup->username, sizeof(name));
6002

    
   
6668

   
6003
	/* Check the list of devices */
6669
	/* Check the list of devices */
6004
	if (fup->relatedpeer) {
6670
	if (fup->relatedpeer) {
6005
		p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
6671
		p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
6006
		inuse = &p->inUse;
6672
		inuse = &p->inuse;
6007
		call_limit = &p->call_limit;
6673
		call_limit = &p->call_limit;
6008
		inringing = &p->inRinging;
6674
		ringing = &p->ringing;
6009
		ast_copy_string(name, fup->peername, sizeof(name));
6675
		ast_copy_string(name, fup->peername, sizeof(name));
6010
	}
6676
	}
6011
	if (!p) {
6677
	if (!p) {
6012
		ast_debug(2, "%s is not a local device, no call limit\n", name);
6678
		ast_debug(2, "%s is not a local device, no call limit\n", name);
6013
		return 0;
6679
		return 0;
6014
	}
6680
	}
6015

    
   
6681

   
6016
	switch(event) {
6682
	switch(event) {
6017
	/* incoming and outgoing affects the inUse counter */
6683
	/* incoming and outgoing affects the inuse counter */
6018
	case DEC_CALL_LIMIT:
6684
	case DEC_CALL_LIMIT:
6019
		/* Decrement inuse count if applicable */
6685
		/* Decrement inuse count if applicable */
6020
		if (inuse) {
6686
		if (inuse) {
6021
			sip_pvt_lock(fup);
6687
			sip_pvt_lock(fup);
6022
			ao2_lock(p);
6688
			ao2_lock(p);
[+20] [20] 8 lines
[+20] static int update_call_counter(struct sip_pvt *fup, int event)
6031
			ao2_unlock(p);
6697
			ao2_unlock(p);
6032
			sip_pvt_unlock(fup);
6698
			sip_pvt_unlock(fup);
6033
		}
6699
		}
6034

    
   
6700

   
6035
		/* Decrement ringing count if applicable */
6701
		/* Decrement ringing count if applicable */
6036
		if (inringing) {
6702
		if (ringing) {
6037
			sip_pvt_lock(fup);
6703
			sip_pvt_lock(fup);
6038
			ao2_lock(p);
6704
			ao2_lock(p);
6039
			if (*inringing > 0) {
6705
			if (*ringing > 0) {
6040
				if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6706
				if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6041
					(*inringing)--;
6707
					(*ringing)--;
6042
					ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
6708
					ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
6043
				}
6709
				}
6044
			} else {
6710
			} else {
6045
			   *inringing = 0;
6711
			   *ringing = 0;
6046
			}
6712
			}
6047
			ao2_unlock(p);
6713
			ao2_unlock(p);
6048
			sip_pvt_unlock(fup);
6714
			sip_pvt_unlock(fup);
6049
		}
6715
		}
6050

    
   
6716

   
[+20] [20] 21 lines
[+20] static int update_call_counter(struct sip_pvt *fup, int event)
6072
				ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
6738
				ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
6073
				sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
6739
				sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
6074
				return -1;
6740
				return -1;
6075
			}
6741
			}
6076
		}
6742
		}
6077
		if (inringing && (event == INC_CALL_RINGING)) {
6743
		if (ringing && (event == INC_CALL_RINGING)) {
6078
			sip_pvt_lock(fup);
6744
			sip_pvt_lock(fup);
6079
			ao2_lock(p);
6745
			ao2_lock(p);
6080
			if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6746
			if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6081
				(*inringing)++;
6747
				(*ringing)++;
6082
				ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
6748
				ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
6083
			}
6749
			}
6084
			ao2_unlock(p);
6750
			ao2_unlock(p);
6085
			sip_pvt_unlock(fup);
6751
			sip_pvt_unlock(fup);
6086
		}
6752
		}
[+20] [20] 11 lines
[+20] static int update_call_counter(struct sip_pvt *fup, int event)
6098
			ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
6764
			ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
6099
		}
6765
		}
6100
		break;
6766
		break;
6101

    
   
6767

   
6102
	case DEC_CALL_RINGING:
6768
	case DEC_CALL_RINGING:
6103
		if (inringing) {
6769
		if (ringing) {
6104
			sip_pvt_lock(fup);
6770
			sip_pvt_lock(fup);
6105
			ao2_lock(p);
6771
			ao2_lock(p);
6106
			if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6772
			if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6107
				if (*inringing > 0) {
6773
				if (*ringing > 0) {
6108
					(*inringing)--;
6774
					(*ringing)--;
6109
				}
6775
				}
6110
				ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
6776
				ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
6111
			}
6777
			}
6112
			ao2_unlock(p);
6778
			ao2_unlock(p);
6113
			sip_pvt_unlock(fup);
6779
			sip_pvt_unlock(fup);
[+20] [20] 199 lines
[+20] [+] const char *hangup_cause2sip(int cause)
6313

    
   
6979

   
6314
	/* Never reached */
6980
	/* Never reached */
6315
	return 0;
6981
	return 0;
6316
}
6982
}
6317

    
   
6983

   

    
   
6984
static int reinvite_timeout(const void *data)

    
   
6985
{

    
   
6986
	struct sip_pvt *dialog = (struct sip_pvt *) data;

    
   
6987
	struct ast_channel *owner = sip_pvt_lock_full(dialog);

    
   
6988
	dialog->reinviteid = -1;

    
   
6989
	check_pendings(dialog);

    
   
6990
	if (owner) {

    
   
6991
		ast_channel_unlock(owner);

    
   
6992
		ast_channel_unref(owner);

    
   
6993
	}

    
   
6994
	ao2_unlock(dialog);

    
   
6995
	dialog_unref(dialog, "unref for reinvite timeout");
Moved from 2513

    
   
6996
	return 0;
Moved from 2514

    
   
6997
}

    
   
6998

   
6318
/*! \brief  sip_hangup: Hangup SIP call
6999
/*! \brief  sip_hangup: Hangup SIP call
6319
 * Part of PBX interface, called from ast_hangup */
7000
 * Part of PBX interface, called from ast_hangup */
6320
static int sip_hangup(struct ast_channel *ast)
7001
static int sip_hangup(struct ast_channel *ast)
6321
{
7002
{
6322
	struct sip_pvt *p = ast_channel_tech_pvt(ast);
7003
	struct sip_pvt *p = ast_channel_tech_pvt(ast);
6323
	int needcancel = FALSE;
7004
	int needcancel = FALSE;
6324
	int needdestroy = 0;
7005
	int needdestroy = 0;
6325
	struct ast_channel *oldowner = ast;
7006
	struct ast_channel *oldowner = ast;
6326

    
   
7007

   
6327
	if (!p) {
7008
	if (!p) {
6328
		ast_debug(1, "Asked to hangup channel that was not connected\n");
7009
		ast_debug(1, "Asked to hangup channel that was not connected\n");
6329
		return 0;
7010
		return 0;
6330
	}
7011
	}
6331
	if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {

   
6332
		ast_debug(1, "This call was answered elsewhere");

   
6333
		if (ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
7012
	if (ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
6334
			ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
7013
		ast_debug(1, "This call was answered elsewhere\n");
6335
		}

   
6336
		append_history(p, "Cancel", "Call answered elsewhere");
7014
		append_history(p, "Cancel", "Call answered elsewhere");
6337
		p->answered_elsewhere = TRUE;
7015
		p->answered_elsewhere = TRUE;
6338
	}
7016
	}
6339

    
   
7017

   
6340
	/* Store hangupcause locally in PVT so we still have it before disconnect */
7018
	/* Store hangupcause locally in PVT so we still have it before disconnect */
[+20] [20] 15 lines
[+20] static int sip_hangup(struct ast_channel *ast)
6356
		sip_pvt_unlock(p);
7034
		sip_pvt_unlock(p);
6357
		ast_module_unref(ast_module_info->self);
7035
		ast_module_unref(ast_module_info->self);
6358
		return 0;
7036
		return 0;
6359
	}
7037
	}
6360

    
   
7038

   
6361
	if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {

   
6362
		if (p->refer)

   
6363
			ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast_channel_name(ast), p->callid);

   
6364
		else

   
6365
			ast_debug(1, "Hanging up zombie call. Be scared.\n");

   
6366
	} else

   
6367
		ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
7039
	ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
6368

    
   
7040

   
6369
	sip_pvt_lock(p);
7041
	sip_pvt_lock(p);
6370
	if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
7042
	if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
6371
		if (sipdebug)
7043
		if (sipdebug)
[+20] [20] 101 lines
[+20] static int sip_hangup(struct ast_channel *ast)
6473
						ast_rtp_instance_set_stats_vars(bridge, q->rtp);
7145
						ast_rtp_instance_set_stats_vars(bridge, q->rtp);
6474
					}
7146
					}
6475
					ast_channel_unlock(bridge);
7147
					ast_channel_unlock(bridge);
6476
				}
7148
				}
6477

    
   
7149

   
6478
				if (p->do_history || oldowner) {
7150
				/*

    
   
7151
				 * The channel variables are set below just to get the AMI

    
   
7152
				 * VarSet event because the channel is being hungup.

    
   
7153
				 */
6479
					if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
7154
				if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
6480
						if (p->do_history) {
7155
					if (p->do_history) {
6481
							append_history(p, "RTCPaudio", "Quality:%s", quality);
7156
						append_history(p, "RTCPaudio", "Quality:%s", quality);
6482
						}
7157
					}
6483
						if (oldowner) {

   
6484
							pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
7158
					pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
6485
						}
7159
				}
6486
					}

   
6487
					if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
7160
				if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
6488
						if (p->do_history) {
7161
					if (p->do_history) {
6489
							append_history(p, "RTCPvideo", "Quality:%s", quality);
7162
						append_history(p, "RTCPvideo", "Quality:%s", quality);
6490
						}
7163
					}
6491
						if (oldowner) {

   
6492
							pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
7164
					pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
6493
						}

   
6494
					}
7165
				}
6495
					if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
7166
				if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
6496
						if (p->do_history) {
7167
					if (p->do_history) {
6497
							append_history(p, "RTCPtext", "Quality:%s", quality);
7168
						append_history(p, "RTCPtext", "Quality:%s", quality);
6498
						}
7169
					}
6499
						if (oldowner) {

   
6500
							pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
7170
					pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
6501
						}
7171
				}
6502
					}

   
6503
				}

   
6504

    
   
7172

   
6505
				/* Send a hangup */
7173
				/* Send a hangup */
6506
				if (ast_channel_state(oldowner) == AST_STATE_UP) {
7174
				if (ast_channel_state(oldowner) == AST_STATE_UP) {
6507
					transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
7175
					transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
6508
				}
7176
				}
6509

    
   
7177

   
6510
			} else {
7178
			} else {
6511
				/* Note we will need a BYE when this all settles out
7179
				/* Note we will need a BYE when this all settles out
6512
				   but we can't send one while we have "INVITE" outstanding. */
7180
				   but we can't send one while we have "INVITE" outstanding. */
6513
				ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
7181
				ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
6514
				ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);	
7182
				ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);	
6515
				AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
7183
				AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
6516
				if (sip_cancel_destroy(p))
7184
				if (sip_cancel_destroy(p)) {
6517
					ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
7185
					ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
6518
			}
7186
				}

    
   
7187
				/* If we have an ongoing reinvite, there is a chance that we have gotten a provisional

    
   
7188
				 * response, but something weird has happened and we will never receive a final response.

    
   
7189
				 * So, just in case, check for pending actions after a bit of time to trigger the pending

    
   
7190
				 * bye that we are setting above */

    
   
7191
				if (p->ongoing_reinvite && p->reinviteid < 0) {

    
   
7192
					p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));

    
   
7193
				}

    
   
7194
			}
6519
		}
7195
		}
6520
	}
7196
	}
6521
	if (needdestroy) {
7197
	if (needdestroy) {
6522
		pvt_set_needdestroy(p, "hangup");
7198
		pvt_set_needdestroy(p, "hangup");
6523
	}
7199
	}
[+20] [20] 164 lines
[+20] [+] static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
6688
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
7364
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
6689
{
7365
{
6690
	int ret = -1;
7366
	int ret = -1;
6691
	struct sip_pvt *p;
7367
	struct sip_pvt *p;
6692

    
   
7368

   
6693
	if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
7369
	if (newchan && ast_test_flag(ast_channel_flags(newchan), AST_FLAG_ZOMBIE))
6694
		ast_debug(1, "New channel is zombie\n");
7370
		ast_debug(1, "New channel is zombie\n");
6695
	if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
7371
	if (oldchan && ast_test_flag(ast_channel_flags(oldchan), AST_FLAG_ZOMBIE))
6696
		ast_debug(1, "Old channel is zombie\n");
7372
		ast_debug(1, "Old channel is zombie\n");
6697

    
   
7373

   
6698
	if (!newchan || !ast_channel_tech_pvt(newchan)) {
7374
	if (!newchan || !ast_channel_tech_pvt(newchan)) {
6699
		if (!newchan)
7375
		if (!newchan)
6700
			ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
7376
			ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
[+20] [20] 215 lines
[+20] [+] static int initialize_udptl(struct sip_pvt *p)
6916
	}
7592
	}
6917

    
   
7593

   
6918
	return 0;
7594
	return 0;
6919
}
7595
}
6920

    
   
7596

   

    
   
7597

   

    
   
7598
static int sipinfo_send(

    
   
7599
		struct ast_channel *chan,

    
   
7600
		struct ast_variable *headers,

    
   
7601
		const char *content_type,

    
   
7602
		const char *content,

    
   
7603
		const char *useragent_filter)

    
   
7604
{

    
   
7605
	struct sip_pvt *p;

    
   
7606
	struct ast_variable *var;

    
   
7607
	struct sip_request req;

    
   
7608
	int res = -1;

    
   
7609

   

    
   
7610
	ast_channel_lock(chan);

    
   
7611

   

    
   
7612
	if (ast_channel_tech(chan) != &sip_tech) {

    
   
7613
		ast_log(LOG_WARNING, "Attempted to send a custom INFO on a non-SIP channel %s\n", ast_channel_name(chan));

    
   
7614
		ast_channel_unlock(chan);
Moved from 26008

    
   
7615
		return res;
Moved from 26009

    
   
7616
	}

    
   
7617

   

    
   
7618
	p = ast_channel_tech_pvt(chan);

    
   
7619
	sip_pvt_lock(p);

    
   
7620

   

    
   
7621
	if (!(ast_strlen_zero(useragent_filter))) {

    
   
7622
		int match = (strstr(p->useragent, useragent_filter)) ? 1 : 0;

    
   
7623
		if (!match) {
Moved from 2546

    
   
7624
			goto cleanup;
Moved from 2547

    
   
7625
		}

    
   
7626
	}

    
   
7627

   

    
   
7628
	reqprep(&req, p, SIP_INFO, 0, 1);

    
   
7629
	for (var = headers; var; var = var->next) {

    
   
7630
		add_header(&req, var->name, var->value);

    
   
7631
	}

    
   
7632
	if (!ast_strlen_zero(content) && !ast_strlen_zero(content_type)) {

    
   
7633
		add_header(&req, "Content-Type", content_type);

    
   
7634
		add_content(&req, content);

    
   
7635
	}

    
   
7636

   

    
   
7637
	res = send_request(p, &req, XMIT_RELIABLE, p->ocseq);

    
   
7638

   

    
   
7639
cleanup:

    
   
7640
	sip_pvt_unlock(p);

    
   
7641
	ast_channel_unlock(chan);
Moved from 26008

    
   
7642
	return res;
Moved from 26009

    
   
7643
}
6921
/*! \brief Play indication to user
7644
/*! \brief Play indication to user
6922
 * With SIP a lot of indications is sent as messages, letting the device play
7645
 * With SIP a lot of indications is sent as messages, letting the device play
6923
   the indication - busy signal, congestion etc
7646
   the indication - busy signal, congestion etc
6924
   \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
7647
   \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
6925
*/
7648
*/
[+20] [20] 156 lines
[+20] [+] static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
7082
			ast_aoc_destroy_decoded(decoded);
7805
			ast_aoc_destroy_decoded(decoded);
7083
		}
7806
		}
7084
		break;
7807
		break;
7085
	case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
7808
	case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
7086
		break;
7809
		break;

    
   
7810
	case AST_CONTROL_FLASH: /* We don't currently handle AST_CONTROL_FLASH here, but it is expected, so we don't need to warn either. */

    
   
7811
		res = -1;

    
   
7812
		break;

    
   
7813
	case AST_CONTROL_PVT_CAUSE_CODE: /* these should be handled by the code in channel.c */
7087
	case -1:
7814
	case -1:
7088
		res = -1;
7815
		res = -1;
7089
		break;
7816
		break;
7090
	default:
7817
	default:
7091
		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
7818
		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
[+20] [20] 13 lines
[+20] static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
7105
 *
7832
 *
7106
 * \pre i is locked
7833
 * \pre i is locked
7107
 *
7834
 *
7108
 * \return New ast_channel locked.
7835
 * \return New ast_channel locked.
7109
 */
7836
 */
7110
static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
7837
static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid, struct ast_callid *callid)
7111
{
7838
{
7112
	struct ast_channel *tmp;
7839
	struct ast_channel *tmp;
7113
	struct ast_variable *v = NULL;
7840
	struct ast_variable *v = NULL;
7114
	struct ast_format fmt;
7841
	struct ast_format fmt;
7115
	struct ast_format_cap *what = NULL; /* SHALLOW COPY DO NOT DESTROY! */
7842
	struct ast_format_cap *what = NULL; /* SHALLOW COPY DO NOT DESTROY! */
[+20] [20] 18 lines
[+20] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid) [+] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid, struct ast_callid *callid)
7134
	if (!tmp) {
7861
	if (!tmp) {
7135
		ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
7862
		ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
7136
		sip_pvt_lock(i);
7863
		sip_pvt_lock(i);
7137
		return NULL;
7864
		return NULL;
7138
	}
7865
	}

    
   
7866

   

    
   
7867
	/* If we sent in a callid, bind it to the channel. */

    
   
7868
	if (callid) {

    
   
7869
		ast_channel_callid_set(tmp, callid);

    
   
7870
	}

    
   
7871

   
7139
	ast_channel_lock(tmp);
7872
	ast_channel_lock(tmp);
7140
	sip_pvt_lock(i);
7873
	sip_pvt_lock(i);
7141
	ast_channel_cc_params_init(tmp, i->cc_params);
7874
	ast_channel_cc_params_init(tmp, i->cc_params);
7142
	ast_channel_caller(tmp)->id.tag = ast_strdup(i->cid_tag);
7875
	ast_channel_caller(tmp)->id.tag = ast_strdup(i->cid_tag);
7143

    
   
7876

   
[+20] [20] 67 lines
[+20] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid) [+] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid, struct ast_callid *callid)
7211
	 * UDPTL is created as needed in the lifetime of a dialog, its file
7944
	 * UDPTL is created as needed in the lifetime of a dialog, its file
7212
	 * descriptor is set in initialize_udptl */
7945
	 * descriptor is set in initialize_udptl */
7213
	if (i->rtp) {
7946
	if (i->rtp) {
7214
		ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
7947
		ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
7215
		ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
7948
		ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));

    
   
7949
		ast_rtp_instance_set_write_format(i->rtp, &fmt);

    
   
7950
		ast_rtp_instance_set_read_format(i->rtp, &fmt);
7216
	}
7951
	}
7217
	if (needvideo && i->vrtp) {
7952
	if (needvideo && i->vrtp) {
7218
		ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
7953
		ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
7219
		ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
7954
		ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
7220
	}
7955
	}
[+20] [20] 9 lines
[+20] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid) [+] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid, struct ast_callid *callid)
7230
	}
7965
	}
7231
	ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
7966
	ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
7232

    
   
7967

   
7233
	ast_format_copy(ast_channel_writeformat(tmp), &fmt);
7968
	ast_format_copy(ast_channel_writeformat(tmp), &fmt);
7234
	ast_format_copy(ast_channel_rawwriteformat(tmp), &fmt);
7969
	ast_format_copy(ast_channel_rawwriteformat(tmp), &fmt);
7235
	ast_rtp_instance_set_write_format(i->rtp, &fmt);

   
7236

    
   
7970

   
7237
	ast_format_copy(ast_channel_readformat(tmp), &fmt);
7971
	ast_format_copy(ast_channel_readformat(tmp), &fmt);
7238
	ast_format_copy(ast_channel_rawreadformat(tmp), &fmt);
7972
	ast_format_copy(ast_channel_rawreadformat(tmp), &fmt);
7239
	ast_rtp_instance_set_read_format(i->rtp, &fmt);

   
7240

    
   
7973

   
7241
	ast_channel_tech_pvt_set(tmp, dialog_ref(i, "sip_new: set chan->tech_pvt to i"));
7974
	ast_channel_tech_pvt_set(tmp, dialog_ref(i, "sip_new: set chan->tech_pvt to i"));
7242

    
   
7975

   
7243
	ast_channel_callgroup_set(tmp, i->callgroup);
7976
	ast_channel_callgroup_set(tmp, i->callgroup);
7244
	ast_channel_pickupgroup_set(tmp, i->pickupgroup);
7977
	ast_channel_pickupgroup_set(tmp, i->pickupgroup);

    
   
7978

   

    
   
7979
	ast_channel_named_callgroups_set(tmp, i->named_callgroups);

    
   
7980
	ast_channel_named_pickupgroups_set(tmp, i->named_pickupgroups);

    
   
7981

   
7245
	ast_channel_caller(tmp)->id.name.presentation = i->callingpres;
7982
	ast_channel_caller(tmp)->id.name.presentation = i->callingpres;
7246
	ast_channel_caller(tmp)->id.number.presentation = i->callingpres;
7983
	ast_channel_caller(tmp)->id.number.presentation = i->callingpres;
7247
	if (!ast_strlen_zero(i->parkinglot)) {
7984
	if (!ast_strlen_zero(i->parkinglot)) {
7248
		ast_channel_parkinglot_set(tmp, i->parkinglot);
7985
		ast_channel_parkinglot_set(tmp, i->parkinglot);
7249
	}
7986
	}
[+20] [20] 75 lines
[+20] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid) [+] static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid, struct ast_callid *callid)
7325
			"Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
8062
			"Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
7326
			ast_channel_name(tmp), ast_channel_uniqueid(tmp), "SIP", i->callid, i->fullcontact);
8063
			ast_channel_name(tmp), ast_channel_uniqueid(tmp), "SIP", i->callid, i->fullcontact);
7327
	}
8064
	}
7328

    
   
8065

   
7329
	return tmp;
8066
	return tmp;
7330
}

   
7331

    
   

   
7332
/*! \brief Reads one line of SIP message body */

   
7333
static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)

   
7334
{

   
7335
	if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter) {

   
7336
		return ast_skip_blanks(line + nameLen + 1);

   
7337
	}

   
7338

    
   

   
7339
	return "";

   
7340
}
8067
}
7341

    
   
8068

   
7342
/*! \brief Lookup 'name' in the SDP starting
8069
/*! \brief Lookup 'name' in the SDP starting
7343
 * at the 'start' line. Returns the matching line, and 'start'
8070
 * at the 'start' line. Returns the matching line, and 'start'
7344
 * is updated with the next line number.
8071
 * is updated with the next line number.
7345
 */
8072
 */
7346
static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
8073
static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
7347
{
8074
{
7348
	int len = strlen(name);
8075
	int len = strlen(name);

    
   
8076
	const char *line;
7349

    
   
8077

   
7350
	while (*start < (req->sdp_start + req->sdp_count)) {
8078
	while (*start < (req->sdp_start + req->sdp_count)) {
7351
		const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
8079
		line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
7352
		if (r[0] != '\0')
8080
		if (!strncasecmp(line, name, len) && line[len] == '=') {
7353
			return r;
8081
			return ast_skip_blanks(line + len + 1);

    
   
8082
		}
7354
	}
8083
	}
7355

    
   
8084

   
7356
	/* if the line was not found, ensure that *start points past the SDP */
8085
	/* if the line was not found, ensure that *start points past the SDP */
7357
	(*start)++;
8086
	(*start)++;
7358

    
   
8087

   
[+20] [20] 24 lines
[+20] [+] static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
7383
	}
8112
	}
7384

    
   
8113

   
7385
	return type;
8114
	return type;
7386
}
8115
}
7387

    
   
8116

   
7388
/*! \brief Get a specific line from the message body */
8117
/*! \brief Get a specific line from the message content */
7389
static char *get_body(struct sip_request *req, char *name, char delimiter)
8118
static char *get_content_line(struct sip_request *req, char *name, char delimiter)
7390
{
8119
{
7391
	int x;
8120
	int i;
7392
	int len = strlen(name);
8121
	int len = strlen(name);
7393
	char *r;
8122
	const char *line;
7394

    
   
8123

   
7395
	for (x = 0; x < req->lines; x++) {
8124
	for (i = 0; i < req->lines; i++) {
7396
		r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
8125
		line = REQ_OFFSET_TO_STR(req, line[i]);
7397
		if (r[0] != '\0') {
8126
		if (!strncasecmp(line, name, len) && line[len] == delimiter) {
7398
			return r;
8127
			return ast_skip_blanks(line + len + 1);
7399
		}
8128
		}
7400
	}
8129
	}
7401

    
   
8130

   
7402
	return "";
8131
	return "";
7403
}
8132
}
[+20] [20] 99 lines
[+20] [+] static const char *__get_header(const struct sip_request *req, const char *name, int *start)
7503
{
8232
{
7504
	int start = 0;
8233
	int start = 0;
7505
	return __get_header(req, name, &start);
8234
	return __get_header(req, name, &start);
7506
}
8235
}
7507

    
   
8236

   

    
   
8237

   

    
   
8238
AST_THREADSTORAGE(sip_content_buf);

    
   
8239

   

    
   
8240
/*! \brief Get message body content */

    
   
8241
static char *get_content(struct sip_request *req)

    
   
8242
{

    
   
8243
	struct ast_str *str;

    
   
8244
	int i;

    
   
8245

   

    
   
8246
	if (!(str = ast_str_thread_get(&sip_content_buf, 128))) {

    
   
8247
		return NULL;

    
   
8248
	}

    
   
8249

   

    
   
8250
	ast_str_reset(str);

    
   
8251

   

    
   
8252
	for (i = 0; i < req->lines; i++) {

    
   
8253
		if (ast_str_append(&str, 0, "%s\n", REQ_OFFSET_TO_STR(req, line[i])) < 0) {

    
   
8254
			return NULL;

    
   
8255
		}

    
   
8256
	}

    
   
8257

   

    
   
8258
	return ast_str_buffer(str);

    
   
8259
}

    
   
8260

   
7508
/*! \brief Read RTP from network */
8261
/*! \brief Read RTP from network */
7509
static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
8262
static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
7510
{
8263
{
7511
	/* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
8264
	/* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
7512
	struct ast_frame *f;
8265
	struct ast_frame *f;
[+20] [20] 46 lines
[+20] static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
7559
	}
8312
	}
7560
	/* Don't forward RFC2833 if we're not supposed to */
8313
	/* Don't forward RFC2833 if we're not supposed to */
7561
	if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
8314
	if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
7562
	    (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
8315
	    (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
7563
		ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
8316
		ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);

    
   
8317
		ast_frfree(f);
7564
		return &ast_null_frame;
8318
		return &ast_null_frame;
7565
	}
8319
	}
7566

    
   
8320

   
7567
	/* We already hold the channel lock */
8321
	/* We already hold the channel lock */
7568
	if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
8322
	if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
7569
		return f;
8323
		return f;
7570
	}
8324
	}
7571

    
   
8325

   
7572
	if (f && !ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format)) {
8326
	if (f && !ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format)) {
7573
		if (!ast_format_cap_iscompatible(p->jointcaps, &f->subclass.format)) {
8327
		if (!ast_format_cap_iscompatible(p->jointcaps, &f->subclass.format)) {
7574
			ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
8328
			ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
7575
				ast_getformatname(&f->subclass.format), ast_channel_name(p->owner));
8329
				ast_getformatname(&f->subclass.format), ast_channel_name(p->owner));

    
   
8330
			ast_frfree(f);
7576
			return &ast_null_frame;
8331
			return &ast_null_frame;
7577
		}
8332
		}
7578
		ast_debug(1, "Oooh, format changed to %s\n",
8333
		ast_debug(1, "Oooh, format changed to %s\n",
7579
			ast_getformatname(&f->subclass.format));
8334
			ast_getformatname(&f->subclass.format));
7580
		ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
8335
		ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
[+20] [20] 53 lines
[+20] [+] static struct ast_frame *sip_read(struct ast_channel *ast)
7634
				ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
8389
				ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
7635
				pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
8390
				pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
7636
				if (ast_async_goto(ast, target_context, "fax", 1)) {
8391
				if (ast_async_goto(ast, target_context, "fax", 1)) {
7637
					ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
8392
					ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
7638
				}
8393
				}

    
   
8394
				ast_frfree(fr);
7639
				fr = &ast_null_frame;
8395
				fr = &ast_null_frame;
7640
			} else {
8396
			} else {
7641
				ast_channel_lock(ast);
8397
				ast_channel_lock(ast);
7642
				sip_pvt_lock(p);
8398
				sip_pvt_lock(p);
7643
				ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
8399
				ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
7644
			}
8400
			}
7645
		}
8401
		}
7646
	}
8402
	}
7647

    
   
8403

   
7648
	/* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
8404
	/* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
7649
	if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast_channel_state(ast) != AST_STATE_UP) {
8405
	if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast_channel_state(ast) != AST_STATE_UP) {

    
   
8406
		ast_frfree(fr);
7650
		fr = &ast_null_frame;
8407
		fr = &ast_null_frame;
7651
	}
8408
	}
7652

    
   
8409

   
7653
	sip_pvt_unlock(p);
8410
	sip_pvt_unlock(p);
7654

    
   
8411

   
[+20] [20] 100 lines
[+20] [+] static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
7755

    
   
8512

   
7756
	ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
8513
	ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
7757
}
8514
}
7758

    
   
8515

   
7759
/*! \brief Make our SIP dialog tag */
8516
/*! \brief Make our SIP dialog tag */
7760
static void make_our_tag(char *tagbuf, size_t len)
8517
static void make_our_tag(struct sip_pvt *pvt)
7761
{
8518
{
7762
	snprintf(tagbuf, len, "as%08lx", ast_random());
8519
	ast_string_field_build(pvt, tag, "as%08lx", ast_random());
7763
}
8520
}
7764

    
   
8521

   
7765
/*! \brief Allocate Session-Timers struct w/in dialog */
8522
/*! \brief Allocate Session-Timers struct w/in dialog */
7766
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
8523
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
7767
{
8524
{
[+20] [20] 12 lines
[+20] static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
7780
	stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
8537
	stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
7781

    
   
8538

   
7782
	return p->stimer;
8539
	return p->stimer;
7783
}
8540
}
7784

    
   
8541

   

    
   
8542
static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)

    
   
8543
{

    
   
8544
	if (pvt->logger_callid) {

    
   
8545
		ast_callid_unref(pvt->logger_callid);

    
   
8546
	}

    
   
8547
	ast_callid_ref(callid);

    
   
8548
	pvt->logger_callid = callid;

    
   
8549
}

    
   
8550

   
7785
/*! \brief Allocate sip_pvt structure, set defaults and link in the container.
8551
/*! \brief Allocate sip_pvt structure, set defaults and link in the container.
7786
 * Returns a reference to the object so whoever uses it later must
8552
 * Returns a reference to the object so whoever uses it later must
7787
 * remember to release the reference.
8553
 * remember to release the reference.
7788
 */
8554
 */
7789
struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
8555
struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
7790
				 int useglobal_nat, const int intended_method, struct sip_request *req)
8556
				 int useglobal_nat, const int intended_method, struct sip_request *req, struct ast_callid *logger_callid)
7791
{
8557
{
7792
	struct sip_pvt *p;
8558
	struct sip_pvt *p;
7793

    
   
8559

   
7794
	if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
8560
	if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
7795
		return NULL;
8561
		return NULL;
[+20] [20] 5 lines
[+20] static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p) [+] static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)
7801

    
   
8567

   
7802
	if (!(p->cc_params = ast_cc_config_params_init())) {
8568
	if (!(p->cc_params = ast_cc_config_params_init())) {
7803
		ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
8569
		ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
7804
		return NULL;
8570
		return NULL;
7805
	}
8571
	}

    
   
8572

   

    
   
8573
	if (logger_callid) {

    
   
8574
		sip_pvt_callid_set(p, logger_callid);

    
   
8575
	}

    
   
8576

   
7806
	p->caps = ast_format_cap_alloc_nolock();
8577
	p->caps = ast_format_cap_alloc_nolock();
7807
	p->jointcaps = ast_format_cap_alloc_nolock();
8578
	p->jointcaps = ast_format_cap_alloc_nolock();
7808
	p->peercaps = ast_format_cap_alloc_nolock();
8579
	p->peercaps = ast_format_cap_alloc_nolock();
7809
	p->redircaps = ast_format_cap_alloc_nolock();
8580
	p->redircaps = ast_format_cap_alloc_nolock();
7810
	p->prefcaps = ast_format_cap_alloc_nolock();
8581
	p->prefcaps = ast_format_cap_alloc_nolock();
[+20] [20] 41 lines
[+20] static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p) [+] static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)
7852

    
   
8623

   
7853
	p->socket.fd = -1;
8624
	p->socket.fd = -1;
7854
	p->method = intended_method;
8625
	p->method = intended_method;
7855
	p->initid = -1;
8626
	p->initid = -1;
7856
	p->waitid = -1;
8627
	p->waitid = -1;

    
   
8628
	p->reinviteid = -1;
7857
	p->autokillid = -1;
8629
	p->autokillid = -1;
7858
	p->request_queue_sched_id = -1;
8630
	p->request_queue_sched_id = -1;
7859
	p->provisional_keepalive_sched_id = -1;
8631
	p->provisional_keepalive_sched_id = -1;
7860
	p->t38id = -1;
8632
	p->t38id = -1;
7861
	p->subscribed = NONE;
8633
	p->subscribed = NONE;
[+20] [20] 23 lines
[+20] static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p) [+] static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)
7885
	ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
8657
	ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
7886

    
   
8658

   
7887
	p->do_history = recordhistory;
8659
	p->do_history = recordhistory;
7888

    
   
8660

   
7889
	p->branch = ast_random();	
8661
	p->branch = ast_random();	
7890
	make_our_tag(p->tag, sizeof(p->tag));
8662
	make_our_tag(p);
7891
	p->ocseq = INITIAL_CSEQ;
8663
	p->ocseq = INITIAL_CSEQ;
7892
	p->allowed_methods = UINT_MAX;
8664
	p->allowed_methods = UINT_MAX;
7893

    
   
8665

   
7894
	if (sip_methods[intended_method].need_rtp) {
8666
	if (sip_methods[intended_method].need_rtp) {
7895
		p->maxcallbitrate = default_maxcallbitrate;
8667
		p->maxcallbitrate = default_maxcallbitrate;
[+20] [20] 29 lines
[+20] static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p) [+] static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)
7925
	ast_string_field_set(p, context, sip_cfg.default_context);
8697
	ast_string_field_set(p, context, sip_cfg.default_context);
7926
	ast_string_field_set(p, parkinglot, default_parkinglot);
8698
	ast_string_field_set(p, parkinglot, default_parkinglot);
7927
	ast_string_field_set(p, engine, default_engine);
8699
	ast_string_field_set(p, engine, default_engine);
7928

    
   
8700

   
7929
	AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
8701
	AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);

    
   
8702
	AST_LIST_HEAD_INIT_NOLOCK(&p->offered_media);
7930

    
   
8703

   
7931
	/* Add to active dialog list */
8704
	/* Add to active dialog list */
7932

    
   
8705

   
7933
	ao2_t_link(dialogs, p, "link pvt into dialogs table");
8706
	ao2_t_link(dialogs, p, "link pvt into dialogs table");
7934

    
   
8707

   
[+20] [20] 24 lines
[+20] [+] static int process_via(struct sip_pvt *p, const struct sip_request *req)
7959
		ast_log(LOG_ERROR, "error processing via header\n");
8732
		ast_log(LOG_ERROR, "error processing via header\n");
7960
		return -1;
8733
		return -1;
7961
	}
8734
	}
7962

    
   
8735

   
7963
	if (via->maddr) {
8736
	if (via->maddr) {
7964
		if (ast_sockaddr_resolve_first(&p->sa, via->maddr, PARSE_PORT_FORBID)) {
8737
		if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
7965
			ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
8738
			ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
7966
			ast_log(LOG_ERROR, "error processing via header\n");
8739
			ast_log(LOG_ERROR, "error processing via header\n");
7967
			free_via(via);
8740
			free_via(via);
7968
			return -1;
8741
			return -1;
7969
		}
8742
		}
[+20] [20] 43 lines
[+20] [+] enum match_req_res {
8013
 */
8786
 */
8014
static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
8787
static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
8015
{
8788
{
8016
	const char *init_ruri = NULL;
8789
	const char *init_ruri = NULL;
8017
	if (sip_pvt_ptr->initreq.headers) {
8790
	if (sip_pvt_ptr->initreq.headers) {
8018
		init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
8791
		init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlpart2);
8019
	}
8792
	}
8020

    
   
8793

   
8021
	/*
8794
	/*
8022
	 * Match Tags and call-id to Dialog
8795
	 * Match Tags and call-id to Dialog
8023
	 */
8796
	 */
[+20] [20] 144 lines
[+20] static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
8168
 * exists only to properly terminiate the the forked request immediately.
8941
 * exists only to properly terminiate the the forked request immediately.
8169
 */
8942
 */
8170
static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
8943
static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
8171
{
8944
{
8172
	struct sip_pvt *p;
8945
	struct sip_pvt *p;

    
   
8946
	const char *callid;

    
   
8947
	struct ast_callid *logger_callid;

    
   
8948

   

    
   
8949
	sip_pvt_lock(original);

    
   
8950
	callid = ast_strdupa(original->callid);

    
   
8951
	logger_callid = original->logger_callid;

    
   
8952
	if (logger_callid) {

    
   
8953
		ast_callid_ref(logger_callid);

    
   
8954
	}

    
   
8955
	sip_pvt_unlock(original);
8173

    
   
8956

   
8174
	if (!(p = sip_alloc(original->callid, addr, 1, SIP_INVITE, req)))  {
8957
	p = sip_alloc(callid, addr, 1, SIP_INVITE, req, logger_callid);

    
   
8958
	if (logger_callid) {

    
   
8959
		ast_callid_unref(logger_callid);

    
   
8960
	}

    
   
8961
	if (!p)  {
8175
		return; /* alloc error */
8962
		return; /* alloc error */
8176
	}
8963
	}

    
   
8964

   

    
   
8965
	/* Lock p and original private structures. */

    
   
8966
	sip_pvt_lock(p);

    
   
8967
	while (sip_pvt_trylock(original)) {

    
   
8968
		/* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */

    
   
8969
		sip_pvt_unlock(p);

    
   
8970
		sched_yield();

    
   
8971
		sip_pvt_lock(p);

    
   
8972
	}

    
   
8973

   
8177
	p->invitestate = INV_TERMINATED;
8974
	p->invitestate = INV_TERMINATED;
8178
	p->ocseq = original->ocseq;
8975
	p->ocseq = original->ocseq;
8179
	p->branch = original->branch;
8976
	p->branch = original->branch;
8180

    
   
8977

   
8181
	memcpy(&p->flags, &original->flags, sizeof(p->flags));
8978
	memcpy(&p->flags, &original->flags, sizeof(p->flags));
8182
	copy_request(&p->initreq, &original->initreq);
8979
	copy_request(&p->initreq, &original->initreq);
8183
	ast_string_field_set(p, theirtag, new_theirtag);
8980
	ast_string_field_set(p, theirtag, new_theirtag);
8184
	ast_copy_string(p->tag, original->tag, sizeof(p->tag));
8981
	ast_string_field_set(p, tag, original->tag);
8185
	ast_string_field_set(p, uri, original->uri);
8982
	ast_string_field_set(p, uri, original->uri);
8186
	ast_string_field_set(p, our_contact, original->our_contact);
8983
	ast_string_field_set(p, our_contact, original->our_contact);
8187
	ast_string_field_set(p, fullcontact, original->fullcontact);
8984
	ast_string_field_set(p, fullcontact, original->fullcontact);

    
   
8985

   

    
   
8986
	sip_pvt_unlock(original);

    
   
8987

   
8188
	parse_ok_contact(p, req);
8988
	parse_ok_contact(p, req);
8189
	build_route(p, req, 1, 0);
8989
	build_route(p, req, 1, 0);
8190

    
   
8990

   
8191
	transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
8991
	transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
8192
	transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
8992
	transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
8193

    
   
8993

   
8194
	pvt_set_needdestroy(p, "forked request"); /* this dialog will terminate once the BYE is responed to or times out. */
8994
	pvt_set_needdestroy(p, "forked request"); /* this dialog will terminate once the BYE is responed to or times out. */

    
   
8995
	sip_pvt_unlock(p);
8195
	dialog_unref(p, "setup forked invite termination");
8996
	dialog_unref(p, "setup forked invite termination");
8196
}
8997
}
8197

    
   
8998

   
8198
/*! \internal
8999
/*! \internal
8199
 *
9000
 *
[+20] [20] 147 lines
[+20] [+] static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
8347
		args.callid = NULL; /* we already matched this. */
9148
		args.callid = NULL; /* we already matched this. */
8348
		args.totag = totag;
9149
		args.totag = totag;
8349
		args.fromtag = fromtag;
9150
		args.fromtag = fromtag;
8350
		args.seqno = seqno;
9151
		args.seqno = seqno;
8351
		/* get via header information. */
9152
		/* get via header information. */
8352
		args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
9153
		args.ruri = REQ_OFFSET_TO_STR(req, rlpart2);
8353
		via = parse_via(sip_get_header(req, "Via"));
9154
		via = parse_via(sip_get_header(req, "Via"));
8354
		if (via) {
9155
		if (via) {
8355
			args.viasentby = via->sent_by;
9156
			args.viasentby = via->sent_by;
8356
			args.viabranch = via->branch;
9157
			args.viabranch = via->branch;
8357
		}
9158
		}
8358
		/* determine if this is a Request with authentication credentials. */
9159
		/* determine if this is a Request with authentication credentials. */
8359
		if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
9160
		if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
8360
			!ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
9161
			!ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
8361
			args.authentication_present = 1;
9162
			args.authentication_present = 1;
8362
		}
9163
		}
8363
		/* if it is a response, get the response code */
9164
		/* if it is a response, get the response code */
8364
		if (req->method == SIP_RESPONSE) {
9165
		if (req->method == SIP_RESPONSE) {
8365
			const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
9166
			const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
8366
			int respid;
9167
			int respid;
8367
			if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
9168
			if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
8368
				args.respid = respid;
9169
				args.respid = respid;
8369
			}
9170
			}
8370
		}
9171
		}
8371

    
   
9172

   
8372
		/* Iterate a list of dialogs already matched by Call-id */
9173
		/* Iterate a list of dialogs already matched by Call-id */
8373
		while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
9174
		while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {

    
   
9175
			sip_pvt_lock(sip_pvt_ptr);
8374
			found = match_req_to_dialog(sip_pvt_ptr, &args);
9176
			found = match_req_to_dialog(sip_pvt_ptr, &args);

    
   
9177
			sip_pvt_unlock(sip_pvt_ptr);
8375

    
   
9178

   
8376
			switch (found) {
9179
			switch (found) {
8377
			case SIP_REQ_MATCH:
9180
			case SIP_REQ_MATCH:
8378
				ao2_iterator_destroy(iterator);
9181
				ao2_iterator_destroy(iterator);
8379
				dialog_unref(fork_pvt, "unref fork_pvt");
9182
				dialog_unref(fork_pvt, "unref fork_pvt");
[+20] [20] 13 lines
[+20] static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
8393
				fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
9196
				fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
8394
				/* fall through */
9197
				/* fall through */
8395
			case SIP_REQ_NOT_MATCH:
9198
			case SIP_REQ_NOT_MATCH:
8396
			default:
9199
			default:
8397
				dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
9200
				dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");

    
   
9201
				break;
8398
			}
9202
			}
8399
		}
9203
		}
8400
		if (iterator) {
9204
		if (iterator) {
8401
			ao2_iterator_destroy(iterator);
9205
			ao2_iterator_destroy(iterator);
8402
		}
9206
		}
[+20] [20] 15 lines
[+20] static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
8418
	} /* end of pedantic mode Request/Reponse to Dialog matching */
9222
	} /* end of pedantic mode Request/Reponse to Dialog matching */
8419

    
   
9223

   
8420
	/* See if the method is capable of creating a dialog */
9224
	/* See if the method is capable of creating a dialog */
8421
	if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
9225
	if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
8422
		struct sip_pvt *p = NULL;
9226
		struct sip_pvt *p = NULL;

    
   
9227
		struct ast_callid *logger_callid = NULL;

    
   
9228

   

    
   
9229
		if (intended_method == SIP_INVITE) {

    
   
9230
			logger_callid = ast_create_callid();

    
   
9231
		}
8423

    
   
9232

   
8424
		if (intended_method == SIP_REFER) {

   
8425
			/* We do support REFER, but not outside of a dialog yet */

   
8426
			transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");

   
8427
	

   
8428
		/* Ok, time to create a new SIP dialog object, a pvt */
9233
		/* Ok, time to create a new SIP dialog object, a pvt */
8429
		} else if (!(p = sip_alloc(callid, addr, 1, intended_method, req)))  {
9234
		if (!(p = sip_alloc(callid, addr, 1, intended_method, req, logger_callid)))  {
8430
			/* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
9235
			/* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
8431
				getting a dialog from sip_alloc.
9236
				getting a dialog from sip_alloc.
8432

    
   
9237

   
8433
				Without a dialog we can't retransmit and handle ACKs and all that, but at least
9238
				Without a dialog we can't retransmit and handle ACKs and all that, but at least
8434
				send an error message.
9239
				send an error message.
8435

    
   
9240

   
8436
				Sorry, we apologize for the inconvienience
9241
				Sorry, we apologize for the inconvienience
8437
			*/
9242
			*/
8438
			transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
9243
			transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
8439
			ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
9244
			ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
8440
		}
9245
		}

    
   
9246
		/* If we created an ast_callid for an invite, we need to free it now. */

    
   
9247
		if (logger_callid) {

    
   
9248
			ast_callid_unref(logger_callid);

    
   
9249
		}
8441
		return p; /* can be NULL */
9250
		return p; /* can be NULL */
8442
	} else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
9251
	} else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
8443
		/* A method we do not support, let's take it on the volley */
9252
		/* A method we do not support, let's take it on the volley */
8444
		transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
9253
		transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
8445
		ast_debug(2, "Got a request with unsupported SIP method.\n");
9254
		ast_debug(2, "Got a request with unsupported SIP method.\n");
[+20] [20] 52 lines
[+20] [+] static int sip_register(const char *value, int lineno)
8498
{
9307
{
8499
	struct sip_subscription_mwi *mwi;
9308
	struct sip_subscription_mwi *mwi;
8500
	int portnum = 0;
9309
	int portnum = 0;
8501
	enum sip_transport transport = SIP_TRANSPORT_UDP;
9310
	enum sip_transport transport = SIP_TRANSPORT_UDP;
8502
	char buf[256] = "";
9311
	char buf[256] = "";
8503
	char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL, *at = NULL;
9312
	char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
8504

    
   
9313

   
8505
	if (!value) {
9314
	if (!value) {
8506
		return -1;
9315
		return -1;
8507
	}
9316
	}
8508

    
   
9317

   
8509
	ast_copy_string(buf, value, sizeof(buf));
9318
	ast_copy_string(buf, value, sizeof(buf));
8510

    
   
9319

   
8511
	if (!(at = strstr(buf, "@"))) {
9320
	username = buf;
8512
		return -1;

   
8513
	}

   
8514

    
   
9321

   
8515
	if ((hostname = strrchr(buf, '@'))) {
9322
	if ((hostname = strrchr(buf, '@'))) {
8516
		*hostname++ = '\0';
9323
		*hostname++ = '\0';
8517
		username = buf;
9324
	} else {

    
   
9325
		return -1;
8518
	}
9326
	}
8519

    
   
9327

   
8520
	if ((secret = strchr(username, ':'))) {
9328
	if ((secret = strchr(username, ':'))) {
8521
		*secret++ = '\0';
9329
		*secret++ = '\0';
8522
		if ((authuser = strchr(secret, ':'))) {
9330
		if ((authuser = strchr(secret, ':'))) {
[+20] [20] 399 lines
[+20] [+] static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
8922
		ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);	/* Clear both flags */
9730
		ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);	/* Clear both flags */
8923
		return;
9731
		return;
8924
	}
9732
	}
8925
	/* No address for RTP, we're on hold */
9733
	/* No address for RTP, we're on hold */
8926

    
   
9734

   

    
   
9735
	/* Ensure hold flags are cleared so that overlapping flags do not conflict */

    
   
9736
	ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);

    
   
9737

   
8927
	if (sendonly == 1)	/* One directional hold (sendonly/recvonly) */
9738
	if (sendonly == 1)	/* One directional hold (sendonly/recvonly) */
8928
		ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
9739
		ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
8929
	else if (sendonly == 2)	/* Inactive stream */
9740
	else if (sendonly == 2)	/* Inactive stream */
8930
		ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
9741
		ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
8931
	else
9742
	else
[+20] [20] 68 lines
[+20] [+] static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
9000
static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
9811
static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
9001
{
9812
{
9002
	return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
9813
	return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
9003
}
9814
}
9004

    
   
9815

   
9005
/*! \brief Process SIP SDP offer, select formats and activate RTP channels
9816
/*! \brief Check the media stream list to see if the given type already exists */

    
   
9817
static int has_media_stream(struct sip_pvt *p, enum media_type m)

    
   
9818
{

    
   
9819
	struct offered_media *offer = NULL;

    
   
9820
	AST_LIST_TRAVERSE(&p->offered_media, offer, next) {

    
   
9821
		if (m == offer->type) {

    
   
9822
			return 1;

    
   
9823
		}

    
   
9824
	}

    
   
9825
	return 0;

    
   
9826
}

    
   
9827

   

    
   
9828
/*! \brief Process SIP SDP offer, select formats and activate media channels
9006
	If offer is rejected, we will not change any properties of the call
9829
	If offer is rejected, we will not change any properties of the call
9007
 	Return 0 on success, a negative value on errors.
9830
 	Return 0 on success, a negative value on errors.
9008
	Must be called after find_sdp().
9831
	Must be called after find_sdp().
9009
*/
9832
*/
9010
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
9833
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
[+20] [20] 9 lines
[+20] static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr) [+] static int has_media_stream(struct sip_pvt *p, enum media_type m)
9020
	char type = '\0';
9843
	char type = '\0';
9021
	const char *value = NULL;
9844
	const char *value = NULL;
9022
	const char *m = NULL;           /* SDP media offer */
9845
	const char *m = NULL;           /* SDP media offer */
9023
	const char *nextm = NULL;
9846
	const char *nextm = NULL;
9024
	int len = -1;
9847
	int len = -1;

    
   
9848
	struct offered_media *offer;
9025

    
   
9849

   
9026
	/* Host information */
9850
	/* Host information */
9027
	struct ast_sockaddr sessionsa;
9851
	struct ast_sockaddr sessionsa;
9028
	struct ast_sockaddr audiosa;
9852
	struct ast_sockaddr audiosa;
9029
	struct ast_sockaddr videosa;
9853
	struct ast_sockaddr videosa;
9030
	struct ast_sockaddr textsa;
9854
	struct ast_sockaddr textsa;
9031
	struct ast_sockaddr imagesa;
9855
	struct ast_sockaddr imagesa;
9032
	struct ast_sockaddr *sa = NULL;	/*!< RTP Audio host IP */
9856
	struct ast_sockaddr *sa = NULL;		/*!< RTP audio destination IP address */
9033
	struct ast_sockaddr *vsa = NULL;	/*!< RTP video host IP */
9857
	struct ast_sockaddr *vsa = NULL;	/*!< RTP video destination IP address */
9034
	struct ast_sockaddr *tsa = NULL;	/*!< RTP text host IP */
9858
	struct ast_sockaddr *tsa = NULL;	/*!< RTP text destination IP address */
9035
	struct ast_sockaddr *isa = NULL;     /*!< UDPTL host ip */
9859
	struct ast_sockaddr *isa = NULL;	/*!< UDPTL image destination IP address */
9036
	int portno = -1;		/*!< RTP Audio port number */
9860
 	int portno = -1;			/*!< RTP audio destination port number */
9037
	int vportno = -1;		/*!< RTP Video port number */
9861
 	int vportno = -1;			/*!< RTP video destination port number */
9038
	int tportno = -1;		/*!< RTP Text port number */
9862
	int tportno = -1;			/*!< RTP text destination port number */
9039
	int udptlportno = -1;		/*!< UDPTL Image port number */
9863
	int udptlportno = -1;			/*!< UDPTL image destination port number */
9040

    
   
9864

   
9041
	/* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */	
9865
	/* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
9042
	struct ast_format_cap *peercapability = ast_format_cap_alloc_nolock();
9866
	struct ast_format_cap *peercapability = ast_format_cap_alloc_nolock();
9043
	struct ast_format_cap *vpeercapability = ast_format_cap_alloc_nolock();
9867
	struct ast_format_cap *vpeercapability = ast_format_cap_alloc_nolock();
9044
	struct ast_format_cap *tpeercapability = ast_format_cap_alloc_nolock();
9868
	struct ast_format_cap *tpeercapability = ast_format_cap_alloc_nolock();
9045

    
   
9869

   
9046
	int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
9870
	int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
9047

    
   
9871

   
9048
	struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
9872
	struct ast_rtp_codecs newaudiortp = { 0, }, newvideortp = { 0, }, newtextrtp = { 0, };
9049
	struct ast_format_cap *newjointcapability = ast_format_cap_alloc_nolock(); /* Negotiated capability */
9873
	struct ast_format_cap *newjointcapability = ast_format_cap_alloc_nolock(); /* Negotiated capability */
9050
	struct ast_format_cap *newpeercapability = ast_format_cap_alloc_nolock();
9874
	struct ast_format_cap *newpeercapability = ast_format_cap_alloc_nolock();
9051
	int newnoncodeccapability;
9875
	int newnoncodeccapability;
9052

    
   
9876

   
9053
	const char *codecs;
9877
	const char *codecs;
9054
	int codec;
9878
	int codec;
9055

    
   
9879

   
9056
	/* SRTP */
9880
	/* SRTP */
9057
	int secure_audio = FALSE;
9881
	int secure_audio = FALSE;
9058
	int secure_video = FALSE;
9882
	int secure_video = FALSE;
9059

    
   
9883

   
9060
	/* Others */
9884
	/* Others */
9061
	int sendonly = -1;
9885
	int sendonly = -1;
9062
	int vsendonly = -1;

   
9063
	int numberofports;
9886
	int numberofports;
9064
	int numberofmediastreams = 0;

   
9065
	int last_rtpmap_codec = 0;
9887
	int last_rtpmap_codec = 0;
9066
	int red_data_pt[10];		/* For T.140 red */
9888
	int red_data_pt[10];		/* For T.140 RED */
9067
	int red_num_gen = 0;		/* For T.140 red */
9889
	int red_num_gen = 0;		/* For T.140 RED */
9068
	char red_fmtp[100] = "empty";	/* For T.140 red */
9890
	char red_fmtp[100] = "empty";	/* For T.140 RED */
9069
	int debug = sip_debug_test_pvt(p);
9891
	int debug = sip_debug_test_pvt(p);
9070

    
   
9892

   
9071
	/* START UNKNOWN */
9893
	/* START UNKNOWN */
9072
	char buf[SIPBUFSIZE];
9894
	char buf[SIPBUFSIZE];
9073
	struct ast_format tmp_fmt;
9895
	struct ast_format tmp_fmt;
[+20] [20] 8 lines
[+20] static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr) [+] static int has_media_stream(struct sip_pvt *p, enum media_type m)
9082
	if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
9904
	if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
9083
		res = -1;
9905
		res = -1;
9084
		goto process_sdp_cleanup;
9906
		goto process_sdp_cleanup;
9085
	}
9907
	}
9086

    
   
9908

   
9087
	/* Make sure that the codec structures are all cleared out */
9909
	if (ast_rtp_codecs_payloads_initialize(&newaudiortp) || ast_rtp_codecs_payloads_initialize(&newvideortp) ||
9088
	ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
9910
	    ast_rtp_codecs_payloads_initialize(&newtextrtp)) {
9089
	ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
9911
		res = -1;
9090
	ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
9912
		goto process_sdp_cleanup;

    
   
9913
	}
9091

    
   
9914

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

    
   
9917

   
9095
	memset(p->offered_media, 0, sizeof(p->offered_media));
9918
	offered_media_list_destroy(p);
9096

    
   

   
9097
	if (p->vrtp) {

   
9098
		ast_rtp_codecs_payloads_clear(&newvideortp, NULL);

   
9099
	}

   
9100

    
   

   
9101
	if (p->trtp) {

   
9102
		ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);

   
9103
	}

   
9104

    
   
9919

   
9105
	/* Scan for the first media stream (m=) line to limit scanning of globals */
9920
	/* Scan for the first media stream (m=) line to limit scanning of globals */
9106
	nextm = get_sdp_iterate(&next, req, "m");
9921
	nextm = get_sdp_iterate(&next, req, "m");
9107
	if (ast_strlen_zero(nextm)) {
9922
	if (ast_strlen_zero(nextm)) {
9108
		ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
9923
		ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
[+20] [20] 11 lines
[+20] static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr) [+] static int has_media_stream(struct sip_pvt *p, enum media_type m)
9120
			 */
9935
			 */
9121
			if (!process_sdp_o(value, p)) {
9936
			if (!process_sdp_o(value, p)) {
9122
				res = (p->session_modify == FALSE) ? 0 : -1;
9937
				res = (p->session_modify == FALSE) ? 0 : -1;
9123
				goto process_sdp_cleanup;
9938
				goto process_sdp_cleanup;
9124
			}
9939
			}

    
   
9940
			processed = TRUE;
9125
			break;
9941
			break;
9126
		case 'c':
9942
		case 'c':
9127
			if (process_sdp_c(value, &sessionsa)) {
9943
			if (process_sdp_c(value, &sessionsa)) {
9128
				processed = TRUE;
9944
				processed = TRUE;
9129
				sa = &sessionsa;
9945
				sa = &sessionsa;
9130
				vsa = sa;
9946
				vsa = sa;
9131
				tsa = sa;
9947
				tsa = sa;
9132
				isa = sa;
9948
				isa = sa;
9133
			}
9949
			}
9134
			break;
9950
			break;
9135
		case 'a':
9951
		case 'a':
9136
			if (process_sdp_a_sendonly(value, &sendonly)) {
9952
			if (process_sdp_a_sendonly(value, &sendonly)) {
9137
				processed = TRUE;
9953
				processed = TRUE;
9138
				vsendonly = sendonly;

   
9139
			}
9954
			}
9140
			else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
9955
			else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
9141
				processed = TRUE;
9956
				processed = TRUE;
9142
			else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
9957
			else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
9143
				processed = TRUE;
9958
				processed = TRUE;
9144
			else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
9959
			else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
9145
				processed = TRUE;
9960
				processed = TRUE;
9146
			else if (process_sdp_a_image(value, p))
9961
			else if (process_sdp_a_image(value, p))
9147
				processed = TRUE;
9962
				processed = TRUE;

    
   
9963

   

    
   
9964
			if (process_sdp_a_ice(value, p, p->rtp)) {

    
   
9965
				processed = TRUE;

    
   
9966
			}

    
   
9967
			if (process_sdp_a_ice(value, p, p->vrtp)) {

    
   
9968
				processed = TRUE;

    
   
9969
			}

    
   
9970
			if (process_sdp_a_ice(value, p, p->trtp)) {

    
   
9971
				processed = TRUE;

    
   
9972
			}

    
   
9973

   

    
   
9974
			if (process_sdp_a_dtls(value, p, p->rtp)) {

    
   
9975
				processed = TRUE;

    
   
9976
			}

    
   
9977
			if (process_sdp_a_dtls(value, p, p->vrtp)) {

    
   
9978
				processed = TRUE;

    
   
9979
			}

    
   
9980
			if (process_sdp_a_dtls(value, p, p->trtp)) {

    
   
9981
				processed = TRUE;

    
   
9982
			}

    
   
9983

   
9148
			break;
9984
			break;
9149
		}
9985
		}
9150

    
   
9986

   
9151
		ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
9987
		ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
9152
	}
9988
	}
9153

    
   
9989

   
9154
	/* default: novideo and notext set */
9990
	/* default: novideo and notext set */
9155
	p->novideo = TRUE;
9991
	p->novideo = TRUE;
9156
	p->notext = TRUE;
9992
	p->notext = TRUE;
9157

    
   
9993

   
9158
	/* Scan media stream (m=) specific parameters loop */
9994
	/* Scan media stream (m=) specific parameters loop */
9159
	while (!ast_strlen_zero(nextm)) {
9995
	while (!ast_strlen_zero(nextm)) {
9160
		int audio = FALSE;
9996
		int audio = FALSE;
9161
		int video = FALSE;
9997
		int video = FALSE;
9162
		int image = FALSE;
9998
		int image = FALSE;
9163
		int text = FALSE;
9999
		int text = FALSE;
9164
		char protocol[5] = {0,};
10000
		int processed_crypto = FALSE;

    
   
10001
		char protocol[18] = {0,};
9165
		int x;
10002
		int x;

    
   
10003
		struct ast_rtp_engine_dtls *dtls;
9166

    
   
10004

   
9167
		numberofports = 1;
10005
		numberofports = 0;
9168
		len = -1;
10006
		len = -1;
9169
		start = next;
10007
		start = next;
9170
		m = nextm;
10008
		m = nextm;
9171
		iterator = next;
10009
		iterator = next;
9172
		nextm = get_sdp_iterate(&next, req, "m");
10010
		nextm = get_sdp_iterate(&next, req, "m");
9173

    
   
10011

   
9174
		/* Search for audio media definition */
10012
		if (!(offer = ast_calloc(1, sizeof(*offer)))) {
9175
		if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10013
			ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer list\n");
9176
		    (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
10014
			res = -1;

    
   
10015
			goto process_sdp_cleanup;

    
   
10016
		}

    
   
10017
		AST_LIST_INSERT_TAIL(&p->offered_media, offer, next);

    
   
10018
		offer->type = SDP_UNKNOWN;

    
   
10019

   

    
   
10020
		/* Check for 'audio' media offer */

    
   
10021
		if (strncmp(m, "audio ", 6) == 0) {

    
   
10022
			if ((sscanf(m, "audio %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||

    
   
10023
			    (sscanf(m, "audio %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {

    
   
10024
				codecs = m + len;

    
   
10025
				/* produce zero-port m-line since it may be needed later

    
   
10026
				 * length is "m=audio 0 " + protocol + " " + codecs + "\0" */

    
   
10027
				if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 1))) {

    
   
10028
					ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");

    
   
10029
					res = -1;

    
   
10030
					goto process_sdp_cleanup;

    
   
10031
				}

    
   
10032
				/* guaranteed to be exactly the right length */

    
   
10033
				sprintf(offer->decline_m_line, "m=audio 0 %s %s", protocol, codecs);

    
   
10034

   
9177
			if (x == 0) {
10035
				if (x == 0) {
9178
				ast_log(LOG_WARNING, "ignoring 'audio' media offer because port number is zero");
10036
					ast_debug(1, "Ignoring audio media offer because port number is zero\n");
9179
				continue;
10037
					continue;
9180
			}
10038
				}
9181
			if (!strcmp(protocol, "SAVP")) {
10039

   
9182
				secure_audio = 1;
10040
				if (has_media_stream(p, SDP_AUDIO)) {
9183
			} else if (strcmp(protocol, "AVP")) {
10041
					ast_log(LOG_WARNING, "Declining non-primary audio stream: %s\n", m);
9184
				ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);

   
9185
				continue;
10042
					continue;
9186
			}
10043
				}
9187
			if (p->offered_media[SDP_AUDIO].order_offered) {
10044

   
9188
				ast_log(LOG_WARNING, "Multiple audio streams are not supported\n");
10045
				/* Check number of ports offered for stream */
9189
				res = -3;
10046
				if (numberofports > 1) {
9190
				goto process_sdp_cleanup;
10047
					ast_log(LOG_WARNING, "%d ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);

    
   
10048
				}

    
   
10049

   

    
   
10050
				if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {

    
   
10051
					ast_log(LOG_WARNING, "Received SAVPF profle in audio offer but AVPF is not enabled: %s\n", m);

    
   
10052
					continue;

    
   
10053
				} else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {

    
   
10054
					ast_log(LOG_WARNING, "Received SAVP profile in audio offer but AVPF is enabled: %s\n", m);

    
   
10055
					continue;

    
   
10056
				} else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {

    
   
10057
					secure_audio = 1;

    
   
10058

   

    
   
10059
					if (p->srtp) {

    
   
10060
						ast_set_flag(p->srtp, SRTP_CRYPTO_OFFER_OK);
9191
			}
10061
					}

    
   
10062
				} else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {

    
   
10063
					secure_audio = 1;

    
   
10064
				} else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {

    
   
10065
					ast_log(LOG_WARNING, "Received AVPF profile in audio offer but AVPF is not enabled: %s\n", m);

    
   
10066
					continue;

    
   
10067
				} else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {

    
   
10068
					ast_log(LOG_WARNING, "Received AVP profile in audio offer but AVPF is enabled: %s\n", m);

    
   
10069
					continue;

    
   
10070
				} else if ((!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) &&

    
   
10071
					   (!(dtls = ast_rtp_instance_get_dtls(p->rtp)) || !dtls->active(p->rtp))) {

    
   
10072
					ast_log(LOG_WARNING, "Received UDP/TLS in audio offer but DTLS is not enabled: %s\n", m);

    
   
10073
					continue;

    
   
10074
				} else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {

    
   
10075
					ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);

    
   
10076
					continue;

    
   
10077
				}

    
   
10078

   
9192
			audio = TRUE;
10079
				audio = TRUE;
9193
			p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
10080
				offer->type = SDP_AUDIO;
9194
			portno = x;
10081
				portno = x;
9195

    
   
10082

   
9196
			/* Scan through the RTP payload types specified in a "m=" line: */
10083
				/* Scan through the RTP payload types specified in a "m=" line: */
9197
			codecs = m + len;

   
9198
			ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));

   
9199
			for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10084
				for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
9200
				if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10085
					if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
9201
					ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
10086
						ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
9202
					res = -1;
10087
						res = -1;
9203
					goto process_sdp_cleanup;
10088
						goto process_sdp_cleanup;
9204
				}
10089
					}
9205
				if (debug)
10090
					if (debug) {
9206
					ast_verbose("Found RTP audio format %d\n", codec);
10091
						ast_verbose("Found RTP audio format %d\n", codec);

    
   
10092
					}
9207

    
   
10093

   
9208
				ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
10094
					ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
9209
			}
10095
				}
9210
		/* Search for video media definition */
10096
			} else {
9211
		} else if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10097
				ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
9212
			   (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
10098
				res = -1;

    
   
10099
				goto process_sdp_cleanup;

    
   
10100
			}

    
   
10101
		}

    
   
10102
		/* Check for 'video' media offer */

    
   
10103
		else if (strncmp(m, "video ", 6) == 0) {

    
   
10104
			if ((sscanf(m, "video %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||

    
   
10105
			    (sscanf(m, "video %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {

    
   
10106
				codecs = m + len;

    
   
10107
				/* produce zero-port m-line since it may be needed later

    
   
10108
				 * length is "m=video 0 " + protocol + " " + codecs + "\0" */

    
   
10109
				if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 1))) {

    
   
10110
					ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");

    
   
10111
					res = -1;

    
   
10112
					goto process_sdp_cleanup;

    
   
10113
				}

    
   
10114
				/* guaranteed to be exactly the right length */

    
   
10115
				sprintf(offer->decline_m_line, "m=video 0 %s %s", protocol, codecs);

    
   
10116

   
9213
			if (x == 0) {
10117
				if (x == 0) {
9214
				ast_log(LOG_WARNING, "ignoring 'video' media offer because port number is zero");
10118
					ast_debug(1, "Ignoring video stream offer because port number is zero\n");
9215
				continue;
10119
					continue;
9216
			}
10120
				}