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