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