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