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