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