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