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