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