Add base XML documentation for res_sip
[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                                 </description>
66                                 <configOption name="100rel" default="yes">
67                                         <synopsis>Allow support for RFC3262 provisional ACK tags</synopsis>
68                                         <description>
69                                                 <enumlist>
70                                                         <enum name="no" />
71                                                         <enum name="required" />
72                                                         <enum name="yes" />
73                                                 </enumlist>
74                                         </description>
75                                 </configOption>
76                                 <configOption name="aggregate_mwi" default="yes">
77                                         <synopsis></synopsis>
78                                         <description><para>When enabled, <replaceable>aggregate_mwi</replaceable> condenses message
79                                         waiting notifications from multiple mailboxes into a single NOTIFY. If it is disabled,
80                                         individual NOTIFYs are sent for each mailbox.</para></description>
81                                 </configOption>
82                                 <configOption name="allow">
83                                         <synopsis>Media Codec(s) to allow</synopsis>
84                                 </configOption>
85                                 <configOption name="aors">
86                                         <synopsis>AoR(s) to be used with the endpoint</synopsis>
87                                         <description><para>
88                                                 List of comma separated AoRs that the endpoint should be associated with.
89                                         </para></description>
90                                 </configOption>
91                                 <configOption name="auth">
92                                         <synopsis>Authentication Object(s) associated with the endpoint</synopsis>
93                                         <description><para>
94                                                 This is a comma-delimited list of <replaceable>auth</replaceable> sections defined
95                                                 in <filename>res_sip.conf</filename> to be used to verify inbound connection attempts.
96                                                 </para><para>
97                                                 Endpoints without an <literal>authentication</literal> object
98                                                 configured will allow connections without vertification.
99                                         </para></description>
100                                 </configOption>
101                                 <configOption name="callerid">
102                                         <synopsis>CallerID information for the endpoint</synopsis>
103                                         <description><para>
104                                                 Must be in the format <literal>Name &lt;Number&gt;</literal>,
105                                                 or only <literal>&lt;Number&gt;</literal>.
106                                         </para></description>
107                                 </configOption>
108                                 <configOption name="callerid_privacy">
109                                         <synopsis>Default privacy level</synopsis>
110                                         <description>
111                                                 <enumlist>
112                                                         <enum name="allowed_not_screened" />
113                                                         <enum name="allowed_passed_screened" />
114                                                         <enum name="allowed_failed_screened" />
115                                                         <enum name="allowed" />
116                                                         <enum name="prohib_not_screened" />
117                                                         <enum name="prohib_passed_screened" />
118                                                         <enum name="prohib_failed_screened" />
119                                                         <enum name="prohib" />
120                                                         <enum name="unavailable" />
121                                                 </enumlist>
122                                         </description>
123                                 </configOption>
124                                 <configOption name="callerid_tag">
125                                         <synopsis>Internal id_tag for the endpoint</synopsis>
126                                 </configOption>
127                                 <configOption name="context">
128                                         <synopsis>Dialplan context for inbound sessions</synopsis>
129                                 </configOption>
130                                 <configOption name="direct_media_glare_mitigation" default="none">
131                                         <synopsis>Mitigation of direct media (re)INVITE glare</synopsis>
132                                         <description>
133                                                 <para>
134                                                 This setting attempts to avoid creating INVITE glare scenarios
135                                                 by disabling direct media reINVITEs in one direction thereby allowing
136                                                 designated servers (according to this option) to initiate direct
137                                                 media reINVITEs without contention and significantly reducing call
138                                                 setup time.
139                                                 </para>
140                                                 <para>
141                                                 A more detailed description of how this option functions can be found on
142                                                 the Asterisk wiki https://wiki.asterisk.org/wiki/display/AST/SIP+Direct+Media+Reinvite+Glare+Avoidance
143                                                 </para>
144                                                 <enumlist>
145                                                         <enum name="none" />
146                                                         <enum name="outgoing" />
147                                                         <enum name="incoming" />
148                                                 </enumlist>
149                                         </description>
150                                 </configOption>
151                                 <configOption name="direct_media_method" default="invite">
152                                         <synopsis>Direct Media method type</synopsis>
153                                         <description>
154                                                 <para>Method for setting up Direct Media between endpoints.</para>
155                                                 <enumlist>
156                                                         <enum name="invite" />
157                                                         <enum name="reinvite">
158                                                                 <para>Alias for the <literal>invite</literal> value.</para>
159                                                         </enum>
160                                                         <enum name="update" />
161                                                 </enumlist>
162                                         </description>
163                                 </configOption>
164                                 <configOption name="direct_media" default="yes">
165                                         <synopsis>Determines whether media may flow directly between endpoints.</synopsis>
166                                 </configOption>
167                                 <configOption name="disable_direct_media_on_nat" default="no">
168                                         <synopsis>Disable direct media session refreshes when NAT obstructs the media session</synopsis>
169                                 </configOption>
170                                 <configOption name="disallow">
171                                         <synopsis>Media Codec(s) to disallow</synopsis>
172                                 </configOption>
173                                 <configOption name="dtmfmode" default="rfc4733">
174                                         <synopsis>DTMF mode</synopsis>
175                                         <description>
176                                                 <para>This setting allows to choose the DTMF mode for endpoint communication.</para>
177                                                 <enumlist>
178                                                         <enum name="rfc4733">
179                                                                 <para>DTMF is sent out of band of the main audio stream.This
180                                                                 supercedes the older <emphasis>RFC-2833</emphasis> used within
181                                                                 the older <literal>chan_sip</literal>.</para>
182                                                         </enum>
183                                                         <enum name="inband">
184                                                                 <para>DTMF is sent as part of audio stream.</para>
185                                                         </enum>
186                                                         <enum name="info">
187                                                                 <para>DTMF is sent as SIP INFO packets.</para>
188                                                         </enum>
189                                                 </enumlist>
190                                         </description>
191                                 </configOption>
192                                 <configOption name="external_media_address">
193                                         <synopsis>IP used for External Media handling</synopsis>
194                                 </configOption>
195                                 <configOption name="force_rport" default="yes">
196                                         <synopsis>Force use of return port</synopsis>
197                                 </configOption>
198                                 <configOption name="ice_support" default="no">
199                                         <synopsis>Enable the ICE mechanism to help traverse NAT</synopsis>
200                                 </configOption>
201                                 <configOption name="identify_by" default="username,location">
202                                         <synopsis>Way(s) for Endpoint to be identified</synopsis>
203                                         <description><para>
204                                                 There are currently two methods to identify an endpoint. By default
205                                                 both are used to identify an endpoint.
206                                                 </para>
207                                                 <enumlist>
208                                                         <enum name="username" />
209                                                         <enum name="location" />
210                                                         <enum name="username,location" />
211                                                 </enumlist>
212                                         </description>
213                                 </configOption>
214                                 <configOption name="mailboxes">
215                                         <synopsis>Mailbox(es) to be associated with</synopsis>
216                                 </configOption>
217                                 <configOption name="mohsuggest" default="default">
218                                         <synopsis>Default Music On Hold class</synopsis>
219                                 </configOption>
220                                 <configOption name="outbound_auth">
221                                         <synopsis>Authentication object used for outbound requests</synopsis>
222                                 </configOption>
223                                 <configOption name="outbound_proxy">
224                                         <synopsis>Proxy through which to send requests</synopsis>
225                                 </configOption>
226                                 <configOption name="qualify_frequency" default="0">
227                                         <synopsis>Interval at which to qualify an endpoint</synopsis>
228                                         <description><para>
229                                                 Interval between attempts to qualify the endpoint for reachability.
230                                                 If <literal>0</literal> never qualify. Time in seconds.
231                                         </para></description>
232                                 </configOption>
233                                 <configOption name="rewrite_contact">
234                                         <synopsis>Allow Contact header to be rewritten with the source IP address-port</synopsis>
235                                 </configOption>
236                                 <configOption name="rtp_ipv6" default="no">
237                                         <synopsis>Allow use of IPv6 for RTP traffic</synopsis>
238                                 </configOption>
239                                 <configOption name="rtp_symmetric" default="no">
240                                         <synopsis>Enforce that RTP must be symmetric</synopsis>
241                                 </configOption>
242                                 <configOption name="send_pai" default="no">
243                                         <synopsis>Send the P-Asserted-Identity header</synopsis>
244                                 </configOption>
245                                 <configOption name="send_rpid" default="no">
246                                         <synopsis>Send the Remote-Party-ID header</synopsis>
247                                 </configOption>
248                                 <configOption name="timers_min_se" default="90">
249                                         <synopsis>Minimum session timers expiration period</synopsis>
250                                         <description><para>
251                                                 Minimium session timer expiration period. Time in seconds.
252                                         </para></description>
253                                 </configOption>
254                                 <configOption name="timers" default="yes">
255                                         <synopsis>Session timers for SIP packets</synopsis>
256                                         <description>
257                                                 <enumlist>
258                                                         <enum name="forced" />
259                                                         <enum name="no" />
260                                                         <enum name="required" />
261                                                         <enum name="yes" />
262                                                 </enumlist>
263                                         </description>
264                                 </configOption>
265                                 <configOption name="timers_sess_expires" default="1800">
266                                         <synopsis>Maximum session timer expiration period</synopsis>
267                                         <description><para>
268                                                 Maximium session timer expiration period. Time in seconds.
269                                         </para></description>
270                                 </configOption>
271                                 <configOption name="transport">
272                                         <synopsis>Desired transport configuration</synopsis>
273                                         <description><para>
274                                                 This will set the desired transport configuration to send SIP data through.
275                                                 </para>
276                                                 <warning><para>Not specifying a transport will <emphasis>DEFAULT</emphasis>
277                                                 to the first configured transport in <filename>res_sip.conf</filename> which is
278                                                 valid for the URI we are trying to contact.
279                                                 </para></warning>
280                                         </description>
281                                 </configOption>
282                                 <configOption name="trust_id_inbound" default="no">
283                                         <synopsis>Trust inbound CallerID information from endpoint</synopsis>
284                                         <description><para>This option determines whether res_sip will accept identification from the endpoint
285                                         received in a P-Asserted-Identity or Remote-Party-ID header. If <literal>no</literal>,
286                                         the configured Caller-ID from res_sip.conf will always be used as the identity for the
287                                         endpoint.</para></description>
288                                 </configOption>
289                                 <configOption name="trust_id_outbound" default="no">
290                                         <synopsis>Trust endpoint with private CallerID information</synopsis>
291                                         <description><para>This option determines whether res_sip will send identification
292                                         information to the endpoint that has been marked as private. If <literal>no</literal>,
293                                         private Caller-ID information will not be forwarded to the endpoint.</para></description>
294                                 </configOption>
295                                 <configOption name="type">
296                                         <synopsis>Must be of type 'endpoint'.</synopsis>
297                                 </configOption>
298                                 <configOption name="use_ptime" default="no">
299                                         <synopsis>Use Endpoint's requested packetisation interval</synopsis>
300                                 </configOption>
301                         </configObject>
302                         <configObject name="auth">
303                                 <synopsis>Authentication type</synopsis>
304                                 <description><para>
305                                         Authentication objects hold the authenitcation information for use
306                                         by <literal>endpoints</literal>. This also allows for multiple <literal>
307                                         endpoints</literal> to use the same information. Choice of MD5/plaintext
308                                         and setting of username.
309                                 </para></description>
310                                 <configOption name="auth_type" default="userpass">
311                                         <synopsis>Authentication type</synopsis>
312                                         <description><para>
313                                                 This option specifies which of the password style config options should be read,
314                                                 either 'password' or 'md5_cred' when trying to authenticate an endpoint inbound request.
315                                                 </para>
316                                                 <enumlist>
317                                                         <enum name="md5"/>
318                                                         <enum name="userpass"/>
319                                                 </enumlist>
320                                         </description>
321                                 </configOption>
322                                 <configOption name="nonce_lifetime" default="32">
323                                         <synopsis>Lifetime of a nonce associated with this authentication config.</synopsis>
324                                 </configOption>
325                                 <configOption name="md5_cred">
326                                         <synopsis>MD5 Hash used for authentication.</synopsis>
327                                         <description><para>Only used when auth_type is <literal>md5</literal>.</para></description>
328                                 </configOption>
329                                 <configOption name="password">
330                                         <synopsis>PlainText password used for authentication.</synopsis>
331                                         <description><para>Only used when auth_type is <literal>userpass</literal>.</para></description>
332                                 </configOption>
333                                 <configOption name="realm" default="asterisk">
334                                         <synopsis>SIP realm for endpoint</synopsis>
335                                 </configOption>
336                                 <configOption name="type">
337                                         <synopsis>Must be 'auth'</synopsis>
338                                 </configOption>
339                                 <configOption name="username">
340                                         <synopsis>Username to use for account</synopsis>
341                                 </configOption>
342                         </configObject>
343                         <configObject name="nat_hook">
344                                 <synopsis>XXX This exists only to prevent XML documentation errors.</synopsis>
345                                 <configOption name="external_media_address">
346                                         <synopsis>I should be undocumented or hidden</synopsis>
347                                 </configOption>
348                                 <configOption name="method">
349                                         <synopsis>I should be undocumented or hidden</synopsis>
350                                 </configOption>
351                         </configObject>
352                         <configObject name="domain_alias">
353                                 <synopsis>Domain Alias</synopsis>
354                                 <description><para>
355                                         Signifies that a domain is an alias. Used for checking the domain of
356                                         the AoR to which the endpoint is binding.
357                                 </para></description>
358                                 <configOption name="type">
359                                         <synopsis>Must be of type 'domain_alias'.</synopsis>
360                                 </configOption>
361                                 <configOption name="domain">
362                                         <synopsis>Domain to be aliased</synopsis>
363                                 </configOption>
364                         </configObject>
365                         <configObject name="transport">
366                                 <synopsis>SIP Transport</synopsis>
367                                 <description><para>
368                                         <emphasis>Transports</emphasis>
369                                         </para>
370                                         <para>There are different transports and protocol derivatives
371                                                 supported by <literal>res_sip</literal>. They are in order of
372                                                 preference: UDP, TCP, and WebSocket (WS).</para>
373                                         <warning><para>
374                                                 Multiple endpoints using the same connection is <emphasis>NOT</emphasis>
375                                                 supported. Doing so may result in broken calls.
376                                         </para></warning>
377                                 </description>
378                                 <configOption name="async_operations" default="1">
379                                         <synopsis>Number of simultaneous Asynchronous Operations</synopsis>
380                                 </configOption>
381                                 <configOption name="bind">
382                                         <synopsis>IP Address and optional port to bind to for this transport</synopsis>
383                                 </configOption>
384                                 <configOption name="ca_list_file">
385                                         <synopsis>File containing a list of certificates to read (TLS ONLY)</synopsis>
386                                 </configOption>
387                                 <configOption name="cert_file">
388                                         <synopsis>Certificate file for endpoint (TLS ONLY)</synopsis>
389                                 </configOption>
390                                 <configOption name="cipher">
391                                         <synopsis>Preferred Cryptography Cipher (TLS ONLY)</synopsis>
392                                         <description><para>
393                                                 Many options for acceptable ciphers see link for more:
394                                                 http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS
395                                         </para></description>
396                                 </configOption>
397                                 <configOption name="domain">
398                                         <synopsis>Domain the transport comes from</synopsis>
399                                 </configOption>
400                                 <configOption name="external_media_address">
401                                         <synopsis>External Address to use in RTP handling</synopsis>
402                                 </configOption>
403                                 <configOption name="external_signaling_address">
404                                         <synopsis>External address for SIP signalling</synopsis>
405                                 </configOption>
406                                 <configOption name="external_signaling_port" default="0">
407                                         <synopsis>External port for SIP signalling</synopsis>
408                                 </configOption>
409                                 <configOption name="method">
410                                         <synopsis>Method of SSL transport (TLS ONLY)</synopsis>
411                                         <description>
412                                                 <enumlist>
413                                                         <enum name="default" />
414                                                         <enum name="unspecified" />
415                                                         <enum name="tlsv1" />
416                                                         <enum name="sslv2" />
417                                                         <enum name="sslv3" />
418                                                         <enum name="sslv23" />
419                                                 </enumlist>
420                                         </description>
421                                 </configOption>
422                                 <configOption name="localnet">
423                                         <synopsis>Network to consider local (used for NAT purposes).</synopsis>
424                                         <description><para>This must be in CIDR or dotted decimal format with the IP
425                                         and mask separated with a slash ('/').</para></description>
426                                 </configOption>
427                                 <configOption name="password">
428                                         <synopsis>Password required for transport</synopsis>
429                                 </configOption>
430                                 <configOption name="privkey_file">
431                                         <synopsis>Private key file (TLS ONLY)</synopsis>
432                                 </configOption>
433                                 <configOption name="protocol" default="udp">
434                                         <synopsis>Protocol to use for SIP traffic</synopsis>
435                                         <description>
436                                                 <enumlist>
437                                                         <enum name="udp" />
438                                                         <enum name="tcp" />
439                                                         <enum name="tls" />
440                                                 </enumlist>
441                                         </description>
442                                 </configOption>
443                                 <configOption name="require_client_cert" default="false">
444                                         <synopsis>Require client certificate (TLS ONLY)</synopsis>
445                                 </configOption>
446                                 <configOption name="type">
447                                         <synopsis>Must be of type 'transport'.</synopsis>
448                                 </configOption>
449                                 <configOption name="verify_client" default="false">
450                                         <synopsis>Require verification of client certificate (TLS ONLY)</synopsis>
451                                 </configOption>
452                                 <configOption name="verify_server" default="false">
453                                         <synopsis>Require verification of server certificate (TLS ONLY)</synopsis>
454                                 </configOption>
455                         </configObject>
456                         <configObject name="contact">
457                                 <synopsis>A way of creating an aliased name to a SIP URI</synopsis>
458                                 <description><para>
459                                         Contacts are a way to hide SIP URIs from the dialplan directly.
460                                         They are also used to make a group of contactable parties when
461                                         in use with <literal>AoR</literal> lists.
462                                 </para></description>
463                                 <configOption name="type">
464                                         <synopsis>Must be of type 'contact'.</synopsis>
465                                 </configOption>
466                                 <configOption name="uri">
467                                         <synopsis>SIP URI to contact peer</synopsis>
468                                 </configOption>
469                                 <configOption name="expiration_time">
470                                         <synopsis>Time to keep alive a contact</synopsis>
471                                         <description><para>
472                                                 Time to keep alive a contact. String style specification.
473                                         </para></description>
474                                 </configOption>
475                         </configObject>
476                         <configObject name="aor">
477                                 <synopsis>The configuration for a location of an endpoint</synopsis>
478                                 <description><para>
479                                         An AoR is what allows Asterisk to contact an endpoint via res_sip. If no
480                                         AoRs are specified, an endpoint will not be reachable by Asterisk.
481                                         Beyond that, an AoR has other uses within Asterisk.
482                                         </para><para>
483                                         An <literal>AoR</literal> is a way to allow dialing a group
484                                         of <literal>Contacts</literal> that all use the same
485                                         <literal>endpoint</literal> for calls.
486                                         </para><para>
487                                         This can be used as another way of grouping a list of contacts to dial
488                                         rather than specifing them each directly when dialing via the dialplan.
489                                         This must be used in conjuction with the <literal>PJSIP_DIAL_CONTACTS</literal>.
490                                 </para></description>
491                                 <configOption name="contact">
492                                         <synopsis>Permanent contacts assigned to AoR</synopsis>
493                                         <description><para>
494                                                 Contacts included in this list will be called whenever referenced
495                                                 by <literal>chan_pjsip</literal>.
496                                         </para></description>
497                                 </configOption>
498                                 <configOption name="default_expiration" default="3600">
499                                         <synopsis>Default expiration time in seconds for contacts that are dynamically bound to an AoR.</synopsis>
500                                 </configOption>
501                                 <configOption name="mailboxes">
502                                         <synopsis>Mailbox(es) to be associated with</synopsis>
503                                         <description><para>This option applies when an external entity subscribes to an AoR
504                                         for message waiting indications. The mailboxes specified here will be
505                                         subscribed to.</para></description>
506                                 </configOption>
507                                 <configOption name="maximum_expiration" default="7200">
508                                         <synopsis>Maximum time to keep an AoR</synopsis>
509                                         <description><para>
510                                                 Maximium time to keep a peer with explicit expiration. Time in seconds.
511                                         </para></description>
512                                 </configOption>
513                                 <configOption name="max_contacts" default="0">
514                                         <synopsis>Maximum number of contacts that can bind to an AoR</synopsis>
515                                         <description><para>
516                                                 Maximum number of contacts that can associate with this AoR.
517                                                 </para>
518                                                 <note><para>This should be set to <literal>1</literal> and
519                                                 <replaceable>remove_existing</replaceable> set to <literal>yes</literal> if you
520                                                 wish to stick with the older <literal>chan_sip</literal> behaviour.
521                                                 </para></note>
522                                         </description>
523                                 </configOption>
524                                 <configOption name="minimum_expiration" default="60">
525                                         <synopsis>Minimum keep alive time for an AoR</synopsis>
526                                         <description><para>
527                                                 Minimum time to keep a peer with an explict expiration. Time in seconds.
528                                         </para></description>
529                                 </configOption>
530                                 <configOption name="remove_existing" default="no">
531                                         <synopsis>Determines whether new contacts replace existing ones.</synopsis>
532                                         <description><para>
533                                                 On receiving a new registration to the AoR should it remove
534                                                 the existing contact that was registered against it?
535                                                 </para>
536                                                 <note><para>This should be set to <literal>yes</literal> and
537                                                 <replaceable>max_contacts</replaceable> set to <literal>1</literal> if you
538                                                 wish to stick with the older <literal>chan_sip</literal> behaviour.
539                                                 </para></note>
540                                         </description>
541                                 </configOption>
542                                 <configOption name="type">
543                                         <synopsis>Must be of type 'aor'.</synopsis>
544                                 </configOption>
545                         </configObject>
546                 </configFile>
547         </configInfo>
548  ***/
549
550
551 static pjsip_endpoint *ast_pjsip_endpoint;
552
553 static struct ast_threadpool *sip_threadpool;
554
555 static int register_service(void *data)
556 {
557         pjsip_module **module = data;
558         if (!ast_pjsip_endpoint) {
559                 ast_log(LOG_ERROR, "There is no PJSIP endpoint. Unable to register services\n");
560                 return -1;
561         }
562         if (pjsip_endpt_register_module(ast_pjsip_endpoint, *module) != PJ_SUCCESS) {
563                 ast_log(LOG_ERROR, "Unable to register module %.*s\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name));
564                 return -1;
565         }
566         ast_debug(1, "Registered SIP service %.*s (%p)\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name), *module);
567         ast_module_ref(ast_module_info->self);
568         return 0;
569 }
570
571 int ast_sip_register_service(pjsip_module *module)
572 {
573         return ast_sip_push_task_synchronous(NULL, register_service, &module);
574 }
575
576 static int unregister_service(void *data)
577 {
578         pjsip_module **module = data;
579         ast_module_unref(ast_module_info->self);
580         if (!ast_pjsip_endpoint) {
581                 return -1;
582         }
583         pjsip_endpt_unregister_module(ast_pjsip_endpoint, *module);
584         ast_debug(1, "Unregistered SIP service %.*s\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name));
585         return 0;
586 }
587
588 void ast_sip_unregister_service(pjsip_module *module)
589 {
590         ast_sip_push_task_synchronous(NULL, unregister_service, &module);
591 }
592
593 static struct ast_sip_authenticator *registered_authenticator;
594
595 int ast_sip_register_authenticator(struct ast_sip_authenticator *auth)
596 {
597         if (registered_authenticator) {
598                 ast_log(LOG_WARNING, "Authenticator %p is already registered. Cannot register a new one\n", registered_authenticator);
599                 return -1;
600         }
601         registered_authenticator = auth;
602         ast_debug(1, "Registered SIP authenticator module %p\n", auth);
603         ast_module_ref(ast_module_info->self);
604         return 0;
605 }
606
607 void ast_sip_unregister_authenticator(struct ast_sip_authenticator *auth)
608 {
609         if (registered_authenticator != auth) {
610                 ast_log(LOG_WARNING, "Trying to unregister authenticator %p but authenticator %p registered\n",
611                                 auth, registered_authenticator);
612                 return;
613         }
614         registered_authenticator = NULL;
615         ast_debug(1, "Unregistered SIP authenticator %p\n", auth);
616         ast_module_unref(ast_module_info->self);
617 }
618
619 int ast_sip_requires_authentication(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
620 {
621         if (!registered_authenticator) {
622                 ast_log(LOG_WARNING, "No SIP authenticator registered. Assuming authentication is not required\n");
623                 return 0;
624         }
625
626         return registered_authenticator->requires_authentication(endpoint, rdata);
627 }
628
629 enum ast_sip_check_auth_result ast_sip_check_authentication(struct ast_sip_endpoint *endpoint,
630                 pjsip_rx_data *rdata, pjsip_tx_data *tdata)
631 {
632         if (!registered_authenticator) {
633                 ast_log(LOG_WARNING, "No SIP authenticator registered. Assuming authentication is successful\n");
634                 return 0;
635         }
636         return registered_authenticator->check_authentication(endpoint, rdata, tdata);
637 }
638
639 static struct ast_sip_outbound_authenticator *registered_outbound_authenticator;
640
641 int ast_sip_register_outbound_authenticator(struct ast_sip_outbound_authenticator *auth)
642 {
643         if (registered_outbound_authenticator) {
644                 ast_log(LOG_WARNING, "Outbound authenticator %p is already registered. Cannot register a new one\n", registered_outbound_authenticator);
645                 return -1;
646         }
647         registered_outbound_authenticator = auth;
648         ast_debug(1, "Registered SIP outbound authenticator module %p\n", auth);
649         ast_module_ref(ast_module_info->self);
650         return 0;
651 }
652
653 void ast_sip_unregister_outbound_authenticator(struct ast_sip_outbound_authenticator *auth)
654 {
655         if (registered_outbound_authenticator != auth) {
656                 ast_log(LOG_WARNING, "Trying to unregister outbound authenticator %p but outbound authenticator %p registered\n",
657                                 auth, registered_outbound_authenticator);
658                 return;
659         }
660         registered_outbound_authenticator = NULL;
661         ast_debug(1, "Unregistered SIP outbound authenticator %p\n", auth);
662         ast_module_unref(ast_module_info->self);
663 }
664
665 int ast_sip_create_request_with_auth(const char **auths, size_t num_auths, pjsip_rx_data *challenge,
666                 pjsip_transaction *tsx, pjsip_tx_data **new_request)
667 {
668         if (!registered_outbound_authenticator) {
669                 ast_log(LOG_WARNING, "No SIP outbound authenticator registered. Cannot respond to authentication challenge\n");
670                 return -1;
671         }
672         return registered_outbound_authenticator->create_request_with_auth(auths, num_auths, challenge, tsx, new_request);
673 }
674
675 struct endpoint_identifier_list {
676         struct ast_sip_endpoint_identifier *identifier;
677         AST_RWLIST_ENTRY(endpoint_identifier_list) list;
678 };
679
680 static AST_RWLIST_HEAD_STATIC(endpoint_identifiers, endpoint_identifier_list);
681
682 int ast_sip_register_endpoint_identifier(struct ast_sip_endpoint_identifier *identifier)
683 {
684         struct endpoint_identifier_list *id_list_item;
685         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
686
687         id_list_item = ast_calloc(1, sizeof(*id_list_item));
688         if (!id_list_item) {
689                 ast_log(LOG_ERROR, "Unabled to add endpoint identifier. Out of memory.\n");
690                 return -1;
691         }
692         id_list_item->identifier = identifier;
693
694         AST_RWLIST_INSERT_TAIL(&endpoint_identifiers, id_list_item, list);
695         ast_debug(1, "Registered endpoint identifier %p\n", identifier);
696
697         ast_module_ref(ast_module_info->self);
698         return 0;
699 }
700
701 void ast_sip_unregister_endpoint_identifier(struct ast_sip_endpoint_identifier *identifier)
702 {
703         struct endpoint_identifier_list *iter;
704         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
705         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&endpoint_identifiers, iter, list) {
706                 if (iter->identifier == identifier) {
707                         AST_RWLIST_REMOVE_CURRENT(list);
708                         ast_free(iter);
709                         ast_debug(1, "Unregistered endpoint identifier %p\n", identifier);
710                         ast_module_unref(ast_module_info->self);
711                         break;
712                 }
713         }
714         AST_RWLIST_TRAVERSE_SAFE_END;
715 }
716
717 struct ast_sip_endpoint *ast_sip_identify_endpoint(pjsip_rx_data *rdata)
718 {
719         struct endpoint_identifier_list *iter;
720         struct ast_sip_endpoint *endpoint = NULL;
721         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
722         AST_RWLIST_TRAVERSE(&endpoint_identifiers, iter, list) {
723                 ast_assert(iter->identifier->identify_endpoint != NULL);
724                 endpoint = iter->identifier->identify_endpoint(rdata);
725                 if (endpoint) {
726                         break;
727                 }
728         }
729         return endpoint;
730 }
731
732 pjsip_endpoint *ast_sip_get_pjsip_endpoint(void)
733 {
734         return ast_pjsip_endpoint;
735 }
736
737 static int sip_dialog_create_from(pj_pool_t *pool, pj_str_t *from, const char *user, const pj_str_t *target, pjsip_tpselector *selector)
738 {
739         pj_str_t tmp, local_addr;
740         pjsip_uri *uri;
741         pjsip_sip_uri *sip_uri;
742         pjsip_transport_type_e type = PJSIP_TRANSPORT_UNSPECIFIED;
743         int local_port;
744         char uuid_str[AST_UUID_STR_LEN];
745
746         if (!user) {
747                 RAII_VAR(struct ast_uuid *, uuid, ast_uuid_generate(), ast_free_ptr);
748                 if (!uuid) {
749                         return -1;
750                 }
751                 user = ast_uuid_to_str(uuid, uuid_str, sizeof(uuid_str));
752         }
753
754         /* Parse the provided target URI so we can determine what transport it will end up using */
755         pj_strdup_with_null(pool, &tmp, target);
756
757         if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
758             (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
759                 return -1;
760         }
761
762         sip_uri = pjsip_uri_get_uri(uri);
763
764         /* Determine the transport type to use */
765         if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
766                 type = PJSIP_TRANSPORT_TLS;
767         } else if (!sip_uri->transport_param.slen) {
768                 type = PJSIP_TRANSPORT_UDP;
769         } else {
770                 type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
771         }
772
773         if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
774                 return -1;
775         }
776
777         /* If the host is IPv6 turn the transport into an IPv6 version */
778         if (pj_strchr(&sip_uri->host, ':')) {
779                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
780         }
781
782         /* Get the local bound address for the transport that will be used when communicating with the provided URI */
783         if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()), pool, type, selector,
784                                                               &local_addr, &local_port) != PJ_SUCCESS) {
785                 return -1;
786         }
787
788         /* If IPv6 was not specified in the host but is in the transport, set the proper type */
789         if (!pj_strchr(&sip_uri->host, ':') && pj_strchr(&local_addr, ':')) {
790                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
791         }
792
793         from->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
794         from->slen = pj_ansi_snprintf(from->ptr, PJSIP_MAX_URL_SIZE,
795                                       "<%s:%s@%s%.*s%s:%d%s%s>",
796                                       (pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE) ? "sips" : "sip",
797                                       user,
798                                       (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
799                                       (int)local_addr.slen,
800                                       local_addr.ptr,
801                                       (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
802                                       local_port,
803                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
804                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
805
806         return 0;
807 }
808
809 static int sip_get_tpselector_from_endpoint(const struct ast_sip_endpoint *endpoint, pjsip_tpselector *selector)
810 {
811         RAII_VAR(struct ast_sip_transport *, transport, NULL, ao2_cleanup);
812         const char *transport_name = endpoint->transport;
813
814         if (ast_strlen_zero(transport_name)) {
815                 return 0;
816         }
817
818         transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", transport_name);
819
820         if (!transport || !transport->state) {
821                 return -1;
822         }
823
824         if (transport->type == AST_TRANSPORT_UDP) {
825                 selector->type = PJSIP_TPSELECTOR_TRANSPORT;
826                 selector->u.transport = transport->state->transport;
827         } else if (transport->type == AST_TRANSPORT_TCP || transport->type == AST_TRANSPORT_TLS) {
828                 selector->type = PJSIP_TPSELECTOR_LISTENER;
829                 selector->u.listener = transport->state->factory;
830         } else {
831                 return -1;
832         }
833
834         return 0;
835 }
836
837 pjsip_dialog *ast_sip_create_dialog(const struct ast_sip_endpoint *endpoint, const char *uri, const char *request_user)
838 {
839         pj_str_t local_uri = { "sip:temp@temp", 13 }, remote_uri;
840         pjsip_dialog *dlg = NULL;
841         const char *outbound_proxy = endpoint->outbound_proxy;
842         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
843         static const pj_str_t HCONTACT = { "Contact", 7 };
844
845         pj_cstr(&remote_uri, uri);
846
847         if (pjsip_dlg_create_uac(pjsip_ua_instance(), &local_uri, NULL, &remote_uri, NULL, &dlg) != PJ_SUCCESS) {
848                 return NULL;
849         }
850
851         if (sip_get_tpselector_from_endpoint(endpoint, &selector)) {
852                 pjsip_dlg_terminate(dlg);
853                 return NULL;
854         }
855
856         if (sip_dialog_create_from(dlg->pool, &local_uri, NULL, &remote_uri, &selector)) {
857                 pjsip_dlg_terminate(dlg);
858                 return NULL;
859         }
860
861         /* Update the dialog with the new local URI, we do it afterwards so we can use the dialog pool for construction */
862         pj_strdup_with_null(dlg->pool, &dlg->local.info_str, &local_uri);
863         dlg->local.info->uri = pjsip_parse_uri(dlg->pool, dlg->local.info_str.ptr, dlg->local.info_str.slen, 0);
864         dlg->local.contact = pjsip_parse_hdr(dlg->pool, &HCONTACT, local_uri.ptr, local_uri.slen, NULL);
865
866         /* If a request user has been specified and we are permitted to change it, do so */
867         if (!ast_strlen_zero(request_user) && (PJSIP_URI_SCHEME_IS_SIP(dlg->target) || PJSIP_URI_SCHEME_IS_SIPS(dlg->target))) {
868                 pjsip_sip_uri *target = pjsip_uri_get_uri(dlg->target);
869                 pj_strdup2(dlg->pool, &target->user, request_user);
870         }
871
872         /* We have to temporarily bump up the sess_count here so the dialog is not prematurely destroyed */
873         dlg->sess_count++;
874
875         pjsip_dlg_set_transport(dlg, &selector);
876
877         if (!ast_strlen_zero(outbound_proxy)) {
878                 pjsip_route_hdr route_set, *route;
879                 static const pj_str_t ROUTE_HNAME = { "Route", 5 };
880                 pj_str_t tmp;
881
882                 pj_list_init(&route_set);
883
884                 pj_strdup2_with_null(dlg->pool, &tmp, outbound_proxy);
885                 if (!(route = pjsip_parse_hdr(dlg->pool, &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL))) {
886                         pjsip_dlg_terminate(dlg);
887                         return NULL;
888                 }
889                 pj_list_push_back(&route_set, route);
890
891                 pjsip_dlg_set_route_set(dlg, &route_set);
892         }
893
894         dlg->sess_count--;
895
896         return dlg;
897 }
898
899 /* PJSIP doesn't know about the INFO method, so we have to define it ourselves */
900 const pjsip_method pjsip_info_method = {PJSIP_OTHER_METHOD, {"INFO", 4} };
901
902 static struct {
903         const char *method;
904         const pjsip_method *pmethod;
905 } methods [] = {
906         { "INVITE", &pjsip_invite_method },
907         { "CANCEL", &pjsip_cancel_method },
908         { "ACK", &pjsip_ack_method },
909         { "BYE", &pjsip_bye_method },
910         { "REGISTER", &pjsip_register_method },
911         { "OPTIONS", &pjsip_options_method },
912         { "SUBSCRIBE", &pjsip_subscribe_method },
913         { "NOTIFY", &pjsip_notify_method },
914         { "PUBLISH", &pjsip_publish_method },
915         { "INFO", &pjsip_info_method },
916 };
917
918 static const pjsip_method *get_pjsip_method(const char *method)
919 {
920         int i;
921         for (i = 0; i < ARRAY_LEN(methods); ++i) {
922                 if (!strcmp(method, methods[i].method)) {
923                         return methods[i].pmethod;
924                 }
925         }
926         return NULL;
927 }
928
929 static int create_in_dialog_request(const pjsip_method *method, struct pjsip_dialog *dlg, pjsip_tx_data **tdata)
930 {
931         if (pjsip_dlg_create_request(dlg, method, -1, tdata) != PJ_SUCCESS) {
932                 ast_log(LOG_WARNING, "Unable to create in-dialog request.\n");
933                 return -1;
934         }
935
936         return 0;
937 }
938
939 static int create_out_of_dialog_request(const pjsip_method *method, struct ast_sip_endpoint *endpoint,
940                 const char *uri, pjsip_tx_data **tdata)
941 {
942         RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
943         pj_str_t remote_uri;
944         pj_str_t from;
945         pj_pool_t *pool;
946         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
947
948         if (ast_strlen_zero(uri)) {
949                 contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
950                 if (!contact || ast_strlen_zero(contact->uri)) {
951                         ast_log(LOG_ERROR, "Unable to retrieve contact for endpoint %s\n",
952                                         ast_sorcery_object_get_id(endpoint));
953                         return -1;
954                 }
955
956                 pj_cstr(&remote_uri, contact->uri);
957         } else {
958                 pj_cstr(&remote_uri, uri);
959         }
960
961         if (sip_get_tpselector_from_endpoint(endpoint, &selector)) {
962                 ast_log(LOG_ERROR, "Unable to retrieve PJSIP transport selector for endpoint %s\n",
963                                 ast_sorcery_object_get_id(endpoint));
964                 return -1;
965         }
966
967         pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Outbound request", 256, 256);
968
969         if (!pool) {
970                 ast_log(LOG_ERROR, "Unable to create PJLIB memory pool\n");
971                 return -1;
972         }
973
974         if (sip_dialog_create_from(pool, &from, NULL, &remote_uri, &selector)) {
975                 ast_log(LOG_ERROR, "Unable to create From header for %.*s request to endpoint %s\n",
976                                 (int) pj_strlen(&method->name), pj_strbuf(&method->name), ast_sorcery_object_get_id(endpoint));
977                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
978                 return -1;
979         }
980
981         if (pjsip_endpt_create_request(ast_sip_get_pjsip_endpoint(), method, &remote_uri,
982                         &from, &remote_uri, &from, NULL, -1, NULL, tdata) != PJ_SUCCESS) {
983                 ast_log(LOG_ERROR, "Unable to create outbound %.*s request to endpoint %s\n",
984                                 (int) pj_strlen(&method->name), pj_strbuf(&method->name), ast_sorcery_object_get_id(endpoint));
985                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
986                 return -1;
987         }
988
989         /* We can release this pool since request creation copied all the necessary
990          * data into the outbound request's pool
991          */
992         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
993         return 0;
994 }
995
996 int ast_sip_create_request(const char *method, struct pjsip_dialog *dlg,
997                 struct ast_sip_endpoint *endpoint, const char *uri, pjsip_tx_data **tdata)
998 {
999         const pjsip_method *pmethod = get_pjsip_method(method);
1000
1001         if (!pmethod) {
1002                 ast_log(LOG_WARNING, "Unknown method '%s'. Cannot send request\n", method);
1003                 return -1;
1004         }
1005
1006         if (dlg) {
1007                 return create_in_dialog_request(pmethod, dlg, tdata);
1008         } else {
1009                 return create_out_of_dialog_request(pmethod, endpoint, uri, tdata);
1010         }
1011 }
1012
1013 static int send_in_dialog_request(pjsip_tx_data *tdata, struct pjsip_dialog *dlg)
1014 {
1015         if (pjsip_dlg_send_request(dlg, tdata, -1, NULL) != PJ_SUCCESS) {
1016                 ast_log(LOG_WARNING, "Unable to send in-dialog request.\n");
1017                 return -1;
1018         }
1019         return 0;
1020 }
1021
1022 static void send_request_cb(void *token, pjsip_event *e)
1023 {
1024         RAII_VAR(struct ast_sip_endpoint *, endpoint, token, ao2_cleanup);
1025         pjsip_transaction *tsx = e->body.tsx_state.tsx;
1026         pjsip_rx_data *challenge = e->body.tsx_state.src.rdata;
1027         pjsip_tx_data *tdata;
1028
1029         if (tsx->status_code != 401 && tsx->status_code != 407) {
1030                 return;
1031         }
1032
1033         if (!ast_sip_create_request_with_auth(endpoint->sip_outbound_auths, endpoint->num_outbound_auths, challenge, tsx, &tdata)) {
1034                 pjsip_endpt_send_request(ast_sip_get_pjsip_endpoint(), tdata, -1, NULL, NULL);
1035         }
1036 }
1037
1038 static int send_out_of_dialog_request(pjsip_tx_data *tdata, struct ast_sip_endpoint *endpoint)
1039 {
1040         ao2_ref(endpoint, +1);
1041         if (pjsip_endpt_send_request(ast_sip_get_pjsip_endpoint(), tdata, -1, endpoint, send_request_cb) != PJ_SUCCESS) {
1042                 ast_log(LOG_ERROR, "Error attempting to send outbound %.*s request to endpoint %s\n",
1043                                 (int) pj_strlen(&tdata->msg->line.req.method.name),
1044                                 pj_strbuf(&tdata->msg->line.req.method.name),
1045                                 ast_sorcery_object_get_id(endpoint));
1046                 ao2_ref(endpoint, -1);
1047                 return -1;
1048         }
1049
1050         return 0;
1051 }
1052
1053 int ast_sip_send_request(pjsip_tx_data *tdata, struct pjsip_dialog *dlg, struct ast_sip_endpoint *endpoint)
1054 {
1055         ast_assert(tdata->msg->type == PJSIP_REQUEST_MSG);
1056
1057         if (dlg) {
1058                 return send_in_dialog_request(tdata, dlg);
1059         } else {
1060                 return send_out_of_dialog_request(tdata, endpoint);
1061         }
1062 }
1063
1064 int ast_sip_add_header(pjsip_tx_data *tdata, const char *name, const char *value)
1065 {
1066         pj_str_t hdr_name;
1067         pj_str_t hdr_value;
1068         pjsip_generic_string_hdr *hdr;
1069         
1070         pj_cstr(&hdr_name, name);
1071         pj_cstr(&hdr_value, value);
1072
1073         hdr = pjsip_generic_string_hdr_create(tdata->pool, &hdr_name, &hdr_value);
1074
1075         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *) hdr);
1076         return 0;
1077 }
1078
1079 static pjsip_msg_body *ast_body_to_pjsip_body(pj_pool_t *pool, const struct ast_sip_body *body)
1080 {
1081         pj_str_t type;
1082         pj_str_t subtype;
1083         pj_str_t body_text;
1084
1085         pj_cstr(&type, body->type);
1086         pj_cstr(&subtype, body->subtype);
1087         pj_cstr(&body_text, body->body_text);
1088         
1089         return pjsip_msg_body_create(pool, &type, &subtype, &body_text);
1090 }
1091
1092 int ast_sip_add_body(pjsip_tx_data *tdata, const struct ast_sip_body *body)
1093 {
1094         pjsip_msg_body *pjsip_body = ast_body_to_pjsip_body(tdata->pool, body);
1095         tdata->msg->body = pjsip_body;
1096         return 0;
1097 }
1098
1099 int ast_sip_add_body_multipart(pjsip_tx_data *tdata, const struct ast_sip_body *bodies[], int num_bodies)
1100 {
1101         int i;
1102         /* NULL for type and subtype automatically creates "multipart/mixed" */
1103         pjsip_msg_body *body = pjsip_multipart_create(tdata->pool, NULL, NULL);
1104
1105         for (i = 0; i < num_bodies; ++i) {
1106                 pjsip_multipart_part *part = pjsip_multipart_create_part(tdata->pool);
1107                 part->body = ast_body_to_pjsip_body(tdata->pool, bodies[i]);
1108                 pjsip_multipart_add_part(tdata->pool, body, part);
1109         }
1110
1111         tdata->msg->body = body;
1112         return 0;
1113 }
1114
1115 int ast_sip_append_body(pjsip_tx_data *tdata, const char *body_text)
1116 {
1117         size_t combined_size = strlen(body_text) + tdata->msg->body->len;
1118         struct ast_str *body_buffer = ast_str_alloca(combined_size);
1119
1120         ast_str_set(&body_buffer, 0, "%.*s%s", (int) tdata->msg->body->len, (char *) tdata->msg->body->data, body_text);
1121
1122         tdata->msg->body->data = pj_pool_alloc(tdata->pool, combined_size);
1123         pj_memcpy(tdata->msg->body->data, ast_str_buffer(body_buffer), combined_size);
1124         tdata->msg->body->len = combined_size;
1125
1126         return 0;
1127 }
1128
1129 struct ast_taskprocessor *ast_sip_create_serializer(void)
1130 {
1131         struct ast_taskprocessor *serializer;
1132         RAII_VAR(struct ast_uuid *, uuid, ast_uuid_generate(), ast_free_ptr);
1133         char name[AST_UUID_STR_LEN];
1134
1135         if (!uuid) {
1136                 return NULL;
1137         }
1138
1139         ast_uuid_to_str(uuid, name, sizeof(name));
1140
1141         serializer = ast_threadpool_serializer(name, sip_threadpool);
1142         if (!serializer) {
1143                 return NULL;
1144         }
1145         return serializer;
1146 }
1147
1148 int ast_sip_push_task(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
1149 {
1150         if (serializer) {
1151                 return ast_taskprocessor_push(serializer, sip_task, task_data);
1152         } else {
1153                 return ast_threadpool_push(sip_threadpool, sip_task, task_data);
1154         }
1155 }
1156
1157 struct sync_task_data {
1158         ast_mutex_t lock;
1159         ast_cond_t cond;
1160         int complete;
1161         int fail;
1162         int (*task)(void *);
1163         void *task_data;
1164 };
1165
1166 static int sync_task(void *data)
1167 {
1168         struct sync_task_data *std = data;
1169         std->fail = std->task(std->task_data);
1170
1171         ast_mutex_lock(&std->lock);
1172         std->complete = 1;
1173         ast_cond_signal(&std->cond);
1174         ast_mutex_unlock(&std->lock);
1175         return std->fail;
1176 }
1177
1178 int ast_sip_push_task_synchronous(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
1179 {
1180         /* This method is an onion */
1181         struct sync_task_data std;
1182         ast_mutex_init(&std.lock);
1183         ast_cond_init(&std.cond, NULL);
1184         std.fail = std.complete = 0;
1185         std.task = sip_task;
1186         std.task_data = task_data;
1187
1188         if (serializer) {
1189                 if (ast_taskprocessor_push(serializer, sync_task, &std)) {
1190                         return -1;
1191                 }
1192         } else {
1193                 if (ast_threadpool_push(sip_threadpool, sync_task, &std)) {
1194                         return -1;
1195                 }
1196         }
1197
1198         ast_mutex_lock(&std.lock);
1199         while (!std.complete) {
1200                 ast_cond_wait(&std.cond, &std.lock);
1201         }
1202         ast_mutex_unlock(&std.lock);
1203
1204         ast_mutex_destroy(&std.lock);
1205         ast_cond_destroy(&std.cond);
1206         return std.fail;
1207 }
1208
1209 void ast_copy_pj_str(char *dest, pj_str_t *src, size_t size)
1210 {
1211         size_t chars_to_copy = MIN(size - 1, pj_strlen(src));
1212         memcpy(dest, pj_strbuf(src), chars_to_copy);
1213         dest[chars_to_copy] = '\0';
1214 }
1215
1216 pj_caching_pool caching_pool;
1217 pj_pool_t *memory_pool;
1218 pj_thread_t *monitor_thread;
1219 static int monitor_continue;
1220
1221 static void *monitor_thread_exec(void *endpt)
1222 {
1223         while (monitor_continue) {
1224                 const pj_time_val delay = {0, 10};
1225                 pjsip_endpt_handle_events(ast_pjsip_endpoint, &delay);
1226         }
1227         return NULL;
1228 }
1229
1230 static void stop_monitor_thread(void)
1231 {
1232         monitor_continue = 0;
1233         pj_thread_join(monitor_thread);
1234 }
1235
1236 AST_THREADSTORAGE(pj_thread_storage);
1237 AST_THREADSTORAGE(servant_id_storage);
1238 #define SIP_SERVANT_ID 0xDEFECA7E
1239
1240 static void sip_thread_start(void)
1241 {
1242         pj_thread_desc *desc;
1243         pj_thread_t *thread;
1244         uint32_t *servant_id;
1245
1246         servant_id = ast_threadstorage_get(&servant_id_storage, sizeof(*servant_id));
1247         if (!servant_id) {
1248                 ast_log(LOG_ERROR, "Could not set SIP servant ID in thread-local storage.\n");
1249                 return;
1250         }
1251         *servant_id = SIP_SERVANT_ID;
1252
1253         desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
1254         if (!desc) {
1255                 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
1256                 return;
1257         }
1258         pj_bzero(*desc, sizeof(*desc));
1259
1260         if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
1261                 ast_log(LOG_ERROR, "Couldn't register thread with PJLIB.\n");
1262         }
1263 }
1264
1265 int ast_sip_thread_is_servant(void)
1266 {
1267         uint32_t *servant_id;
1268
1269         servant_id = ast_threadstorage_get(&servant_id_storage, sizeof(*servant_id));
1270         if (!servant_id) {
1271                 return 0;
1272         }
1273
1274         return *servant_id == SIP_SERVANT_ID;
1275 }
1276
1277 static int load_module(void)
1278 {
1279     /* The third parameter is just copied from
1280      * example code from PJLIB. This can be adjusted
1281      * if necessary.
1282          */
1283         pj_status_t status;
1284
1285         /* XXX For the time being, create hard-coded threadpool
1286          * options. Just bump up by five threads every time we
1287          * don't have any available threads. Idle threads time
1288          * out after a minute. No maximum size
1289          */
1290         struct ast_threadpool_options options = {
1291                 .version = AST_THREADPOOL_OPTIONS_VERSION,
1292                 .auto_increment = 5,
1293                 .max_size = 0,
1294                 .idle_timeout = 60,
1295                 .initial_size = 0,
1296                 .thread_start = sip_thread_start,
1297         };
1298         sip_threadpool = ast_threadpool_create("SIP", NULL, &options);
1299
1300         if (pj_init() != PJ_SUCCESS) {
1301                 return AST_MODULE_LOAD_DECLINE;
1302         }
1303
1304         if (pjlib_util_init() != PJ_SUCCESS) {
1305                 pj_shutdown();
1306                 return AST_MODULE_LOAD_DECLINE;
1307         }
1308
1309         pj_caching_pool_init(&caching_pool, NULL, 1024 * 1024);
1310         if (pjsip_endpt_create(&caching_pool.factory, "SIP", &ast_pjsip_endpoint) != PJ_SUCCESS) {
1311                 ast_log(LOG_ERROR, "Failed to create PJSIP endpoint structure. Aborting load\n");
1312                 goto error;
1313         }
1314         memory_pool = pj_pool_create(&caching_pool.factory, "SIP", 1024, 1024, NULL);
1315         if (!memory_pool) {
1316                 ast_log(LOG_ERROR, "Failed to create memory pool for SIP. Aborting load\n");
1317                 goto error;
1318         }
1319
1320         pjsip_tsx_layer_init_module(ast_pjsip_endpoint);
1321         pjsip_ua_init_module(ast_pjsip_endpoint, NULL);
1322
1323         monitor_continue = 1;
1324         status = pj_thread_create(memory_pool, "SIP", (pj_thread_proc *) &monitor_thread_exec,
1325                         NULL, PJ_THREAD_DEFAULT_STACK_SIZE * 2, 0, &monitor_thread);
1326         if (status != PJ_SUCCESS) {
1327                 ast_log(LOG_ERROR, "Failed to start SIP monitor thread. Aborting load\n");
1328                 goto error;
1329         }
1330
1331         if (ast_res_sip_initialize_configuration()) {
1332                 ast_log(LOG_ERROR, "Failed to initialize SIP configuration. Aborting load\n");
1333                 goto error;
1334         }
1335
1336         if (ast_sip_initialize_distributor()) {
1337                 ast_log(LOG_ERROR, "Failed to register distributor module. Aborting load\n");
1338                 goto error;
1339         }
1340
1341         if (ast_sip_initialize_outbound_authentication()) {
1342                 ast_log(LOG_ERROR, "Failed to initialize outbound authentication. Aborting load\n");
1343                 goto error;
1344         }
1345
1346         ast_res_sip_init_options_handling(0);
1347
1348 return AST_MODULE_LOAD_SUCCESS;
1349
1350 error:
1351         ast_res_sip_destroy_configuration();
1352         if (monitor_thread) {
1353                 stop_monitor_thread();
1354         }
1355         if (memory_pool) {
1356                 pj_pool_release(memory_pool);
1357                 memory_pool = NULL;
1358         }
1359         if (ast_pjsip_endpoint) {
1360                 pjsip_endpt_destroy(ast_pjsip_endpoint);
1361                 ast_pjsip_endpoint = NULL;
1362         }
1363         pj_caching_pool_destroy(&caching_pool);
1364         /* XXX Should have a way of stopping monitor thread */
1365         return AST_MODULE_LOAD_DECLINE;
1366 }
1367
1368 static int reload_module(void)
1369 {
1370         if (ast_res_sip_reload_configuration()) {
1371                 return AST_MODULE_LOAD_DECLINE;
1372         }
1373         ast_res_sip_init_options_handling(1);
1374         return 0;
1375 }
1376
1377 static int unload_pjsip(void *data)
1378 {
1379         if (memory_pool) {
1380                 pj_pool_release(memory_pool);
1381                 memory_pool = NULL;
1382         }
1383         if (ast_pjsip_endpoint) {
1384                 pjsip_endpt_destroy(ast_pjsip_endpoint);
1385                 ast_pjsip_endpoint = NULL;
1386         }
1387         pj_caching_pool_destroy(&caching_pool);
1388         return 0;
1389 }
1390
1391 static int unload_module(void)
1392 {
1393         ast_res_sip_destroy_configuration();
1394         if (monitor_thread) {
1395                 stop_monitor_thread();
1396         }
1397         /* The thread this is called from cannot call PJSIP/PJLIB functions,
1398          * so we have to push the work to the threadpool to handle
1399          */
1400         ast_sip_push_task_synchronous(NULL, unload_pjsip, NULL);
1401
1402         ast_threadpool_shutdown(sip_threadpool);
1403
1404         return 0;
1405 }
1406
1407 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Basic SIP resource",
1408                 .load = load_module,
1409                 .unload = unload_module,
1410                 .reload = reload_module,
1411                 .load_pri = AST_MODPRI_CHANNEL_DEPEND - 5,
1412 );