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