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