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