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