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