res_http_websocket: Close websocket correctly and use careful fwrite
[asterisk/asterisk.git] / res / res_pjsip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Mark Michelson <mmichelson@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 #include "asterisk.h"
20
21 #include <pjsip.h>
22 /* Needed for SUBSCRIBE, NOTIFY, and PUBLISH method definitions */
23 #include <pjsip_simple.h>
24 #include <pjlib.h>
25
26 #include "asterisk/res_pjsip.h"
27 #include "res_pjsip/include/res_pjsip_private.h"
28 #include "asterisk/linkedlists.h"
29 #include "asterisk/logger.h"
30 #include "asterisk/lock.h"
31 #include "asterisk/utils.h"
32 #include "asterisk/astobj2.h"
33 #include "asterisk/module.h"
34 #include "asterisk/threadpool.h"
35 #include "asterisk/taskprocessor.h"
36 #include "asterisk/uuid.h"
37 #include "asterisk/sorcery.h"
38
39 /*** MODULEINFO
40         <depend>pjproject</depend>
41         <depend>res_sorcery_config</depend>
42         <support_level>core</support_level>
43  ***/
44
45 /*** DOCUMENTATION
46         <configInfo name="res_pjsip" language="en_US">
47                 <synopsis>SIP Resource using PJProject</synopsis>
48                 <configFile name="pjsip.conf">
49                         <configObject name="endpoint">
50                                 <synopsis>Endpoint</synopsis>
51                                 <description><para>
52                                         The <emphasis>Endpoint</emphasis> is the primary configuration object.
53                                         It contains the core SIP related options only, endpoints are <emphasis>NOT</emphasis>
54                                         dialable entries of their own. Communication with another SIP device is
55                                         accomplished via Addresses of Record (AoRs) which have one or more
56                                         contacts assicated with them. Endpoints <emphasis>NOT</emphasis> configured to
57                                         use a <literal>transport</literal> will default to first transport found
58                                         in <filename>pjsip.conf</filename> that matches its type.
59                                         </para>
60                                         <para>Example: An Endpoint has been configured with no transport.
61                                         When it comes time to call an AoR, PJSIP will find the
62                                         first transport that matches the type. A SIP URI of <literal>sip:5000@[11::33]</literal>
63                                         will use the first IPv6 transport and try to send the request.
64                                         </para>
65                                         <para>If the anonymous endpoint identifier is in use an endpoint with the name
66                                         "anonymous@domain" will be searched for as a last resort. If this is not found
67                                         it will fall back to searching for "anonymous". If neither endpoints are found
68                                         the anonymous endpoint identifier will not return an endpoint and anonymous
69                                         calling will not be possible.
70                                         </para>
71                                 </description>
72                                 <configOption name="100rel" default="yes">
73                                         <synopsis>Allow support for RFC3262 provisional ACK tags</synopsis>
74                                         <description>
75                                                 <enumlist>
76                                                         <enum name="no" />
77                                                         <enum name="required" />
78                                                         <enum name="yes" />
79                                                 </enumlist>
80                                         </description>
81                                 </configOption>
82                                 <configOption name="aggregate_mwi" default="yes">
83                                         <synopsis></synopsis>
84                                         <description><para>When enabled, <replaceable>aggregate_mwi</replaceable> condenses message
85                                         waiting notifications from multiple mailboxes into a single NOTIFY. If it is disabled,
86                                         individual NOTIFYs are sent for each mailbox.</para></description>
87                                 </configOption>
88                                 <configOption name="allow">
89                                         <synopsis>Media Codec(s) to allow</synopsis>
90                                 </configOption>
91                                 <configOption name="aors">
92                                         <synopsis>AoR(s) to be used with the endpoint</synopsis>
93                                         <description><para>
94                                                 List of comma separated AoRs that the endpoint should be associated with.
95                                         </para></description>
96                                 </configOption>
97                                 <configOption name="auth">
98                                         <synopsis>Authentication Object(s) associated with the endpoint</synopsis>
99                                         <description><para>
100                                                 This is a comma-delimited list of <replaceable>auth</replaceable> sections defined
101                                                 in <filename>pjsip.conf</filename> to be used to verify inbound connection attempts.
102                                                 </para><para>
103                                                 Endpoints without an <literal>authentication</literal> object
104                                                 configured will allow connections without vertification.
105                                         </para></description>
106                                 </configOption>
107                                 <configOption name="callerid">
108                                         <synopsis>CallerID information for the endpoint</synopsis>
109                                         <description><para>
110                                                 Must be in the format <literal>Name &lt;Number&gt;</literal>,
111                                                 or only <literal>&lt;Number&gt;</literal>.
112                                         </para></description>
113                                 </configOption>
114                                 <configOption name="callerid_privacy">
115                                         <synopsis>Default privacy level</synopsis>
116                                         <description>
117                                                 <enumlist>
118                                                         <enum name="allowed_not_screened" />
119                                                         <enum name="allowed_passed_screened" />
120                                                         <enum name="allowed_failed_screened" />
121                                                         <enum name="allowed" />
122                                                         <enum name="prohib_not_screened" />
123                                                         <enum name="prohib_passed_screened" />
124                                                         <enum name="prohib_failed_screened" />
125                                                         <enum name="prohib" />
126                                                         <enum name="unavailable" />
127                                                 </enumlist>
128                                         </description>
129                                 </configOption>
130                                 <configOption name="callerid_tag">
131                                         <synopsis>Internal id_tag for the endpoint</synopsis>
132                                 </configOption>
133                                 <configOption name="context">
134                                         <synopsis>Dialplan context for inbound sessions</synopsis>
135                                 </configOption>
136                                 <configOption name="direct_media_glare_mitigation" default="none">
137                                         <synopsis>Mitigation of direct media (re)INVITE glare</synopsis>
138                                         <description>
139                                                 <para>
140                                                 This setting attempts to avoid creating INVITE glare scenarios
141                                                 by disabling direct media reINVITEs in one direction thereby allowing
142                                                 designated servers (according to this option) to initiate direct
143                                                 media reINVITEs without contention and significantly reducing call
144                                                 setup time.
145                                                 </para>
146                                                 <para>
147                                                 A more detailed description of how this option functions can be found on
148                                                 the Asterisk wiki https://wiki.asterisk.org/wiki/display/AST/SIP+Direct+Media+Reinvite+Glare+Avoidance
149                                                 </para>
150                                                 <enumlist>
151                                                         <enum name="none" />
152                                                         <enum name="outgoing" />
153                                                         <enum name="incoming" />
154                                                 </enumlist>
155                                         </description>
156                                 </configOption>
157                                 <configOption name="direct_media_method" default="invite">
158                                         <synopsis>Direct Media method type</synopsis>
159                                         <description>
160                                                 <para>Method for setting up Direct Media between endpoints.</para>
161                                                 <enumlist>
162                                                         <enum name="invite" />
163                                                         <enum name="reinvite">
164                                                                 <para>Alias for the <literal>invite</literal> value.</para>
165                                                         </enum>
166                                                         <enum name="update" />
167                                                 </enumlist>
168                                         </description>
169                                 </configOption>
170                                 <configOption name="connected_line_method" default="invite">
171                                         <synopsis>Connected line method type</synopsis>
172                                         <description>
173                                                 <para>Method used when updating connected line information.</para>
174                                                 <enumlist>
175                                                         <enum name="invite" />
176                                                         <enum name="reinvite">
177                                                                 <para>Alias for the <literal>invite</literal> value.</para>
178                                                         </enum>
179                                                         <enum name="update" />
180                                                 </enumlist>
181                                         </description>
182                                 </configOption>
183                                 <configOption name="direct_media" default="yes">
184                                         <synopsis>Determines whether media may flow directly between endpoints.</synopsis>
185                                 </configOption>
186                                 <configOption name="disable_direct_media_on_nat" default="no">
187                                         <synopsis>Disable direct media session refreshes when NAT obstructs the media session</synopsis>
188                                 </configOption>
189                                 <configOption name="disallow">
190                                         <synopsis>Media Codec(s) to disallow</synopsis>
191                                 </configOption>
192                                 <configOption name="dtmf_mode" default="rfc4733">
193                                         <synopsis>DTMF mode</synopsis>
194                                         <description>
195                                                 <para>This setting allows to choose the DTMF mode for endpoint communication.</para>
196                                                 <enumlist>
197                                                         <enum name="rfc4733">
198                                                                 <para>DTMF is sent out of band of the main audio stream.This
199                                                                 supercedes the older <emphasis>RFC-2833</emphasis> used within
200                                                                 the older <literal>chan_sip</literal>.</para>
201                                                         </enum>
202                                                         <enum name="inband">
203                                                                 <para>DTMF is sent as part of audio stream.</para>
204                                                         </enum>
205                                                         <enum name="info">
206                                                                 <para>DTMF is sent as SIP INFO packets.</para>
207                                                         </enum>
208                                                 </enumlist>
209                                         </description>
210                                 </configOption>
211                                 <configOption name="media_address">
212                                         <synopsis>IP address used in SDP for media handling</synopsis>
213                                         <description><para>
214                                                 At the time of SDP creation, the IP address defined here will be used as
215                                                 the media address for individual streams in the SDP.
216                                         </para>
217                                         <note><para>
218                                                 Be aware that the <literal>external_media_address</literal> option, set in Transport
219                                                 configuration, can also affect the final media address used in the SDP.
220                                         </para></note>
221                                         </description>
222                                 </configOption>
223                                 <configOption name="force_rport" default="yes">
224                                         <synopsis>Force use of return port</synopsis>
225                                 </configOption>
226                                 <configOption name="ice_support" default="no">
227                                         <synopsis>Enable the ICE mechanism to help traverse NAT</synopsis>
228                                 </configOption>
229                                 <configOption name="identify_by" default="username,location">
230                                         <synopsis>Way(s) for Endpoint to be identified</synopsis>
231                                         <description><para>
232                                                 An endpoint can be identified in multiple ways. Currently, the only supported
233                                                 option is <literal>username</literal>, which matches the endpoint based on the
234                                                 username in the From header.
235                                                 </para>
236                                                 <note><para>Endpoints can also be identified by IP address; however, that method
237                                                 of identification is not handled by this configuration option. See the documentation
238                                                 for the <literal>identify</literal> configuration section for more details on that
239                                                 method of endpoint identification. If this option is set to <literal>username</literal>
240                                                 and an <literal>identify</literal> configuration section exists for the endpoint, then
241                                                 the endpoint can be identified in multiple ways.</para></note>
242                                                 <enumlist>
243                                                         <enum name="username" />
244                                                 </enumlist>
245                                         </description>
246                                 </configOption>
247                                 <configOption name="redirect_method">
248                                         <synopsis>How redirects received from an endpoint are handled</synopsis>
249                                         <description><para>
250                                                 When a redirect is received from an endpoint there are multiple ways it can be handled.
251                                                 If this option is set to <literal>user</literal> the user portion of the redirect target
252                                                 is treated as an extension within the dialplan and dialed using a Local channel. If this option
253                                                 is set to <literal>uri_core</literal> the target URI is returned to the dialing application
254                                                 which dials it using the PJSIP channel driver and endpoint originally used. If this option is
255                                                 set to <literal>uri_pjsip</literal> the redirect occurs within chan_pjsip itself and is not exposed
256                                                 to the core at all. The <literal>uri_pjsip</literal> option has the benefit of being more efficient
257                                                 and also supporting multiple potential redirect targets. The con is that since redirection occurs
258                                                 within chan_pjsip redirecting information is not forwarded and redirection can not be
259                                                 prevented.
260                                                 </para>
261                                                 <enumlist>
262                                                         <enum name="user" />
263                                                         <enum name="uri_core" />
264                                                         <enum name="uri_pjsip" />
265                                                 </enumlist>
266                                         </description>
267                                 </configOption>
268                                 <configOption name="mailboxes">
269                                         <synopsis>NOTIFY the endpoint when state changes for any of the specified mailboxes</synopsis>
270                                         <description><para>
271                                                 Asterisk will send unsolicited MWI NOTIFY messages to the endpoint when state
272                                                 changes happen for any of the specified mailboxes. More than one mailbox can be
273                                                 specified with a comma-delimited string. app_voicemail mailboxes must be specified
274                                                 as mailbox@context; for example: mailboxes=6001@default. For mailboxes provided by
275                                                 external sources, such as through the res_external_mwi module, you must specify
276                                                 strings supported by the external system.
277                                         </para><para>
278                                                 For endpoints that SUBSCRIBE for MWI, use the <literal>mailboxes</literal> option in your AOR
279                                                 configuration.
280                                         </para></description>
281                                 </configOption>
282                                 <configOption name="moh_suggest" default="default">
283                                         <synopsis>Default Music On Hold class</synopsis>
284                                 </configOption>
285                                 <configOption name="outbound_auth">
286                                         <synopsis>Authentication object used for outbound requests</synopsis>
287                                 </configOption>
288                                 <configOption name="outbound_proxy">
289                                         <synopsis>Proxy through which to send requests, a full SIP URI must be provided</synopsis>
290                                 </configOption>
291                                 <configOption name="rewrite_contact">
292                                         <synopsis>Allow Contact header to be rewritten with the source IP address-port</synopsis>
293                                         <description><para>
294                                                 On inbound SIP messages from this endpoint, the Contact header will be changed to have the
295                                                 source IP address and port. This option does not affect outbound messages send to this
296                                                 endpoint.
297                                         </para></description>
298                                 </configOption>
299                                 <configOption name="rtp_ipv6" default="no">
300                                         <synopsis>Allow use of IPv6 for RTP traffic</synopsis>
301                                 </configOption>
302                                 <configOption name="rtp_symmetric" default="no">
303                                         <synopsis>Enforce that RTP must be symmetric</synopsis>
304                                 </configOption>
305                                 <configOption name="send_diversion" default="yes">
306                                         <synopsis>Send the Diversion header, conveying the diversion
307                                         information to the called user agent</synopsis>
308                                 </configOption>
309                                 <configOption name="send_pai" default="no">
310                                         <synopsis>Send the P-Asserted-Identity header</synopsis>
311                                 </configOption>
312                                 <configOption name="send_rpid" default="no">
313                                         <synopsis>Send the Remote-Party-ID header</synopsis>
314                                 </configOption>
315                                 <configOption name="timers_min_se" default="90">
316                                         <synopsis>Minimum session timers expiration period</synopsis>
317                                         <description><para>
318                                                 Minimium session timer expiration period. Time in seconds.
319                                         </para></description>
320                                 </configOption>
321                                 <configOption name="timers" default="yes">
322                                         <synopsis>Session timers for SIP packets</synopsis>
323                                         <description>
324                                                 <enumlist>
325                                                         <enum name="forced" />
326                                                         <enum name="no" />
327                                                         <enum name="required" />
328                                                         <enum name="yes" />
329                                                 </enumlist>
330                                         </description>
331                                 </configOption>
332                                 <configOption name="timers_sess_expires" default="1800">
333                                         <synopsis>Maximum session timer expiration period</synopsis>
334                                         <description><para>
335                                                 Maximium session timer expiration period. Time in seconds.
336                                         </para></description>
337                                 </configOption>
338                                 <configOption name="transport">
339                                         <synopsis>Desired transport configuration</synopsis>
340                                         <description><para>
341                                                 This will set the desired transport configuration to send SIP data through.
342                                                 </para>
343                                                 <warning><para>Not specifying a transport will <emphasis>DEFAULT</emphasis>
344                                                 to the first configured transport in <filename>pjsip.conf</filename> which is
345                                                 valid for the URI we are trying to contact.
346                                                 </para></warning>
347                                                 <warning><para>Transport configuration is not affected by reloads. In order to
348                                                 change transports, a full Asterisk restart is required</para></warning>
349                                         </description>
350                                 </configOption>
351                                 <configOption name="trust_id_inbound" default="no">
352                                         <synopsis>Accept identification information received from this endpoint</synopsis>
353                                         <description><para>This option determines whether Asterisk will accept
354                                         identification from the endpoint from headers such as P-Asserted-Identity
355                                         or Remote-Party-ID header. This option applies both to calls originating from the
356                                         endpoint and calls originating from Asterisk. If <literal>no</literal>, the
357                                         configured Caller-ID from pjsip.conf will always be used as the identity for
358                                         the endpoint.</para></description>
359                                 </configOption>
360                                 <configOption name="trust_id_outbound" default="no">
361                                         <synopsis>Send private identification details to the endpoint.</synopsis>
362                                         <description><para>This option determines whether res_pjsip will send private
363                                         identification information to the endpoint. If <literal>no</literal>,
364                                         private Caller-ID information will not be forwarded to the endpoint.
365                                         "Private" in this case refers to any method of restricting identification.
366                                         Example: setting <replaceable>callerid_privacy</replaceable> to any
367                                         <literal>prohib</literal> variation.
368                                         Example: If <replaceable>trust_id_inbound</replaceable> is set to
369                                         <literal>yes</literal>, the presence of a <literal>Privacy: id</literal>
370                                         header in a SIP request or response would indicate the identification
371                                         provided in the request is private.</para></description>
372                                 </configOption>
373                                 <configOption name="type">
374                                         <synopsis>Must be of type 'endpoint'.</synopsis>
375                                 </configOption>
376                                 <configOption name="use_ptime" default="no">
377                                         <synopsis>Use Endpoint's requested packetisation interval</synopsis>
378                                 </configOption>
379                                 <configOption name="use_avpf" default="no">
380                                         <synopsis>Determines whether res_pjsip will use and enforce usage of AVPF for this
381                                         endpoint.</synopsis>
382                                         <description><para>
383                                                 If set to <literal>yes</literal>, res_pjsip will use the AVPF or SAVPF RTP
384                                                 profile for all media offers on outbound calls and media updates and will
385                                                 decline media offers not using the AVPF or SAVPF profile.
386                                         </para><para>
387                                                 If set to <literal>no</literal>, res_pjsip will use the AVP or SAVP RTP
388                                                 profile for all media offers on outbound calls and media updates, but will
389                                                 accept either the AVP/AVPF or SAVP/SAVPF RTP profile for all inbound
390                                                 media offers.
391                                         </para></description>
392                                 </configOption>
393                                 <configOption name="media_encryption" default="no">
394                                         <synopsis>Determines whether res_pjsip will use and enforce usage of media encryption
395                                         for this endpoint.</synopsis>
396                                         <description>
397                                                 <enumlist>
398                                                         <enum name="no"><para>
399                                                                 res_pjsip will offer no encryption and allow no encryption to be setup.
400                                                         </para></enum>
401                                                         <enum name="sdes"><para>
402                                                                 res_pjsip will offer standard SRTP setup via in-SDP keys. Encrypted SIP
403                                                                 transport should be used in conjunction with this option to prevent
404                                                                 exposure of media encryption keys.
405                                                         </para></enum>
406                                                         <enum name="dtls"><para>
407                                                                 res_pjsip will offer DTLS-SRTP setup.
408                                                         </para></enum>
409                                                 </enumlist>
410                                         </description>
411                                 </configOption>
412                                 <configOption name="inband_progress" default="no">
413                                         <synopsis>Determines whether chan_pjsip will indicate ringing using inband
414                                             progress.</synopsis>
415                                         <description><para>
416                                                 If set to <literal>yes</literal>, chan_pjsip will send a 183 Session Progress
417                                                 when told to indicate ringing and will immediately start sending ringing
418                                                 as audio.
419                                         </para><para>
420                                                 If set to <literal>no</literal>, chan_pjsip will send a 180 Ringing when told
421                                                 to indicate ringing and will NOT send it as audio.
422                                         </para></description>
423                                 </configOption>
424                                 <configOption name="call_group">
425                                         <synopsis>The numeric pickup groups for a channel.</synopsis>
426                                         <description><para>
427                                                 Can be set to a comma separated list of numbers or ranges between the values
428                                                 of 0-63 (maximum of 64 groups).
429                                         </para></description>
430                                 </configOption>
431                                 <configOption name="pickup_group">
432                                         <synopsis>The numeric pickup groups that a channel can pickup.</synopsis>
433                                         <description><para>
434                                                 Can be set to a comma separated list of numbers or ranges between the values
435                                                 of 0-63 (maximum of 64 groups).
436                                         </para></description>
437                                 </configOption>
438                                 <configOption name="named_call_group">
439                                         <synopsis>The named pickup groups for a channel.</synopsis>
440                                         <description><para>
441                                                 Can be set to a comma separated list of case sensitive strings limited by
442                                                 supported line length.
443                                         </para></description>
444                                 </configOption>
445                                 <configOption name="named_pickup_group">
446                                         <synopsis>The named pickup groups that a channel can pickup.</synopsis>
447                                         <description><para>
448                                                 Can be set to a comma separated list of case sensitive strings limited by
449                                                 supported line length.
450                                         </para></description>
451                                 </configOption>
452                                 <configOption name="device_state_busy_at" default="0">
453                                         <synopsis>The number of in-use channels which will cause busy to be returned as device state</synopsis>
454                                         <description><para>
455                                                 When the number of in-use channels for the endpoint matches the devicestate_busy_at setting the
456                                                 PJSIP channel driver will return busy as the device state instead of in use.
457                                         </para></description>
458                                 </configOption>
459                                 <configOption name="t38_udptl" default="no">
460                                         <synopsis>Whether T.38 UDPTL support is enabled or not</synopsis>
461                                         <description><para>
462                                                 If set to yes T.38 UDPTL support will be enabled, and T.38 negotiation requests will be accepted
463                                                 and relayed.
464                                         </para></description>
465                                 </configOption>
466                                 <configOption name="t38_udptl_ec" default="none">
467                                         <synopsis>T.38 UDPTL error correction method</synopsis>
468                                         <description>
469                                                 <enumlist>
470                                                         <enum name="none"><para>
471                                                                 No error correction should be used.
472                                                         </para></enum>
473                                                         <enum name="fec"><para>
474                                                                 Forward error correction should be used.
475                                                         </para></enum>
476                                                         <enum name="redundancy"><para>
477                                                                 Redundacy error correction should be used.
478                                                         </para></enum>
479                                                 </enumlist>
480                                         </description>
481                                 </configOption>
482                                 <configOption name="t38_udptl_maxdatagram" default="0">
483                                         <synopsis>T.38 UDPTL maximum datagram size</synopsis>
484                                         <description><para>
485                                                 This option can be set to override the maximum datagram of a remote endpoint for broken
486                                                 endpoints.
487                                         </para></description>
488                                 </configOption>
489                                 <configOption name="fax_detect" default="no">
490                                         <synopsis>Whether CNG tone detection is enabled</synopsis>
491                                         <description><para>
492                                                 This option can be set to send the session to the fax extension when a CNG tone is
493                                                 detected.
494                                         </para></description>
495                                 </configOption>
496                                 <configOption name="t38_udptl_nat" default="no">
497                                         <synopsis>Whether NAT support is enabled on UDPTL sessions</synopsis>
498                                         <description><para>
499                                                 When enabled the UDPTL stack will send UDPTL packets to the source address of
500                                                 received packets.
501                                         </para></description>
502                                 </configOption>
503                                 <configOption name="t38_udptl_ipv6" default="no">
504                                         <synopsis>Whether IPv6 is used for UDPTL Sessions</synopsis>
505                                         <description><para>
506                                                 When enabled the UDPTL stack will use IPv6.
507                                         </para></description>
508                                 </configOption>
509                                 <configOption name="tone_zone">
510                                         <synopsis>Set which country's indications to use for channels created for this endpoint.</synopsis>
511                                 </configOption>
512                                 <configOption name="language">
513                                         <synopsis>Set the default language to use for channels created for this endpoint.</synopsis>
514                                 </configOption>
515                                 <configOption name="one_touch_recording" default="no">
516                                         <synopsis>Determines whether one-touch recording is allowed for this endpoint.</synopsis>
517                                         <see-also>
518                                                 <ref type="configOption">record_on_feature</ref>
519                                                 <ref type="configOption">record_off_feature</ref>
520                                         </see-also>
521                                 </configOption>
522                                 <configOption name="record_on_feature" default="automixmon">
523                                         <synopsis>The feature to enact when one-touch recording is turned on.</synopsis>
524                                         <description>
525                                                 <para>When an INFO request for one-touch recording arrives with a Record header set to "on", this
526                                                 feature will be enabled for the channel. The feature designated here can be any built-in
527                                                 or dynamic feature defined in features.conf.</para>
528                                                 <note><para>This setting has no effect if the endpoint's one_touch_recording option is disabled</para></note>
529                                         </description>
530                                         <see-also>
531                                                 <ref type="configOption">one_touch_recording</ref>
532                                                 <ref type="configOption">record_off_feature</ref>
533                                         </see-also>
534                                 </configOption>
535                                 <configOption name="record_off_feature" default="automixmon">
536                                         <synopsis>The feature to enact when one-touch recording is turned off.</synopsis>
537                                         <description>
538                                                 <para>When an INFO request for one-touch recording arrives with a Record header set to "off", this
539                                                 feature will be enabled for the channel. The feature designated here can be any built-in
540                                                 or dynamic feature defined in features.conf.</para>
541                                                 <note><para>This setting has no effect if the endpoint's one_touch_recording option is disabled</para></note>
542                                         </description>
543                                         <see-also>
544                                                 <ref type="configOption">one_touch_recording</ref>
545                                                 <ref type="configOption">record_on_feature</ref>
546                                         </see-also>
547                                 </configOption>
548                                 <configOption name="rtp_engine" default="asterisk">
549                                         <synopsis>Name of the RTP engine to use for channels created for this endpoint</synopsis>
550                                 </configOption>
551                                 <configOption name="allow_transfer" default="yes">
552                                         <synopsis>Determines whether SIP REFER transfers are allowed for this endpoint</synopsis>
553                                 </configOption>
554                                 <configOption name="sdp_owner" default="-">
555                                         <synopsis>String placed as the username portion of an SDP origin (o=) line.</synopsis>
556                                 </configOption>
557                                 <configOption name="sdp_session" default="Asterisk">
558                                         <synopsis>String used for the SDP session (s=) line.</synopsis>
559                                 </configOption>
560                                 <configOption name="tos_audio">
561                                         <synopsis>DSCP TOS bits for audio streams</synopsis>
562                                         <description><para>
563                                                 See https://wiki.asterisk.org/wiki/display/AST/IP+Quality+of+Service for more information about QoS settings
564                                         </para></description>
565                                 </configOption>
566                                 <configOption name="tos_video">
567                                         <synopsis>DSCP TOS bits for video streams</synopsis>
568                                         <description><para>
569                                                 See https://wiki.asterisk.org/wiki/display/AST/IP+Quality+of+Service for more information about QoS settings
570                                         </para></description>
571                                 </configOption>
572                                 <configOption name="cos_audio">
573                                         <synopsis>Priority for audio streams</synopsis>
574                                         <description><para>
575                                                 See https://wiki.asterisk.org/wiki/display/AST/IP+Quality+of+Service for more information about QoS settings
576                                         </para></description>
577                                 </configOption>
578                                 <configOption name="cos_video">
579                                         <synopsis>Priority for video streams</synopsis>
580                                         <description><para>
581                                                 See https://wiki.asterisk.org/wiki/display/AST/IP+Quality+of+Service for more information about QoS settings
582                                         </para></description>
583                                 </configOption>
584                                 <configOption name="allow_subscribe" default="yes">
585                                         <synopsis>Determines if endpoint is allowed to initiate subscriptions with Asterisk.</synopsis>
586                                 </configOption>
587                                 <configOption name="sub_min_expiry" default="60">
588                                         <synopsis>The minimum allowed expiry time for subscriptions initiated by the endpoint.</synopsis>
589                                 </configOption>
590                                 <configOption name="from_user">
591                                         <synopsis>Username to use in From header for requests to this endpoint.</synopsis>
592                                 </configOption>
593                                 <configOption name="mwi_from_user">
594                                         <synopsis>Username to use in From header for unsolicited MWI NOTIFYs to this endpoint.</synopsis>
595                                 </configOption>
596                                 <configOption name="from_domain">
597                                         <synopsis>Domain to user in From header for requests to this endpoint.</synopsis>
598                                 </configOption>
599                                 <configOption name="dtls_verify">
600                                         <synopsis>Verify that the provided peer certificate is valid</synopsis>
601                                         <description><para>
602                                                 This option only applies if <replaceable>media_encryption</replaceable> is
603                                                 set to <literal>dtls</literal>.
604                                         </para></description>
605                                 </configOption>
606                                 <configOption name="dtls_rekey">
607                                         <synopsis>Interval at which to renegotiate the TLS session and rekey the SRTP session</synopsis>
608                                         <description><para>
609                                                 This option only applies if <replaceable>media_encryption</replaceable> is
610                                                 set to <literal>dtls</literal>.
611                                         </para><para>
612                                                 If this is not set or the value provided is 0 rekeying will be disabled.
613                                         </para></description>
614                                 </configOption>
615                                 <configOption name="dtls_cert_file">
616                                         <synopsis>Path to certificate file to present to peer</synopsis>
617                                         <description><para>
618                                                 This option only applies if <replaceable>media_encryption</replaceable> is
619                                                 set to <literal>dtls</literal>.
620                                         </para></description>
621                                 </configOption>
622                                 <configOption name="dtls_private_key">
623                                         <synopsis>Path to private key for certificate file</synopsis>
624                                         <description><para>
625                                                 This option only applies if <replaceable>media_encryption</replaceable> is
626                                                 set to <literal>dtls</literal>.
627                                         </para></description>
628                                 </configOption>
629                                 <configOption name="dtls_cipher">
630                                         <synopsis>Cipher to use for DTLS negotiation</synopsis>
631                                         <description><para>
632                                                 This option only applies if <replaceable>media_encryption</replaceable> is
633                                                 set to <literal>dtls</literal>.
634                                         </para><para>
635                                                 Many options for acceptable ciphers. See link for more:
636                                                 http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS
637                                         </para></description>
638                                 </configOption>
639                                 <configOption name="dtls_ca_file">
640                                         <synopsis>Path to certificate authority certificate</synopsis>
641                                         <description><para>
642                                                 This option only applies if <replaceable>media_encryption</replaceable> is
643                                                 set to <literal>dtls</literal>.
644                                         </para></description>
645                                 </configOption>
646                                 <configOption name="dtls_ca_path">
647                                         <synopsis>Path to a directory containing certificate authority certificates</synopsis>
648                                         <description><para>
649                                                 This option only applies if <replaceable>media_encryption</replaceable> is
650                                                 set to <literal>dtls</literal>.
651                                         </para></description>
652                                 </configOption>
653                                 <configOption name="dtls_setup">
654                                         <synopsis>Whether we are willing to accept connections, connect to the other party, or both.</synopsis>
655                                         <description>
656                                                 <para>
657                                                         This option only applies if <replaceable>media_encryption</replaceable> is
658                                                         set to <literal>dtls</literal>.
659                                                 </para>
660                                                 <enumlist>
661                                                         <enum name="active"><para>
662                                                                 res_pjsip will make a connection to the peer.
663                                                         </para></enum>
664                                                         <enum name="passive"><para>
665                                                                 res_pjsip will accept connections from the peer.
666                                                         </para></enum>
667                                                         <enum name="actpass"><para>
668                                                                 res_pjsip will offer and accept connections from the peer.
669                                                         </para></enum>
670                                                 </enumlist>
671                                         </description>
672                                 </configOption>
673                                 <configOption name="srtp_tag_32">
674                                         <synopsis>Determines whether 32 byte tags should be used instead of 80 byte tags.</synopsis>
675                                         <description><para>
676                                                 This option only applies if <replaceable>media_encryption</replaceable> is
677                                                 set to <literal>sdes</literal> or <literal>dtls</literal>.
678                                         </para></description>
679                                 </configOption>
680                                 <configOption name="set_var">
681                                         <synopsis>Variable set on a channel involving the endpoint.</synopsis>
682                                         <description><para>
683                                                 When a new channel is created using the endpoint set the specified
684                                                 variable(s) on that channel. For multiple channel variables specify
685                                                 multiple 'set_var'(s).
686                                         </para></description>
687                                 </configOption>
688                                 <configOption name="message_context">
689                                         <synopsis>Context to route incoming MESSAGE requests to.</synopsis>
690                                         <description><para>
691                                                 If specified, incoming MESSAGE requests will be routed to the indicated
692                                                 dialplan context. If no <replaceable>message_context</replaceable> is
693                                                 specified, then the <replaceable>context</replaceable> setting is used.
694                                         </para></description>
695                                 </configOption>
696                         </configObject>
697                         <configObject name="auth">
698                                 <synopsis>Authentication type</synopsis>
699                                 <description><para>
700                                         Authentication objects hold the authentication information for use
701                                         by other objects such as <literal>endpoints</literal> or <literal>registrations</literal>.
702                                         This also allows for multiple objects to use a single auth object. See
703                                         the <literal>auth_type</literal> config option for password style choices.
704                                 </para></description>
705                                 <configOption name="auth_type" default="userpass">
706                                         <synopsis>Authentication type</synopsis>
707                                         <description><para>
708                                                 This option specifies which of the password style config options should be read
709                                                 when trying to authenticate an endpoint inbound request. If set to <literal>userpass</literal>
710                                                 then we'll read from the 'password' option. For <literal>md5</literal> we'll read
711                                                 from 'md5_cred'.
712                                                 </para>
713                                                 <enumlist>
714                                                         <enum name="md5"/>
715                                                         <enum name="userpass"/>
716                                                 </enumlist>
717                                         </description>
718                                 </configOption>
719                                 <configOption name="nonce_lifetime" default="32">
720                                         <synopsis>Lifetime of a nonce associated with this authentication config.</synopsis>
721                                 </configOption>
722                                 <configOption name="md5_cred">
723                                         <synopsis>MD5 Hash used for authentication.</synopsis>
724                                         <description><para>Only used when auth_type is <literal>md5</literal>.</para></description>
725                                 </configOption>
726                                 <configOption name="password">
727                                         <synopsis>PlainText password used for authentication.</synopsis>
728                                         <description><para>Only used when auth_type is <literal>userpass</literal>.</para></description>
729                                 </configOption>
730                                 <configOption name="realm" default="asterisk">
731                                         <synopsis>SIP realm for endpoint</synopsis>
732                                 </configOption>
733                                 <configOption name="type">
734                                         <synopsis>Must be 'auth'</synopsis>
735                                 </configOption>
736                                 <configOption name="username">
737                                         <synopsis>Username to use for account</synopsis>
738                                 </configOption>
739                         </configObject>
740                         <configObject name="domain_alias">
741                                 <synopsis>Domain Alias</synopsis>
742                                 <description><para>
743                                         Signifies that a domain is an alias. If the domain on a session is
744                                         not found to match an AoR then this object is used to see if we have
745                                         an alias for the AoR to which the endpoint is binding. This objects
746                                         name as defined in configuration should be the domain alias and a
747                                         config option is provided to specify the domain to be aliased.
748                                 </para></description>
749                                 <configOption name="type">
750                                         <synopsis>Must be of type 'domain_alias'.</synopsis>
751                                 </configOption>
752                                 <configOption name="domain">
753                                         <synopsis>Domain to be aliased</synopsis>
754                                 </configOption>
755                         </configObject>
756                         <configObject name="transport">
757                                 <synopsis>SIP Transport</synopsis>
758                                 <description><para>
759                                         <emphasis>Transports</emphasis>
760                                         </para>
761                                         <para>There are different transports and protocol derivatives
762                                                 supported by <literal>res_pjsip</literal>. They are in order of
763                                                 preference: UDP, TCP, and WebSocket (WS).</para>
764                                         <note><para>Changes to transport configuration in pjsip.conf will only be
765                                                 effected on a complete restart of Asterisk. A module reload
766                                                 will not suffice.</para></note>
767                                 </description>
768                                 <configOption name="async_operations" default="1">
769                                         <synopsis>Number of simultaneous Asynchronous Operations</synopsis>
770                                 </configOption>
771                                 <configOption name="bind">
772                                         <synopsis>IP Address and optional port to bind to for this transport</synopsis>
773                                 </configOption>
774                                 <configOption name="ca_list_file">
775                                         <synopsis>File containing a list of certificates to read (TLS ONLY)</synopsis>
776                                 </configOption>
777                                 <configOption name="cert_file">
778                                         <synopsis>Certificate file for endpoint (TLS ONLY)</synopsis>
779                                 </configOption>
780                                 <configOption name="cipher">
781                                         <synopsis>Preferred Cryptography Cipher (TLS ONLY)</synopsis>
782                                         <description><para>
783                                                 Many options for acceptable ciphers see link for more:
784                                                 http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS
785                                         </para></description>
786                                 </configOption>
787                                 <configOption name="domain">
788                                         <synopsis>Domain the transport comes from</synopsis>
789                                 </configOption>
790                                 <configOption name="external_media_address">
791                                         <synopsis>External IP address to use in RTP handling</synopsis>
792                                         <description><para>
793                                                 When a request or response is sent out, if the destination of the
794                                                 message is outside the IP network defined in the option <literal>localnet</literal>,
795                                                 and the media address in the SDP is within the localnet network, then the
796                                                 media address in the SDP will be rewritten to the value defined for
797                                                 <literal>external_media_address</literal>.
798                                         </para></description>
799                                 </configOption>
800                                 <configOption name="external_signaling_address">
801                                         <synopsis>External address for SIP signalling</synopsis>
802                                 </configOption>
803                                 <configOption name="external_signaling_port" default="0">
804                                         <synopsis>External port for SIP signalling</synopsis>
805                                 </configOption>
806                                 <configOption name="method">
807                                         <synopsis>Method of SSL transport (TLS ONLY)</synopsis>
808                                         <description>
809                                                 <enumlist>
810                                                         <enum name="default" />
811                                                         <enum name="unspecified" />
812                                                         <enum name="tlsv1" />
813                                                         <enum name="sslv2" />
814                                                         <enum name="sslv3" />
815                                                         <enum name="sslv23" />
816                                                 </enumlist>
817                                         </description>
818                                 </configOption>
819                                 <configOption name="local_net">
820                                         <synopsis>Network to consider local (used for NAT purposes).</synopsis>
821                                         <description><para>This must be in CIDR or dotted decimal format with the IP
822                                         and mask separated with a slash ('/').</para></description>
823                                 </configOption>
824                                 <configOption name="password">
825                                         <synopsis>Password required for transport</synopsis>
826                                 </configOption>
827                                 <configOption name="priv_key_file">
828                                         <synopsis>Private key file (TLS ONLY)</synopsis>
829                                 </configOption>
830                                 <configOption name="protocol" default="udp">
831                                         <synopsis>Protocol to use for SIP traffic</synopsis>
832                                         <description>
833                                                 <enumlist>
834                                                         <enum name="udp" />
835                                                         <enum name="tcp" />
836                                                         <enum name="tls" />
837                                                         <enum name="ws" />
838                                                         <enum name="wss" />
839                                                 </enumlist>
840                                         </description>
841                                 </configOption>
842                                 <configOption name="require_client_cert" default="false">
843                                         <synopsis>Require client certificate (TLS ONLY)</synopsis>
844                                 </configOption>
845                                 <configOption name="type">
846                                         <synopsis>Must be of type 'transport'.</synopsis>
847                                 </configOption>
848                                 <configOption name="verify_client" default="false">
849                                         <synopsis>Require verification of client certificate (TLS ONLY)</synopsis>
850                                 </configOption>
851                                 <configOption name="verify_server" default="false">
852                                         <synopsis>Require verification of server certificate (TLS ONLY)</synopsis>
853                                 </configOption>
854                                 <configOption name="tos" default="false">
855                                         <synopsis>Enable TOS for the signalling sent over this transport</synopsis>
856                                         <description>
857                                         <para>See <literal>https://wiki.asterisk.org/wiki/display/AST/IP+Quality+of+Service</literal>
858                                         for more information on this parameter.</para>
859                                         <note><para>This option does not apply to the <replaceable>ws</replaceable>
860                                         or the <replaceable>wss</replaceable> protocols.</para></note>
861                                         </description>
862                                 </configOption>
863                                 <configOption name="cos" default="false">
864                                         <synopsis>Enable COS for the signalling sent over this transport</synopsis>
865                                         <description>
866                                         <para>See <literal>https://wiki.asterisk.org/wiki/display/AST/IP+Quality+of+Service</literal>
867                                         for more information on this parameter.</para>
868                                         <note><para>This option does not apply to the <replaceable>ws</replaceable>
869                                         or the <replaceable>wss</replaceable> protocols.</para></note>
870                                         </description>
871                                 </configOption>
872                                 <configOption name="websocket_write_timeout">
873                                         <synopsis>The timeout (in milliseconds) to set on WebSocket connections.</synopsis>
874                                         <description>
875                                                 <para>If a websocket connection accepts input slowly, the timeout
876                                                 for writes to it can be increased to keep it from being disconnected.
877                                                 Value is in milliseconds; default is 100 ms.</para>
878                                         </description>
879                                 </configOption>
880                         </configObject>
881                         <configObject name="contact">
882                                 <synopsis>A way of creating an aliased name to a SIP URI</synopsis>
883                                 <description><para>
884                                         Contacts are a way to hide SIP URIs from the dialplan directly.
885                                         They are also used to make a group of contactable parties when
886                                         in use with <literal>AoR</literal> lists.
887                                 </para></description>
888                                 <configOption name="type">
889                                         <synopsis>Must be of type 'contact'.</synopsis>
890                                 </configOption>
891                                 <configOption name="uri">
892                                         <synopsis>SIP URI to contact peer</synopsis>
893                                 </configOption>
894                                 <configOption name="expiration_time">
895                                         <synopsis>Time to keep alive a contact</synopsis>
896                                         <description><para>
897                                                 Time to keep alive a contact. String style specification.
898                                         </para></description>
899                                 </configOption>
900                                 <configOption name="qualify_frequency" default="0">
901                                         <synopsis>Interval at which to qualify a contact</synopsis>
902                                         <description><para>
903                                                 Interval between attempts to qualify the contact for reachability.
904                                                 If <literal>0</literal> never qualify. Time in seconds.
905                                         </para></description>
906                                 </configOption>
907                                 <configOption name="outbound_proxy">
908                                         <synopsis>Outbound proxy used when sending OPTIONS request</synopsis>
909                                         <description><para>
910                                                 If set the provided URI will be used as the outbound proxy when an
911                                                 OPTIONS request is sent to a contact for qualify purposes.
912                                         </para></description>
913                                 </configOption>
914                                 <configOption name="path">
915                                         <synopsis>Stored Path vector for use in Route headers on outgoing requests.</synopsis>
916                                 </configOption>
917                                 <configOption name="user_agent">
918                                         <synopsis>User-Agent header from registration.</synopsis>
919                                         <description><para>
920                                                 The User-Agent is automatically stored based on data present in incoming SIP
921                                                 REGISTER requests and is not intended to be configured manually.
922                                         </para></description>
923                                 </configOption>
924                         </configObject>
925                         <configObject name="aor">
926                                 <synopsis>The configuration for a location of an endpoint</synopsis>
927                                 <description><para>
928                                         An AoR is what allows Asterisk to contact an endpoint via res_pjsip. If no
929                                         AoRs are specified, an endpoint will not be reachable by Asterisk.
930                                         Beyond that, an AoR has other uses within Asterisk, such as inbound
931                                         registration.
932                                         </para><para>
933                                         An <literal>AoR</literal> is a way to allow dialing a group
934                                         of <literal>Contacts</literal> that all use the same
935                                         <literal>endpoint</literal> for calls.
936                                         </para><para>
937                                         This can be used as another way of grouping a list of contacts to dial
938                                         rather than specifing them each directly when dialing via the dialplan.
939                                         This must be used in conjuction with the <literal>PJSIP_DIAL_CONTACTS</literal>.
940                                         </para><para>
941                                         Registrations: For Asterisk to match an inbound registration to an endpoint,
942                                         the AoR object name must match the user portion of the SIP URI in the "To:"
943                                         header of the inbound SIP registration. That will usually be equivalent
944                                         to the "user name" set in your hard or soft phones configuration.
945                                 </para></description>
946                                 <configOption name="contact">
947                                         <synopsis>Permanent contacts assigned to AoR</synopsis>
948                                         <description><para>
949                                                 Contacts specified will be called whenever referenced
950                                                 by <literal>chan_pjsip</literal>.
951                                                 </para><para>
952                                                 Use a separate "contact=" entry for each contact required. Contacts
953                                                 are specified using a SIP URI.
954                                         </para></description>
955                                 </configOption>
956                                 <configOption name="default_expiration" default="3600">
957                                         <synopsis>Default expiration time in seconds for contacts that are dynamically bound to an AoR.</synopsis>
958                                 </configOption>
959                                 <configOption name="mailboxes">
960                                         <synopsis>Allow subscriptions for the specified mailbox(es)</synopsis>
961                                         <description><para>This option applies when an external entity subscribes to an AoR
962                                                 for Message Waiting Indications. The mailboxes specified will be subscribed to.
963                                                 More than one mailbox can be specified with a comma-delimited string.
964                                                 app_voicemail mailboxes must be specified as mailbox@context;
965                                                 for example: mailboxes=6001@default. For mailboxes provided by external sources,
966                                                 such as through the res_external_mwi module, you must specify strings supported by
967                                                 the external system.
968                                         </para><para>
969                                                 For endpoints that cannot SUBSCRIBE for MWI, you can set the <literal>mailboxes</literal> option in your
970                                                 endpoint configuration section to enable unsolicited MWI NOTIFYs to the endpoint.
971                                         </para></description>
972                                 </configOption>
973                                 <configOption name="maximum_expiration" default="7200">
974                                         <synopsis>Maximum time to keep an AoR</synopsis>
975                                         <description><para>
976                                                 Maximium time to keep a peer with explicit expiration. Time in seconds.
977                                         </para></description>
978                                 </configOption>
979                                 <configOption name="max_contacts" default="0">
980                                         <synopsis>Maximum number of contacts that can bind to an AoR</synopsis>
981                                         <description><para>
982                                                 Maximum number of contacts that can associate with this AoR. This value does
983                                                 not affect the number of contacts that can be added with the "contact" option.
984                                                 It only limits contacts added through external interaction, such as
985                                                 registration.
986                                                 </para>
987                                                 <note><para>This should be set to <literal>1</literal> and
988                                                 <replaceable>remove_existing</replaceable> set to <literal>yes</literal> if you
989                                                 wish to stick with the older <literal>chan_sip</literal> behaviour.
990                                                 </para></note>
991                                         </description>
992                                 </configOption>
993                                 <configOption name="minimum_expiration" default="60">
994                                         <synopsis>Minimum keep alive time for an AoR</synopsis>
995                                         <description><para>
996                                                 Minimum time to keep a peer with an explict expiration. Time in seconds.
997                                         </para></description>
998                                 </configOption>
999                                 <configOption name="remove_existing" default="no">
1000                                         <synopsis>Determines whether new contacts replace existing ones.</synopsis>
1001                                         <description><para>
1002                                                 On receiving a new registration to the AoR should it remove
1003                                                 the existing contact that was registered against it?
1004                                                 </para>
1005                                                 <note><para>This should be set to <literal>yes</literal> and
1006                                                 <replaceable>max_contacts</replaceable> set to <literal>1</literal> if you
1007                                                 wish to stick with the older <literal>chan_sip</literal> behaviour.
1008                                                 </para></note>
1009                                         </description>
1010                                 </configOption>
1011                                 <configOption name="type">
1012                                         <synopsis>Must be of type 'aor'.</synopsis>
1013                                 </configOption>
1014                                 <configOption name="qualify_frequency" default="0">
1015                                         <synopsis>Interval at which to qualify an AoR</synopsis>
1016                                         <description><para>
1017                                                 Interval between attempts to qualify the AoR for reachability.
1018                                                 If <literal>0</literal> never qualify. Time in seconds.
1019                                         </para></description>
1020                                 </configOption>
1021                                 <configOption name="authenticate_qualify" default="no">
1022                                         <synopsis>Authenticates a qualify request if needed</synopsis>
1023                                         <description><para>
1024                                                 If true and a qualify request receives a challenge or authenticate response
1025                                                 authentication is attempted before declaring the contact available.
1026                                         </para></description>
1027                                 </configOption>
1028                                 <configOption name="outbound_proxy">
1029                                         <synopsis>Outbound proxy used when sending OPTIONS request</synopsis>
1030                                         <description><para>
1031                                                 If set the provided URI will be used as the outbound proxy when an
1032                                                 OPTIONS request is sent to a contact for qualify purposes.
1033                                         </para></description>
1034                                 </configOption>
1035                                 <configOption name="support_path">
1036                                         <synopsis>Enables Path support for REGISTER requests and Route support for other requests.</synopsis>
1037                                         <description><para>
1038                                                 When this option is enabled, the Path headers in register requests will be saved
1039                                                 and its contents will be used in Route headers for outbound out-of-dialog requests
1040                                                 and in Path headers for outbound 200 responses. Path support will also be indicated
1041                                                 in the Supported header.
1042                                         </para></description>
1043                                 </configOption>
1044                         </configObject>
1045                         <configObject name="system">
1046                                 <synopsis>Options that apply to the SIP stack as well as other system-wide settings</synopsis>
1047                                 <description><para>
1048                                         The settings in this section are global. In addition to being global, the values will
1049                                         not be re-evaluated when a reload is performed. This is because the values must be set
1050                                         before the SIP stack is initialized. The only way to reset these values is to either
1051                                         restart Asterisk, or unload res_pjsip.so and then load it again.
1052                                 </para></description>
1053                                 <configOption name="timer_t1" default="500">
1054                                         <synopsis>Set transaction timer T1 value (milliseconds).</synopsis>
1055                                         <description><para>
1056                                                 Timer T1 is the base for determining how long to wait before retransmitting
1057                                                 requests that receive no response when using an unreliable transport (e.g. UDP).
1058                                                 For more information on this timer, see RFC 3261, Section 17.1.1.1.
1059                                         </para></description>
1060                                 </configOption>
1061                                 <configOption name="timer_b" default="32000">
1062                                         <synopsis>Set transaction timer B value (milliseconds).</synopsis>
1063                                         <description><para>
1064                                                 Timer B determines the maximum amount of time to wait after sending an INVITE
1065                                                 request before terminating the transaction. It is recommended that this be set
1066                                                 to 64 * Timer T1, but it may be set higher if desired. For more information on
1067                                                 this timer, see RFC 3261, Section 17.1.1.1.
1068                                         </para></description>
1069                                 </configOption>
1070                                 <configOption name="compact_headers" default="no">
1071                                         <synopsis>Use the short forms of common SIP header names.</synopsis>
1072                                 </configOption>
1073                                 <configOption name="threadpool_initial_size" default="0">
1074                                         <synopsis>Initial number of threads in the res_pjsip threadpool.</synopsis>
1075                                 </configOption>
1076                                 <configOption name="threadpool_auto_increment" default="5">
1077                                         <synopsis>The amount by which the number of threads is incremented when necessary.</synopsis>
1078                                 </configOption>
1079                                 <configOption name="threadpool_idle_timeout" default="60">
1080                                         <synopsis>Number of seconds before an idle thread should be disposed of.</synopsis>
1081                                 </configOption>
1082                                 <configOption name="threadpool_max_size" default="0">
1083                                         <synopsis>Maximum number of threads in the res_pjsip threadpool.
1084                                         A value of 0 indicates no maximum.</synopsis>
1085                                 </configOption>
1086                                 <configOption name="type">
1087                                         <synopsis>Must be of type 'system'.</synopsis>
1088                                 </configOption>
1089                         </configObject>
1090                         <configObject name="global">
1091                                 <synopsis>Options that apply globally to all SIP communications</synopsis>
1092                                 <description><para>
1093                                         The settings in this section are global. Unlike options in the <literal>system</literal>
1094                                         section, these options can be refreshed by performing a reload.
1095                                 </para></description>
1096                                 <configOption name="max_forwards" default="70">
1097                                         <synopsis>Value used in Max-Forwards header for SIP requests.</synopsis>
1098                                 </configOption>
1099                                 <configOption name="type">
1100                                         <synopsis>Must be of type 'global'.</synopsis>
1101                                 </configOption>
1102                                 <configOption name="user_agent" default="Asterisk &lt;Asterisk Version&gt;">
1103                                         <synopsis>Value used in User-Agent header for SIP requests and Server header for SIP responses.</synopsis>
1104                                 </configOption>
1105                                 <configOption name="default_outbound_endpoint" default="default_outbound_endpoint">
1106                                         <synopsis>Endpoint to use when sending an outbound request to a URI without a specified endpoint.</synopsis>
1107                                 </configOption>
1108                                 <configOption name="debug" default="no">
1109                                         <synopsis>Enable/Disable SIP debug logging.  Valid options include yes|no or
1110                                         a host address</synopsis>
1111                                 </configOption>
1112                         </configObject>
1113                 </configFile>
1114         </configInfo>
1115         <manager name="PJSIPQualify" language="en_US">
1116                 <synopsis>
1117                         Qualify a chan_pjsip endpoint.
1118                 </synopsis>
1119                 <syntax>
1120                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1121                         <parameter name="Endpoint" required="true">
1122                                 <para>The endpoint you want to qualify.</para>
1123                         </parameter>
1124                 </syntax>
1125                 <description>
1126                         <para>Qualify a chan_pjsip endpoint.</para>
1127                 </description>
1128         </manager>
1129         <manager name="PJSIPShowEndpoints" language="en_US">
1130                 <synopsis>
1131                         Lists PJSIP endpoints.
1132                 </synopsis>
1133                 <syntax />
1134                 <description>
1135                         <para>
1136                         Provides a listing of all endpoints.  For each endpoint an <literal>EndpointList</literal> event
1137                         is raised that contains relevant attributes and status information.  Once all
1138                         endpoints have been listed an <literal>EndpointListComplete</literal> event is issued.
1139                         </para>
1140                 </description>
1141         </manager>
1142         <manager name="PJSIPShowEndpoint" language="en_US">
1143                 <synopsis>
1144                         Detail listing of an endpoint and its objects.
1145                 </synopsis>
1146                 <syntax>
1147                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1148                         <parameter name="Endpoint" required="true">
1149                                 <para>The endpoint to list.</para>
1150                         </parameter>
1151                 </syntax>
1152                 <description>
1153                         <para>
1154                         Provides a detailed listing of options for a given endpoint.  Events are issued
1155                         showing the configuration and status of the endpoint and associated objects.  These
1156                         events include <literal>EndpointDetail</literal>, <literal>AorDetail</literal>,
1157                         <literal>AuthDetail</literal>, <literal>TransportDetail</literal>, and
1158                         <literal>IdentifyDetail</literal>.  Some events may be listed multiple times if multiple objects are
1159                         associated (for instance AoRs).  Once all detail events have been raised a final
1160                         <literal>EndpointDetailComplete</literal> event is issued.
1161                         </para>
1162                 </description>
1163         </manager>
1164  ***/
1165
1166 #define MOD_DATA_CONTACT "contact"
1167
1168 static pjsip_endpoint *ast_pjsip_endpoint;
1169
1170 static struct ast_threadpool *sip_threadpool;
1171
1172 static int register_service(void *data)
1173 {
1174         pjsip_module **module = data;
1175         if (!ast_pjsip_endpoint) {
1176                 ast_log(LOG_ERROR, "There is no PJSIP endpoint. Unable to register services\n");
1177                 return -1;
1178         }
1179         if (pjsip_endpt_register_module(ast_pjsip_endpoint, *module) != PJ_SUCCESS) {
1180                 ast_log(LOG_ERROR, "Unable to register module %.*s\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name));
1181                 return -1;
1182         }
1183         ast_debug(1, "Registered SIP service %.*s (%p)\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name), *module);
1184         ast_module_ref(ast_module_info->self);
1185         return 0;
1186 }
1187
1188 int ast_sip_register_service(pjsip_module *module)
1189 {
1190         return ast_sip_push_task_synchronous(NULL, register_service, &module);
1191 }
1192
1193 static int unregister_service(void *data)
1194 {
1195         pjsip_module **module = data;
1196         ast_module_unref(ast_module_info->self);
1197         if (!ast_pjsip_endpoint) {
1198                 return -1;
1199         }
1200         pjsip_endpt_unregister_module(ast_pjsip_endpoint, *module);
1201         ast_debug(1, "Unregistered SIP service %.*s\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name));
1202         return 0;
1203 }
1204
1205 void ast_sip_unregister_service(pjsip_module *module)
1206 {
1207         ast_sip_push_task_synchronous(NULL, unregister_service, &module);
1208 }
1209
1210 static struct ast_sip_authenticator *registered_authenticator;
1211
1212 int ast_sip_register_authenticator(struct ast_sip_authenticator *auth)
1213 {
1214         if (registered_authenticator) {
1215                 ast_log(LOG_WARNING, "Authenticator %p is already registered. Cannot register a new one\n", registered_authenticator);
1216                 return -1;
1217         }
1218         registered_authenticator = auth;
1219         ast_debug(1, "Registered SIP authenticator module %p\n", auth);
1220         ast_module_ref(ast_module_info->self);
1221         return 0;
1222 }
1223
1224 void ast_sip_unregister_authenticator(struct ast_sip_authenticator *auth)
1225 {
1226         if (registered_authenticator != auth) {
1227                 ast_log(LOG_WARNING, "Trying to unregister authenticator %p but authenticator %p registered\n",
1228                                 auth, registered_authenticator);
1229                 return;
1230         }
1231         registered_authenticator = NULL;
1232         ast_debug(1, "Unregistered SIP authenticator %p\n", auth);
1233         ast_module_unref(ast_module_info->self);
1234 }
1235
1236 int ast_sip_requires_authentication(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
1237 {
1238         if (!registered_authenticator) {
1239                 ast_log(LOG_WARNING, "No SIP authenticator registered. Assuming authentication is not required\n");
1240                 return 0;
1241         }
1242
1243         return registered_authenticator->requires_authentication(endpoint, rdata);
1244 }
1245
1246 enum ast_sip_check_auth_result ast_sip_check_authentication(struct ast_sip_endpoint *endpoint,
1247                 pjsip_rx_data *rdata, pjsip_tx_data *tdata)
1248 {
1249         if (!registered_authenticator) {
1250                 ast_log(LOG_WARNING, "No SIP authenticator registered. Assuming authentication is successful\n");
1251                 return 0;
1252         }
1253         return registered_authenticator->check_authentication(endpoint, rdata, tdata);
1254 }
1255
1256 static struct ast_sip_outbound_authenticator *registered_outbound_authenticator;
1257
1258 int ast_sip_register_outbound_authenticator(struct ast_sip_outbound_authenticator *auth)
1259 {
1260         if (registered_outbound_authenticator) {
1261                 ast_log(LOG_WARNING, "Outbound authenticator %p is already registered. Cannot register a new one\n", registered_outbound_authenticator);
1262                 return -1;
1263         }
1264         registered_outbound_authenticator = auth;
1265         ast_debug(1, "Registered SIP outbound authenticator module %p\n", auth);
1266         ast_module_ref(ast_module_info->self);
1267         return 0;
1268 }
1269
1270 void ast_sip_unregister_outbound_authenticator(struct ast_sip_outbound_authenticator *auth)
1271 {
1272         if (registered_outbound_authenticator != auth) {
1273                 ast_log(LOG_WARNING, "Trying to unregister outbound authenticator %p but outbound authenticator %p registered\n",
1274                                 auth, registered_outbound_authenticator);
1275                 return;
1276         }
1277         registered_outbound_authenticator = NULL;
1278         ast_debug(1, "Unregistered SIP outbound authenticator %p\n", auth);
1279         ast_module_unref(ast_module_info->self);
1280 }
1281
1282 int ast_sip_create_request_with_auth(const struct ast_sip_auth_vector *auths, pjsip_rx_data *challenge,
1283                 pjsip_transaction *tsx, pjsip_tx_data **new_request)
1284 {
1285         if (!registered_outbound_authenticator) {
1286                 ast_log(LOG_WARNING, "No SIP outbound authenticator registered. Cannot respond to authentication challenge\n");
1287                 return -1;
1288         }
1289         return registered_outbound_authenticator->create_request_with_auth(auths, challenge, tsx, new_request);
1290 }
1291
1292 struct endpoint_identifier_list {
1293         struct ast_sip_endpoint_identifier *identifier;
1294         AST_RWLIST_ENTRY(endpoint_identifier_list) list;
1295 };
1296
1297 static AST_RWLIST_HEAD_STATIC(endpoint_identifiers, endpoint_identifier_list);
1298
1299 int ast_sip_register_endpoint_identifier(struct ast_sip_endpoint_identifier *identifier)
1300 {
1301         struct endpoint_identifier_list *id_list_item;
1302         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
1303
1304         id_list_item = ast_calloc(1, sizeof(*id_list_item));
1305         if (!id_list_item) {
1306                 ast_log(LOG_ERROR, "Unabled to add endpoint identifier. Out of memory.\n");
1307                 return -1;
1308         }
1309         id_list_item->identifier = identifier;
1310
1311         AST_RWLIST_INSERT_TAIL(&endpoint_identifiers, id_list_item, list);
1312         ast_debug(1, "Registered endpoint identifier %p\n", identifier);
1313
1314         ast_module_ref(ast_module_info->self);
1315         return 0;
1316 }
1317
1318 void ast_sip_unregister_endpoint_identifier(struct ast_sip_endpoint_identifier *identifier)
1319 {
1320         struct endpoint_identifier_list *iter;
1321         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
1322         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&endpoint_identifiers, iter, list) {
1323                 if (iter->identifier == identifier) {
1324                         AST_RWLIST_REMOVE_CURRENT(list);
1325                         ast_free(iter);
1326                         ast_debug(1, "Unregistered endpoint identifier %p\n", identifier);
1327                         ast_module_unref(ast_module_info->self);
1328                         break;
1329                 }
1330         }
1331         AST_RWLIST_TRAVERSE_SAFE_END;
1332 }
1333
1334 struct ast_sip_endpoint *ast_sip_identify_endpoint(pjsip_rx_data *rdata)
1335 {
1336         struct endpoint_identifier_list *iter;
1337         struct ast_sip_endpoint *endpoint = NULL;
1338         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1339         AST_RWLIST_TRAVERSE(&endpoint_identifiers, iter, list) {
1340                 ast_assert(iter->identifier->identify_endpoint != NULL);
1341                 endpoint = iter->identifier->identify_endpoint(rdata);
1342                 if (endpoint) {
1343                         break;
1344                 }
1345         }
1346         return endpoint;
1347 }
1348
1349 AST_RWLIST_HEAD_STATIC(endpoint_formatters, ast_sip_endpoint_formatter);
1350
1351 int ast_sip_register_endpoint_formatter(struct ast_sip_endpoint_formatter *obj)
1352 {
1353         SCOPED_LOCK(lock, &endpoint_formatters, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
1354         AST_RWLIST_INSERT_TAIL(&endpoint_formatters, obj, next);
1355         ast_module_ref(ast_module_info->self);
1356         return 0;
1357 }
1358
1359 void ast_sip_unregister_endpoint_formatter(struct ast_sip_endpoint_formatter *obj)
1360 {
1361         struct ast_sip_endpoint_formatter *i;
1362         SCOPED_LOCK(lock, &endpoint_formatters, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
1363         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&endpoint_formatters, i, next) {
1364                 if (i == obj) {
1365                         AST_RWLIST_REMOVE_CURRENT(next);
1366                         ast_module_unref(ast_module_info->self);
1367                         break;
1368                 }
1369         }
1370         AST_RWLIST_TRAVERSE_SAFE_END;
1371 }
1372
1373 int ast_sip_format_endpoint_ami(struct ast_sip_endpoint *endpoint,
1374                                 struct ast_sip_ami *ami, int *count)
1375 {
1376         int res = 0;
1377         struct ast_sip_endpoint_formatter *i;
1378         SCOPED_LOCK(lock, &endpoint_formatters, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1379         *count = 0;
1380         AST_RWLIST_TRAVERSE(&endpoint_formatters, i, next) {
1381                 if (i->format_ami && ((res = i->format_ami(endpoint, ami)) < 0)) {
1382                         return res;
1383                 }
1384
1385                 if (!res) {
1386                         (*count)++;
1387                 }
1388         }
1389         return 0;
1390 }
1391
1392 pjsip_endpoint *ast_sip_get_pjsip_endpoint(void)
1393 {
1394         return ast_pjsip_endpoint;
1395 }
1396
1397 static int sip_dialog_create_from(pj_pool_t *pool, pj_str_t *from, const char *user, const char *domain, const pj_str_t *target, pjsip_tpselector *selector)
1398 {
1399         pj_str_t tmp, local_addr;
1400         pjsip_uri *uri;
1401         pjsip_sip_uri *sip_uri;
1402         pjsip_transport_type_e type = PJSIP_TRANSPORT_UNSPECIFIED;
1403         int local_port;
1404         char uuid_str[AST_UUID_STR_LEN];
1405
1406         if (ast_strlen_zero(user)) {
1407                 RAII_VAR(struct ast_uuid *, uuid, ast_uuid_generate(), ast_free_ptr);
1408                 if (!uuid) {
1409                         return -1;
1410                 }
1411                 user = ast_uuid_to_str(uuid, uuid_str, sizeof(uuid_str));
1412         }
1413
1414         /* Parse the provided target URI so we can determine what transport it will end up using */
1415         pj_strdup_with_null(pool, &tmp, target);
1416
1417         if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
1418             (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
1419                 return -1;
1420         }
1421
1422         sip_uri = pjsip_uri_get_uri(uri);
1423
1424         /* Determine the transport type to use */
1425         if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
1426                 type = PJSIP_TRANSPORT_TLS;
1427         } else if (!sip_uri->transport_param.slen) {
1428                 type = PJSIP_TRANSPORT_UDP;
1429         } else {
1430                 type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
1431         }
1432
1433         if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
1434                 return -1;
1435         }
1436
1437         /* If the host is IPv6 turn the transport into an IPv6 version */
1438         if (pj_strchr(&sip_uri->host, ':') && type < PJSIP_TRANSPORT_START_OTHER) {
1439                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
1440         }
1441
1442         if (!ast_strlen_zero(domain)) {
1443                 from->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
1444                 from->slen = pj_ansi_snprintf(from->ptr, PJSIP_MAX_URL_SIZE,
1445                                 "<sip:%s@%s%s%s>",
1446                                 user,
1447                                 domain,
1448                                 (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
1449                                 (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
1450                 return 0;
1451         }
1452
1453         /* Get the local bound address for the transport that will be used when communicating with the provided URI */
1454         if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()), pool, type, selector,
1455                                                               &local_addr, &local_port) != PJ_SUCCESS) {
1456
1457                 /* If no local address can be retrieved using the transport manager use the host one */
1458                 pj_strdup(pool, &local_addr, pj_gethostname());
1459                 local_port = pjsip_transport_get_default_port_for_type(PJSIP_TRANSPORT_UDP);
1460         }
1461
1462         /* If IPv6 was specified in the transport, set the proper type */
1463         if (pj_strchr(&local_addr, ':') && type < PJSIP_TRANSPORT_START_OTHER) {
1464                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
1465         }
1466
1467         from->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
1468         from->slen = pj_ansi_snprintf(from->ptr, PJSIP_MAX_URL_SIZE,
1469                                       "<sip:%s@%s%.*s%s:%d%s%s>",
1470                                       user,
1471                                       (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
1472                                       (int)local_addr.slen,
1473                                       local_addr.ptr,
1474                                       (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
1475                                       local_port,
1476                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
1477                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
1478
1479         return 0;
1480 }
1481
1482 static int sip_get_tpselector_from_endpoint(const struct ast_sip_endpoint *endpoint, pjsip_tpselector *selector)
1483 {
1484         RAII_VAR(struct ast_sip_transport *, transport, NULL, ao2_cleanup);
1485         const char *transport_name = endpoint->transport;
1486
1487         if (ast_strlen_zero(transport_name)) {
1488                 return 0;
1489         }
1490
1491         transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", transport_name);
1492
1493         if (!transport || !transport->state) {
1494                 ast_log(LOG_ERROR, "Unable to retrieve PJSIP transport '%s' for endpoint '%s'\n",
1495                         transport_name, ast_sorcery_object_get_id(endpoint));
1496                 return -1;
1497         }
1498
1499         if (transport->state->transport) {
1500                 selector->type = PJSIP_TPSELECTOR_TRANSPORT;
1501                 selector->u.transport = transport->state->transport;
1502         } else if (transport->state->factory) {
1503                 selector->type = PJSIP_TPSELECTOR_LISTENER;
1504                 selector->u.listener = transport->state->factory;
1505         } else if (transport->type == AST_TRANSPORT_WS || transport->type == AST_TRANSPORT_WSS) {
1506                 /* The WebSocket transport has no factory as it can not create outgoing connections, so
1507                  * even if an endpoint is locked to a WebSocket transport we let the PJSIP logic
1508                  * find the existing connection if available and use it.
1509                  */
1510                 return 0;
1511         } else {
1512                 return -1;
1513         }
1514
1515         return 0;
1516 }
1517
1518 pjsip_dialog *ast_sip_create_dialog_uac(const struct ast_sip_endpoint *endpoint, const char *uri, const char *request_user)
1519 {
1520         char enclosed_uri[PJSIP_MAX_URL_SIZE];
1521         pj_str_t local_uri = { "sip:temp@temp", 13 }, remote_uri, target_uri;
1522         pjsip_dialog *dlg = NULL;
1523         const char *outbound_proxy = endpoint->outbound_proxy;
1524         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
1525         static const pj_str_t HCONTACT = { "Contact", 7 };
1526
1527         snprintf(enclosed_uri, sizeof(enclosed_uri), "<%s>", uri);
1528         pj_cstr(&remote_uri, enclosed_uri);
1529
1530         pj_cstr(&target_uri, uri);
1531
1532         if (pjsip_dlg_create_uac(pjsip_ua_instance(), &local_uri, NULL, &remote_uri, &target_uri, &dlg) != PJ_SUCCESS) {
1533                 return NULL;
1534         }
1535
1536         if (sip_get_tpselector_from_endpoint(endpoint, &selector)) {
1537                 pjsip_dlg_terminate(dlg);
1538                 return NULL;
1539         }
1540
1541         if (sip_dialog_create_from(dlg->pool, &local_uri, endpoint->fromuser, endpoint->fromdomain, &remote_uri, &selector)) {
1542                 pjsip_dlg_terminate(dlg);
1543                 return NULL;
1544         }
1545
1546         /* Update the dialog with the new local URI, we do it afterwards so we can use the dialog pool for construction */
1547         pj_strdup_with_null(dlg->pool, &dlg->local.info_str, &local_uri);
1548         dlg->local.info->uri = pjsip_parse_uri(dlg->pool, dlg->local.info_str.ptr, dlg->local.info_str.slen, 0);
1549         dlg->local.contact = pjsip_parse_hdr(dlg->pool, &HCONTACT, local_uri.ptr, local_uri.slen, NULL);
1550
1551         /* If a request user has been specified and we are permitted to change it, do so */
1552         if (!ast_strlen_zero(request_user)) {
1553                 pjsip_sip_uri *sip_uri;
1554
1555                 if (PJSIP_URI_SCHEME_IS_SIP(dlg->target) || PJSIP_URI_SCHEME_IS_SIPS(dlg->target)) {
1556                         sip_uri = pjsip_uri_get_uri(dlg->target);
1557                         pj_strdup2(dlg->pool, &sip_uri->user, request_user);
1558                 }
1559                 if (PJSIP_URI_SCHEME_IS_SIP(dlg->remote.info->uri) || PJSIP_URI_SCHEME_IS_SIPS(dlg->remote.info->uri)) {
1560                         sip_uri = pjsip_uri_get_uri(dlg->remote.info->uri);
1561                         pj_strdup2(dlg->pool, &sip_uri->user, request_user);
1562                 }
1563         }
1564
1565         /* We have to temporarily bump up the sess_count here so the dialog is not prematurely destroyed */
1566         dlg->sess_count++;
1567
1568         pjsip_dlg_set_transport(dlg, &selector);
1569
1570         if (!ast_strlen_zero(outbound_proxy)) {
1571                 pjsip_route_hdr route_set, *route;
1572                 static const pj_str_t ROUTE_HNAME = { "Route", 5 };
1573                 pj_str_t tmp;
1574
1575                 pj_list_init(&route_set);
1576
1577                 pj_strdup2_with_null(dlg->pool, &tmp, outbound_proxy);
1578                 if (!(route = pjsip_parse_hdr(dlg->pool, &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL))) {
1579                         dlg->sess_count--;
1580                         pjsip_dlg_terminate(dlg);
1581                         return NULL;
1582                 }
1583                 pj_list_insert_nodes_before(&route_set, route);
1584
1585                 pjsip_dlg_set_route_set(dlg, &route_set);
1586         }
1587
1588         dlg->sess_count--;
1589
1590         return dlg;
1591 }
1592
1593 pjsip_dialog *ast_sip_create_dialog_uas(const struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
1594 {
1595         pjsip_dialog *dlg;
1596         pj_str_t contact;
1597         pjsip_transport_type_e type = rdata->tp_info.transport->key.type;
1598         pj_status_t status;
1599
1600         contact.ptr = pj_pool_alloc(rdata->tp_info.pool, PJSIP_MAX_URL_SIZE);
1601         contact.slen = pj_ansi_snprintf(contact.ptr, PJSIP_MAX_URL_SIZE,
1602                         "<sip:%s%.*s%s:%d%s%s>",
1603                         (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
1604                         (int)rdata->tp_info.transport->local_name.host.slen,
1605                         rdata->tp_info.transport->local_name.host.ptr,
1606                         (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
1607                         rdata->tp_info.transport->local_name.port,
1608                         (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
1609                         (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
1610
1611         status = pjsip_dlg_create_uas(pjsip_ua_instance(), rdata, &contact, &dlg);
1612         if (status != PJ_SUCCESS) {
1613                 char err[PJ_ERR_MSG_SIZE];
1614
1615                 pj_strerror(status, err, sizeof(err));
1616                 ast_log(LOG_ERROR, "Could not create dialog with endpoint %s. %s\n",
1617                                 ast_sorcery_object_get_id(endpoint), err);
1618                 return NULL;
1619         }
1620
1621         return dlg;
1622 }
1623
1624 int ast_sip_create_rdata(pjsip_rx_data *rdata, char *packet, const char *src_name, int src_port,
1625         char *transport_type, const char *local_name, int local_port)
1626 {
1627         pj_str_t tmp;
1628
1629         rdata->tp_info.transport = PJ_POOL_ZALLOC_T(rdata->tp_info.pool, pjsip_transport);
1630         if (!rdata->tp_info.transport) {
1631                 return -1;
1632         }
1633
1634         ast_copy_string(rdata->pkt_info.packet, packet, sizeof(rdata->pkt_info.packet));
1635         ast_copy_string(rdata->pkt_info.src_name, src_name, sizeof(rdata->pkt_info.src_name));
1636         rdata->pkt_info.src_port = src_port;
1637
1638         pjsip_parse_rdata(packet, strlen(packet), rdata);
1639         if (!rdata->msg_info.msg) {
1640                 return -1;
1641         }
1642
1643         pj_strdup2(rdata->tp_info.pool, &rdata->msg_info.via->recvd_param, rdata->pkt_info.src_name);
1644         rdata->msg_info.via->rport_param = -1;
1645
1646         rdata->tp_info.transport->key.type = pjsip_transport_get_type_from_name(pj_cstr(&tmp, transport_type));
1647         rdata->tp_info.transport->type_name = transport_type;
1648         pj_strdup2(rdata->tp_info.pool, &rdata->tp_info.transport->local_name.host, local_name);
1649         rdata->tp_info.transport->local_name.port = local_port;
1650
1651         return 0;
1652 }
1653
1654 /* PJSIP doesn't know about the INFO method, so we have to define it ourselves */
1655 static const pjsip_method info_method = {PJSIP_OTHER_METHOD, {"INFO", 4} };
1656 static const pjsip_method message_method = {PJSIP_OTHER_METHOD, {"MESSAGE", 7} };
1657
1658 static struct {
1659         const char *method;
1660         const pjsip_method *pmethod;
1661 } methods [] = {
1662         { "INVITE", &pjsip_invite_method },
1663         { "CANCEL", &pjsip_cancel_method },
1664         { "ACK", &pjsip_ack_method },
1665         { "BYE", &pjsip_bye_method },
1666         { "REGISTER", &pjsip_register_method },
1667         { "OPTIONS", &pjsip_options_method },
1668         { "SUBSCRIBE", &pjsip_subscribe_method },
1669         { "NOTIFY", &pjsip_notify_method },
1670         { "PUBLISH", &pjsip_publish_method },
1671         { "INFO", &info_method },
1672         { "MESSAGE", &message_method },
1673 };
1674
1675 static const pjsip_method *get_pjsip_method(const char *method)
1676 {
1677         int i;
1678         for (i = 0; i < ARRAY_LEN(methods); ++i) {
1679                 if (!strcmp(method, methods[i].method)) {
1680                         return methods[i].pmethod;
1681                 }
1682         }
1683         return NULL;
1684 }
1685
1686 static int create_in_dialog_request(const pjsip_method *method, struct pjsip_dialog *dlg, pjsip_tx_data **tdata)
1687 {
1688         if (pjsip_dlg_create_request(dlg, method, -1, tdata) != PJ_SUCCESS) {
1689                 ast_log(LOG_WARNING, "Unable to create in-dialog request.\n");
1690                 return -1;
1691         }
1692
1693         return 0;
1694 }
1695
1696 static pj_bool_t supplement_on_rx_request(pjsip_rx_data *rdata);
1697 static pjsip_module supplement_module = {
1698         .name = { "Out of dialog supplement hook", 29 },
1699         .id = -1,
1700         .priority = PJSIP_MOD_PRIORITY_APPLICATION - 1,
1701         .on_rx_request = supplement_on_rx_request,
1702 };
1703
1704 static int create_out_of_dialog_request(const pjsip_method *method, struct ast_sip_endpoint *endpoint,
1705                 const char *uri, struct ast_sip_contact *provided_contact, pjsip_tx_data **tdata)
1706 {
1707         RAII_VAR(struct ast_sip_contact *, contact, ao2_bump(provided_contact), ao2_cleanup);
1708         pj_str_t remote_uri;
1709         pj_str_t from;
1710         pj_pool_t *pool;
1711         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
1712
1713         if (ast_strlen_zero(uri)) {
1714                 if (!endpoint && !contact) {
1715                         ast_log(LOG_ERROR, "An endpoint and/or uri must be specified\n");
1716                         return -1;
1717                 }
1718
1719                 if (!contact) {
1720                         contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
1721                 }
1722                 if (!contact || ast_strlen_zero(contact->uri)) {
1723                         ast_log(LOG_ERROR, "Unable to retrieve contact for endpoint %s\n",
1724                                         ast_sorcery_object_get_id(endpoint));
1725                         return -1;
1726                 }
1727
1728                 pj_cstr(&remote_uri, contact->uri);
1729         } else {
1730                 pj_cstr(&remote_uri, uri);
1731         }
1732
1733         if (endpoint) {
1734                 if (sip_get_tpselector_from_endpoint(endpoint, &selector)) {
1735                         ast_log(LOG_ERROR, "Unable to retrieve PJSIP transport selector for endpoint %s\n",
1736                                 ast_sorcery_object_get_id(endpoint));
1737                         return -1;
1738                 }
1739         }
1740
1741         pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Outbound request", 256, 256);
1742
1743         if (!pool) {
1744                 ast_log(LOG_ERROR, "Unable to create PJLIB memory pool\n");
1745                 return -1;
1746         }
1747
1748         if (sip_dialog_create_from(pool, &from, endpoint ? endpoint->fromuser : NULL,
1749                                 endpoint ? endpoint->fromdomain : NULL, &remote_uri, &selector)) {
1750                 ast_log(LOG_ERROR, "Unable to create From header for %.*s request to endpoint %s\n",
1751                                 (int) pj_strlen(&method->name), pj_strbuf(&method->name), ast_sorcery_object_get_id(endpoint));
1752                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1753                 return -1;
1754         }
1755
1756         if (pjsip_endpt_create_request(ast_sip_get_pjsip_endpoint(), method, &remote_uri,
1757                         &from, &remote_uri, &from, NULL, -1, NULL, tdata) != PJ_SUCCESS) {
1758                 ast_log(LOG_ERROR, "Unable to create outbound %.*s request to endpoint %s\n",
1759                                 (int) pj_strlen(&method->name), pj_strbuf(&method->name), ast_sorcery_object_get_id(endpoint));
1760                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1761                 return -1;
1762         }
1763
1764         /* If an outbound proxy is specified on the endpoint apply it to this request */
1765         if (endpoint && !ast_strlen_zero(endpoint->outbound_proxy) &&
1766                 ast_sip_set_outbound_proxy((*tdata), endpoint->outbound_proxy)) {
1767                 ast_log(LOG_ERROR, "Unable to apply outbound proxy on request %.*s to endpoint %s\n",
1768                         (int) pj_strlen(&method->name), pj_strbuf(&method->name), ast_sorcery_object_get_id(endpoint));
1769                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1770                 return -1;
1771         }
1772
1773         ast_sip_mod_data_set((*tdata)->pool, (*tdata)->mod_data, supplement_module.id, MOD_DATA_CONTACT, ao2_bump(contact));
1774
1775         /* We can release this pool since request creation copied all the necessary
1776          * data into the outbound request's pool
1777          */
1778         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1779         return 0;
1780 }
1781
1782 int ast_sip_create_request(const char *method, struct pjsip_dialog *dlg,
1783                 struct ast_sip_endpoint *endpoint, const char *uri,
1784                 struct ast_sip_contact *contact, pjsip_tx_data **tdata)
1785 {
1786         const pjsip_method *pmethod = get_pjsip_method(method);
1787
1788         if (!pmethod) {
1789                 ast_log(LOG_WARNING, "Unknown method '%s'. Cannot send request\n", method);
1790                 return -1;
1791         }
1792
1793         if (dlg) {
1794                 return create_in_dialog_request(pmethod, dlg, tdata);
1795         } else {
1796                 return create_out_of_dialog_request(pmethod, endpoint, uri, contact, tdata);
1797         }
1798 }
1799
1800 AST_RWLIST_HEAD_STATIC(supplements, ast_sip_supplement);
1801
1802 int ast_sip_register_supplement(struct ast_sip_supplement *supplement)
1803 {
1804         struct ast_sip_supplement *iter;
1805         int inserted = 0;
1806         SCOPED_LOCK(lock, &supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
1807
1808         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&supplements, iter, next) {
1809                 if (iter->priority > supplement->priority) {
1810                         AST_RWLIST_INSERT_BEFORE_CURRENT(supplement, next);
1811                         inserted = 1;
1812                         break;
1813                 }
1814         }
1815         AST_RWLIST_TRAVERSE_SAFE_END;
1816
1817         if (!inserted) {
1818                 AST_RWLIST_INSERT_TAIL(&supplements, supplement, next);
1819         }
1820         ast_module_ref(ast_module_info->self);
1821         return 0;
1822 }
1823
1824 void ast_sip_unregister_supplement(struct ast_sip_supplement *supplement)
1825 {
1826         struct ast_sip_supplement *iter;
1827         SCOPED_LOCK(lock, &supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
1828         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&supplements, iter, next) {
1829                 if (supplement == iter) {
1830                         AST_RWLIST_REMOVE_CURRENT(next);
1831                         ast_module_unref(ast_module_info->self);
1832                         break;
1833                 }
1834         }
1835         AST_RWLIST_TRAVERSE_SAFE_END;
1836 }
1837
1838 static int send_in_dialog_request(pjsip_tx_data *tdata, struct pjsip_dialog *dlg)
1839 {
1840         if (pjsip_dlg_send_request(dlg, tdata, -1, NULL) != PJ_SUCCESS) {
1841                 ast_log(LOG_WARNING, "Unable to send in-dialog request.\n");
1842                 return -1;
1843         }
1844         return 0;
1845 }
1846
1847 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
1848 {
1849         pj_str_t method;
1850
1851         if (ast_strlen_zero(supplement_method)) {
1852                 return PJ_TRUE;
1853         }
1854
1855         pj_cstr(&method, supplement_method);
1856
1857         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
1858 }
1859
1860 /*! \brief Structure to hold information about an outbound request */
1861 struct send_request_data {
1862         struct ast_sip_endpoint *endpoint;              /*! The endpoint associated with this request */
1863         void *token;                                    /*! Information to be provided to the callback upon receipt of a response */
1864         void (*callback)(void *token, pjsip_event *e);  /*! The callback to be called upon receipt of a response */
1865 };
1866
1867 static void send_request_data_destroy(void *obj)
1868 {
1869         struct send_request_data *req_data = obj;
1870         ao2_cleanup(req_data->endpoint);
1871 }
1872
1873 static struct send_request_data *send_request_data_alloc(struct ast_sip_endpoint *endpoint,
1874         void *token, void (*callback)(void *token, pjsip_event *e))
1875 {
1876         struct send_request_data *req_data = ao2_alloc(sizeof(*req_data), send_request_data_destroy);
1877
1878         if (!req_data) {
1879                 return NULL;
1880         }
1881
1882         req_data->endpoint = ao2_bump(endpoint);
1883         req_data->token = token;
1884         req_data->callback = callback;
1885
1886         return req_data;
1887 }
1888
1889 static void send_request_cb(void *token, pjsip_event *e)
1890 {
1891         RAII_VAR(struct send_request_data *, req_data, token, ao2_cleanup);
1892         pjsip_transaction *tsx = e->body.tsx_state.tsx;
1893         pjsip_rx_data *challenge = e->body.tsx_state.src.rdata;
1894         pjsip_tx_data *tdata;
1895         struct ast_sip_supplement *supplement;
1896
1897         AST_RWLIST_RDLOCK(&supplements);
1898         AST_LIST_TRAVERSE(&supplements, supplement, next) {
1899                 if (supplement->incoming_response && does_method_match(&challenge->msg_info.cseq->method.name, supplement->method)) {
1900                         supplement->incoming_response(req_data->endpoint, challenge);
1901                 }
1902         }
1903         AST_RWLIST_UNLOCK(&supplements);
1904
1905         if ((tsx->status_code == 401 || tsx->status_code == 407)
1906                 && req_data->endpoint
1907                 && !ast_sip_create_request_with_auth(&req_data->endpoint->outbound_auths, challenge, tsx, &tdata)
1908                 && pjsip_endpt_send_request(ast_sip_get_pjsip_endpoint(), tdata, -1, req_data->token, req_data->callback)
1909                         == PJ_SUCCESS) {
1910                 return;
1911         }
1912
1913         if (req_data->callback) {
1914                 req_data->callback(req_data->token, e);
1915         }
1916 }
1917
1918 static int send_out_of_dialog_request(pjsip_tx_data *tdata, struct ast_sip_endpoint *endpoint,
1919         void *token, void (*callback)(void *token, pjsip_event *e))
1920 {
1921         struct ast_sip_supplement *supplement;
1922         struct send_request_data *req_data = send_request_data_alloc(endpoint, token, callback);
1923         struct ast_sip_contact *contact = ast_sip_mod_data_get(tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT);
1924
1925         if (!req_data) {
1926                 pjsip_tx_data_dec_ref(tdata);
1927                 return -1;
1928         }
1929
1930         AST_RWLIST_RDLOCK(&supplements);
1931         AST_LIST_TRAVERSE(&supplements, supplement, next) {
1932                 if (supplement->outgoing_request && does_method_match(&tdata->msg->line.req.method.name, supplement->method)) {
1933                         supplement->outgoing_request(endpoint, contact, tdata);
1934                 }
1935         }
1936         AST_RWLIST_UNLOCK(&supplements);
1937
1938         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT, NULL);
1939         ao2_cleanup(contact);
1940
1941         if (pjsip_endpt_send_request(ast_sip_get_pjsip_endpoint(), tdata, -1, req_data, send_request_cb) != PJ_SUCCESS) {
1942                 ast_log(LOG_ERROR, "Error attempting to send outbound %.*s request to endpoint %s\n",
1943                                 (int) pj_strlen(&tdata->msg->line.req.method.name),
1944                                 pj_strbuf(&tdata->msg->line.req.method.name),
1945                                 endpoint ? ast_sorcery_object_get_id(endpoint) : "<unknown>");
1946                 ao2_cleanup(req_data);
1947                 return -1;
1948         }
1949
1950         return 0;
1951 }
1952
1953 int ast_sip_send_request(pjsip_tx_data *tdata, struct pjsip_dialog *dlg,
1954         struct ast_sip_endpoint *endpoint, void *token,
1955         void (*callback)(void *token, pjsip_event *e))
1956 {
1957         ast_assert(tdata->msg->type == PJSIP_REQUEST_MSG);
1958
1959         if (dlg) {
1960                 return send_in_dialog_request(tdata, dlg);
1961         } else {
1962                 return send_out_of_dialog_request(tdata, endpoint, token, callback);
1963         }
1964 }
1965
1966 int ast_sip_set_outbound_proxy(pjsip_tx_data *tdata, const char *proxy)
1967 {
1968         pjsip_route_hdr *route;
1969         static const pj_str_t ROUTE_HNAME = { "Route", 5 };
1970         pj_str_t tmp;
1971
1972         pj_strdup2_with_null(tdata->pool, &tmp, proxy);
1973         if (!(route = pjsip_parse_hdr(tdata->pool, &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL))) {
1974                 return -1;
1975         }
1976
1977         pj_list_insert_nodes_before(&tdata->msg->hdr, (pjsip_hdr*)route);
1978
1979         return 0;
1980 }
1981
1982 int ast_sip_add_header(pjsip_tx_data *tdata, const char *name, const char *value)
1983 {
1984         pj_str_t hdr_name;
1985         pj_str_t hdr_value;
1986         pjsip_generic_string_hdr *hdr;
1987
1988         pj_cstr(&hdr_name, name);
1989         pj_cstr(&hdr_value, value);
1990
1991         hdr = pjsip_generic_string_hdr_create(tdata->pool, &hdr_name, &hdr_value);
1992
1993         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *) hdr);
1994         return 0;
1995 }
1996
1997 static pjsip_msg_body *ast_body_to_pjsip_body(pj_pool_t *pool, const struct ast_sip_body *body)
1998 {
1999         pj_str_t type;
2000         pj_str_t subtype;
2001         pj_str_t body_text;
2002
2003         pj_cstr(&type, body->type);
2004         pj_cstr(&subtype, body->subtype);
2005         pj_cstr(&body_text, body->body_text);
2006
2007         return pjsip_msg_body_create(pool, &type, &subtype, &body_text);
2008 }
2009
2010 int ast_sip_add_body(pjsip_tx_data *tdata, const struct ast_sip_body *body)
2011 {
2012         pjsip_msg_body *pjsip_body = ast_body_to_pjsip_body(tdata->pool, body);
2013         tdata->msg->body = pjsip_body;
2014         return 0;
2015 }
2016
2017 int ast_sip_add_body_multipart(pjsip_tx_data *tdata, const struct ast_sip_body *bodies[], int num_bodies)
2018 {
2019         int i;
2020         /* NULL for type and subtype automatically creates "multipart/mixed" */
2021         pjsip_msg_body *body = pjsip_multipart_create(tdata->pool, NULL, NULL);
2022
2023         for (i = 0; i < num_bodies; ++i) {
2024                 pjsip_multipart_part *part = pjsip_multipart_create_part(tdata->pool);
2025                 part->body = ast_body_to_pjsip_body(tdata->pool, bodies[i]);
2026                 pjsip_multipart_add_part(tdata->pool, body, part);
2027         }
2028
2029         tdata->msg->body = body;
2030         return 0;
2031 }
2032
2033 int ast_sip_append_body(pjsip_tx_data *tdata, const char *body_text)
2034 {
2035         size_t combined_size = strlen(body_text) + tdata->msg->body->len;
2036         struct ast_str *body_buffer = ast_str_alloca(combined_size);
2037
2038         ast_str_set(&body_buffer, 0, "%.*s%s", (int) tdata->msg->body->len, (char *) tdata->msg->body->data, body_text);
2039
2040         tdata->msg->body->data = pj_pool_alloc(tdata->pool, combined_size);
2041         pj_memcpy(tdata->msg->body->data, ast_str_buffer(body_buffer), combined_size);
2042         tdata->msg->body->len = combined_size;
2043
2044         return 0;
2045 }
2046
2047 struct ast_taskprocessor *ast_sip_create_serializer(void)
2048 {
2049         struct ast_taskprocessor *serializer;
2050         RAII_VAR(struct ast_uuid *, uuid, ast_uuid_generate(), ast_free_ptr);
2051         char name[AST_UUID_STR_LEN];
2052
2053         if (!uuid) {
2054                 return NULL;
2055         }
2056
2057         ast_uuid_to_str(uuid, name, sizeof(name));
2058
2059         serializer = ast_threadpool_serializer(name, sip_threadpool);
2060         if (!serializer) {
2061                 return NULL;
2062         }
2063         return serializer;
2064 }
2065
2066 int ast_sip_push_task(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
2067 {
2068         if (serializer) {
2069                 return ast_taskprocessor_push(serializer, sip_task, task_data);
2070         } else {
2071                 return ast_threadpool_push(sip_threadpool, sip_task, task_data);
2072         }
2073 }
2074
2075 struct sync_task_data {
2076         ast_mutex_t lock;
2077         ast_cond_t cond;
2078         int complete;
2079         int fail;
2080         int (*task)(void *);
2081         void *task_data;
2082 };
2083
2084 static int sync_task(void *data)
2085 {
2086         struct sync_task_data *std = data;
2087         std->fail = std->task(std->task_data);
2088
2089         ast_mutex_lock(&std->lock);
2090         std->complete = 1;
2091         ast_cond_signal(&std->cond);
2092         ast_mutex_unlock(&std->lock);
2093         return std->fail;
2094 }
2095
2096 int ast_sip_push_task_synchronous(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
2097 {
2098         /* This method is an onion */
2099         struct sync_task_data std;
2100
2101         if (ast_sip_thread_is_servant()) {
2102                 return sip_task(task_data);
2103         }
2104
2105         ast_mutex_init(&std.lock);
2106         ast_cond_init(&std.cond, NULL);
2107         std.fail = std.complete = 0;
2108         std.task = sip_task;
2109         std.task_data = task_data;
2110
2111         if (serializer) {
2112                 if (ast_taskprocessor_push(serializer, sync_task, &std)) {
2113                         return -1;
2114                 }
2115         } else {
2116                 if (ast_threadpool_push(sip_threadpool, sync_task, &std)) {
2117                         return -1;
2118                 }
2119         }
2120
2121         ast_mutex_lock(&std.lock);
2122         while (!std.complete) {
2123                 ast_cond_wait(&std.cond, &std.lock);
2124         }
2125         ast_mutex_unlock(&std.lock);
2126
2127         ast_mutex_destroy(&std.lock);
2128         ast_cond_destroy(&std.cond);
2129         return std.fail;
2130 }
2131
2132 void ast_copy_pj_str(char *dest, const pj_str_t *src, size_t size)
2133 {
2134         size_t chars_to_copy = MIN(size - 1, pj_strlen(src));
2135         memcpy(dest, pj_strbuf(src), chars_to_copy);
2136         dest[chars_to_copy] = '\0';
2137 }
2138
2139 int ast_sip_is_content_type(pjsip_media_type *content_type, char *type, char *subtype)
2140 {
2141         pjsip_media_type compare;
2142
2143         if (!content_type) {
2144                 return 0;
2145         }
2146
2147         pjsip_media_type_init2(&compare, type, subtype);
2148
2149         return pjsip_media_type_cmp(content_type, &compare, 0) ? 0 : -1;
2150 }
2151
2152 pj_caching_pool caching_pool;
2153 pj_pool_t *memory_pool;
2154 pj_thread_t *monitor_thread;
2155 static int monitor_continue;
2156
2157 static void *monitor_thread_exec(void *endpt)
2158 {
2159         while (monitor_continue) {
2160                 const pj_time_val delay = {0, 10};
2161                 pjsip_endpt_handle_events(ast_pjsip_endpoint, &delay);
2162         }
2163         return NULL;
2164 }
2165
2166 static void stop_monitor_thread(void)
2167 {
2168         monitor_continue = 0;
2169         pj_thread_join(monitor_thread);
2170 }
2171
2172 AST_THREADSTORAGE(pj_thread_storage);
2173 AST_THREADSTORAGE(servant_id_storage);
2174 #define SIP_SERVANT_ID 0x5E2F1D
2175
2176 static void sip_thread_start(void)
2177 {
2178         pj_thread_desc *desc;
2179         pj_thread_t *thread;
2180         uint32_t *servant_id;
2181
2182         servant_id = ast_threadstorage_get(&servant_id_storage, sizeof(*servant_id));
2183         if (!servant_id) {
2184                 ast_log(LOG_ERROR, "Could not set SIP servant ID in thread-local storage.\n");
2185                 return;
2186         }
2187         *servant_id = SIP_SERVANT_ID;
2188
2189         desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
2190         if (!desc) {
2191                 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
2192                 return;
2193         }
2194         pj_bzero(*desc, sizeof(*desc));
2195
2196         if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
2197                 ast_log(LOG_ERROR, "Couldn't register thread with PJLIB.\n");
2198         }
2199 }
2200
2201 int ast_sip_thread_is_servant(void)
2202 {
2203         uint32_t *servant_id;
2204
2205         if (monitor_thread &&
2206                         pthread_self() == *(pthread_t *)pj_thread_get_os_handle(monitor_thread)) {
2207                 return 1;
2208         }
2209
2210         servant_id = ast_threadstorage_get(&servant_id_storage, sizeof(*servant_id));
2211         if (!servant_id) {
2212                 return 0;
2213         }
2214
2215         return *servant_id == SIP_SERVANT_ID;
2216 }
2217
2218 void *ast_sip_dict_get(void *ht, const char *key)
2219 {
2220         unsigned int hval = 0;
2221
2222         if (!ht) {
2223                 return NULL;
2224         }
2225
2226         return pj_hash_get(ht, key, PJ_HASH_KEY_STRING, &hval);
2227 }
2228
2229 void *ast_sip_dict_set(pj_pool_t* pool, void *ht,
2230                        const char *key, void *val)
2231 {
2232         if (!ht) {
2233                 ht = pj_hash_create(pool, 11);
2234         }
2235
2236         pj_hash_set(pool, ht, key, PJ_HASH_KEY_STRING, 0, val);
2237
2238         return ht;
2239 }
2240
2241 static pj_bool_t supplement_on_rx_request(pjsip_rx_data *rdata)
2242 {
2243         struct ast_sip_supplement *supplement;
2244
2245         if (pjsip_rdata_get_dlg(rdata)) {
2246                 return PJ_FALSE;
2247         }
2248
2249         AST_RWLIST_RDLOCK(&supplements);
2250         AST_LIST_TRAVERSE(&supplements, supplement, next) {
2251                 if (supplement->incoming_request && does_method_match(&rdata->msg_info.msg->line.req.method.name, supplement->method)) {
2252                         supplement->incoming_request(ast_pjsip_rdata_get_endpoint(rdata), rdata);
2253                 }
2254         }
2255         AST_RWLIST_UNLOCK(&supplements);
2256
2257         return PJ_FALSE;
2258 }
2259
2260 int ast_sip_send_response(pjsip_response_addr *res_addr, pjsip_tx_data *tdata, struct ast_sip_endpoint *sip_endpoint)
2261 {
2262         struct ast_sip_supplement *supplement;
2263         pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
2264         struct ast_sip_contact *contact = ast_sip_mod_data_get(tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT);
2265
2266         AST_RWLIST_RDLOCK(&supplements);
2267         AST_LIST_TRAVERSE(&supplements, supplement, next) {
2268                 if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
2269                         supplement->outgoing_response(sip_endpoint, contact, tdata);
2270                 }
2271         }
2272         AST_RWLIST_UNLOCK(&supplements);
2273
2274         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT, NULL);
2275         ao2_cleanup(contact);
2276
2277         return pjsip_endpt_send_response(ast_sip_get_pjsip_endpoint(), res_addr, tdata, NULL, NULL);
2278 }
2279
2280 int ast_sip_create_response(const pjsip_rx_data *rdata, int st_code,
2281         struct ast_sip_contact *contact, pjsip_tx_data **tdata)
2282 {
2283         int res = pjsip_endpt_create_response(ast_sip_get_pjsip_endpoint(), rdata, st_code, NULL, tdata);
2284
2285         if (!res) {
2286                 ast_sip_mod_data_set((*tdata)->pool, (*tdata)->mod_data, supplement_module.id, MOD_DATA_CONTACT, ao2_bump(contact));
2287         }
2288
2289         return res;
2290 }
2291
2292 static void remove_request_headers(pjsip_endpoint *endpt)
2293 {
2294         const pjsip_hdr *request_headers = pjsip_endpt_get_request_headers(endpt);
2295         pjsip_hdr *iter = request_headers->next;
2296
2297         while (iter != request_headers) {
2298                 pjsip_hdr *to_erase = iter;
2299                 iter = iter->next;
2300                 pj_list_erase(to_erase);
2301         }
2302 }
2303
2304 /*!
2305  * \internal
2306  * \brief Reload configuration within a PJSIP thread
2307  */
2308 static int reload_configuration_task(void *obj)
2309 {
2310         ast_res_pjsip_reload_configuration();
2311         ast_res_pjsip_init_options_handling(1);
2312         ast_sip_initialize_dns();
2313         return 0;
2314 }
2315
2316 static int load_module(void)
2317 {
2318         /* The third parameter is just copied from
2319          * example code from PJLIB. This can be adjusted
2320          * if necessary.
2321          */
2322         pj_status_t status;
2323         struct ast_threadpool_options options;
2324
2325         if (pj_init() != PJ_SUCCESS) {
2326                 return AST_MODULE_LOAD_DECLINE;
2327         }
2328
2329         if (pjlib_util_init() != PJ_SUCCESS) {
2330                 pj_shutdown();
2331                 return AST_MODULE_LOAD_DECLINE;
2332         }
2333
2334         pj_caching_pool_init(&caching_pool, NULL, 1024 * 1024);
2335         if (pjsip_endpt_create(&caching_pool.factory, "SIP", &ast_pjsip_endpoint) != PJ_SUCCESS) {
2336                 ast_log(LOG_ERROR, "Failed to create PJSIP endpoint structure. Aborting load\n");
2337                 pj_caching_pool_destroy(&caching_pool);
2338                 return AST_MODULE_LOAD_DECLINE;
2339         }
2340
2341         /* PJSIP will automatically try to add a Max-Forwards header. Since we want to control that,
2342          * we need to stop PJSIP from doing it automatically
2343          */
2344         remove_request_headers(ast_pjsip_endpoint);
2345
2346         memory_pool = pj_pool_create(&caching_pool.factory, "SIP", 1024, 1024, NULL);
2347         if (!memory_pool) {
2348                 ast_log(LOG_ERROR, "Failed to create memory pool for SIP. Aborting load\n");
2349                 pjsip_endpt_destroy(ast_pjsip_endpoint);
2350                 ast_pjsip_endpoint = NULL;
2351                 pj_caching_pool_destroy(&caching_pool);
2352                 return AST_MODULE_LOAD_DECLINE;
2353         }
2354
2355         if (ast_sip_initialize_system()) {
2356                 ast_log(LOG_ERROR, "Failed to initialize SIP 'system' configuration section. Aborting load\n");
2357                 pj_pool_release(memory_pool);
2358                 memory_pool = NULL;
2359                 pjsip_endpt_destroy(ast_pjsip_endpoint);
2360                 ast_pjsip_endpoint = NULL;
2361                 pj_caching_pool_destroy(&caching_pool);
2362                 return AST_MODULE_LOAD_DECLINE;
2363         }
2364
2365         sip_get_threadpool_options(&options);
2366         options.thread_start = sip_thread_start;
2367         sip_threadpool = ast_threadpool_create("SIP", NULL, &options);
2368         if (!sip_threadpool) {
2369                 ast_log(LOG_ERROR, "Failed to create SIP threadpool. Aborting load\n");
2370                 ast_sip_destroy_system();
2371                 pj_pool_release(memory_pool);
2372                 memory_pool = NULL;
2373                 pjsip_endpt_destroy(ast_pjsip_endpoint);
2374                 ast_pjsip_endpoint = NULL;
2375                 pj_caching_pool_destroy(&caching_pool);
2376                 return AST_MODULE_LOAD_DECLINE;
2377         }
2378
2379         ast_sip_initialize_dns();
2380
2381         pjsip_tsx_layer_init_module(ast_pjsip_endpoint);
2382         pjsip_ua_init_module(ast_pjsip_endpoint, NULL);
2383
2384         monitor_continue = 1;
2385         status = pj_thread_create(memory_pool, "SIP", (pj_thread_proc *) &monitor_thread_exec,
2386                         NULL, PJ_THREAD_DEFAULT_STACK_SIZE * 2, 0, &monitor_thread);
2387         if (status != PJ_SUCCESS) {
2388                 ast_log(LOG_ERROR, "Failed to start SIP monitor thread. Aborting load\n");
2389                 ast_sip_destroy_system();
2390                 pj_pool_release(memory_pool);
2391                 memory_pool = NULL;
2392                 pjsip_endpt_destroy(ast_pjsip_endpoint);
2393                 ast_pjsip_endpoint = NULL;
2394                 pj_caching_pool_destroy(&caching_pool);
2395                 return AST_MODULE_LOAD_DECLINE;
2396         }
2397
2398         ast_sip_initialize_global_headers();
2399
2400         if (ast_res_pjsip_initialize_configuration(ast_module_info)) {
2401                 ast_log(LOG_ERROR, "Failed to initialize SIP configuration. Aborting load\n");
2402                 ast_sip_destroy_global_headers();
2403                 stop_monitor_thread();
2404                 ast_sip_destroy_system();
2405                 pj_pool_release(memory_pool);
2406                 memory_pool = NULL;
2407                 pjsip_endpt_destroy(ast_pjsip_endpoint);
2408                 ast_pjsip_endpoint = NULL;
2409                 pj_caching_pool_destroy(&caching_pool);
2410                 return AST_MODULE_LOAD_DECLINE;
2411         }
2412
2413         if (ast_sip_initialize_distributor()) {
2414                 ast_log(LOG_ERROR, "Failed to register distributor module. Aborting load\n");
2415                 ast_res_pjsip_destroy_configuration();
2416                 ast_sip_destroy_global_headers();
2417                 stop_monitor_thread();
2418                 ast_sip_destroy_system();
2419                 pj_pool_release(memory_pool);
2420                 memory_pool = NULL;
2421                 pjsip_endpt_destroy(ast_pjsip_endpoint);
2422                 ast_pjsip_endpoint = NULL;
2423                 pj_caching_pool_destroy(&caching_pool);
2424                 return AST_MODULE_LOAD_DECLINE;
2425         }
2426
2427         if (ast_sip_register_service(&supplement_module)) {
2428                 ast_log(LOG_ERROR, "Failed to initialize supplement hooks. Aborting load\n");
2429                 ast_sip_destroy_distributor();
2430                 ast_res_pjsip_destroy_configuration();
2431                 ast_sip_destroy_global_headers();
2432                 stop_monitor_thread();
2433                 ast_sip_destroy_system();
2434                 pj_pool_release(memory_pool);
2435                 memory_pool = NULL;
2436                 pjsip_endpt_destroy(ast_pjsip_endpoint);
2437                 ast_pjsip_endpoint = NULL;
2438                 pj_caching_pool_destroy(&caching_pool);
2439                 return AST_MODULE_LOAD_DECLINE;
2440         }
2441
2442         if (ast_sip_initialize_outbound_authentication()) {
2443                 ast_log(LOG_ERROR, "Failed to initialize outbound authentication. Aborting load\n");
2444                 ast_sip_unregister_service(&supplement_module);
2445                 ast_sip_destroy_distributor();
2446                 ast_res_pjsip_destroy_configuration();
2447                 ast_sip_destroy_global_headers();
2448                 stop_monitor_thread();
2449                 ast_sip_destroy_system();
2450                 pj_pool_release(memory_pool);
2451                 memory_pool = NULL;
2452                 pjsip_endpt_destroy(ast_pjsip_endpoint);
2453                 ast_pjsip_endpoint = NULL;
2454                 pj_caching_pool_destroy(&caching_pool);
2455                 return AST_MODULE_LOAD_DECLINE;
2456         }
2457
2458         ast_res_pjsip_init_options_handling(0);
2459
2460         ast_module_ref(ast_module_info->self);
2461
2462         return AST_MODULE_LOAD_SUCCESS;
2463 }
2464
2465 static int reload_module(void)
2466 {
2467         if (ast_sip_push_task(NULL, reload_configuration_task, NULL)) {
2468                 ast_log(LOG_WARNING, "Failed to reload PJSIP\n");
2469                 return -1;
2470         }
2471
2472         return 0;
2473 }
2474
2475 static int unload_module(void)
2476 {
2477         /* This will never get called as this module can't be unloaded */
2478         return 0;
2479 }
2480
2481 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Basic SIP resource",
2482                 .load = load_module,
2483                 .unload = unload_module,
2484                 .reload = reload_module,
2485                 .load_pri = AST_MODPRI_CHANNEL_DEPEND - 5,
2486 );