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