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