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