Asterisk - The Open Source Telephony Project  18.5.0
chan_sip.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2012, Digium, Inc.
5  *
6  * Mark Spencer <[email protected]>
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 /*!
20  * \file
21  * \brief Implementation of Session Initiation Protocol
22  *
23  * \author Mark Spencer <[email protected]>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  *
28  * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29  * Configuration file \link Config_sip sip.conf \endlink
30  *
31  * ********** IMPORTANT *
32  * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
33  * settings, dialplan commands and dialplans apps/functions
34  * See \ref sip_tcp_tls
35  *
36  *
37  * ******** General TODO:s
38  * \todo Better support of forking
39  * \todo VIA branch tag transaction checking
40  * \todo Transaction support
41  *
42  * ******** Wishlist: Improvements
43  * - Support of SIP domains for devices, so that we match on username\@domain in the From: header
44  * - Connect registrations with a specific device on the incoming call. It's not done
45  * automatically in Asterisk
46  *
47  * \ingroup channel_drivers
48  *
49  * \par Overview of the handling of SIP sessions
50  * The SIP channel handles several types of SIP sessions, or dialogs,
51  * not all of them being "telephone calls".
52  * - Incoming calls that will be sent to the PBX core
53  * - Outgoing calls, generated by the PBX
54  * - SIP subscriptions and notifications of states and voicemail messages
55  * - SIP registrations, both inbound and outbound
56  * - SIP peer management (peerpoke, OPTIONS)
57  * - SIP text messages
58  *
59  * In the SIP channel, there's a list of active SIP dialogs, which includes
60  * all of these when they are active. "sip show channels" in the CLI will
61  * show most of these, excluding subscriptions which are shown by
62  * "sip show subscriptions"
63  *
64  * \par incoming packets
65  * Incoming packets are received in the monitoring thread, then handled by
66  * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
67  * sipsock_read() function parses the packet and matches an existing
68  * dialog or starts a new SIP dialog.
69  *
70  * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
71  * If it is a response to an outbound request, the packet is sent to handle_response().
72  * If it is a request, handle_incoming() sends it to one of a list of functions
73  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
74  * sipsock_read locks the ast_channel if it exists (an active call) and
75  * unlocks it after we have processed the SIP message.
76  *
77  * A new INVITE is sent to handle_request_invite(), that will end up
78  * starting a new channel in the PBX, the new channel after that executing
79  * in a separate channel thread. This is an incoming "call".
80  * When the call is answered, either by a bridged channel or the PBX itself
81  * the sip_answer() function is called.
82  *
83  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
84  * in rtp.c
85  *
86  * \par Outbound calls
87  * Outbound calls are set up by the PBX through the sip_request_call()
88  * function. After that, they are activated by sip_call().
89  *
90  * \par Hanging up
91  * The PBX issues a hangup on both incoming and outgoing calls through
92  * the sip_hangup() function
93  */
94 
95 /*! \li \ref chan_sip.c uses configuration files \ref sip.conf and \ref sip_notify.conf
96  * \addtogroup configuration_file
97  */
98 
99 /*! \page sip.conf sip.conf
100  * \verbinclude sip.conf.sample
101  */
102 
103 /*! \page sip_notify.conf sip_notify.conf
104  * \verbinclude sip_notify.conf.sample
105  */
106 
107 /*!
108  * \page sip_tcp_tls SIP TCP and TLS support
109  *
110  * \par tcpfixes TCP implementation changes needed
111  * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
112  * \todo Save TCP/TLS sessions in registry
113  * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
114  * \todo Add TCP/TLS information to function SIPPEER and CHANNEL function
115  * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
116  * The tcpbindaddr config option should only be used to open ADDITIONAL ports
117  * So we should propably go back to
118  * bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
119  * if tlsenable=yes, open TLS port (provided we also have cert)
120  * tcpbindaddr = extra address for additional TCP connections
121  * tlsbindaddr = extra address for additional TCP/TLS connections
122  * udpbindaddr = extra address for additional UDP connections
123  * These three options should take multiple IP/port pairs
124  * Note: Since opening additional listen sockets is a *new* feature we do not have today
125  * the XXXbindaddr options needs to be disabled until we have support for it
126  *
127  * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
128  * thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
129  * even if udp is the configured first transport.
130  *
131  * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
132  * specially to communication with other peers (proxies).
133  * \todo We need to test TCP sessions with SIP proxies and in regards
134  * to the SIP outbound specs.
135  * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
136  *
137  * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
138  * message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
139  * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
140  * multiple domains in our TLS implementation, meaning one socket and one cert per domain
141  * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
142  * also considering outbound proxy options.
143  * First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port: DNS naptr, srv, AAA)
144  * Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
145  * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
146  * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
147  * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
148  * devices directly from the dialplan. UDP is only a fallback if no other method works,
149  * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
150  * MTU (like INIVTE with video, audio and RTT) TCP should be preferred.
151  *
152  * When dialling unconfigured peers (with no port number) or devices in external domains
153  * NAPTR records MUST be consulted to find configured transport. If they are not found,
154  * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
155  * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
156  * \note this only applies if there's no outbound proxy configured for the session. If an outbound
157  * proxy is configured, these procedures might apply for locating the proxy and determining
158  * the transport to use for communication with the proxy.
159  * \par Other bugs to fix ----
160  * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
161  * - sets TLS port as default for all TCP connections, unless other port is given in contact.
162  * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
163  * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
164  * a bad guess.
165  * - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
166  * get_destination(struct sip_pvt *p, struct sip_request *oreq)
167  * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
168  * we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
169  * fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
170  * channel variable in the dialplan.
171  * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
172  * - As above, if we have a SIPS: uri in the refer-to header
173  * - Does not check transport in refer_to uri.
174  */
175 
176 /*** MODULEINFO
177  <use type="module">res_crypto</use>
178  <use type="module">res_http_websocket</use>
179  <support_level>deprecated</support_level>
180  ***/
181 
182 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
183 
184  The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
185  refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
186  request at a negotiated interval. If a session refresh fails then all the entities that support Session-
187  Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
188  the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
189  that do not support Session-Timers).
190 
191  The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
192  per-peer settings override the global settings. The following new parameters have been
193  added to the sip.conf file.
194  session-timers=["accept", "originate", "refuse"]
195  session-expires=[integer]
196  session-minse=[integer]
197  session-refresher=["uas", "uac"]
198 
199  The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
200  Asterisk. The Asterisk can be configured in one of the following three modes:
201 
202  1. Accept :: In the "accept" mode, the Asterisk server honors
203  session-timers requests made by remote end-points. A remote
204  end-point can request Asterisk to engage session-timers by either
205  sending it an INVITE request with a "Supported: timer" header in
206  it or by responding to Asterisk's INVITE with a 200 OK that
207  contains Session-Expires: header in it. In this mode, the Asterisk
208  server does not request session-timers from remote
209  end-points. This is the default mode.
210 
211  2. Originate :: In the "originate" mode, the Asterisk server
212  requests the remote end-points to activate session-timers in
213  addition to honoring such requests made by the remote
214  end-points. In order to get as much protection as possible against
215  hanging SIP channels due to network or end-point failures,
216  Asterisk resends periodic re-INVITEs even if a remote end-point
217  does not support the session-timers feature.
218 
219  3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not
220  support session- timers for inbound or outbound requests. If a
221  remote end-point requests session-timers in a dialog, then
222  Asterisk ignores that request unless it's noted as a requirement
223  (Require: header), in which case the INVITE is rejected with a 420
224  Bad Extension response.
225 
226 */
227 
228 #include "asterisk.h"
229 
230 #include <signal.h>
231 #include <regex.h>
232 #include <inttypes.h>
233 
234 #include "asterisk/network.h"
235 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
236 #include "asterisk/lock.h"
237 #include "asterisk/config.h"
238 #include "asterisk/module.h"
239 #include "asterisk/pbx.h"
240 #include "asterisk/sched.h"
241 #include "asterisk/io.h"
242 #include "asterisk/rtp_engine.h"
243 #include "asterisk/udptl.h"
244 #include "asterisk/acl.h"
245 #include "asterisk/manager.h"
246 #include "asterisk/callerid.h"
247 #include "asterisk/cli.h"
248 #include "asterisk/musiconhold.h"
249 #include "asterisk/dsp.h"
250 #include "asterisk/pickup.h"
251 #include "asterisk/parking.h"
252 #include "asterisk/srv.h"
253 #include "asterisk/astdb.h"
254 #include "asterisk/causes.h"
255 #include "asterisk/utils.h"
256 #include "asterisk/file.h"
257 #include "asterisk/astobj2.h"
258 #include "asterisk/dnsmgr.h"
259 #include "asterisk/devicestate.h"
260 #include "asterisk/netsock2.h"
261 #include "asterisk/localtime.h"
262 #include "asterisk/abstract_jb.h"
263 #include "asterisk/threadstorage.h"
264 #include "asterisk/translate.h"
265 #include "asterisk/ast_version.h"
266 #include "asterisk/aoc.h"
267 #include "asterisk/message.h"
268 #include "sip/include/sip.h"
269 #include "sip/include/globals.h"
272 #include "sip/include/sip_utils.h"
273 #include "asterisk/sdp_srtp.h"
274 #include "asterisk/ccss.h"
275 #include "asterisk/xml.h"
276 #include "sip/include/dialog.h"
277 #include "sip/include/dialplan_functions.h"
279 #include "sip/include/route.h"
280 #include "asterisk/sip_api.h"
281 #include "asterisk/mwi.h"
282 #include "asterisk/bridge.h"
283 #include "asterisk/stasis.h"
285 #include "asterisk/stasis_system.h"
288 #include "asterisk/http_websocket.h"
289 #include "asterisk/format_cache.h"
290 #include "asterisk/linkedlists.h" /* for AST_LIST_NEXT */
291 
292 /*** DOCUMENTATION
293  <application name="SIPDtmfMode" language="en_US">
294  <synopsis>
295  Change the dtmfmode for a SIP call.
296  </synopsis>
297  <syntax>
298  <parameter name="mode" required="true">
299  <enumlist>
300  <enum name="inband" />
301  <enum name="info" />
302  <enum name="rfc2833" />
303  </enumlist>
304  </parameter>
305  </syntax>
306  <description>
307  <para>Changes the dtmfmode for a SIP call.</para>
308  </description>
309  </application>
310  <application name="SIPAddHeader" language="en_US">
311  <synopsis>
312  Add a SIP header to the outbound call.
313  </synopsis>
314  <syntax argsep=":">
315  <parameter name="Header" required="true" />
316  <parameter name="Content" required="true" />
317  </syntax>
318  <description>
319  <para>Adds a header to a SIP call placed with DIAL.</para>
320  <para>Remember to use the X-header if you are adding non-standard SIP
321  headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
322  Adding the wrong headers may jeopardize the SIP dialog.</para>
323  <para>Always returns <literal>0</literal>.</para>
324  </description>
325  </application>
326  <application name="SIPRemoveHeader" language="en_US">
327  <synopsis>
328  Remove SIP headers previously added with SIPAddHeader
329  </synopsis>
330  <syntax>
331  <parameter name="Header" required="false" />
332  </syntax>
333  <description>
334  <para>SIPRemoveHeader() allows you to remove headers which were previously
335  added with SIPAddHeader(). If no parameter is supplied, all previously added
336  headers will be removed. If a parameter is supplied, only the matching headers
337  will be removed.</para>
338  <para>For example you have added these 2 headers:</para>
339  <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
340  <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
341  <para></para>
342  <para>// remove all headers</para>
343  <para>SIPRemoveHeader();</para>
344  <para>// remove all P- headers</para>
345  <para>SIPRemoveHeader(P-);</para>
346  <para>// remove only the PAI header (note the : at the end)</para>
347  <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
348  <para></para>
349  <para>Always returns <literal>0</literal>.</para>
350  </description>
351  </application>
352  <application name="SIPSendCustomINFO" language="en_US">
353  <synopsis>
354  Send a custom INFO frame on specified channels.
355  </synopsis>
356  <syntax>
357  <parameter name="Data" required="true" />
358  <parameter name="UserAgent" required="false" />
359  </syntax>
360  <description>
361  <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
362  active SIP channels or on channels with the specified User Agent. This
363  application is only available if TEST_FRAMEWORK is defined.</para>
364  </description>
365  </application>
366  <function name="SIP_HEADER" language="en_US">
367  <synopsis>
368  Gets the specified SIP header from an incoming INVITE message.
369  </synopsis>
370  <syntax>
371  <parameter name="name" required="true" />
372  <parameter name="number">
373  <para>If not specified, defaults to <literal>1</literal>.</para>
374  </parameter>
375  </syntax>
376  <description>
377  <para>Since there are several headers (such as Via) which can occur multiple
378  times, SIP_HEADER takes an optional second argument to specify which header with
379  that name to retrieve. Headers start at offset <literal>1</literal>.</para>
380  <para>This function does not access headers from the REFER message if the call
381  was transferred. To obtain the REFER headers, set the dialplan variable
382  <variable>GET_TRANSFERRER_DATA</variable> to the prefix of the headers of the
383  REFER message that you need to access; for example, <literal>X-</literal> to
384  get all headers starting with <literal>X-</literal>. The variable must be set
385  before a call to the application that starts the channel that may eventually
386  transfer back into the dialplan, and must be inherited by that channel, so prefix
387  it with the <literal>_</literal> or <literal>__</literal> when setting (or
388  set it in the pre-dial handler executed on the new channel). To get all headers
389  of the REFER message, set the value to <literal>*</literal>. Headers
390  are returned in the form of a dialplan hash TRANSFER_DATA, and can be accessed
391  with the functions <variable>HASHKEYS(TRANSFER_DATA)</variable> and, e. g.,
392  <variable>HASH(TRANSFER_DATA,X-That-Special-Header)</variable>.</para>
393  <para>Please also note that contents of the SDP (an attachment to the
394  SIP request) can't be accessed with this function.</para>
395  </description>
396  <see-also>
397  <ref type="function">SIP_HEADERS</ref>
398  </see-also>
399  </function>
400  <function name="SIP_HEADERS" language="en_US">
401  <synopsis>
402  Gets the list of SIP header names from an incoming INVITE message.
403  </synopsis>
404  <syntax>
405  <parameter name="prefix">
406  <para>If specified, only the headers matching the given prefix are returned.</para>
407  </parameter>
408  </syntax>
409  <description>
410  <para>Returns a comma-separated list of header names (without values) from the
411  INVITE message that originated the current channel. Multiple headers with the
412  same name are included in the list only once. The returned list can be iterated
413  over using the functions POP() and SIP_HEADER().</para>
414  <para>For example, <literal>${SIP_HEADERS(Co)}</literal> might return
415  <literal>Contact,Content-Length,Content-Type</literal>. As a practical example,
416  you may use <literal>${SIP_HEADERS(X-)}</literal> to enumerate optional extended
417  headers.</para>
418  <para>This function does not access headers from the incoming SIP REFER message;
419  see the documentation of the function SIP_HEADER for how to access them.</para>
420  <para>Please observe that contents of the SDP (an attachment to the
421  SIP request) can't be accessed with this function.</para>
422  </description>
423  <see-also>
424  <ref type="function">SIP_HEADER</ref>
425  <ref type="function">POP</ref>
426  </see-also>
427  </function>
428  <function name="SIPPEER" language="en_US">
429  <synopsis>
430  Gets SIP peer information.
431  </synopsis>
432  <syntax>
433  <parameter name="peername" required="true" />
434  <parameter name="item">
435  <enumlist>
436  <enum name="ip">
437  <para>(default) The IP address.</para>
438  </enum>
439  <enum name="port">
440  <para>The port number.</para>
441  </enum>
442  <enum name="mailbox">
443  <para>The configured mailbox.</para>
444  </enum>
445  <enum name="context">
446  <para>The configured context.</para>
447  </enum>
448  <enum name="expire">
449  <para>The epoch time of the next expire.</para>
450  </enum>
451  <enum name="dynamic">
452  <para>Is it dynamic? (yes/no).</para>
453  </enum>
454  <enum name="callerid_name">
455  <para>The configured Caller ID name.</para>
456  </enum>
457  <enum name="callerid_num">
458  <para>The configured Caller ID number.</para>
459  </enum>
460  <enum name="callgroup">
461  <para>The configured Callgroup.</para>
462  </enum>
463  <enum name="pickupgroup">
464  <para>The configured Pickupgroup.</para>
465  </enum>
466  <enum name="namedcallgroup">
467  <para>The configured Named Callgroup.</para>
468  </enum>
469  <enum name="namedpickupgroup">
470  <para>The configured Named Pickupgroup.</para>
471  </enum>
472  <enum name="codecs">
473  <para>The configured codecs.</para>
474  </enum>
475  <enum name="status">
476  <para>Status (if qualify=yes).</para>
477  </enum>
478  <enum name="regexten">
479  <para>Extension activated at registration.</para>
480  </enum>
481  <enum name="limit">
482  <para>Call limit (call-limit).</para>
483  </enum>
484  <enum name="busylevel">
485  <para>Configured call level for signalling busy.</para>
486  </enum>
487  <enum name="curcalls">
488  <para>Current amount of calls. Only available if call-limit is set.</para>
489  </enum>
490  <enum name="language">
491  <para>Default language for peer.</para>
492  </enum>
493  <enum name="accountcode">
494  <para>Account code for this peer.</para>
495  </enum>
496  <enum name="useragent">
497  <para>Current user agent header used by peer.</para>
498  </enum>
499  <enum name="maxforwards">
500  <para>The value used for SIP loop prevention in outbound requests</para>
501  </enum>
502  <enum name="chanvar[name]">
503  <para>A channel variable configured with setvar for this peer.</para>
504  </enum>
505  <enum name="codec[x]">
506  <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
507  </enum>
508  </enumlist>
509  </parameter>
510  </syntax>
511  <description></description>
512  </function>
513  <function name="CHECKSIPDOMAIN" language="en_US">
514  <synopsis>
515  Checks if domain is a local domain.
516  </synopsis>
517  <syntax>
518  <parameter name="domain" required="true" />
519  </syntax>
520  <description>
521  <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
522  as a local SIP domain that this Asterisk server is configured to handle.
523  Returns the domain name if it is locally handled, otherwise an empty string.
524  Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
525  </description>
526  </function>
527  <manager name="SIPpeers" language="en_US">
528  <synopsis>
529  List SIP peers (text format).
530  </synopsis>
531  <syntax>
532  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
533  </syntax>
534  <description>
535  <para>Lists SIP peers in text format with details on current status.
536  <literal>Peerlist</literal> will follow as separate events, followed by a final event called
537  <literal>PeerlistComplete</literal>.</para>
538  </description>
539  </manager>
540  <manager name="SIPshowpeer" language="en_US">
541  <synopsis>
542  show SIP peer (text format).
543  </synopsis>
544  <syntax>
545  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
546  <parameter name="Peer" required="true">
547  <para>The peer name you want to check.</para>
548  </parameter>
549  </syntax>
550  <description>
551  <para>Show one SIP peer with details on current status.</para>
552  </description>
553  </manager>
554  <manager name="SIPqualifypeer" language="en_US">
555  <synopsis>
556  Qualify SIP peers.
557  </synopsis>
558  <syntax>
559  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
560  <parameter name="Peer" required="true">
561  <para>The peer name you want to qualify.</para>
562  </parameter>
563  </syntax>
564  <description>
565  <para>Qualify a SIP peer.</para>
566  </description>
567  <see-also>
568  <ref type="managerEvent">SIPQualifyPeerDone</ref>
569  </see-also>
570  </manager>
571  <manager name="SIPshowregistry" language="en_US">
572  <synopsis>
573  Show SIP registrations (text format).
574  </synopsis>
575  <syntax>
576  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
577  </syntax>
578  <description>
579  <para>Lists all registration requests and status. Registrations will follow as separate
580  events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
581  </description>
582  </manager>
583  <manager name="SIPnotify" language="en_US">
584  <synopsis>
585  Send a SIP notify.
586  </synopsis>
587  <syntax>
588  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
589  <parameter name="Channel" required="true">
590  <para>Peer to receive the notify.</para>
591  </parameter>
592  <parameter name="Variable" required="true">
593  <para>At least one variable pair must be specified.
594  <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
595  </parameter>
596  <parameter name="Call-ID" required="false">
597  <para>When specified, SIP notity will be sent as a part of an existing dialog.</para>
598  </parameter>
599  </syntax>
600  <description>
601  <para>Sends a SIP Notify event.</para>
602  <para>All parameters for this event must be specified in the body of this request
603  via multiple <literal>Variable: name=value</literal> sequences.</para>
604  </description>
605  </manager>
606  <manager name="SIPpeerstatus" language="en_US">
607  <synopsis>
608  Show the status of one or all of the sip peers.
609  </synopsis>
610  <syntax>
611  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
612  <parameter name="Peer" required="false">
613  <para>The peer name you want to check.</para>
614  </parameter>
615  </syntax>
616  <description>
617  <para>Retrieves the status of one or all of the sip peers. If no peer name is specified, status
618  for all of the sip peers will be retrieved.</para>
619  </description>
620  </manager>
621  <info name="MessageDestinationInfo" language="en_US" tech="SIP">
622  <para>Specifying a prefix of <literal>sip:</literal> will send the
623  message as a SIP MESSAGE request.</para>
624  </info>
625  <info name="MessageFromInfo" language="en_US" tech="SIP">
626  <para>The <literal>from</literal> parameter can be a configured peer name
627  or in the form of "display-name" &lt;URI&gt;.</para>
628  </info>
629  <info name="MessageToInfo" language="en_US" tech="SIP">
630  <para>Ignored</para>
631  </info>
632  <managerEvent language="en_US" name="SIPQualifyPeerDone">
633  <managerEventInstance class="EVENT_FLAG_CALL">
634  <synopsis>Raised when SIPQualifyPeer has finished qualifying the specified peer.</synopsis>
635  <syntax>
636  <parameter name="Peer">
637  <para>The name of the peer.</para>
638  </parameter>
639  <parameter name="ActionID">
640  <para>This is only included if an ActionID Header was sent with the action request, in which case it will be that ActionID.</para>
641  </parameter>
642  </syntax>
643  <see-also>
644  <ref type="manager">SIPqualifypeer</ref>
645  </see-also>
646  </managerEventInstance>
647  </managerEvent>
648  <managerEvent language="en_US" name="SessionTimeout">
649  <managerEventInstance class="EVENT_FLAG_CALL">
650  <synopsis>Raised when a SIP session times out.</synopsis>
651  <syntax>
652  <channel_snapshot/>
653  <parameter name="Source">
654  <para>The source of the session timeout.</para>
655  <enumlist>
656  <enum name="RTPTimeout" />
657  <enum name="SIPSessionTimer" />
658  </enumlist>
659  </parameter>
660  </syntax>
661  </managerEventInstance>
662  </managerEvent>
663  ***/
664 
665 static int log_level = -1;
666 
667 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
668 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
670 static int min_subexpiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted subscription time */
671 static int max_subexpiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted subscription time */
673 
674 static int unauth_sessions = 0;
677 
678 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
679  * \note Values shown here match the defaults shown in sip.conf.sample */
681 {
682  .flags = 0,
683  .max_size = 200,
684  .resync_threshold = 1000,
685  .impl = "fixed",
686  .target_extra = 40,
687 };
688 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
689 
690 static const char config[] = "sip.conf"; /*!< Main configuration file */
691 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
692 
693 /*! \brief Readable descriptions of device states.
694  * \note Should be aligned to above table as index */
695 static const struct invstate2stringtable {
696  const enum invitestates state;
697  const char *desc;
698 } invitestate2string[] = {
699  {INV_NONE, "None" },
700  {INV_CALLING, "Calling (Trying)"},
701  {INV_PROCEEDING, "Proceeding "},
702  {INV_EARLY_MEDIA, "Early media"},
703  {INV_COMPLETED, "Completed (done)"},
704  {INV_CONFIRMED, "Confirmed (up)"},
705  {INV_TERMINATED, "Done"},
706  {INV_CANCELLED, "Cancelled"}
707 };
708 
709 /*! \brief Subscription types that we support. We support
710  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
711  * - SIMPLE presence used for device status
712  * - Voicemail notification subscriptions
713  */
714 static const struct cfsubscription_types {
716  const char * const event;
717  const char * const mediatype;
718  const char * const text;
719 } subscription_types[] = {
720  { NONE, "-", "unknown", "unknown" },
721  /* RFC 4235: SIP Dialog event package */
722  { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
723  { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
724  { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
725  { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
726  { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
727 };
728 
729 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
730  * structure and then route the messages according to the type.
731  *
732  * \note Note that sip_methods[i].id == i must hold or the code breaks
733  */
734 static const struct cfsip_methods {
735  enum sipmethod id;
736  int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
737  char * const text;
738  enum can_create_dialog can_create;
739 } sip_methods[] = {
740  { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
741  { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
742  { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
743  { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
744  { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
745  { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
746  { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
747  { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
748  { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
749  { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
750  { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
751  { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
752  { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
753  { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
754  { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
755  { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
757 };
758 
759 /*! \brief Diversion header reasons
760  *
761  * The core defines a bunch of constants used to define
762  * redirecting reasons. This provides a translation table
763  * between those and the strings which may be present in
764  * a SIP Diversion header
765  */
766 static const struct sip_reasons {
768  const char *text;
769 } sip_reason_table[] = {
770  { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
771  { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
772  { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
773  { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
774  { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
775  { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
776  { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
777  { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
778  { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
779  { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
780  { AST_REDIRECTING_REASON_AWAY, "away" },
781  { AST_REDIRECTING_REASON_CALL_FWD_DTE, "cf_dte" }, /* Non-standard */
782  { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm" }, /* Non-standard */
783 };
784 
785 
786 /*! \name DefaultSettings
787  Default setttings are used as a channel setting and as a default when
788  configuring devices
789 */
790 static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
791 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
792 static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
793 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
794 static int default_fromdomainport; /*!< Default domain port on outbound messages */
795 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
796 static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
797 static int default_qualify; /*!< Default Qualify= setting */
798 static int default_keepalive; /*!< Default keepalive= setting */
799 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
800 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
801  * a bridged channel on hold */
802 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
803 static char default_engine[256]; /*!< Default RTP engine */
804 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
805 static char default_zone[MAX_TONEZONE_COUNTRY]; /*!< Default tone zone for channels created from the SIP driver */
806 static unsigned int default_transports; /*!< Default Transports (enum ast_transport) that are acceptable */
807 static unsigned int default_primary_transport; /*!< Default primary Transport (enum ast_transport) for outbound connections to devices */
808 
809 static struct sip_settings sip_cfg; /*!< SIP configuration data.
810  \note in the future we could have multiple of these (per domain, per device group etc) */
811 
812 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
813 #define SIP_PEDANTIC_DECODE(str) \
814  if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
815  ast_uri_decode(str, ast_uri_sip_user); \
816  } \
817 
818 static unsigned int chan_idx; /*!< used in naming sip channel */
819 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
820 
821 static int global_relaxdtmf; /*!< Relax DTMF */
822 static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
823 static int global_rtptimeout; /*!< Time out call if no RTP */
824 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
825 static int global_rtpkeepalive; /*!< Send RTP keepalives */
826 static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
827 static int global_regattempts_max; /*!< Registration attempts before giving up */
828 static int global_reg_retry_403; /*!< Treat 403 responses to registrations as 401 responses */
829 static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
830 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
831  * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
832  * with just a boolean flag in the device structure */
833 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
834 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
835 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
836 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
837 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
838 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
839 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
840 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
841 static unsigned int recordhistory; /*!< Record SIP history. Off by default */
842 static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
843 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
844 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
845 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
846 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
847 static int global_t1; /*!< T1 time */
848 static int global_t1min; /*!< T1 roundtrip time minimum */
849 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
850 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
851 static int global_qualifyfreq; /*!< Qualify frequency */
852 static int global_qualify_gap; /*!< Time between our group of peer pokes */
853 static int global_qualify_peers; /*!< Number of peers to poke at a given time */
854 
855 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
856 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher */
857 static int global_min_se; /*!< Lowest threshold for session refresh interval */
858 static int global_max_se; /*!< Highest threshold for session refresh interval */
859 
860 static int global_store_sip_cause; /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
861 
862 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
863 static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
864 /*@}*/
865 
866 /*!
867  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
868  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
869  * event package. This variable is set at module load time and may be checked at runtime to determine
870  * if XML parsing support was found.
871  */
872 static int can_parse_xml;
873 
874 /*! \name Object counters @{
875  *
876  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
877  * should be used to modify these values.
878  */
879 static int speerobjs = 0; /*!< Static peers */
880 static int rpeerobjs = 0; /*!< Realtime peers */
881 static int apeerobjs = 0; /*!< Autocreated peer objects */
882 /*! @} */
883 
884 static struct ast_flags global_flags[3] = {{0}}; /*!< global SIP_ flags */
885 static unsigned int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
886 
887 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
888 static struct stasis_subscription *acl_change_sub; /*!< subscription id for named ACL system change events */
889 static int network_change_sched_id = -1;
890 
891 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
892 
894 
895 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
896  when it's doing something critical. */
898 
900 
901 /*! \brief This is the thread for the monitor which checks for input on the channels
902  which are not currently in use. */
904 
905 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
906 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
907 
908 struct ast_sched_context *sched; /*!< The scheduling context */
909 static struct io_context *io; /*!< The IO context */
910 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
911 struct sip_pkt;
912 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
913 
914 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
915 
916 static enum sip_debug_e sipdebug;
917 
918 /*! \brief extra debugging for 'text' related events.
919  * At the moment this is set together with sip_debug_console.
920  * \note It should either go away or be implemented properly.
921  */
922 static int sipdebug_text;
923 
924 static const struct _map_x_s referstatusstrings[] = {
925  { REFER_IDLE, "<none>" },
926  { REFER_SENT, "Request sent" },
927  { REFER_RECEIVED, "Request received" },
928  { REFER_CONFIRMED, "Confirmed" },
929  { REFER_ACCEPTED, "Accepted" },
930  { REFER_RINGING, "Target ringing" },
931  { REFER_200OK, "Done" },
932  { REFER_FAILED, "Failed" },
933  { REFER_NOAUTH, "Failed - auth failure" },
934  { -1, NULL} /* terminator */
935 };
936 
937 /* --- Hash tables of various objects --------*/
938 #ifdef LOW_MEMORY
939 static const int HASH_PEER_SIZE = 17;
940 static const int HASH_DIALOG_SIZE = 17;
941 static const int HASH_REGISTRY_SIZE = 17;
942 #else
943 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
944 static const int HASH_DIALOG_SIZE = 563;
945 static const int HASH_REGISTRY_SIZE = 563;
946 #endif
947 
948 static const struct {
950  const char *service_string;
951 } sip_cc_service_map [] = {
952  [AST_CC_NONE] = { AST_CC_NONE, "" },
953  [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
954  [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
955  [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
956 };
957 
958 static const struct {
960  const char *state_string;
962  [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
963  [CC_READY] = {CC_READY, "cc-state: ready"},
964 };
965 
967 
968 
969 /*!
970  * Used to create new entity IDs by ESCs.
971  */
972 static int esc_etag_counter;
973 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
974 
975 #ifdef HAVE_LIBXML2
976 static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
977 
980  .modify_handler = cc_esc_publish_handler,
981 };
982 #endif
983 
984 /*!
985  * \brief The Event State Compositors
986  *
987  * An Event State Compositor is an entity which
988  * accepts PUBLISH requests and acts appropriately
989  * based on these requests.
990  *
991  * The actual event_state_compositor structure is simply
992  * an ao2_container of sip_esc_entrys. When an incoming
993  * PUBLISH is received, we can match the appropriate sip_esc_entry
994  * using the entity ID of the incoming PUBLISH.
995  */
996 static struct event_state_compositor {
998  const char * name;
1001 } event_state_compositors [] = {
1002 #ifdef HAVE_LIBXML2
1003  {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
1004 #endif
1005 };
1006 
1008  int state;
1011  const char *presence_subtype;
1012  const char *presence_message;
1013 };
1014 
1015 
1016 static const int ESC_MAX_BUCKETS = 37;
1017 
1018 /*!
1019  * \details
1020  * Here we implement the container for dialogs which are in the
1021  * dialog_needdestroy state to iterate only through the dialogs
1022  * unlink them instead of iterate through all dialogs
1023  */
1025 
1026 /*!
1027  * \details
1028  * Here we implement the container for dialogs which have rtp
1029  * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1030  * set. We use this container instead the whole dialog list.
1031  */
1033 
1034 /*!
1035  * \details
1036  * Here we implement the container for dialogs (sip_pvt), defining
1037  * generic wrapper functions to ease the transition from the current
1038  * implementation (a single linked list) to a different container.
1039  * In addition to a reference to the container, we need functions to lock/unlock
1040  * the container and individual items, and functions to add/remove
1041  * references to the individual items.
1042  */
1043 static struct ao2_container *dialogs;
1044 #define sip_pvt_lock(x) ao2_lock(x)
1045 #define sip_pvt_trylock(x) ao2_trylock(x)
1046 #define sip_pvt_unlock(x) ao2_unlock(x)
1047 
1048 /*! \brief The table of TCP threads */
1049 static struct ao2_container *threadt;
1050 
1051 /*! \brief The peer list: Users, Peers and Friends */
1052 static struct ao2_container *peers;
1054 
1055 /*! \brief A bogus peer, to be used when authentication should fail */
1056 static AO2_GLOBAL_OBJ_STATIC(g_bogus_peer);
1057 /*! \brief We can recognize the bogus peer by this invalid MD5 hash */
1058 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
1059 
1060 /*! \brief The register list: Other SIP proxies we register with and receive calls from */
1062 
1063 /*! \brief The MWI subscription list */
1065 
1066 static int temp_pvt_init(void *);
1067 static void temp_pvt_cleanup(void *);
1068 
1069 /*! \brief A per-thread temporary pvt structure */
1071 
1072 /*! \brief A per-thread buffer for transport to string conversion */
1074 
1075 /*! \brief Size of the SIP transport buffer */
1076 #define SIP_TRANSPORT_STR_BUFSIZE 128
1077 
1078 /*! \brief Authentication container for realm authentication */
1079 static struct sip_auth_container *authl = NULL;
1080 /*! \brief Global authentication container protection while adjusting the references. */
1082 
1084 STASIS_MESSAGE_TYPE_DEFN_LOCAL(session_timeout_type,
1086  );
1087 
1088 /* --- Sockets and networking --------------*/
1089 
1090 /*! \brief Main socket for UDP SIP communication.
1091  *
1092  * sipsock is shared between the SIP manager thread (which handles reload
1093  * requests), the udp io handler (sipsock_read()) and the user routines that
1094  * issue udp writes (using __sip_xmit()).
1095  * The socket is -1 only when opening fails (this is a permanent condition),
1096  * or when we are handling a reload() that changes its address (this is
1097  * a transient situation during which we might have a harmless race, see
1098  * below). Because the conditions for the race to be possible are extremely
1099  * rare, we don't want to pay the cost of locking on every I/O.
1100  * Rather, we remember that when the race may occur, communication is
1101  * bound to fail anyways, so we just live with this event and let
1102  * the protocol handle this above us.
1103  */
1104 static int sipsock = -1;
1105 
1106 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
1107 
1108 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1109  * internip is initialized picking a suitable address from one of the
1110  * interfaces, and the same port number we bind to. It is used as the
1111  * default address/port in SIP messages, and as the default address
1112  * (but not port) in SDP messages.
1113  */
1114 static struct ast_sockaddr internip;
1115 
1116 /*! \brief our external IP address/port for SIP sessions.
1117  * externaddr.sin_addr is only set when we know we might be behind
1118  * a NAT, and this is done using a variety of (mutually exclusive)
1119  * ways from the config file:
1120  *
1121  * + with "externaddr = host[:port]" we specify the address/port explicitly.
1122  * The address is looked up only once when (re)loading the config file;
1123  *
1124  * + with "externhost = host[:port]" we do a similar thing, but the
1125  * hostname is stored in externhost, and the hostname->IP mapping
1126  * is refreshed every 'externrefresh' seconds;
1127  *
1128  * Other variables (externhost, externexpire, externrefresh) are used
1129  * to support the above functions.
1130  */
1131 static struct ast_sockaddr externaddr; /*!< External IP address if we are behind NAT */
1132 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1133 static struct ast_sockaddr rtpbindaddr; /*!< RTP: The address we bind to */
1134 
1135 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1136 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1137 static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
1138 static uint16_t externtcpport; /*!< external tcp port */
1139 static uint16_t externtlsport; /*!< external tls port */
1140 
1141 /*! \brief List of local networks
1142  * We store "localnet" addresses from the config file into an access list,
1143  * marked as 'DENY', so the call to ast_apply_ha() will return
1144  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1145  * (i.e. presumably public) addresses.
1146  */
1147 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1148 
1149 static int ourport_tcp; /*!< The port used for TCP connections */
1150 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1151 static struct ast_sockaddr debugaddr;
1152 
1153 static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
1154 
1155 /*! some list management macros. */
1156 
1157 #define UNLINK(element, head, prev) do { \
1158  if (prev) \
1159  (prev)->next = (element)->next; \
1160  else \
1161  (head) = (element)->next; \
1162  } while (0)
1163 
1165 
1166 struct show_peers_context;
1167 
1168 /*---------------------------- Forward declarations of functions in chan_sip.c */
1169 /* Note: This is added to help splitting up chan_sip.c into several files
1170  in coming releases. */
1171 
1172 /*--- PBX interface functions */
1173 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause);
1174 static int sip_devicestate(const char *data);
1175 static int sip_sendtext(struct ast_channel *ast, const char *text);
1176 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1177 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1178 static int sip_hangup(struct ast_channel *ast);
1179 static int sip_answer(struct ast_channel *ast);
1180 static struct ast_frame *sip_read(struct ast_channel *ast);
1181 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1182 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1183 static int sip_transfer(struct ast_channel *ast, const char *dest);
1184 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1185 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1186 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1187 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1188 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1189 static const char *sip_get_callid(struct ast_channel *chan);
1190 
1191 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1192 static int sip_standard_port(enum ast_transport type, int port);
1193 static int sip_prepare_socket(struct sip_pvt *p);
1194 static int get_address_family_filter(unsigned int transport);
1195 
1196 /*--- Transmitting responses and requests */
1197 static int sipsock_read(int *id, int fd, short events, void *ignore);
1198 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1199 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1200 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1201 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1202 static int retrans_pkt(const void *data);
1203 static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1204 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1205 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1206 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1207 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
1208 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1209 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
1210 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1211 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1212 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
1213 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1214 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1215 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1216 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1217 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1218 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1219 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1220 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1221 static int transmit_message(struct sip_pvt *p, int init, int auth);
1222 static int transmit_refer(struct sip_pvt *p, const char *dest);
1223 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1224 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1225 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1226 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1227 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1228 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1229 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1230 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1231 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1232 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1233 
1234 /* Misc dialog routines */
1235 static int __sip_autodestruct(const void *data);
1236 static int update_call_counter(struct sip_pvt *fup, int event);
1237 static int auto_congest(const void *arg);
1238 static struct sip_pvt *__find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method,
1239  const char *file, int line, const char *func);
1240 #define find_call(req, addr, intended_method) \
1241  __find_call(req, addr, intended_method, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1242 
1243 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1244 static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf);
1245 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1246  struct sip_request *req, const char *uri);
1247 static int get_sip_pvt_from_replaces(const char *callid, const char *totag, const char *fromtag,
1248  struct sip_pvt **out_pvt, struct ast_channel **out_chan);
1249 static void check_pendings(struct sip_pvt *p);
1250 static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan);
1251 
1252 static void *sip_pickup_thread(void *stuff);
1253 static int sip_pickup(struct ast_channel *chan);
1254 
1255 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1256 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1257 
1258 /*--- Codec handling / SDP */
1259 static void try_suggested_sip_codec(struct sip_pvt *p);
1260 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1261 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1262 static int find_sdp(struct sip_request *req);
1263 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action, int is_offer);
1264 static int process_sdp_o(const char *o, struct sip_pvt *p);
1265 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1266 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1267 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance, int rtcp_mux);
1268 static int process_sdp_a_rtcp_mux(const char *a, struct sip_pvt *p, int *requested);
1269 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1270 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1271 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1272 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
1273 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1274 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1275 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1276 static void start_ice(struct ast_rtp_instance *instance, int offer);
1277 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1278  struct ast_str **m_buf, struct ast_str **a_buf,
1279  int debug, int *min_packet_size, int *max_packet_size);
1280 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1281  struct ast_str **m_buf, struct ast_str **a_buf,
1282  int debug);
1283 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1284 static void do_setnat(struct sip_pvt *p);
1285 static void stop_media_flows(struct sip_pvt *p);
1286 
1287 /*--- Authentication stuff */
1288 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1289 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1290 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1291  const char *secret, const char *md5secret, int sipmethod,
1292  const char *uri, enum xmittype reliable);
1293 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1294  int sipmethod, const char *uri, enum xmittype reliable,
1295  struct ast_sockaddr *addr, struct sip_peer **authpeer);
1296 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1297 
1298 /*--- Domain handling */
1299 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1300 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1301 static void clear_sip_domains(void);
1302 
1303 /*--- SIP realm authentication */
1304 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1305 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1306 
1307 /*--- Misc functions */
1308 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1309 static int reload_config(enum channelreloadreason reason);
1310 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
1311 static int expire_register(const void *data);
1312 static void *do_monitor(void *data);
1313 static int restart_monitor(void);
1314 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1315 static struct ast_variable *copy_vars(struct ast_variable *src);
1316 static int dialog_find_multiple(void *obj, void *arg, int flags);
1317 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1318 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1319 static int sip_refer_alloc(struct sip_pvt *p);
1320 static void sip_refer_destroy(struct sip_pvt *p);
1321 static int sip_notify_alloc(struct sip_pvt *p);
1322 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1323 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
1324 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
1325 
1326 /*--- Device monitoring and Device/extension state/event handling */
1327 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
1328 static int cb_extensionstate(const char *context, const char *exten, struct ast_state_cb_info *info, void *data);
1329 static int sip_poke_noanswer(const void *data);
1330 static int sip_poke_peer(struct sip_peer *peer, int force);
1331 static void sip_poke_all_peers(void);
1332 static void sip_peer_hold(struct sip_pvt *p, int hold);
1333 static void mwi_event_cb(void *, struct stasis_subscription *, struct stasis_message *);
1334 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1335 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1336 static void sip_keepalive_all_peers(void);
1337 #define peer_in_destruction(peer) (ao2_ref(peer, 0) == 0)
1338 
1339 /*--- Applications, functions, CLI and manager command helpers */
1340 static const char *sip_nat_mode(const struct sip_pvt *p);
1341 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1342 static char *transfermode2str(enum transfermodes mode) attribute_const;
1343 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1344 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1345 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1346 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
1347 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1348 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1349 static void print_group(int fd, ast_group_t group, int crlf);
1350 static void print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
1351 static const char *dtmfmode2str(int mode) attribute_const;
1352 static int str2dtmfmode(const char *str) attribute_unused;
1353 static const char *insecure2str(int mode) attribute_const;
1354 static const char *allowoverlap2str(int mode) attribute_const;
1355 static void cleanup_stale_contexts(char *new, char *old);
1356 static const char *domain_mode_to_text(const enum domain_mode mode);
1357 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1358 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1359 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1360 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1361 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1362 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1363 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1364 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1365 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1366 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1367 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1368 static char *complete_sip_peer(const char *word, int state, int flags2);
1369 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1370 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1371 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1372 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1373 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
1374 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1375 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1376 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1377 static char *sip_do_debug_ip(int fd, const char *arg);
1378 static char *sip_do_debug_peer(int fd, const char *arg);
1379 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1380 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1381 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1382 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1383 static int sip_addheader(struct ast_channel *chan, const char *data);
1384 static int sip_do_reload(enum channelreloadreason reason);
1385 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1387  const char *name, int flag);
1388 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1389  const char *name, int flag, unsigned int transport);
1390 
1391 /*--- Debugging
1392  Functions for enabling debug per IP or fully, or enabling history logging for
1393  a SIP dialog
1394 */
1395 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1396 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1397 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1398 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1399 static void sip_dump_history(struct sip_pvt *dialog);
1400 
1401 /*--- Device object handling */
1402 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1403 static int update_call_counter(struct sip_pvt *fup, int event);
1404 static void sip_destroy_peer(struct sip_peer *peer);
1405 static void sip_destroy_peer_fn(void *peer);
1406 static void set_peer_defaults(struct sip_peer *peer);
1407 static struct sip_peer *temp_peer(const char *name);
1408 static void register_peer_exten(struct sip_peer *peer, int onoff);
1409 static int sip_poke_peer_s(const void *data);
1410 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1411 static void reg_source_db(struct sip_peer *peer);
1412 static void destroy_association(struct sip_peer *peer);
1413 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1414 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1415 static void set_socket_transport(struct sip_socket *socket, int transport);
1416 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1417 
1418 /* Realtime device support */
1419 static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms, const char *path);
1420 static void update_peer(struct sip_peer *p, int expire);
1422 static const char *get_name_from_variable(const struct ast_variable *var);
1423 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1424 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1425 
1426 /*--- Internal UA client handling (outbound registrations) */
1427 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1428 static void sip_registry_destroy(void *reg);
1429 static int sip_register(const char *value, int lineno);
1430 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1431 static int __sip_do_register(struct sip_registry *r);
1432 static int sip_reg_timeout(const void *data);
1433 static void sip_send_all_registers(void);
1434 static int sip_reinvite_retry(const void *data);
1435 
1436 /*--- Parsing SIP requests and responses */
1437 static int determine_firstline_parts(struct sip_request *req);
1438 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1439 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1440 static int find_sip_method(const char *msg);
1441 static unsigned int parse_allowed_methods(struct sip_request *req);
1442 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1443 static int parse_request(struct sip_request *req);
1444 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1445 static int method_match(enum sipmethod id, const char *name);
1446 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1447 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1448 static const char *find_alias(const char *name, const char *_default);
1449 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1450 static void lws2sws(struct ast_str *msgbuf);
1451 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1452 static char *remove_uri_parameters(char *uri);
1453 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1454 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1455 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1456 static int use_reason_header(struct sip_pvt *pvt, struct sip_request *req);
1457 static int set_address_from_contact(struct sip_pvt *pvt);
1458 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1459 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1460 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
1461 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1462 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1463 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1464 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1465 static int get_domain(const char *str, char *domain, int len);
1466 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1467 static char *get_content(struct sip_request *req);
1468 
1469 /*-- TCP connection handling ---*/
1470 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1471 static void *sip_tcp_worker_fn(void *);
1472 
1473 /*--- Constructing requests and responses */
1474 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1475 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1476 static void deinit_req(struct sip_request *req);
1477 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1478 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1479 static int init_resp(struct sip_request *resp, const char *msg);
1480 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1481 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1482 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1483 static void build_via(struct sip_pvt *p);
1484 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1485 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
1486 static char *generate_random_string(char *buf, size_t size);
1487 static void build_callid_pvt(struct sip_pvt *pvt);
1488 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1489 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1490 static void build_localtag_registry(struct sip_registry *reg);
1491 static void make_our_tag(struct sip_pvt *pvt);
1492 static int add_header(struct sip_request *req, const char *var, const char *value);
1493 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1494 static int add_content(struct sip_request *req, const char *line);
1495 static int finalize_content(struct sip_request *req);
1496 static void destroy_msg_headers(struct sip_pvt *pvt);
1497 static int add_text(struct sip_request *req, struct sip_pvt *p);
1498 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1499 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1500 static int add_vidupdate(struct sip_request *req);
1501 static void add_route(struct sip_request *req, struct sip_route *route, int skip);
1502 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1503 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1504 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1505 static void set_destination(struct sip_pvt *p, const char *uri);
1506 static void add_date(struct sip_request *req);
1507 static void add_expires(struct sip_request *req, int expires);
1508 static void build_contact(struct sip_pvt *p, struct sip_request *req, int incoming);
1509 
1510 /*------Request handling functions */
1511 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1512 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1513 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *recount, const char *e, int *nounlock);
1514 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
1515 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1516 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1517 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1518 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1519 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1520 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1521 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1522 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
1523  int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan);
1524 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1525 static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock);
1526 
1527 /*------Response handling functions */
1528 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1529 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1530 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1531 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1532 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1533 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1534 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1535 
1536 /*------ SRTP Support -------- */
1537 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp,
1538  const char *a);
1539 
1540 /*------ T38 Support --------- */
1541 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1542 static void change_t38_state(struct sip_pvt *p, int state);
1543 
1544 /*------ Session-Timers functions --------- */
1545 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1546 static void stop_session_timer(struct sip_pvt *p);
1547 static void start_session_timer(struct sip_pvt *p);
1548 static void restart_session_timer(struct sip_pvt *p);
1549 static const char *strefresherparam2str(enum st_refresher_param r);
1550 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
1551 static int parse_minse(const char *p_hdrval, int *const p_interval);
1552 static int st_get_se(struct sip_pvt *, int max);
1553 static enum st_refresher st_get_refresher(struct sip_pvt *);
1554 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1555 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1556 
1557 /*------- RTP Glue functions -------- */
1558 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
1559 
1560 /*!--- SIP MWI Subscription support */
1561 static int sip_subscribe_mwi(const char *value, int lineno);
1562 static void sip_send_all_mwi_subscriptions(void);
1563 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1564 
1565 /* Scheduler id start/stop/reschedule functions. */
1566 static void stop_provisional_keepalive(struct sip_pvt *pvt);
1567 static void do_stop_session_timer(struct sip_pvt *pvt);
1568 static void stop_reinvite_retry(struct sip_pvt *pvt);
1569 static void stop_retrans_pkt(struct sip_pkt *pkt);
1570 static void stop_t38_abort_timer(struct sip_pvt *pvt);
1571 
1572 /*! \brief Definition of this channel for PBX channel registration */
1574  .type = "SIP",
1575  .description = "Session Initiation Protocol (SIP)",
1577  .requester = sip_request_call, /* called with chan unlocked */
1578  .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1579  .call = sip_call, /* called with chan locked */
1580  .send_html = sip_sendhtml,
1581  .hangup = sip_hangup, /* called with chan locked */
1582  .answer = sip_answer, /* called with chan locked */
1583  .read = sip_read, /* called with chan locked */
1584  .write = sip_write, /* called with chan locked */
1585  .write_video = sip_write, /* called with chan locked */
1586  .write_text = sip_write,
1587  .indicate = sip_indicate, /* called with chan locked */
1588  .transfer = sip_transfer, /* called with chan locked */
1589  .fixup = sip_fixup, /* called with chan locked */
1590  .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1591  .send_digit_end = sip_senddigit_end,
1592  .early_bridge = ast_rtp_instance_early_bridge,
1593  .send_text = sip_sendtext, /* called with chan locked */
1594  .func_channel_read = sip_acf_channel_read,
1595  .setoption = sip_setoption,
1596  .queryoption = sip_queryoption,
1597  .get_pvt_uniqueid = sip_get_callid,
1598 };
1599 
1600 /*! \brief This version of the sip channel tech has no send_digit_begin
1601  * callback so that the core knows that the channel does not want
1602  * DTMF BEGIN frames.
1603  * The struct is initialized just before registering the channel driver,
1604  * and is for use with channels using SIP INFO DTMF.
1605  */
1607 
1608 /*------- CC Support -------- */
1609 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1610 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1611 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1612 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1613 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1614 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1615 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1616 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1617 
1619  .type = "SIP",
1620  .init = sip_cc_agent_init,
1621  .start_offer_timer = sip_cc_agent_start_offer_timer,
1622  .stop_offer_timer = sip_cc_agent_stop_offer_timer,
1623  .respond = sip_cc_agent_respond,
1624  .status_request = sip_cc_agent_status_request,
1625  .start_monitoring = sip_cc_agent_start_monitoring,
1626  .callee_available = sip_cc_agent_recall,
1627  .destructor = sip_cc_agent_destructor,
1628 };
1629 
1630 /* -------- End of declarations of structures, constants and forward declarations of functions
1631  Below starts actual code
1632  ------------------------
1633 */
1634 
1635 static int sip_epa_register(const struct epa_static_data *static_data)
1636 {
1637  struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
1638 
1639  if (!backend) {
1640  return -1;
1641  }
1642 
1643  backend->static_data = static_data;
1644 
1648  return 0;
1649 }
1650 
1651 static void sip_epa_unregister_all(void)
1652 {
1653  struct epa_backend *backend;
1654 
1656  while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
1657  ast_free(backend);
1658  }
1660 }
1661 
1662 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
1663 
1664 static void cc_epa_destructor(void *data)
1665 {
1666  struct sip_epa_entry *epa_entry = data;
1667  struct cc_epa_entry *cc_entry = epa_entry->instance_data;
1668  ast_free(cc_entry);
1669 }
1670 
1671 static const struct epa_static_data cc_epa_static_data = {
1673  .name = "call-completion",
1674  .handle_error = cc_handle_publish_error,
1675  .destructor = cc_epa_destructor,
1676 };
1677 
1678 static const struct epa_static_data *find_static_data(const char * const event_package)
1679 {
1680  const struct epa_backend *backend = NULL;
1681 
1684  if (!strcmp(backend->static_data->name, event_package)) {
1685  break;
1686  }
1687  }
1689  return backend ? backend->static_data : NULL;
1690 }
1691 
1692 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
1693 {
1694  struct sip_epa_entry *epa_entry;
1695  const struct epa_static_data *static_data;
1696 
1697  if (!(static_data = find_static_data(event_package))) {
1698  return NULL;
1699  }
1700 
1701  if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
1702  return NULL;
1703  }
1704 
1705  epa_entry->static_data = static_data;
1706  ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
1707  return epa_entry;
1708 }
1710 {
1712  for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
1713  if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
1714  return service;
1715  }
1716  }
1717  return AST_CC_NONE;
1718 }
1719 
1720 /* Even state compositors code */
1721 static void esc_entry_destructor(void *obj)
1722 {
1723  struct sip_esc_entry *esc_entry = obj;
1724  if (esc_entry->sched_id > -1) {
1725  AST_SCHED_DEL(sched, esc_entry->sched_id);
1726  }
1727 }
1728 
1729 static int esc_hash_fn(const void *obj, const int flags)
1730 {
1731  const struct sip_esc_entry *entry = obj;
1732  return ast_str_hash(entry->entity_tag);
1733 }
1734 
1735 static int esc_cmp_fn(void *obj, void *arg, int flags)
1736 {
1737  struct sip_esc_entry *entry1 = obj;
1738  struct sip_esc_entry *entry2 = arg;
1739 
1740  return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1741 }
1742 
1743 static struct event_state_compositor *get_esc(const char * const event_package) {
1744  int i;
1745  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1746  if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1747  return &event_state_compositors[i];
1748  }
1749  }
1750  return NULL;
1751 }
1752 
1753 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1754  struct sip_esc_entry *entry;
1755  struct sip_esc_entry finder;
1756 
1757  ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1758 
1759  entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1760 
1761  return entry;
1762 }
1763 
1764 static int publish_expire(const void *data)
1765 {
1766  struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1767  struct event_state_compositor *esc = get_esc(esc_entry->event);
1768 
1769  ast_assert(esc != NULL);
1770 
1771  ao2_unlink(esc->compositor, esc_entry);
1772  esc_entry->sched_id = -1;
1773  ao2_ref(esc_entry, -1);
1774  return 0;
1775 }
1776 
1777 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1778 {
1779  int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1780  struct event_state_compositor *esc = get_esc(esc_entry->event);
1781 
1782  ast_assert(esc != NULL);
1783  if (is_linked) {
1784  ao2_unlink(esc->compositor, esc_entry);
1785  }
1786  snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1787  ao2_link(esc->compositor, esc_entry);
1788 }
1789 
1790 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1791 {
1792  struct sip_esc_entry *esc_entry;
1793  int expires_ms;
1794 
1795  if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1796  return NULL;
1797  }
1798 
1799  esc_entry->event = esc->name;
1800 
1801  expires_ms = expires * 1000;
1802  /* Bump refcount for scheduler */
1803  ao2_ref(esc_entry, +1);
1804  esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1805  if (esc_entry->sched_id == -1) {
1806  ao2_ref(esc_entry, -1);
1807  ao2_ref(esc_entry, -1);
1808  return NULL;
1809  }
1810 
1811  /* Note: This links the esc_entry into the ESC properly */
1812  create_new_sip_etag(esc_entry, 0);
1813 
1814  return esc_entry;
1815 }
1816 
1817 static int initialize_escs(void)
1818 {
1819  int i, res = 0;
1820  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1823  if (!event_state_compositors[i].compositor) {
1824  res = -1;
1825  }
1826  }
1827  return res;
1828 }
1829 
1830 static void destroy_escs(void)
1831 {
1832  int i;
1833  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1834  ao2_replace(event_state_compositors[i].compositor, NULL);
1835  }
1836 }
1837 
1838 
1839 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1840 {
1841  struct ast_cc_agent *agent = obj;
1842  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1843  const char *uri = arg;
1844 
1845  return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1846 }
1847 
1848 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1849 {
1850  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1851  return agent;
1852 }
1853 
1854 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1855 {
1856  struct ast_cc_agent *agent = obj;
1857  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1858  const char *uri = arg;
1859 
1860  return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1861 }
1862 
1863 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1864 {
1865  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1866  return agent;
1867 }
1868 
1869 static int find_by_callid_helper(void *obj, void *arg, int flags)
1870 {
1871  struct ast_cc_agent *agent = obj;
1872  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1873  struct sip_pvt *call_pvt = arg;
1874 
1875  return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1876 }
1877 
1879 {
1880  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1881  return agent;
1882 }
1883 
1884 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1885 {
1886  struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1887  struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1888 
1889  if (!agent_pvt) {
1890  return -1;
1891  }
1892 
1893  ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1894 
1895  ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1896  ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1897  agent_pvt->offer_timer_id = -1;
1898  agent->private_data = agent_pvt;
1899  sip_pvt_lock(call_pvt);
1900  ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1901  sip_pvt_unlock(call_pvt);
1902  return 0;
1903 }
1904 
1905 static int sip_offer_timer_expire(const void *data)
1906 {
1907  struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1908  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1909 
1910  agent_pvt->offer_timer_id = -1;
1911 
1912  return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1913 }
1914 
1916 {
1917  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1918  int when;
1919 
1920  when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1921  agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1922  return 0;
1923 }
1924 
1926 {
1927  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1928 
1929  AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1930  return 0;
1931 }
1932 
1933 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1934 {
1935  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1936 
1937  sip_pvt_lock(agent_pvt->subscribe_pvt);
1939  if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1940  /* The second half of this if statement may be a bit hard to grasp,
1941  * so here's an explanation. When a subscription comes into
1942  * chan_sip, as long as it is not malformed, it will be passed
1943  * to the CC core. If the core senses an out-of-order state transition,
1944  * then the core will call this callback with the "reason" set to a
1945  * failure condition.
1946  * However, an out-of-order state transition will occur during a resubscription
1947  * for CC. In such a case, we can see that we have already generated a notify_uri
1948  * and so we can detect that this isn't a *real* failure. Rather, it is just
1949  * something the core doesn't recognize as a legitimate SIP state transition.
1950  * Thus we respond with happiness and flowers.
1951  */
1952  transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1953  transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1954  } else {
1955  transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1956  }
1957  sip_pvt_unlock(agent_pvt->subscribe_pvt);
1958  agent_pvt->is_available = TRUE;
1959 }
1960 
1962 {
1963  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1965  return ast_cc_agent_status_response(agent->core_id, state);
1966 }
1967 
1969 {
1970  /* To start monitoring just means to wait for an incoming PUBLISH
1971  * to tell us that the caller has become available again. No special
1972  * action is needed
1973  */
1974  return 0;
1975 }
1976 
1977 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1978 {
1979  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1980  /* If we have received a PUBLISH beforehand stating that the caller in question
1981  * is not available, we can save ourself a bit of effort here and just report
1982  * the caller as busy
1983  */
1984  if (!agent_pvt->is_available) {
1985  return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1986  agent->device_name);
1987  }
1988  /* Otherwise, we transmit a NOTIFY to the caller and await either
1989  * a PUBLISH or an INVITE
1990  */
1991  sip_pvt_lock(agent_pvt->subscribe_pvt);
1992  transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1993  sip_pvt_unlock(agent_pvt->subscribe_pvt);
1994  return 0;
1995 }
1996 
1997 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1998 {
1999  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
2000 
2001  if (!agent_pvt) {
2002  /* The agent constructor probably failed. */
2003  return;
2004  }
2005 
2007  if (agent_pvt->subscribe_pvt) {
2008  sip_pvt_lock(agent_pvt->subscribe_pvt);
2010  /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
2011  * the subscriber know something went wrong
2012  */
2013  transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
2014  }
2015  sip_pvt_unlock(agent_pvt->subscribe_pvt);
2016  agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
2017  }
2018  ast_free(agent_pvt);
2019 }
2020 
2021 
2022 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
2023 {
2024  const struct sip_monitor_instance *monitor_instance = obj;
2025  return monitor_instance->core_id;
2026 }
2027 
2028 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
2029 {
2030  struct sip_monitor_instance *monitor_instance1 = obj;
2031  struct sip_monitor_instance *monitor_instance2 = arg;
2032 
2033  return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
2034 }
2035 
2036 static void sip_monitor_instance_destructor(void *data)
2037 {
2038  struct sip_monitor_instance *monitor_instance = data;
2039  if (monitor_instance->subscription_pvt) {
2040  sip_pvt_lock(monitor_instance->subscription_pvt);
2041  monitor_instance->subscription_pvt->expiry = 0;
2042  transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
2043  sip_pvt_unlock(monitor_instance->subscription_pvt);
2044  dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
2045  }
2046  if (monitor_instance->suspension_entry) {
2047  monitor_instance->suspension_entry->body[0] = '\0';
2048  transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
2049  ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
2050  }
2051  ast_string_field_free_memory(monitor_instance);
2052 }
2053 
2054 static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)
2055 {
2056  struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
2057 
2058  if (!monitor_instance) {
2059  return NULL;
2060  }
2061 
2062  if (ast_string_field_init(monitor_instance, 256)) {
2063  ao2_ref(monitor_instance, -1);
2064  return NULL;
2065  }
2066 
2067  ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
2068  ast_string_field_set(monitor_instance, peername, peername);
2069  ast_string_field_set(monitor_instance, device_name, device_name);
2070  monitor_instance->core_id = core_id;
2071  ao2_link(sip_monitor_instances, monitor_instance);
2072  return monitor_instance;
2073 }
2074 
2075 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
2076 {
2077  struct sip_monitor_instance *monitor_instance = obj;
2078  return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
2079 }
2080 
2081 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
2082 {
2083  struct sip_monitor_instance *monitor_instance = obj;
2084  return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
2085 }
2086 
2087 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
2088 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
2089 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
2090 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
2091 static void sip_cc_monitor_destructor(void *private_data);
2092 
2094  .type = "SIP",
2095  .request_cc = sip_cc_monitor_request_cc,
2096  .suspend = sip_cc_monitor_suspend,
2097  .unsuspend = sip_cc_monitor_unsuspend,
2098  .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
2099  .destructor = sip_cc_monitor_destructor,
2100 };
2101 
2102 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
2103 {
2104  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2106  int when;
2107 
2108  if (!monitor_instance) {
2109  return -1;
2110  }
2111 
2112  if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, 0))) {
2113  return -1;
2114  }
2115 
2116  when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
2118 
2119  sip_pvt_lock(monitor_instance->subscription_pvt);
2120  ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
2121  create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
2122  ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
2123  monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
2124  monitor_instance->subscription_pvt->expiry = when;
2125 
2126  transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
2127  sip_pvt_unlock(monitor_instance->subscription_pvt);
2128 
2129  ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
2130  *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
2131  return 0;
2132 }
2133 
2134 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
2135 {
2136  struct ast_str *body = ast_str_alloca(size);
2137  char tuple_id[64];
2138 
2139  generate_random_string(tuple_id, sizeof(tuple_id));
2140 
2141  /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
2142  * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
2143  */
2144  ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2145  /* XXX The entity attribute is currently set to the peer name associated with the
2146  * dialog. This is because we currently only call this function for call-completion
2147  * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
2148  * event packages, it may be crucial to have a proper URI as the presentity so this
2149  * should be revisited as support is expanded.
2150  */
2151  ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
2152  ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2153  ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
2154  ast_str_append(&body, 0, "</tuple>\n");
2155  ast_str_append(&body, 0, "</presence>\n");
2156  ast_copy_string(pidf_body, ast_str_buffer(body), size);
2157  return 0;
2158 }
2159 
2160 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2161 {
2162  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2163  enum sip_publish_type publish_type;
2164  struct cc_epa_entry *cc_entry;
2165 
2166  if (!monitor_instance) {
2167  return -1;
2168  }
2169 
2170  if (!monitor_instance->suspension_entry) {
2171  /* We haven't yet allocated the suspension entry, so let's give it a shot */
2172  if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2173  ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2174  ao2_ref(monitor_instance, -1);
2175  return -1;
2176  }
2177  if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2178  ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2179  ao2_ref(monitor_instance, -1);
2180  return -1;
2181  }
2182  cc_entry->core_id = monitor->core_id;
2183  monitor_instance->suspension_entry->instance_data = cc_entry;
2184  publish_type = SIP_PUBLISH_INITIAL;
2185  } else {
2186  publish_type = SIP_PUBLISH_MODIFY;
2187  cc_entry = monitor_instance->suspension_entry->instance_data;
2188  }
2189 
2190  cc_entry->current_state = CC_CLOSED;
2191 
2192  if (ast_strlen_zero(monitor_instance->notify_uri)) {
2193  /* If we have no set notify_uri, then what this means is that we have
2194  * not received a NOTIFY from this destination stating that he is
2195  * currently available.
2196  *
2197  * This situation can arise when the core calls the suspend callbacks
2198  * of multiple destinations. If one of the other destinations aside
2199  * from this one notified Asterisk that he is available, then there
2200  * is no reason to take any suspension action on this device. Rather,
2201  * we should return now and if we receive a NOTIFY while monitoring
2202  * is still "suspended" then we can immediately respond with the
2203  * proper PUBLISH to let this endpoint know what is going on.
2204  */
2205  return 0;
2206  }
2207  construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2208  return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2209 }
2210 
2211 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2212 {
2213  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2214  struct cc_epa_entry *cc_entry;
2215 
2216  if (!monitor_instance) {
2217  return -1;
2218  }
2219 
2220  ast_assert(monitor_instance->suspension_entry != NULL);
2221 
2222  cc_entry = monitor_instance->suspension_entry->instance_data;
2223  cc_entry->current_state = CC_OPEN;
2224  if (ast_strlen_zero(monitor_instance->notify_uri)) {
2225  /* This means we are being asked to unsuspend a call leg we never
2226  * sent a PUBLISH on. As such, there is no reason to send another
2227  * PUBLISH at this point either. We can just return instead.
2228  */
2229  return 0;
2230  }
2231  construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2232  return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2233 }
2234 
2236 {
2237  if (*sched_id != -1) {
2238  AST_SCHED_DEL(sched, *sched_id);
2239  ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2240  }
2241  return 0;
2242 }
2243 
2244 static void sip_cc_monitor_destructor(void *private_data)
2245 {
2246  struct sip_monitor_instance *monitor_instance = private_data;
2247  ao2_unlink(sip_monitor_instances, monitor_instance);
2249 }
2250 
2251 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2252 {
2253  char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2254  char *uri;
2255  char *purpose;
2256  char *service_str;
2257  static const char cc_purpose[] = "purpose=call-completion";
2258  static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2259 
2260  if (ast_strlen_zero(call_info)) {
2261  /* No Call-Info present. Definitely no CC offer */
2262  return -1;
2263  }
2264 
2265  uri = strsep(&call_info, ";");
2266 
2267  while ((purpose = strsep(&call_info, ";"))) {
2268  if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2269  break;
2270  }
2271  }
2272  if (!purpose) {
2273  /* We didn't find the appropriate purpose= parameter. Oh well */
2274  return -1;
2275  }
2276 
2277  /* Okay, call-completion has been offered. Let's figure out what type of service this is */
2278  while ((service_str = strsep(&call_info, ";"))) {
2279  if (!strncmp(service_str, "m=", 2)) {
2280  break;
2281  }
2282  }
2283  if (!service_str) {
2284  /* So they didn't offer a particular service, We'll just go with CCBS since it really
2285  * doesn't matter anyway
2286  */
2287  service_str = "BS";
2288  } else {
2289  /* We already determined that there is an "m=" so no need to check
2290  * the result of this strsep
2291  */
2292  strsep(&service_str, "=");
2293  }
2294 
2295  if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2296  /* Invalid service offered */
2297  return -1;
2298  }
2299 
2300  ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2301 
2302  return 0;
2303 }
2304 
2305 /*
2306  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2307  *
2308  * After taking care of some formalities to be sure that this call is eligible for CC,
2309  * we first try to see if we can make use of native CC. We grab the information from
2310  * the passed-in sip_request (which is always a response to an INVITE). If we can
2311  * use native CC monitoring for the call, then so be it.
2312  *
2313  * If native cc monitoring is not possible or not supported, then we will instead attempt
2314  * to use generic monitoring. Falling back to generic from a failed attempt at using native
2315  * monitoring will only work if the monitor policy of the endpoint is "always"
2316  *
2317  * \param pvt The current dialog. Contains CC parameters for the endpoint
2318  * \param req The response to the INVITE we want to inspect
2319  * \param service The service to use if generic monitoring is to be used. For native
2320  * monitoring, we get the service from the SIP response itself
2321  */
2322 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2323 {
2324  enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2325  int core_id;
2326  char interface_name[AST_CHANNEL_NAME];
2327 
2328  if (monitor_policy == AST_CC_MONITOR_NEVER) {
2329  /* Don't bother, just return */
2330  return;
2331  }
2332 
2333  if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2334  /* For some reason, CC is invalid, so don't try it! */
2335  return;
2336  }
2337 
2338  ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2339 
2340  if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2341  char subscribe_uri[SIPBUFSIZE];
2343  enum ast_cc_service_type offered_service;
2344  struct sip_monitor_instance *monitor_instance;
2345  if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2346  /* If CC isn't being offered to us, or for some reason the CC offer is
2347  * not formatted correctly, then it may still be possible to use generic
2348  * call completion since the monitor policy may be "always"
2349  */
2350  goto generic;
2351  }
2352  ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2353  if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2354  /* Same deal. We can try using generic still */
2355  goto generic;
2356  }
2357  /* We bump the refcount of chan_sip because once we queue this frame, the CC core
2358  * will have a reference to callbacks in this module. We decrement the module
2359  * refcount once the monitor destructor is called
2360  */
2362  ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2363  ao2_ref(monitor_instance, -1);
2364  return;
2365  }
2366 
2367 generic:
2368  if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2369  ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2370  }
2371 }
2372 
2373 /*! \brief Working TLS connection configuration */
2375 
2376 /*! \brief Default TLS connection configuration */
2378 
2379 /*! \brief Default DTLS connection configuration */
2381 
2382 /*! \brief The TCP server definition */
2384  .accept_fd = -1,
2385  .master = AST_PTHREADT_NULL,
2386  .tls_cfg = NULL,
2387  .poll_timeout = -1,
2388  .name = "SIP TCP server",
2389  .accept_fn = ast_tcptls_server_root,
2390  .worker_fn = sip_tcp_worker_fn,
2391 };
2392 
2393 /*! \brief The TCP/TLS server definition */
2395  .accept_fd = -1,
2396  .master = AST_PTHREADT_NULL,
2397  .tls_cfg = &sip_tls_cfg,
2398  .poll_timeout = -1,
2399  .name = "SIP TLS server",
2400  .accept_fn = ast_tcptls_server_root,
2401  .worker_fn = sip_tcp_worker_fn,
2402 };
2403 
2404 /*! \brief Append to SIP dialog history
2405  \return Always returns 0 */
2406 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2407 
2408 /*! \brief map from an integer value to a string.
2409  * If no match is found, return errorstring
2410  */
2411 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2412 {
2413  const struct _map_x_s *cur;
2414 
2415  for (cur = table; cur->s; cur++) {
2416  if (cur->x == x) {
2417  return cur->s;
2418  }
2419  }
2420  return errorstring;
2421 }
2422 
2423 /*! \brief map from a string to an integer value, case insensitive.
2424  * If no match is found, return errorvalue.
2425  */
2426 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2427 {
2428  const struct _map_x_s *cur;
2429 
2430  for (cur = table; cur->s; cur++) {
2431  if (!strcasecmp(cur->s, s)) {
2432  return cur->x;
2433  }
2434  }
2435  return errorvalue;
2436 }
2437 
2438 /*!
2439  * \internal
2440  * \brief Determine if the given string is a SIP token.
2441  * \since 13.8.0
2442  *
2443  * \param str String to determine if is a SIP token.
2444  *
2445  * \note A token is defined by RFC3261 Section 25.1
2446  *
2447  * \return Non-zero if the string is a SIP token.
2448  */
2449 static int sip_is_token(const char *str)
2450 {
2451  int is_token;
2452 
2453  if (ast_strlen_zero(str)) {
2454  /* An empty string is not a token. */
2455  return 0;
2456  }
2457 
2458  is_token = 1;
2459  do {
2460  if (!isalnum(*str)
2461  && !strchr("-.!%*_+`'~", *str)) {
2462  /* The character is not allowed in a token. */
2463  is_token = 0;
2464  break;
2465  }
2466  } while (*++str);
2467 
2468  return is_token;
2469 }
2470 
2471 static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason)
2472 {
2473  int idx;
2474  int code;
2475 
2476  /* use specific string if given */
2477  if (!ast_strlen_zero(reason->str)) {
2478  return reason->str;
2479  }
2480 
2481  code = reason->code;
2482  for (idx = 0; idx < ARRAY_LEN(sip_reason_table); ++idx) {
2483  if (code == sip_reason_table[idx].code) {
2484  return sip_reason_table[idx].text;
2485  }
2486  }
2487 
2488  return "unknown";
2489 }
2490 
2491 /*!
2492  * \brief generic function for determining if a correct transport is being
2493  * used to contact a peer
2494  *
2495  * this is done as a macro so that the "tmpl" var can be passed either a
2496  * sip_request or a sip_peer
2497  */
2498 #define check_request_transport(peer, tmpl) ({ \
2499  int ret = 0; \
2500  if (peer->socket.type == tmpl->socket.type) \
2501  ; \
2502  else if (!(peer->transports & tmpl->socket.type)) {\
2503  ast_log(LOG_ERROR, \
2504  "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2505  sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2506  ); \
2507  ret = 1; \
2508  } else if (peer->socket.type & AST_TRANSPORT_TLS) { \
2509  ast_log(LOG_WARNING, \
2510  "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2511  peer->name, sip_get_transport(tmpl->socket.type) \
2512  ); \
2513  } else { \
2514  ast_debug(1, \
2515  "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2516  peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2517  ); \
2518  }\
2519  (ret); \
2520 })
2521 
2522 /*! \brief
2523  * duplicate a list of channel variables, \return the copy.
2524  */
2525 static struct ast_variable *copy_vars(struct ast_variable *src)
2526 {
2527  struct ast_variable *res = NULL, *tmp, *v = NULL;
2528 
2529  for (v = src ; v ; v = v->next) {
2530  if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2531  tmp->next = res;
2532  res = tmp;
2533  }
2534  }
2535  return res;
2536 }
2537 
2538 static void tcptls_packet_destructor(void *obj)
2539 {
2540  struct tcptls_packet *packet = obj;
2541 
2542  ast_free(packet->data);
2543 }
2544 
2546 {
2547  struct ast_tcptls_session_args *args = obj;
2548  if (args->tls_cfg) {
2549  ast_free(args->tls_cfg->certfile);
2550  ast_free(args->tls_cfg->pvtfile);
2551  ast_free(args->tls_cfg->cipher);
2552  ast_free(args->tls_cfg->cafile);
2553  ast_free(args->tls_cfg->capath);
2554 
2555  ast_ssl_teardown(args->tls_cfg);
2556  }
2557  ast_free(args->tls_cfg);
2558  ast_free((char *) args->name);
2559 }
2560 
2561 static void sip_threadinfo_destructor(void *obj)
2562 {
2563  struct sip_threadinfo *th = obj;
2564  struct tcptls_packet *packet;
2565 
2566  if (th->alert_pipe[0] > -1) {
2567  close(th->alert_pipe[0]);
2568  }
2569  if (th->alert_pipe[1] > -1) {
2570  close(th->alert_pipe[1]);
2571  }
2572  th->alert_pipe[0] = th->alert_pipe[1] = -1;
2573 
2574  while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2575  ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2576  }
2577 
2578  if (th->tcptls_session) {
2579  ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2580  }
2581 }
2582 
2583 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2584 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2585 {
2586  struct sip_threadinfo *th;
2587 
2588  if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2589  return NULL;
2590  }
2591 
2592  th->alert_pipe[0] = th->alert_pipe[1] = -1;
2593 
2594  if (pipe(th->alert_pipe) == -1) {
2595  ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2596  ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2597  return NULL;
2598  }
2599  ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2600  th->tcptls_session = tcptls_session;
2601  th->type = transport ? transport : (ast_iostream_get_ssl(tcptls_session->stream) ? AST_TRANSPORT_TLS: AST_TRANSPORT_TCP);
2602  ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2603  ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2604  return th;
2605 }
2606 
2607 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
2608 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2609 {
2610  int res = len;
2611  struct sip_threadinfo *th = NULL;
2612  struct tcptls_packet *packet = NULL;
2613  struct sip_threadinfo tmp = {
2614  .tcptls_session = tcptls_session,
2615  };
2616  enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2617 
2618  if (!tcptls_session) {
2619  return XMIT_ERROR;
2620  }
2621 
2622  ao2_lock(tcptls_session);
2623 
2624  if (!tcptls_session->stream ||
2625  !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2626  !(packet->data = ast_str_create(len))) {
2627  goto tcptls_write_setup_error;
2628  }
2629 
2630  if (!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) {
2631  ast_log(LOG_ERROR, "Unable to locate tcptls_session helper thread.\n");
2632  goto tcptls_write_setup_error;
2633  }
2634 
2635  /* goto tcptls_write_error should _NOT_ be used beyond this point */
2636  ast_str_set(&packet->data, 0, "%s", (char *) buf);
2637  packet->len = len;
2638 
2639  /* alert tcptls thread handler that there is a packet to be sent.
2640  * must lock the thread info object to guarantee control of the
2641  * packet queue */
2642  ao2_lock(th);
2643  if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2644  ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2645  ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2646  packet = NULL;
2647  res = XMIT_ERROR;
2648  } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2649  AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2650  }
2651  ao2_unlock(th);
2652 
2653  ao2_unlock(tcptls_session);
2654  ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2655  return res;
2656 
2657 tcptls_write_setup_error:
2658  if (th) {
2659  ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2660  }
2661  if (packet) {
2662  ao2_t_ref(packet, -1, "could not allocate packet's data");
2663  }
2664  ao2_unlock(tcptls_session);
2665 
2666  return XMIT_ERROR;
2667 }
2668 
2669 /*! \brief SIP TCP connection handler */
2670 static void *sip_tcp_worker_fn(void *data)
2671 {
2672  struct ast_tcptls_session_instance *tcptls_session = data;
2673 
2674  return _sip_tcp_helper_thread(tcptls_session);
2675 }
2676 
2677 /*! \brief SIP WebSocket connection handler */
2678 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2679 {
2680  int res;
2681 
2682  if (ast_websocket_set_nonblock(session)) {
2683  goto end;
2684  }
2685 
2687  goto end;
2688  }
2689 
2690  while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2691  char *payload;
2692  uint64_t payload_len;
2693  enum ast_websocket_opcode opcode;
2694  int fragmented;
2695 
2696  if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2697  /* We err on the side of caution and terminate the session if any error occurs */
2698  break;
2699  }
2700 
2701  if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2702  struct sip_request req = { 0, };
2703  char data[payload_len + 1];
2704 
2705  if (!(req.data = ast_str_create(payload_len + 1))) {
2706  goto end;
2707  }
2708 
2709  strncpy(data, payload, payload_len);
2710  data[payload_len] = '\0';
2711 
2712  if (ast_str_set(&req.data, -1, "%s", data) == AST_DYNSTR_BUILD_FAILED) {
2713  deinit_req(&req);
2714  goto end;
2715  }
2716 
2717  req.socket.fd = ast_websocket_fd(session);
2719  req.socket.ws_session = session;
2720 
2722  deinit_req(&req);
2723 
2724  } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
2725  break;
2726  }
2727  }
2728 
2729 end:
2730  ast_websocket_unref(session);
2731 }
2732 
2733 /*! \brief Check if the authtimeout has expired.
2734  * \param start the time when the session started
2735  *
2736  * \retval 0 the timeout has expired
2737  * \retval -1 error
2738  * \return the number of milliseconds until the timeout will expire
2739  */
2740 static int sip_check_authtimeout(time_t start)
2741 {
2742  int timeout;
2743  time_t now;
2744  if(time(&now) == -1) {
2745  ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2746  return -1;
2747  }
2748 
2749  timeout = (authtimeout - (now - start)) * 1000;
2750  if (timeout < 0) {
2751  /* we have timed out */
2752  return 0;
2753  }
2754 
2755  return timeout;
2756 }
2757 
2758 /*!
2759  * \brief Indication of a TCP message's integrity
2760  */
2762  /*!
2763  * The message has an error in it with
2764  * regards to its Content-Length header
2765  */
2767  /*!
2768  * The message is incomplete
2769  */
2771  /*!
2772  * The data contains a complete message
2773  * plus a fragment of another.
2774  */
2776  /*!
2777  * The message is complete
2778  */
2780 };
2781 
2782 /*!
2783  * \brief
2784  * Get the content length from an unparsed SIP message
2785  *
2786  * \param message The unparsed SIP message headers
2787  * \return The value of the Content-Length header or -1 if message is invalid
2788  */
2789 static int read_raw_content_length(const char *message)
2790 {
2791  char *content_length_str;
2792  int content_length = -1;
2793 
2794  struct ast_str *msg_copy;
2795  char *msg;
2796 
2797  /* Using a ast_str because lws2sws takes one of those */
2798  if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
2799  return -1;
2800  }
2801  ast_str_set(&msg_copy, 0, "%s", message);
2802 
2804  lws2sws(msg_copy);
2805  }
2806 
2807  msg = ast_str_buffer(msg_copy);
2808 
2809  /* Let's find a Content-Length header */
2810  if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
2811  content_length_str += sizeof("\nContent-Length:") - 1;
2812  } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
2813  content_length_str += sizeof("\nl:") - 1;
2814  } else {
2815  /* RFC 3261 18.3
2816  * "In the case of stream-oriented transports such as TCP, the Content-
2817  * Length header field indicates the size of the body. The Content-
2818  * Length header field MUST be used with stream oriented transports."
2819  */
2820  goto done;
2821  }
2822 
2823  /* Double-check that this is a complete header */
2824  if (!strchr(content_length_str, '\n')) {
2825  goto done;
2826  }
2827 
2828  if (sscanf(content_length_str, "%30d", &content_length) != 1) {
2829  content_length = -1;
2830  }
2831 
2832 done:
2833  ast_free(msg_copy);
2834  return content_length;
2835 }
2836 
2837 /*!
2838  * \brief Check that a message received over TCP is a full message
2839  *
2840  * This will take the information read in and then determine if
2841  * 1) The message is a full SIP request
2842  * 2) The message is a partial SIP request
2843  * 3) The message contains a full SIP request along with another partial request
2844  * \param data The unparsed incoming SIP message.
2845  * \param request The resulting request with extra fragments removed.
2846  * \param overflow If the message contains more than a full request, this is the remainder of the message
2847  * \return The resulting integrity of the message
2848  */
2849 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
2850 {
2851  char *message = ast_str_buffer(*request);
2852  char *body;
2853  int content_length;
2854  int message_len = ast_str_strlen(*request);
2855  int body_len;
2856 
2857  /* Important pieces to search for in a SIP request are \r\n\r\n. This
2858  * marks either
2859  * 1) The division between the headers and body
2860  * 2) The end of the SIP request
2861  */
2862  body = strstr(message, "\r\n\r\n");
2863  if (!body) {
2864  /* This is clearly a partial message since we haven't reached an end
2865  * yet.
2866  */
2867  return MESSAGE_FRAGMENT;
2868  }
2869  body += sizeof("\r\n\r\n") - 1;
2870  body_len = message_len - (body - message);
2871 
2872  body[-1] = '\0';
2873  content_length = read_raw_content_length(message);
2874  body[-1] = '\n';
2875 
2876  if (content_length < 0) {
2877  return MESSAGE_INVALID;
2878  } else if (content_length == 0) {
2879  /* We've definitely received an entire message. We need
2880  * to check if there's also a fragment of another message
2881  * in addition.
2882  */
2883  if (body_len == 0) {
2884  return MESSAGE_COMPLETE;
2885  } else {
2886  ast_str_append(overflow, 0, "%s", body);
2887  ast_str_truncate(*request, message_len - body_len);
2889  }
2890  }
2891  /* Positive content length. Let's see what sort of
2892  * message body we're dealing with.
2893  */
2894  if (body_len < content_length) {
2895  /* We don't have the full message body yet */
2896  return MESSAGE_FRAGMENT;
2897  } else if (body_len > content_length) {
2898  /* We have the full message plus a fragment of a further
2899  * message
2900  */
2901  ast_str_append(overflow, 0, "%s", body + content_length);
2902  ast_str_truncate(*request, message_len - (body_len - content_length));
2904  } else {
2905  /* Yay! Full message with no extra content */
2906  return MESSAGE_COMPLETE;
2907  }
2908 }
2909 
2910 /*!
2911  * \brief Read SIP request or response from a TCP/TLS connection
2912  *
2913  * \param req The request structure to be filled in
2914  * \param tcptls_session The TCP/TLS connection from which to read
2915  * \retval -1 Failed to read data
2916  * \retval 0 Successfully read data
2917  */
2918 static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
2919  int authenticated, time_t start)
2920 {
2922 
2923  while (message_integrity == MESSAGE_FRAGMENT) {
2924  size_t datalen;
2925 
2926  if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
2927  char readbuf[4097];
2928  int timeout;
2929  int res;
2930  if (!tcptls_session->client && !authenticated) {
2931  if ((timeout = sip_check_authtimeout(start)) < 0) {
2932  return -1;
2933  }
2934 
2935  if (timeout == 0) {
2936  ast_debug(2, "SIP TCP/TLS server timed out\n");
2937  return -1;
2938  }
2939  } else {
2940  timeout = -1;
2941  }
2942  res = ast_wait_for_input(ast_iostream_get_fd(tcptls_session->stream), timeout);
2943  if (res < 0) {
2944  ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
2945  return -1;
2946  } else if (res == 0) {
2947  ast_debug(2, "SIP TCP/TLS server timed out\n");
2948  return -1;
2949  }
2950 
2951  res = ast_iostream_read(tcptls_session->stream, readbuf, sizeof(readbuf) - 1);
2952  if (res < 0) {
2953  if (errno == EAGAIN || errno == EINTR) {
2954  continue;
2955  }
2956  ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
2957  return -1;
2958  } else if (res == 0) {
2959  ast_debug(2, "SIP TCP/TLS server has shut down\n");
2960  return -1;
2961  }
2962  readbuf[res] = '\0';
2963  ast_str_append(&req->data, 0, "%s", readbuf);
2964  } else {
2965  ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
2966  ast_str_reset(tcptls_session->overflow_buf);
2967  }
2968 
2969  datalen = ast_str_strlen(req->data);
2970  if (datalen > SIP_MAX_PACKET_SIZE) {
2971  ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
2972  ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
2973  return -1;
2974  }
2975 
2976  message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
2977  }
2978 
2979  return 0;
2980 }
2981 
2982 /*! \brief SIP TCP thread management function
2983  This function reads from the socket, parses the packet into a request
2984 */
2985 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
2986 {
2987  int res, timeout = -1, authenticated = 0, flags;
2988  time_t start;
2989  struct sip_request req = { 0, } , reqcpy = { 0, };
2990  struct sip_threadinfo *me = NULL;
2991  char buf[1024] = "";
2992  struct pollfd fds[2] = { { 0 }, { 0 }, };
2993  struct ast_tcptls_session_args *ca = NULL;
2994 
2995  /* If this is a server session, then the connection has already been
2996  * setup. Check if the authlimit has been reached and if not create the
2997  * threadinfo object so we can access this thread for writing.
2998  *
2999  * if this is a client connection more work must be done.
3000  * 1. We own the parent session args for a client connection. This pointer needs
3001  * to be held on to so we can decrement it's ref count on thread destruction.
3002  * 2. The threadinfo object was created before this thread was launched, however
3003  * it must be found within the threadt table.
3004  * 3. Last, the tcptls_session must be started.
3005  */
3006  if (!tcptls_session->client) {
3008  /* unauth_sessions is decremented in the cleanup code */
3009  goto cleanup;
3010  }
3011 
3012  ast_iostream_nonblock(tcptls_session->stream);
3013  if (!(me = sip_threadinfo_create(tcptls_session, ast_iostream_get_ssl(tcptls_session->stream) ? AST_TRANSPORT_TLS : AST_TRANSPORT_TCP))) {
3014  goto cleanup;
3015  }
3016  me->threadid = pthread_self();
3017  ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
3018  } else {
3019  struct sip_threadinfo tmp = {
3020  .tcptls_session = tcptls_session,
3021  };
3022 
3023  if ((!(ca = tcptls_session->parent)) ||
3024  (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")))) {
3025  goto cleanup;
3026  }
3027 
3028  me->threadid = pthread_self();
3029 
3030  if (!(tcptls_session = ast_tcptls_client_start(tcptls_session))) {
3031  goto cleanup;
3032  }
3033  }
3034 
3035  flags = 1;
3036  if (setsockopt(ast_iostream_get_fd(tcptls_session->stream), SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
3037  ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
3038  goto cleanup;
3039  }
3040 
3041  ast_debug(2, "Starting thread for %s server\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS" : "TCP");
3042 
3043  /* set up pollfd to watch for reads on both the socket and the alert_pipe */
3044  fds[0].fd = ast_iostream_get_fd(tcptls_session->stream);
3045  fds[1].fd = me->alert_pipe[0];
3046  fds[0].events = fds[1].events = POLLIN | POLLPRI;
3047 
3048  if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
3049  goto cleanup;
3050  }
3051  if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
3052  goto cleanup;
3053  }
3054 
3055  if(time(&start) == -1) {
3056  ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
3057  goto cleanup;
3058  }
3059 
3060  /*
3061  * We cannot let the stream exclusively wait for data to arrive.
3062  * We have to wake up the task to send outgoing messages.
3063  */
3064  ast_iostream_set_exclusive_input(tcptls_session->stream, 0);
3065 
3067  tcptls_session->client ? -1 : (authtimeout * 1000));
3068 
3069  for (;;) {
3070  struct ast_str *str_save;
3071 
3072  if (!tcptls_session->client && req.authenticated && !authenticated) {
3073  authenticated = 1;
3074  ast_iostream_set_timeout_disable(tcptls_session->stream);
3076  }
3077 
3078  /* calculate the timeout for unauthenticated server sessions */
3079  if (!tcptls_session->client && !authenticated ) {
3080  if ((timeout = sip_check_authtimeout(start)) < 0) {
3081  goto cleanup;
3082  }
3083 
3084  if (timeout == 0) {
3085  ast_debug(2, "SIP %s server timed out\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP");
3086  goto cleanup;
3087  }
3088  } else {
3089  timeout = -1;
3090  }
3091 
3092  if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
3093  res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
3094  if (res < 0) {
3095  ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP", res);
3096  goto cleanup;
3097  } else if (res == 0) {
3098  /* timeout */
3099  ast_debug(2, "SIP %s server timed out\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP");
3100  goto cleanup;
3101  }
3102  }
3103 
3104  /*
3105  * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
3106  * and writes from alert_pipe fd.
3107  */
3108  if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
3109  fds[0].revents = 0;
3110 
3111  /* clear request structure */
3112  str_save = req.data;
3113  memset(&req, 0, sizeof(req));
3114  req.data = str_save;
3115  ast_str_reset(req.data);
3116 
3117  str_save = reqcpy.data;
3118  memset(&reqcpy, 0, sizeof(reqcpy));
3119  reqcpy.data = str_save;
3120  ast_str_reset(reqcpy.data);
3121 
3122  memset(buf, 0, sizeof(buf));
3123 
3124  if (ast_iostream_get_ssl(tcptls_session->stream)) {
3126  } else {
3128  }
3129  req.socket.fd = ast_iostream_get_fd(tcptls_session->stream);
3130 
3131  res = sip_tcptls_read(&req, tcptls_session, authenticated, start);
3132  if (res < 0) {
3133  goto cleanup;
3134  }
3135 
3136  req.socket.tcptls_session = tcptls_session;
3137  req.socket.ws_session = NULL;
3138  handle_request_do(&req, &tcptls_session->remote_address);
3139  }
3140 
3141  if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
3142  enum sip_tcptls_alert alert;
3143  struct tcptls_packet *packet;
3144 
3145  fds[1].revents = 0;
3146 
3147  if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
3148  ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
3149  goto cleanup;
3150  }
3151 
3152  switch (alert) {
3153  case TCPTLS_ALERT_STOP:
3154  goto cleanup;
3155  case TCPTLS_ALERT_DATA:
3156  ao2_lock(me);
3157  if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
3158  ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
3159  }
3160  ao2_unlock(me);
3161 
3162  if (packet) {
3163  if (ast_iostream_write(tcptls_session->stream, ast_str_buffer(packet->data), packet->len) == -1) {
3164  ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
3165  }
3166  ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
3167  } else {
3168  goto cleanup;
3169  }
3170  break;
3171  default:
3172  ast_log(LOG_ERROR, "Unknown tcptls thread alert '%u'\n", alert);
3173  goto cleanup;
3174  }
3175  }
3176  }
3177 
3178  ast_debug(2, "Shutting down thread for %s server\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS" : "TCP");
3179 
3180 cleanup:
3181  if (tcptls_session && !tcptls_session->client && !authenticated) {
3183  }
3184 
3185  if (me) {
3186  ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
3187  ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
3188  }
3189  deinit_req(&reqcpy);
3190  deinit_req(&req);
3191 
3192  /* if client, we own the parent session arguments and must decrement ref */
3193  if (ca) {
3194  ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
3195  }
3196 
3197  if (tcptls_session) {
3198  ao2_lock(tcptls_session);
3199  ast_tcptls_close_session_file(tcptls_session);
3200  tcptls_session->parent = NULL;
3201  ao2_unlock(tcptls_session);
3202 
3203  ao2_ref(tcptls_session, -1);
3204  tcptls_session = NULL;
3205  }
3206  return NULL;
3207 }
3208 
3209 static void peer_sched_cleanup(struct sip_peer *peer)
3210 {
3211  if (peer->pokeexpire != -1) {
3212  AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
3213  sip_unref_peer(peer, "removing poke peer ref"));
3214  }
3215  if (peer->expire != -1) {
3216  AST_SCHED_DEL_UNREF(sched, peer->expire,
3217  sip_unref_peer(peer, "remove register expire ref"));
3218  }
3219  if (peer->keepalivesend != -1) {
3220  AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
3221  sip_unref_peer(peer, "remove keepalive peer ref"));
3222  }
3223 }
3224 
3225 typedef enum {
3229 
3230 /* this func is used with ao2_callback to unlink/delete all marked or linked
3231  peers, depending on arg */
3232 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
3233 {
3234  struct sip_peer *peer = peerobj;
3235  peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
3236 
3237  if (which == SIP_PEERS_ALL || peer->the_mark) {
3238  peer_sched_cleanup(peer);
3239  if (peer->dnsmgr) {
3240  ast_dnsmgr_release(peer->dnsmgr);
3241  peer->dnsmgr = NULL;
3242  sip_unref_peer(peer, "Release peer from dnsmgr");
3243  }
3244  return CMP_MATCH;
3245  }
3246  return 0;
3247 }
3248 
3250 {
3251  struct ao2_iterator *peers_iter;
3252 
3253  /*
3254  * We must remove the ref outside of the peers container to prevent
3255  * a deadlock condition when unsubscribing from stasis while it is
3256  * invoking a subscription event callback.
3257  */
3258  peers_iter = ao2_t_callback(peers, OBJ_UNLINK | OBJ_MULTIPLE,
3259  match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
3260  if (peers_iter) {
3261  ao2_iterator_destroy(peers_iter);
3262  }
3263 
3264  peers_iter = ao2_t_callback(peers_by_ip, OBJ_UNLINK | OBJ_MULTIPLE,
3265  match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers_by_ip");
3266  if (peers_iter) {
3267  ao2_iterator_destroy(peers_iter);
3268  }
3269 }
3270 
3271 /* \brief Unlink all marked peers from ao2 containers */
3273 {
3275 }
3276 
3278 {
3280 }
3281 
3282 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
3283  *
3284  * This function sets pvt's outboundproxy pointer to the one referenced
3285  * by the proxy parameter. Because proxy may be a refcounted object, and
3286  * because pvt's old outboundproxy may also be a refcounted object, we need
3287  * to maintain the proper refcounts.
3288  *
3289  * \param pvt The sip_pvt for which we wish to set the outboundproxy
3290  * \param proxy The sip_proxy which we will point pvt towards.
3291  * \return Returns void
3292  */
3293 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
3294 {
3295  struct sip_proxy *old_obproxy = pvt->outboundproxy;
3296  /* The sip_cfg.outboundproxy is statically allocated, and so
3297  * we don't ever need to adjust refcounts for it
3298  */
3299  if (proxy && proxy != &sip_cfg.outboundproxy) {
3300  ao2_ref(proxy, +1);
3301  }
3302  pvt->outboundproxy = proxy;
3303  if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
3304  ao2_ref(old_obproxy, -1);
3305  }
3306 }
3307 
3308 static void do_dialog_unlink_sched_items(struct sip_pvt *dialog)
3309 {
3310  struct sip_pkt *cp;
3311 
3312  /* remove all current packets in this dialog */
3313  sip_pvt_lock(dialog);
3314  while ((cp = dialog->packets)) {
3315  /* Unlink and destroy the packet object. */
3316  dialog->packets = dialog->packets->next;
3317  AST_SCHED_DEL_UNREF(sched, cp->retransid,
3318  ao2_t_ref(cp, -1, "Stop scheduled packet retransmission"));
3319  ao2_t_ref(cp, -1, "Packet retransmission list");
3320  }
3321  sip_pvt_unlock(dialog);
3322 
3323  AST_SCHED_DEL_UNREF(sched, dialog->waitid,
3324  dialog_unref(dialog, "Stop scheduled waitid"));
3325 
3326  AST_SCHED_DEL_UNREF(sched, dialog->initid,
3327  dialog_unref(dialog, "Stop scheduled initid"));
3328 
3329  AST_SCHED_DEL_UNREF(sched, dialog->reinviteid,
3330  dialog_unref(dialog, "Stop scheduled reinviteid"));
3331 
3332  AST_SCHED_DEL_UNREF(sched, dialog->autokillid,
3333  dialog_unref(dialog, "Stop scheduled autokillid"));
3334 
3336  dialog_unref(dialog, "Stop scheduled request_queue_sched_id"));
3337 
3339  dialog_unref(dialog, "Stop scheduled provisional keepalive"));
3340 
3341  AST_SCHED_DEL_UNREF(sched, dialog->t38id,
3342  dialog_unref(dialog, "Stop scheduled t38id"));
3343 
3344  if (dialog->stimer) {
3345  dialog->stimer->st_active = FALSE;
3346  do_stop_session_timer(dialog);
3347  }
3348 }
3349 
3350 /* Run by the sched thread. */
3351 static int __dialog_unlink_sched_items(const void *data)
3352 {
3353  struct sip_pvt *dialog = (void *) data;
3354 
3356  dialog_unref(dialog, "Stop scheduled items for unlink action");
3357  return 0;
3358 }
3359 
3360 /*!
3361  * \brief Unlink a dialog from the dialogs container, as well as any other places
3362  * that it may be currently stored.
3363  *
3364  * \note A reference to the dialog must be held before calling this function, and this
3365  * function does not release that reference.
3366  */
3367 void dialog_unlink_all(struct sip_pvt *dialog)
3368 {
3369  struct ast_channel *owner;
3370 
3371  dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
3372 
3373  ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
3374  ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
3375  ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
3376 
3377  /* Unlink us from the owner (channel) if we have one */
3378  owner = sip_pvt_lock_full(dialog);
3379  if (owner) {
3380  ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
3381  ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
3382  ast_channel_unlock(owner);
3383  ast_channel_unref(owner);
3384  sip_set_owner(dialog, NULL);
3385  }
3386  sip_pvt_unlock(dialog);
3387 
3388  if (dialog->registry) {
3389  if (dialog->registry->call == dialog) {
3390  dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
3391  }
3392  ao2_t_replace(dialog->registry, NULL, "delete dialog->registry");
3393  }
3394  if (dialog->stateid != -1) {
3396  dialog->stateid = -1;
3397  }
3398  /* Remove link from peer to subscription of MWI */
3399  if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
3400  dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
3401  }
3402  if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
3403  dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
3404  }
3405 
3406  dialog_ref(dialog, "Stop scheduled items for unlink action");
3407  if (ast_sched_add(sched, 0, __dialog_unlink_sched_items, dialog) < 0) {
3408  /*
3409  * Uh Oh. Fall back to unscheduling things immediately
3410  * despite the potential deadlock risk.
3411  */
3412  dialog_unref(dialog, "Failed to schedule stop scheduled items for unlink action");
3414  }
3415 
3416  dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
3417 }
3418 
3419 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3420  __attribute__((format(printf, 2, 3)));
3421 
3422 
3423 /*! \brief Convert transfer status to string */
3424 static const char *referstatus2str(enum referstatus rstatus)
3425 {
3426  return map_x_s(referstatusstrings, rstatus, "");
3427 }
3428 
3429 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
3430 {
3431  if (pvt->final_destruction_scheduled) {
3432  return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
3433  }
3434  append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3435  if (!pvt->needdestroy) {
3436  pvt->needdestroy = 1;
3437  ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
3438  }
3439 }
3440 
3441 /*! \brief Initialize the initital request packet in the pvt structure.
3442  This packet is used for creating replies and future requests in
3443  a dialog */
3444 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
3445 {
3446  if (p->initreq.headers) {
3447  ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
3448  } else {
3449  ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
3450  }
3451  /* Use this as the basis */
3452  copy_request(&p->initreq, req);
3453  parse_request(&p->initreq);
3454  if (req->debug) {
3455  ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3456  }
3457 }
3458 
3459 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
3460 static void sip_alreadygone(struct sip_pvt *dialog)
3461 {
3462  ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
3463  dialog->alreadygone = 1;
3464 }
3465 
3466 /*! Resolve DNS srv name or host name in a sip_proxy structure */
3467 static int proxy_update(struct sip_proxy *proxy)
3468 {
3469  /* if it's actually an IP address and not a name,
3470  there's no need for a managed lookup */
3471  if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3472  /* Ok, not an IP address, then let's check if it's a domain or host */
3473  /* XXX Todo - if we have proxy port, don't do SRV */
3474  proxy->ip.ss.ss_family = get_address_family_filter(AST_TRANSPORT_UDP); /* Filter address family */
3475  if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
3476  ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
3477  return FALSE;
3478  }
3479 
3480  }
3481 
3482  ast_sockaddr_set_port(&proxy->ip, proxy->port);
3483 
3484  proxy->last_dnsupdate = time(NULL);
3485  return TRUE;
3486 }
3487 
3488 /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
3489  * non-NULL, no allocation is performed and dest is used instead.
3490  * On error NULL is returned. */
3491 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
3492 {
3493  char *mutable_proxy, *sep, *name;
3494  int allocated = 0;
3495 
3496  if (!dest) {
3497  dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
3498  if (!dest) {
3499  ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
3500  return NULL;
3501  }
3502  allocated = 1;
3503  }
3504 
3505  /* Format is: [transport://]name[:port][,force] */
3506  mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
3507  sep = strchr(mutable_proxy, ',');
3508  if (sep) {
3509  *sep++ = '\0';
3510  dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
3511  } else {
3512  dest->force = FALSE;
3513  }
3514 
3515  sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
3516 
3517  /* Check that there is a name at all */
3518  if (ast_strlen_zero(name)) {
3519  if (allocated) {
3520  ao2_ref(dest, -1);
3521  } else {
3522  dest->name[0] = '\0';
3523  }
3524  return NULL;
3525  }
3526  ast_copy_string(dest->name, name, sizeof(dest->name));
3527 
3528  /* Resolve host immediately */
3529  proxy_update(dest);
3530 
3531  return dest;
3532 }
3533 
3534 /*! \brief converts ascii port to int representation. If no
3535  * pt buffer is provided or the pt has errors when being converted
3536  * to an int value, the port provided as the standard is used.
3537  */
3538 unsigned int port_str2int(const char *pt, unsigned int standard)
3539 {
3540  int port = standard;
3541  if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
3542  port = standard;
3543  }
3544 
3545  return port;
3546 }
3547 
3548 /*! \brief Get default outbound proxy or global proxy */
3549 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3550 {
3551  if (dialog && dialog->options && dialog->options->outboundproxy) {
3552  if (sipdebug) {
3553  ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
3554  }
3555  append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
3556  return dialog->options->outboundproxy;
3557  }
3558  if (peer && peer->outboundproxy) {
3559  if (sipdebug) {
3560  ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3561  }
3562  append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3563  return peer->outboundproxy;
3564  }
3565  if (sip_cfg.outboundproxy.name[0]) {
3566  if (sipdebug) {
3567  ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
3568  }
3569  append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
3570  return &sip_cfg.outboundproxy;
3571  }
3572  if (sipdebug) {
3573  ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
3574  }
3575  return NULL;
3576 }
3577 
3578 /*! \brief returns true if 'name' (with optional trailing whitespace)
3579  * matches the sip method 'id'.
3580  * Strictly speaking, SIP methods are case SENSITIVE, but we do
3581  * a case-insensitive comparison to be more tolerant.
3582  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
3583  */
3584 static int method_match(enum sipmethod id, const char *name)
3585 {
3586  int len = strlen(sip_methods[id].text);
3587  int l_name = name ? strlen(name) : 0;
3588  /* true if the string is long enough, and ends with whitespace, and matches */
3589  return (l_name >= len && name && name[len] < 33 &&
3590  !strncasecmp(sip_methods[id].text, name, len));
3591 }
3592 
3593 /*! \brief find_sip_method: Find SIP method from header */
3594 static int find_sip_method(const char *msg)
3595 {
3596  int i, res = 0;
3597 
3598  if (ast_strlen_zero(msg)) {
3599  return 0;
3600  }
3601  for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
3602  if (method_match(i, msg)) {
3603  res = sip_methods[i].id;
3604  }
3605  }
3606  return res;
3607 }
3608 
3609 /*! \brief See if we pass debug IP filter */
3610 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
3611 {
3612  /* Can't debug if sipdebug is not enabled */
3613  if (!sipdebug) {
3614  return 0;
3615  }
3616 
3617  /* A null debug_addr means we'll debug any address */
3619  return 1;
3620  }
3621 
3622  /* If no port was specified for a debug address, just compare the
3623  * addresses, otherwise compare the address and port
3624  */
3625  if (ast_sockaddr_port(&debugaddr)) {
3626  return !ast_sockaddr_cmp(&debugaddr, addr);
3627  } else {
3628  return !ast_sockaddr_cmp_addr(&debugaddr, addr);
3629  }
3630 }
3631 
3632 /*! \brief The real destination address for a write */
3633 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
3634 {
3635  if (p->outboundproxy) {
3636  return &p->outboundproxy->ip;
3637  }
3638 
3639  return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT) ? &p->recv : &p->sa;
3640 }
3641 
3642 /*! \brief Display SIP nat mode */
3643 static const char *sip_nat_mode(const struct sip_pvt *p)
3644 {
3645  return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3646 }
3647 
3648 /*! \brief Test PVT for debugging output */
3649 static inline int sip_debug_test_pvt(struct sip_pvt *p)
3650 {
3651  if (!sipdebug) {
3652  return 0;
3653  }
3654  return sip_debug_test_addr(sip_real_dst(p));
3655 }
3656 
3657 /*! \brief Return int representing a bit field of transport types found in const char *transport */
3658 static int get_transport_str2enum(const char *transport)
3659 {
3660  int res = 0;
3661 
3662  if (ast_strlen_zero(transport)) {
3663  return res;
3664  }
3665 
3666  if (!strcasecmp(transport, "udp")) {
3667  res |= AST_TRANSPORT_UDP;
3668  }
3669  if (!strcasecmp(transport, "tcp")) {
3670  res |= AST_TRANSPORT_TCP;
3671  }
3672  if (!strcasecmp(transport, "tls")) {
3673  res |= AST_TRANSPORT_TLS;
3674  }
3675  if (!strcasecmp(transport, "ws")) {
3676  res |= AST_TRANSPORT_WS;
3677  }
3678  if (!strcasecmp(transport, "wss")) {
3679  res |= AST_TRANSPORT_WSS;
3680  }
3681 
3682  return res;
3683 }
3684 
3685 /*! \brief Return configuration of transports for a device */
3686 static inline const char *get_transport_list(unsigned int transports)
3687 {
3688  char *buf;
3689 
3690  if (!transports) {
3691  return "UNKNOWN";
3692  }
3693 
3695  return "";
3696  }
3697 
3698  memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
3699 
3700  if (transports & AST_TRANSPORT_UDP) {
3701  strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3702  }
3703  if (transports & AST_TRANSPORT_TCP) {
3704  strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3705  }
3706  if (transports & AST_TRANSPORT_TLS) {
3707  strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3708  }
3709  if (transports & AST_TRANSPORT_WS) {
3710  strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3711  }
3712  if (transports & AST_TRANSPORT_WSS) {
3713  strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3714  }
3715 
3716  /* Remove the trailing ',' if present */
3717  if (strlen(buf)) {
3718  buf[strlen(buf) - 1] = 0;
3719  }
3720 
3721  return buf;
3722 }
3723 
3724 /*! \brief Return transport as string */
3726 {
3727  switch (t) {
3728  case AST_TRANSPORT_UDP:
3729  return "UDP";
3730  case AST_TRANSPORT_TCP:
3731  return "TCP";
3732  case AST_TRANSPORT_TLS:
3733  return "TLS";
3734  case AST_TRANSPORT_WS:
3735  case AST_TRANSPORT_WSS:
3736  return "WS";
3737  }
3738 
3739  return "UNKNOWN";
3740 }
3741 
3742 /*! \brief Return protocol string for srv dns query */
3743 static inline const char *get_srv_protocol(enum ast_transport t)
3744 {
3745  switch (t) {
3746  case AST_TRANSPORT_UDP:
3747  return "udp";
3748  case AST_TRANSPORT_WS:
3749  return "ws";
3750  case AST_TRANSPORT_TLS:
3751  case AST_TRANSPORT_TCP:
3752  return "tcp";
3753  case AST_TRANSPORT_WSS:
3754  return "wss";
3755  }
3756 
3757  return "udp";
3758 }
3759 
3760 /*! \brief Return service string for srv dns query */
3761 static inline const char *get_srv_service(enum ast_transport t)
3762 {
3763  switch (t) {
3764  case AST_TRANSPORT_TCP:
3765  case AST_TRANSPORT_UDP:
3766  case AST_TRANSPORT_WS:
3767  return "sip";
3768  case AST_TRANSPORT_TLS:
3769  case AST_TRANSPORT_WSS:
3770  return "sips";
3771  }
3772  return "sip";
3773 }
3774 
3775 /*! \brief Return transport of dialog.
3776  \note this is based on a false assumption. We don't always use the
3777  outbound proxy for all requests in a dialog. It depends on the
3778  "force" parameter. The FIRST request is always sent to the ob proxy.
3779  \todo Fix this function to work correctly
3780 */
3781 static inline const char *get_transport_pvt(struct sip_pvt *p)
3782 {
3783  if (p->outboundproxy && p->outboundproxy->transport) {
3785  }
3786 
3787  return sip_get_transport(p->socket.type);
3788 }
3789 
3790 /*!
3791  * \internal
3792  * \brief Transmit SIP message
3793  *
3794  * \details
3795  * Sends a SIP request or response on a given socket (in the pvt)
3796  * \note
3797  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
3798  *
3799  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3800  */
3801 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
3802 {
3803  int res = 0;
3804  const struct ast_sockaddr *dst = sip_real_dst(p);
3805 
3806  ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", ast_str_buffer(data), get_transport_pvt(p), ast_sockaddr_stringify(dst));
3807 
3808  if (sip_prepare_socket(p) < 0) {
3809  return XMIT_ERROR;
3810  }
3811 
3812  if (p->socket.type == AST_TRANSPORT_UDP) {
3813  res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
3814  } else if (p->socket.tcptls_session) {
3816  if (res < -1) {
3817  return res;
3818  }
3819  } else if (p->socket.ws_session) {
3820  if (!(res = ast_websocket_write_string(p->socket.ws_session, ast_str_buffer(data)))) {
3821  /* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
3822  res = ast_str_strlen(data);
3823  }
3824  } else {
3825  ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3826  return XMIT_ERROR;
3827  }
3828 
3829  if (res == -1) {
3830  switch (errno) {
3831  case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3832  case EHOSTUNREACH: /* Host can't be reached */
3833  case ENETDOWN: /* Interface down */
3834  case ENETUNREACH: /* Network failure */
3835  case ECONNREFUSED: /* ICMP port unreachable */
3836  res = XMIT_ERROR; /* Don't bother with trying to transmit again */
3837  }
3838  }
3839  if (res != ast_str_strlen(data)) {
3840  ast_log(LOG_WARNING, "sip_xmit of %p (len %zu) to %s returned %d: %s\n", data, ast_str_strlen(data), ast_sockaddr_stringify(dst), res, strerror(errno));
3841  }
3842 
3843  return res;
3844 }
3845 
3846 /*! \brief Build a Via header for a request */
3847 static void build_via(struct sip_pvt *p)
3848 {
3849  /* Work around buggy UNIDEN UIP200 firmware */
3850  const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3851 
3852  /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
3853  snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3854  get_transport_pvt(p),
3856  (unsigned)p->branch, rport);
3857 }
3858 
3859 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
3860  *
3861  * Using the localaddr structure built up with localnet statements in sip.conf
3862  * apply it to their address to see if we need to substitute our
3863  * externaddr or can get away with our internal bindaddr
3864  * 'us' is always overwritten.
3865  */
3866 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3867 {
3868  struct ast_sockaddr theirs;
3869 
3870  /* Set want_remap to non-zero if we want to remap 'us' to an externally
3871  * reachable IP address and port. This is done if:
3872  * 1. we have a localaddr list (containing 'internal' addresses marked
3873  * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3874  * and AST_SENSE_ALLOW on 'external' ones);
3875  * 2. externaddr is set, so we know what to use as the
3876  * externally visible address;
3877  * 3. the remote address, 'them', is external;
3878  * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3879  * when passed to ast_apply_ha() so it does need to be remapped.
3880  * This fourth condition is checked later.
3881  */
3882  int want_remap = 0;
3883 
3884  ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3885  /* now ask the system what would it use to talk to 'them' */
3886  ast_ouraddrfor(them, us);
3887  ast_sockaddr_copy(&theirs, them);
3888 
3889  if (ast_sockaddr_is_ipv6(&theirs) && !ast_sockaddr_is_ipv4_mapped(&theirs)) {
3890  if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
3891  ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3892  "but we're using IPv6, which doesn't need it. Please "
3893  "remove \"localnet\" and/or \"externaddr\" settings.\n");
3894  }
3895  } else {
3896  want_remap = localaddr &&
3898  ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3899  }
3900 
3901  if (want_remap &&
3902  (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3903  /* if we used externhost, see if it is time to refresh the info */
3904  if (externexpire && time(NULL) >= externexpire) {
3906  ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3907  }
3908  externexpire = time(NULL) + externrefresh;
3909  }
3912  switch (p->socket.type) {
3913  case AST_TRANSPORT_TCP:
3915  /* for consistency, default to the externaddr port */
3917  }
3918  if (!externtcpport) {
3920  }
3921  if (!externtcpport) {
3923  }
3925  break;
3926  case AST_TRANSPORT_TLS:
3927  if (!externtlsport) {
3929  }
3930  if (!externtlsport) {
3932  }
3934  break;
3935  case AST_TRANSPORT_UDP:
3936  if (!ast_sockaddr_port(&externaddr)) {
3938  }
3939  break;
3940  default:
3941  break;
3942  }
3943  }
3944  ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3945  ast_sockaddr_stringify(them));
3946  } else {
3947  /* no remapping, but we bind to a specific address, so use it. */
3948  switch (p->socket.type) {
3949  case AST_TRANSPORT_TCP:
3950  if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
3951  if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3952  ast_sockaddr_copy(us,
3953  &sip_tcp_desc.local_address);
3954  } else {
3956  ast_sockaddr_port(&sip_tcp_desc.local_address));
3957  }
3958  break;
3959  } /* fall through on purpose */
3960  case AST_TRANSPORT_TLS:
3961  if (!ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
3962  if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3963  ast_sockaddr_copy(us,
3964  &sip_tls_desc.local_address);
3965  } else {
3967  ast_sockaddr_port(&sip_tls_desc.local_address));
3968  }
3969  break;
3970  } /* fall through on purpose */
3971  case AST_TRANSPORT_UDP:
3972  /* fall through on purpose */
3973  default:
3974  if (!ast_sockaddr_is_any(&bindaddr)) {
3976  }
3977  if (!ast_sockaddr_port(us)) {
3979  }
3980  }
3981  }
3982  ast_debug(3, "Setting AST_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
3983 }
3984 
3985 /*! \brief Append to SIP dialog history with arg list */
3986 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3987 {
3988  char buf[80], *c = buf; /* max history length */
3989  struct sip_history *hist;
3990  int l;
3991 
3992  vsnprintf(buf, sizeof(buf), fmt, ap);
3993  strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3994  l = strlen(buf) + 1;
3995  if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
3996  return;
3997  }
3998  if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3999  ast_free(hist);
4000  return;
4001  }
4002  memcpy(hist->event, buf, l);
4003  if (p->history_entries == MAX_HISTORY_ENTRIES) {
4004  struct sip_history *oldest;
4005  oldest = AST_LIST_REMOVE_HEAD(p->history, list);
4006  p->history_entries--;
4007  ast_free(oldest);
4008  }
4009  AST_LIST_INSERT_TAIL(p->history, hist, list);
4010  p->history_entries++;
4011  if (log_level != -1) {
4012  ast_log_dynamic_level(log_level, "%s\n", buf);
4013  }
4014 }
4015 
4016 /*! \brief Append to SIP dialog history with arg list */
4017 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
4018 {
4019  va_list ap;
4020 
4021  if (!p) {
4022  return;
4023  }
4024 
4025  if (!p->do_history && !recordhistory && !dumphistory) {
4026  return;
4027  }
4028 
4029  va_start(ap, fmt);
4030  append_history_va(p, fmt, ap);
4031  va_end(ap);
4032 
4033  return;
4034 }
4035 
4036 /*!
4037  * \brief Retransmit SIP message if no answer
4038  *
4039  * \note Run by the sched thread.
4040  */
4041 static int retrans_pkt(const void *data)
4042 {
4043  struct sip_pkt *pkt = (struct sip_pkt *) data;
4044  struct sip_pkt *prev;
4045  struct sip_pkt *cur;
4046  struct ast_channel *owner_chan;
4047  int reschedule = DEFAULT_RETRANS;
4048  int xmitres = 0;
4049  /* how many ms until retrans timeout is reached */
4050  int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
4051 
4052  /* Do not retransmit if time out is reached. This will be negative if the time between
4053  * the first transmission and now is larger than our timeout period. This is a fail safe
4054  * check in case the scheduler gets behind or the clock is changed. */
4055  if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
4056  pkt->retrans_stop = 1;
4057  }
4058 
4059  /* Lock channel PVT */
4060  sip_pvt_lock(pkt->owner);
4061 
4062  if (!pkt->retrans_stop) {
4063  pkt->retrans++;
4064  if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
4065  if (sipdebug) {
4066  ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
4067  pkt->retransid,
4068  sip_methods[pkt->method].text,
4069  pkt->method);
4070  }
4071  } else {
4072  int siptimer_a;
4073 
4074  if (sipdebug) {
4075  ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
4076  pkt->retransid,
4077  pkt->retrans,
4078  sip_methods[pkt->method].text,
4079  pkt->method);
4080  }
4081  if (!pkt->timer_a) {
4082  pkt->timer_a = 2 ;
4083  } else {
4084  pkt->timer_a = 2 * pkt->timer_a;
4085  }
4086 
4087  /* For non-invites, a maximum of 4 secs */
4088  if (INT_MAX / pkt->timer_a < pkt->timer_t1) {
4089  /*
4090  * Uh Oh, we will have an integer overflow.
4091  * Recalculate previous timeout time instead.
4092  */
4093  pkt->timer_a = pkt->timer_a / 2;
4094  }
4095  siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
4096  if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
4097  siptimer_a = 4000;
4098  }
4099 
4100  /* Reschedule re-transmit */
4101  reschedule = siptimer_a;
4102  ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
4103  pkt->retrans + 1,
4104  siptimer_a,
4105  pkt->timer_t1,
4106  pkt->retransid);
4107  }
4108 
4109  if (sip_debug_test_pvt(pkt->owner)) {
4110  const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
4111 
4112  ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
4113  pkt->retrans, sip_nat_mode(pkt->owner),
4115  ast_str_buffer(pkt->data));
4116  }
4117 
4118  append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
4119  xmitres = __sip_xmit(pkt->owner, pkt->data);
4120 
4121  /* If there was no error during the network transmission, schedule the next retransmission,
4122  * but if the next retransmission is going to be beyond our timeout period, mark the packet's
4123  * stop_retrans value and set the next retransmit to be the exact time of timeout. This will
4124  * allow any responses to the packet to be processed before the packet is destroyed on the next
4125  * call to this function by the scheduler. */
4126  if (xmitres != XMIT_ERROR) {
4127  if (reschedule >= diff) {
4128  pkt->retrans_stop = 1;
4129  reschedule = diff;
4130  }
4131  sip_pvt_unlock(pkt->owner);
4132  return reschedule;
4133  }
4134  }
4135 
4136  /* At this point, either the packet's retransmission timed out, or there was a
4137  * transmission error, either way destroy the scheduler item and this packet. */
4138 
4139  pkt->retransid = -1; /* Kill this scheduler item */
4140 
4141  if (pkt->method != SIP_OPTIONS && xmitres == 0) {
4142  if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
4143  ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
4144  "Packet timed out after %dms with no response\n",
4145  pkt->owner->callid,
4146  pkt->seqno,
4147  pkt->is_fatal ? "Critical" : "Non-critical",
4148  pkt->is_resp ? "Response" : "Request",
4149  (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
4150  }
4151  } else if (pkt->method == SIP_OPTIONS && sipdebug) {
4152  ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n", pkt->owner->callid);
4153  }
4154 
4155  if (xmitres == XMIT_ERROR) {
4156  ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
4157  append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
4158  } else {
4159  append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
4160  }
4161 
4162  sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
4163  owner_chan = sip_pvt_lock_full(pkt->owner);
4164 
4165  if (pkt->is_fatal) {
4166  if (owner_chan) {
4167  ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid);
4168 
4169  if (pkt->is_resp &&
4170  (pkt->response_code >= 200) &&
4171  (pkt->response_code < 300) &&
4172  pkt->owner->pendinginvite &&
4174  /* This is a timeout of the 2XX response to a pending INVITE. In this case terminate the INVITE
4175  * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
4176  * will send the BYE as long as the dialog is not set as "alreadygone")
4177  * RFC 3261 section 13.3.1.4.
4178  * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
4179  * an ACK, the dialog is confirmed, but the session SHOULD be terminated. This is
4180  * accomplished with a BYE, as described in Section 15." */
4182  pkt->owner->pendinginvite = 0;
4183  } else {
4184  /* there is nothing left to do, mark the dialog as gone */
4185  sip_alreadygone(pkt->owner);
4186  }
4187  if (!ast_channel_hangupcause(owner_chan)) {
4189  }
4191  } else {
4192  /* If no channel owner, destroy now */
4193 
4194  /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
4195  if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
4196  pvt_set_needdestroy(pkt->owner, "no response to critical packet");
4197  sip_alreadygone(pkt->owner);
4198  append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
4199  }
4200  }
4201  } else if (pkt->owner->pendinginvite == pkt->seqno) {
4202  ast_log(LOG_WARNING, "Timeout on %s on non-critical invite transaction.\n", pkt->owner->callid);
4204  pkt->owner->pendinginvite = 0;
4205  check_pendings(pkt->owner);
4206  }
4207 
4208  if (owner_chan) {
4209  ast_channel_unlock(owner_chan);
4210  ast_channel_unref(owner_chan);
4211  }
4212 
4213  if (pkt->method == SIP_BYE) {
4214  /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
4215  sip_alreadygone(pkt->owner);
4216  append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
4217  pvt_set_needdestroy(pkt->owner, "no response to BYE");
4218  }
4219 
4220  /* Unlink and destroy the packet object. */
4221  for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
4222  if (cur == pkt) {
4223  /* Unlink the node from the list. */
4224  UNLINK(cur, pkt->owner->packets, prev);
4225  ao2_t_ref(pkt, -1, "Packet retransmission list (retransmission complete)");
4226  break;
4227  }
4228  }
4229 
4230  /*
4231  * If the object was not in the list then we were in the process of
4232  * stopping retransmisions while we were sending this retransmission.
4233  */
4234 
4235  sip_pvt_unlock(pkt->owner);
4236  ao2_t_ref(pkt, -1, "Scheduled packet retransmission complete");
4237  return 0;
4238 }
4239 
4240 /* Run by the sched thread. */
4241 static int __stop_retrans_pkt(const void *data)
4242 {
4243  struct sip_pkt *pkt = (void *) data;
4244 
4245  AST_SCHED_DEL_UNREF(sched, pkt->retransid,
4246  ao2_t_ref(pkt, -1, "Stop scheduled packet retransmission"));
4247  ao2_t_ref(pkt, -1, "Stop packet retransmission action");
4248  return 0;
4249 }
4250 
4251 static void stop_retrans_pkt(struct sip_pkt *pkt)
4252 {
4253  ao2_t_ref(pkt, +1, "Stop packet retransmission action");
4254  if (ast_sched_add(sched, 0, __stop_retrans_pkt, pkt) < 0) {
4255  /* Uh Oh. Expect bad behavior. */
4256  ao2_t_ref(pkt, -1, "Failed to schedule stop packet retransmission action");
4257  }
4258 }
4259 
4260 static void sip_pkt_dtor(void *vdoomed)
4261 {
4262  struct sip_pkt *pkt = (void *) vdoomed;
4263 
4264  if (pkt->owner) {
4265  dialog_unref(pkt->owner, "Retransmission packet is being destroyed");
4266  }
4267  ast_free(pkt->data);
4268 }
4269 
4270 /*!
4271  * \internal
4272  * \brief Transmit packet with retransmits
4273  * \return 0 on success, -1 on failure to allocate packet
4274  */
4275 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
4276 {
4277  struct sip_pkt *pkt = NULL;
4278  int siptimer_a = DEFAULT_RETRANS;
4279  int xmitres = 0;
4280  unsigned respid;
4281 
4282  if (sipmethod == SIP_INVITE) {
4283  /* Note this is a pending invite */
4284  p->pendinginvite = seqno;
4285  }
4286 
4288  if (!pkt) {
4289  return AST_FAILURE;
4290  }
4291  /* copy data, add a terminator and save length */
4292  pkt->data = ast_str_create(ast_str_strlen(data));
4293  if (!pkt->data) {
4294  ao2_t_ref(pkt, -1, "Failed to initialize");
4295  return AST_FAILURE;
4296  }
4297  ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
4298  /* copy other parameters from the caller */
4299  pkt->method = sipmethod;
4300  pkt->seqno = seqno;
4301  pkt->is_resp = resp;
4302  pkt->is_fatal = fatal;
4303  pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
4304 
4305  /* The retransmission list owns a pkt ref */
4306  pkt->next = p->packets;
4307  p->packets = pkt; /* Add it to the queue */
4308 
4309  if (resp) {
4310  /* Parse out the response code */
4311  if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
4312  pkt->response_code = respid;
4313  }
4314  }
4315  pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
4316  if (pkt->timer_t1) {
4317  siptimer_a = pkt->timer_t1;
4318  }
4319 
4320  pkt->time_sent = ast_tvnow(); /* time packet was sent */
4321  pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
4322 
4323  if (!(p->socket.type & AST_TRANSPORT_UDP)) {
4324  /* TCP does not need retransmits as that's built in, but with
4325  * retrans_stop set, we must give it the full timer_H treatment */
4326  pkt->retrans_stop = 1;
4327  siptimer_a = pkt->retrans_stop_time;
4328  }
4329 
4330  /* Schedule retransmission */
4331  ao2_t_ref(pkt, +1, "Schedule packet retransmission");
4332  pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
4333  if (pkt->retransid < 0) {
4334  ao2_t_ref(pkt, -1, "Failed to schedule packet retransmission");
4335  }
4336 
4337  if (sipdebug) {
4338  ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
4339  }
4340 
4341  xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
4342 
4343  if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
4344  append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
4345  ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
4346 
4347  /* Unlink and destroy the packet object. */
4348  p->packets = pkt->next;
4349  stop_retrans_pkt(pkt);
4350  ao2_t_ref(pkt, -1, "Packet retransmission list");
4351  return AST_FAILURE;
4352  } else {
4353  /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
4354  * only wakes up every 1000ms by default, we have to poke the thread here to make
4355  * sure it successfully detects this must be retransmitted in less time than
4356  * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
4358  pthread_kill(monitor_thread, SIGURG);
4359  }
4360  return AST_SUCCESS;
4361  }
4362 }
4363 
4364 /*! \brief Kill a SIP dialog (called only by the scheduler)
4365  * The scheduler has a reference to this dialog when p->autokillid != -1,
4366  * and we are called using that reference. So if the event is not
4367  * rescheduled, we need to call dialog_unref().
4368  */
4369 static int __sip_autodestruct(const void *data)
4370 {
4371  struct sip_pvt *p = (struct sip_pvt *)data;
4372  struct ast_channel *owner;
4373 
4374  /* If this is a subscription, tell the phone that we got a timeout */
4376  struct state_notify_data data = { 0, };
4377 
4379 
4380  transmit_state_notify(p, &data, 1, TRUE); /* Send last notification */
4381  p->subscribed = NONE;
4382  append_history(p, "Subscribestatus", "timeout");
4383  ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
4384  return 10000; /* Reschedule this destruction so that we know that it's gone */
4385  }
4386 
4387  /* If there are packets still waiting for delivery, delay the destruction */
4388  if (p->packets) {
4389  if (!p->needdestroy) {
4390  char method_str[31];
4391 
4392  ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
4393  append_history(p, "ReliableXmit", "timeout");
4394  if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
4395  if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
4396  pvt_set_needdestroy(p, "autodestruct");
4397  }
4398  }
4399  return 10000;
4400  } else {
4401  /* They've had their chance to respond. Time to bail */
4402  __sip_pretend_ack(p);
4403  }
4404  }
4405 
4406  /*
4407  * Lock both the pvt and the channel safely so that we can queue up a frame.
4408  */
4409  owner = sip_pvt_lock_full(p);
4410  if (owner) {
4412  "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n",
4413  p->callid, ast_channel_name(owner), sip_methods[p->method].text);
4415  ast_channel_unlock(owner);
4416  ast_channel_unref(owner);
4417  sip_pvt_unlock(p);
4418  return 10000;
4419  }
4420 
4421  /* Reset schedule ID */
4422  p->autokillid = -1;
4423 
4424  if (p->refer && !p->alreadygone) {
4425  ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
4426  stop_media_flows(p);
4428  append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
4430  sip_pvt_unlock(p);
4431  } else {
4432  append_history(p, "AutoDestroy", "%s", p->callid);
4433  ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
4434  sip_pvt_unlock(p);
4435  dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
4436  }
4437 
4438  dialog_unref(p, "autokillid complete");
4439 
4440  return 0;
4441 }
4442 
4443 static void do_cancel_destroy(struct sip_pvt *pvt)
4444 {
4445  if (-1 < pvt->autokillid) {
4446  append_history(pvt, "CancelDestroy", "");
4447  AST_SCHED_DEL_UNREF(sched, pvt->autokillid,
4448  dialog_unref(pvt, "Stop scheduled autokillid"));
4449  }
4450 }
4451 
4452 /* Run by the sched thread. */
4453 static int __sip_cancel_destroy(const void *data)
4454 {
4455  struct sip_pvt *pvt = (void *) data;
4456 
4457  sip_pvt_lock(pvt);
4458  do_cancel_destroy(pvt);
4459  sip_pvt_unlock(pvt);
4460  dialog_unref(pvt, "Cancel destroy action");
4461  return 0;
4462 }
4463 
4464 void sip_cancel_destroy(struct sip_pvt *pvt)
4465 {
4466  if (pvt->final_destruction_scheduled) {
4467  return;
4468  }
4469 
4470  dialog_ref(pvt, "Cancel destroy action");
4471  if (ast_sched_add(sched, 0, __sip_cancel_destroy, pvt) < 0) {
4472  /* Uh Oh. Expect bad behavior. */
4473  dialog_unref(pvt, "Failed to schedule cancel destroy action");
4474  ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
4475  }
4476 }
4477 
4479  struct sip_pvt *pvt;
4480  int ms;
4481 };
4482 
4483 /* Run by the sched thread. */
4484 static int __sip_scheddestroy(const void *data)
4485 {
4486  struct sip_scheddestroy_data *sched_data = (void *) data;
4487  struct sip_pvt *pvt = sched_data->pvt;
4488  int ms = sched_data->ms;
4489 
4490  ast_free(sched_data);
4491 
4492  sip_pvt_lock(pvt);
4493  do_cancel_destroy(pvt);
4494 
4495  if (pvt->do_history) {
4496  append_history(pvt, "SchedDestroy", "%d ms", ms);
4497  }
4498 
4499  dialog_ref(pvt, "Schedule autokillid");
4500  pvt->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, pvt);
4501  if (pvt->autokillid < 0) {
4502  /* Uh Oh. Expect bad behavior. */
4503  dialog_unref(pvt, "Failed to schedule autokillid");
4504  }
4505 
4506  if (pvt->stimer) {
4507  stop_session_timer(pvt);
4508  }
4509  sip_pvt_unlock(pvt);
4510  dialog_unref(pvt, "Destroy action");
4511  return 0;
4512 }
4513 
4514 static int sip_scheddestroy_full(struct sip_pvt *p, int ms)
4515 {
4516  struct sip_scheddestroy_data *sched_data;
4517 
4518  if (ms < 0) {
4519  if (p->timer_t1 == 0) {
4520  p->timer_t1 = global_t1; /* Set timer T1 if not set (RFC 3261) */
4521  }
4522  if (p->timer_b == 0) {
4523  p->timer_b = global_timer_b; /* Set timer B if not set (RFC 3261) */
4524  }
4525  ms = p->timer_t1 * 64;
4526  }
4527  if (sip_debug_test_pvt(p)) {
4528  ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n",
4529  p->callid, ms, sip_methods[p->method].text);
4530  }
4531 
4532  sched_data = ast_malloc(sizeof(*sched_data));
4533  if (!sched_data) {
4534  /* Uh Oh. Expect bad behavior. */
4535  return -1;
4536  }
4537  sched_data->pvt = p;
4538  sched_data->ms = ms;
4539  dialog_ref(p, "Destroy action");
4540  if (ast_sched_add(sched, 0, __sip_scheddestroy, sched_data) < 0) {
4541  /* Uh Oh. Expect bad behavior. */
4542  dialog_unref(p, "Failed to schedule destroy action");
4543  ast_free(sched_data);
4544  return -1;
4545  }
4546  return 0;
4547 }
4548 
4549 void sip_scheddestroy(struct sip_pvt *p, int ms)
4550 {
4551  if (p->final_destruction_scheduled) {
4552  return; /* already set final destruction */
4553  }
4554  sip_scheddestroy_full(p, ms);
4555 }
4556 
4557 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
4558 {
4559  if (p->final_destruction_scheduled) {
4560  return; /* already set final destruction */
4561  }
4562 
4563  if (!sip_scheddestroy_full(p, ms)) {
4565  }
4566 }
4567 
4568 /*! \brief Acknowledges receipt of a packet and stops retransmission
4569  * called with p locked*/
4570 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
4571 {
4572  struct sip_pkt *cur, *prev = NULL;
4573  const char *msg = "Not Found"; /* used only for debugging */
4574  int res = FALSE;
4575 
4576  /* If we have an outbound proxy for this dialog, then delete it now since
4577  the rest of the requests in this dialog needs to follow the routing.
4578  If obforcing is set, we will keep the outbound proxy during the whole
4579  dialog, regardless of what the SIP rfc says
4580  */
4581  if (p->outboundproxy && !p->outboundproxy->force) {
4582  ref_proxy(p, NULL);
4583  }
4584 
4585  for (cur = p->packets; cur; prev = cur, cur = cur->next) {
4586  if (cur->seqno != seqno || cur->is_resp != resp) {
4587  continue;
4588  }
4589  if (cur->is_resp || cur->method == sipmethod) {
4590  res = TRUE;
4591  msg = "Found";
4592  if (!resp && (seqno == p->pendinginvite)) {
4593  ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
4594  p->pendinginvite = 0;
4595  }
4596  if (cur->retransid > -1) {
4597  if (sipdebug)
4598  ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
4599  }
4600 
4601  /* Unlink and destroy the packet object. */
4602  UNLINK(cur, p->packets, prev);
4603  stop_retrans_pkt(cur);
4604  ao2_t_ref(cur, -1, "Packet retransmission list");
4605  break;
4606  }
4607  }
4608  ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
4609  p->callid, resp ? "Response" : "Request", seqno, msg);
4610  return res;
4611 }
4612 
4613 /*! \brief Pretend to ack all packets
4614  * called with p locked */
4616 {
4617  struct sip_pkt *cur = NULL;
4618 
4619  while (p->packets) {
4620  int method;
4621  if (cur == p->packets) {
4622  ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
4623  return;
4624  }
4625  cur = p->packets;
4626  method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
4627  __sip_ack(p, cur->seqno, cur->is_resp, method);
4628  }
4629 }
4630 
4631 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
4632 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
4633 {
4634  struct sip_pkt *cur;
4635  int res = FALSE;
4636 
4637  for (cur = p->packets; cur; cur = cur->next) {
4638  if (cur->seqno == seqno && cur->is_resp == resp &&
4639  (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
4640  /* this is our baby */
4641  if (cur->retransid > -1) {
4642  if (sipdebug)
4643  ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
4644  }
4645  stop_retrans_pkt(cur);
4646  res = TRUE;
4647  break;
4648  }
4649  }
4650  ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %u: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
4651  return res;
4652 }
4653 
4654 
4655 /*! \brief Copy SIP request, parse it */
4656 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
4657 {
4658  copy_request(dst, src);
4659  parse_request(dst);
4660 }
4661 
4662 /*! \brief add a blank line if no body */
4663 static void add_blank(struct sip_request *req)
4664 {
4665  if (!req->lines) {
4666  /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
4667  ast_str_append(&req->data, 0, "\r\n");
4668  }
4669 }
4670 
4671 /* Run by the sched thread. */
4672 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
4673 {
4674  const char *msg = NULL;
4675  struct ast_channel *chan;
4676  int res = 0;
4677 
4678  chan = sip_pvt_lock_full(pvt);
4679 
4680  if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
4681  msg = "183 Session Progress";
4682  }
4683 
4684  if (pvt->invitestate < INV_COMPLETED) {
4685  if (with_sdp) {
4687  } else {
4688  transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
4689  }
4691  } else {
4693  }
4694 
4695  sip_pvt_unlock(pvt);
4696  if (chan) {
4697  ast_channel_unlock(chan);
4698  ast_channel_unref(chan);
4699  }
4700 
4701  if (!res) {
4702  dialog_unref(pvt, "Schedule provisional keepalive complete");
4703  }
4704  return res;
4705 }
4706 
4707 /* Run by the sched thread. */
4708 static int send_provisional_keepalive(const void *data)
4709 {
4710  struct sip_pvt *pvt = (struct sip_pvt *) data;
4711 
4712  return send_provisional_keepalive_full(pvt, 0);
4713 }
4714 
4715 /* Run by the sched thread. */
4716 static int send_provisional_keepalive_with_sdp(const void *data)
4717 {
4718  struct sip_pvt *pvt = (void *) data;
4719 
4720  return send_provisional_keepalive_full(pvt, 1);
4721 }
4722 
4723 /* Run by the sched thread. */
4724 static int __update_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
4725 {
4727  dialog_unref(pvt, "Stop scheduled provisional keepalive for update"));
4728 
4729  sip_pvt_lock(pvt);
4730  if (pvt->invitestate < INV_COMPLETED) {
4731  /* Provisional keepalive is still needed. */
4732  dialog_ref(pvt, "Schedule provisional keepalive");
4735  pvt);
4736  if (pvt->provisional_keepalive_sched_id < 0) {
4737  dialog_unref(pvt, "Failed to schedule provisional keepalive");
4738  }
4739  }
4740  sip_pvt_unlock(pvt);
4741 
4742  dialog_unref(pvt, "Update provisional keepalive action");
4743  return 0;
4744 }
4745 
4746 /* Run by the sched thread. */
4747 static int __update_provisional_keepalive(const void *data)
4748 {
4749  struct sip_pvt *pvt = (void *) data;
4750 
4751  return __update_provisional_keepalive_full(pvt, 0);
4752 }
4753 
4754 /* Run by the sched thread. */
4755 static int __update_provisional_keepalive_with_sdp(const void *data)
4756 {
4757  struct sip_pvt *pvt = (void *) data;
4758 
4759  return __update_provisional_keepalive_full(pvt, 1);
4760 }
4761 
4762 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
4763 {
4764  dialog_ref(pvt, "Update provisional keepalive action");
4765  if (ast_sched_add(sched, 0,
4767  pvt) < 0) {
4768  dialog_unref(pvt, "Failed to schedule update provisional keepalive action");
4769  }
4770 }
4771 
4772 /* Run by the sched thread. */
4773 static int __stop_provisional_keepalive(const void *data)
4774 {
4775  struct sip_pvt *pvt = (void *) data;
4776 
4778  dialog_unref(pvt, "Stop scheduled provisional keepalive"));
4779  dialog_unref(pvt, "Stop provisional keepalive action");
4780  return 0;
4781 }
4782 
4783 static void stop_provisional_keepalive(struct sip_pvt *pvt)
4784 {
4785  dialog_ref(pvt, "Stop provisional keepalive action");
4786  if (ast_sched_add(sched, 0, __stop_provisional_keepalive, pvt) < 0) {
4787  /* Uh Oh. Expect bad behavior. */
4788  dialog_unref(pvt, "Failed to schedule stop provisional keepalive action");
4789  }
4790 }
4791 
4792 static void add_required_respheader(struct sip_request *req)
4793 {
4794  struct ast_str *str;
4795  int i;
4796 
4797  if (!req->reqsipoptions) {
4798  return;
4799  }
4800 
4801  str = ast_str_create(32);
4802 
4803  for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
4804  if (!(req->reqsipoptions & sip_options[i].id)) {
4805  continue;
4806  }
4807  if (ast_str_strlen(str) > 0) {
4808  ast_str_append(&str, 0, ", ");
4809  }
4810  ast_str_append(&str, 0, "%s", sip_options[i].text);
4811  }
4812 
4813  if (ast_str_strlen(str) > 0) {
4814  add_header(req, "Require", ast_str_buffer(str));
4815  }
4816 
4817  ast_free(str);
4818 }
4819 
4820 /*! \brief Transmit response on SIP request*/
4821 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
4822 {
4823  int res;
4824 
4825  finalize_content(req);
4826  add_blank(req);
4827  if (sip_debug_test_pvt(p)) {
4828  const struct ast_sockaddr *dst = sip_real_dst(p);
4829 
4830  ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
4831  reliable ? "Reliably " : "", sip_nat_mode(p),
4833  ast_str_buffer(req->data));
4834  }
4835  if (p->do_history) {
4836  struct sip_request tmp = { .rlpart1 = 0, };
4837  parse_copy(&tmp, req);
4838  append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"),
4839  (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlpart2) : sip_methods[tmp.method].text);
4840  deinit_req(&tmp);
4841  }
4842 
4843  /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
4844  if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
4846  }
4847 
4848  res = (reliable) ?
4849  __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
4850  __sip_xmit(p, req->data);
4851  deinit_req(req);
4852  if (res > 0) {
4853  return 0;
4854  }
4855  return res;
4856 }
4857 
4858 /*!
4859  * \internal
4860  * \brief Send SIP Request to the other part of the dialogue
4861  * \return see \ref __sip_xmit
4862  */
4863 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
4864 {
4865  int res;
4866 
4867  /* If we have an outbound proxy, reset peer address
4868  Only do this once.
4869  */
4870  if (p->outboundproxy) {
4871  p->sa = p->outboundproxy->ip;
4872  }
4873 
4874  finalize_content(req);
4875  add_blank(req);
4876  if (sip_debug_test_pvt(p)) {
4877  if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
4878  ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
4879  } else {
4880  ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
4881  }
4882  }
4883  if (p->do_history) {
4884  struct sip_request tmp = { .rlpart1 = 0, };
4885  parse_copy(&tmp, req);
4886  append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
4887  deinit_req(&tmp);
4888  }
4889  res = (reliable) ?
4890  __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
4891  __sip_xmit(p, req->data);
4892  deinit_req(req);
4893  return res;
4894 }
4895 
4896 static void enable_dsp_detect(struct sip_pvt *p)
4897 {
4898  int features = 0;
4899 
4900  if (p->dsp) {
4901  return;
4902  }
4903 
4904  if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
4905  (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
4906  if (p->rtp) {
4908  }
4909  features |= DSP_FEATURE_DIGIT_DETECT;
4910  }
4911 
4913  features |= DSP_FEATURE_FAX_DETECT;
4914  }
4915 
4916  if (!features) {
4917  return;
4918  }
4919 
4920  if (!(p->dsp = ast_dsp_new())) {
4921  return;
4922  }
4923 
4924  ast_dsp_set_features(p->dsp, features);
4925  if (global_relaxdtmf) {
4927  }
4928 }
4929 
4930 static void disable_dsp_detect(struct sip_pvt *p)
4931 {
4932  if (p->dsp) {
4933  ast_dsp_free(p->dsp);
4934  p->dsp = NULL;
4935  }
4936 }
4937 
4938 /*! \brief Set an option on a SIP dialog */
4939 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
4940 {
4941  int res = -1;
4942  struct sip_pvt *p = ast_channel_tech_pvt(chan);
4943 
4944  if (!p) {
4945  ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
4946  return -1;
4947  }
4948 
4949  sip_pvt_lock(p);
4950 
4951  switch (option) {
4953  if (p->rtp) {
4954  res = ast_rtp_instance_set_read_format(p->rtp, *(struct ast_format **) data);
4955  }
4956  break;
4958  if (p->rtp) {
4959  res = ast_rtp_instance_set_write_format(p->rtp, *(struct ast_format **) data);
4960  }
4961  break;
4963  if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
4964  (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
4965  char *cp = (char *) data;
4966 
4967  ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
4968  if (*cp) {
4969  enable_dsp_detect(p);
4970  } else {
4971  disable_dsp_detect(p);
4972  }
4973  res = 0;
4974  }
4975  break;
4977  p->req_secure_signaling = *(unsigned int *) data;
4978  res = 0;
4979  break;
4981  ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
4982  res = 0;
4983  break;
4984  default:
4985  break;
4986  }
4987 
4988  sip_pvt_unlock(p);
4989 
4990  return res;
4991 }
4992 
4993 /*! \brief Query an option on a SIP dialog */
4994 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
4995 {
4996  int res = -1;
4998  struct sip_pvt *p = (struct sip_pvt *) ast_channel_tech_pvt(chan);
4999  char *cp;
5000 
5001  if (!p) {
5002  ast_debug(1, "Attempt to Ref a null pointer. Sip private structure is gone!\n");
5003  return -1;
5004  }
5005 
5006  sip_pvt_lock(p);
5007 
5008  switch (option) {
5009  case AST_OPTION_T38_STATE:
5010  /* Make sure we got an ast_t38_state enum passed in */
5011  if (*datalen != sizeof(enum ast_t38_state)) {
5012  ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
5013  break;
5014  }
5015 
5016  /* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
5017  if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
5018  switch (p->t38.state) {
5019  case T38_LOCAL_REINVITE:
5020  case T38_PEER_REINVITE:
5021  state = T38_STATE_NEGOTIATING;
5022  break;
5023  case T38_ENABLED:
5024  state = T38_STATE_NEGOTIATED;
5025  break;
5026  case T38_REJECTED:
5027  state = T38_STATE_REJECTED;
5028  break;
5029  default:
5030  state = T38_STATE_UNKNOWN;
5031  }
5032  }
5033 
5034  *((enum ast_t38_state *) data) = state;
5035  res = 0;
5036 
5037  break;
5039  cp = (char *) data;
5040  *cp = p->dsp ? 1 : 0;
5041  ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
5042  break;
5044  *((unsigned int *) data) = p->req_secure_signaling;
5045  res = 0;
5046  break;
5048  *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
5049  res = 0;
5050  break;
5052  if (p && p->outgoing_call) {
5053  cp = (char *) data;
5054  ast_copy_string(cp, p->dialstring, *datalen);
5055  res = 0;
5056  }
5057  /* We purposely break with a return of -1 in the
5058  * implied else case here
5059  */
5060  break;
5061  default:
5062  break;
5063  }
5064 
5065  sip_pvt_unlock(p);
5066 
5067  return res;
5068 }
5069 
5070 /*! \brief Locate closing quote in a string, skipping escaped quotes.
5071  * optionally with a limit on the search.
5072  * start must be past the first quote.
5073  */
5074 const char *find_closing_quote(const char *start, const char *lim)
5075 {
5076  char last_char = '\0';
5077  const char *s;
5078  for (s = start; *s && s != lim; last_char = *s++) {
5079  if (*s == '"' && last_char != '\\')
5080  break;
5081  }
5082  return s;
5083 }
5084 
5085 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
5086 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
5087 {
5088  struct sip_pvt *p = ast_channel_tech_pvt(chan);
5089 
5090  if (subclass != AST_HTML_URL)
5091  return -1;
5092 
5093  ast_string_field_build(p, url, "<%s>;mode=active", data);
5094 
5095  if (sip_debug_test_pvt(p))
5096  ast_debug(1, "Send URL %s, state = %u!\n", data, ast_channel_state(chan));
5097 
5098  switch (ast_channel_state(chan)) {
5099  case AST_STATE_RING:
5100  transmit_response(p, "100 Trying", &p->initreq);
5101  break;
5102  case AST_STATE_RINGING:
5103  transmit_response(p, "180 Ringing", &p->initreq);
5104  break;
5105  case AST_STATE_UP:
5106  if (!p->pendinginvite) { /* We are up, and have no outstanding invite */
5108  } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
5110  }
5111  break;
5112  default:
5113  ast_log(LOG_WARNING, "Don't know how to send URI when state is %u!\n", ast_channel_state(chan));
5114  }
5115 
5116  return 0;
5117 }
5118 
5119 /*! \brief Deliver SIP call ID for the call */
5120 static const char *sip_get_callid(struct ast_channel *chan)
5121 {
5122  return ast_channel_tech_pvt(chan) ? ((struct sip_pvt *) ast_channel_tech_pvt(chan))->callid : "";
5123 }
5124 
5125 /*!
5126  * \internal
5127  * \brief Send SIP MESSAGE text within a call
5128  * \note Called from PBX core sendtext() application
5129  */
5130 static int sip_sendtext(struct ast_channel *ast, const char *text)
5131 {
5132  struct sip_pvt *dialog = ast_channel_tech_pvt(ast);
5133  int debug;
5134 
5135  if (!dialog) {
5136  return -1;
5137  }
5138  /* NOT ast_strlen_zero, because a zero-length message is specifically
5139  * allowed by RFC 3428 (See section 10, Examples) */
5140  if (!text) {
5141  return 0;
5142  }
5144  ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
5145  return 0;
5146  }
5147 
5148  debug = sip_debug_test_pvt(dialog);
5149  if (debug) {
5150  ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
5151  }
5152 
5153  /* Setup to send text message */
5154  sip_pvt_lock(dialog);
5155  destroy_msg_headers(dialog);
5156  ast_string_field_set(dialog, msg_body, text);
5157  transmit_message(dialog, 0, 0);
5158  sip_pvt_unlock(dialog);
5159  return 0;
5160 }
5161 
5162 /*! \brief Update peer object in realtime storage
5163  If the Asterisk system name is set in asterisk.conf, we will use
5164  that name and store that in the "regserver" field in the sippeers
5165  table to facilitate multi-server setups.
5166 */
5167 static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms, const char *path)
5168 {
5169  char port[10];
5170  char ipaddr[INET6_ADDRSTRLEN];
5171  char regseconds[20];
5172  char *tablename = NULL;
5173  char str_lastms[20];
5174 
5175  const char *sysname = ast_config_AST_SYSTEM_NAME;
5176  char *syslabel = NULL;
5177 
5178  time_t nowtime = time(NULL) + expirey;
5179  const char *fc = fullcontact ? "fullcontact" : NULL;
5180 
5181  int realtimeregs = ast_check_realtime("sipregs");
5182 
5183  tablename = realtimeregs ? "sipregs" : "sippeers";
5184 
5185  snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
5186  snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime); /* Expiration time */
5187  ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
5188  ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
5189 
5190  if (ast_strlen_zero(sysname)) { /* No system name, disable this */
5191  sysname = NULL;
5192  } else if (sip_cfg.rtsave_sysname) {
5193  syslabel = "regserver";
5194  }
5195 
5196  /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
5197  * must also add it to contrib/scripts/asterisk.ldap-schema,
5198  * contrib/scripts/asterisk.ldif,
5199  * and to configs/res_ldap.conf.sample as described in
5200  * bugs 15156 and 15895
5201  */
5202 
5203  /* This is ugly, we need something better ;-) */
5204  if (sip_cfg.rtsave_path) {
5205  if (fc) {
5206  ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
5207  "port", port, "regseconds", regseconds,
5208  deprecated_username ? "username" : "defaultuser", defaultuser,
5209  "useragent", useragent, "lastms", str_lastms,
5210  "path", path, /* Path data can be NULL */
5211  fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
5212  } else {
5213  ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
5214  "port", port, "regseconds", regseconds,
5215  "useragent", useragent, "lastms", str_lastms,
5216  deprecated_username ? "username" : "defaultuser", defaultuser,
5217  "path", path, /* Path data can be NULL */
5218  syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
5219  }
5220  } else {
5221  if (fc) {
5222  ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
5223  "port", port, "regseconds", regseconds,
5224  deprecated_username ? "username" : "defaultuser", defaultuser,
5225  "useragent", useragent, "lastms", str_lastms,
5226  fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
5227  } else {
5228  ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
5229  "port", port, "regseconds", regseconds,
5230  "useragent", useragent, "lastms", str_lastms,
5231  deprecated_username ? "username" : "defaultuser", defaultuser,
5232  syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
5233  }
5234  }
5235 }
5236 
5237 /*! \brief Automatically add peer extension to dial plan */
5238 static void register_peer_exten(struct sip_peer *peer, int onoff)
5239 {
5240  char multi[256];
5241  char *stringp, *ext, *context;
5242  struct pbx_find_info q = { .stacklen = 0 };
5243 
5244  /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
5245  * the name of the global regexten context, if not specified
5246  * individually.
5247  */
5249  return;
5250 
5251  ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
5252  stringp = multi;
5253  while ((ext = strsep(&stringp, "&"))) {
5254  if ((context = strchr(ext, '@'))) {
5255  *context++ = '\0'; /* split ext@context */
5256  if (!ast_context_find(context)) {
5257  ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
5258  continue;
5259  }
5260  } else {
5261  context = sip_cfg.regcontext;
5262  }
5263  if (onoff) {
5264  if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
5265  ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
5266  ast_strdup(peer->name), ast_free_ptr, "SIP");
5267  }
5268  } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
5269  ast_context_remove_extension(context, ext, 1, NULL);
5270  }
5271  }
5272 }
5273 
5274 /*! Destroy mailbox subscriptions */
5276 {
5277  if (mailbox->event_sub) {
5278  mailbox->event_sub = ast_mwi_unsubscribe_and_join(mailbox->event_sub);
5279  }
5280  ast_free(mailbox);
5281 }
5282 
5283 #define REMOVE_MAILBOX_WITH_LOCKED_PEER(__peer) \
5284 ({\
5285  struct sip_mailbox *__mailbox;\
5286  ao2_lock(__peer);\
5287  __mailbox = AST_LIST_REMOVE_HEAD(&(__peer->mailboxes), entry);\
5288  ao2_unlock(__peer);\
5289  __mailbox;\
5290 })
5291 
5292 /*! Destroy all peer-related mailbox subscriptions */
5293 static void clear_peer_mailboxes(struct sip_peer *peer)
5294 {
5295  struct sip_mailbox *mailbox;
5296 
5297  /* Lock the peer while accessing/updating the linked list but NOT while destroying the mailbox */
5298  while ((mailbox = REMOVE_MAILBOX_WITH_LOCKED_PEER(peer))) {
5299  destroy_mailbox(mailbox);
5300  }
5301 }
5302 
5303 static void sip_destroy_peer_fn(void *peer)
5304 {
5305  sip_destroy_peer(peer);
5306 }
5307 
5308 /*! \brief Destroy peer object from memory */
5309 static void sip_destroy_peer(struct sip_peer *peer)
5310 {
5311  ast_debug(3, "Destroying SIP peer %s\n", peer->name);
5312 
5313  /*
5314  * Remove any mailbox event subscriptions for this peer before
5315  * we destroy anything. An event subscription callback may be
5316  * happening right now.
5317  */
5318  clear_peer_mailboxes(peer);
5319 
5320  if (peer->outboundproxy) {
5321  ao2_ref(peer->outboundproxy, -1);
5322  peer->outboundproxy = NULL;
5323  }
5324 
5325  /* Delete it, it needs to disappear */
5326  if (peer->call) {
5327  dialog_unlink_all(peer->call);
5328  peer->call = dialog_unref(peer->call, "peer->call is being unset");
5329  }
5330 
5331  if (peer->mwipvt) { /* We have an active subscription, delete it */
5332  dialog_unlink_all(peer->mwipvt);
5333  peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
5334  }
5335 
5336  if (peer->chanvars) {
5338  peer->chanvars = NULL;
5339  }
5340  sip_route_clear(&peer->path);
5341 
5342  register_peer_exten(peer, FALSE);
5343  ast_free_acl_list(peer->acl);
5346  if (peer->selfdestruct)
5348  else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
5350  ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
5351  } else
5353  if (peer->auth) {
5354  ao2_t_ref(peer->auth, -1, "Removing peer authentication");
5355  peer->auth = NULL;
5356  }
5357 
5358  if (peer->socket.tcptls_session) {
5359  ao2_ref(peer->socket.tcptls_session, -1);
5360  peer->socket.tcptls_session = NULL;
5361  } else if (peer->socket.ws_session) {
5363  peer->socket.ws_session = NULL;
5364  }
5365 
5368 
5370 
5372 
5373  ao2_cleanup(peer->caps);
5374 
5376 
5378  peer->endpoint = NULL;
5379 }
5380 
5381 /*! \brief Update peer data in database (if used) */
5382 static void update_peer(struct sip_peer *p, int expire)
5383 {
5384  int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
5385  if (sip_cfg.peer_rtupdate && (p->is_realtime || rtcachefriends)) {
5386  struct ast_str *r = sip_route_list(&p->path, 0, 0);
5387  if (r) {
5388  realtime_update_peer(p->name, &p->addr, p->username,
5389  p->fullcontact, p->useragent, expire, p->deprecated_username,
5390  p->lastms, ast_str_buffer(r));
5391  ast_free(r);
5392  }
5393  }
5394 }
5395 
5397 {
5398  struct ast_variable *var = NULL;
5399  struct ast_flags flags = {0};
5400  char *cat = NULL;
5401  const char *insecure;
5402  while ((cat = ast_category_browse(cfg, cat))) {
5403  insecure = ast_variable_retrieve(cfg, cat, "insecure");
5404  set_insecure_flags(&flags, insecure, -1);
5405  if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
5406  var = ast_category_root(cfg, cat);
5407  break;
5408  }
5409  }
5410  return var;
5411 }
5412 
5413 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
5414 {
5415  struct ast_config *peerlist;
5416  struct ast_variable *var = NULL;
5417  if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
5418  if ((var = get_insecure_variable_from_config(peerlist))) {
5419  /* Must clone, because var will get freed along with
5420  * peerlist. */
5421  var = ast_variables_dup(var);
5422  }
5423  ast_config_destroy(peerlist);
5424  }
5425  return var;
5426 }
5427 
5428 /* Yes.. the only column that makes sense to pass is "ipaddr", but for
5429  * consistency's sake, we require the column name to be passed. As extra
5430  * argument, we take a pointer to var. We already got the info, so we better
5431  * return it and save the caller a query. If return value is nonzero, then *var
5432  * is nonzero too (and the other way around). */
5433 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
5434 {
5435  struct ast_variable *varregs = NULL;
5436  struct ast_config *regs, *peers;
5437  char *regscat;
5438  const char *regname;
5439 
5440  if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
5441  return NULL;
5442  }
5443 
5444  /* Load *all* peers that are probably insecure=port */
5445  if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
5446  ast_config_destroy(regs);
5447  return NULL;
5448  }
5449 
5450  /* Loop over the sipregs that match IP address and attempt to find an
5451  * insecure=port match to it in sippeers. */
5452  regscat = NULL;
5453  while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
5454  char *peerscat;
5455  const char *peername;
5456 
5457  peerscat = NULL;
5458  while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
5459  if (!strcasecmp(regname, peername)) {
5460  /* Ensure that it really is insecure=port and
5461  * not something else. */
5462  const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
5463  struct ast_flags flags = {0};
5464  set_insecure_flags(&flags, insecure, -1);
5465  if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
5466  /* ENOMEM checks till the bitter end. */
5467  if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
5468  if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
5469  ast_variables_destroy(varregs);
5470  varregs = NULL;
5471  }
5472  }
5473  goto done;
5474  }
5475  }
5476  }
5477  }
5478 
5479 done:
5480  ast_config_destroy(regs);
5481  ast_config_destroy(peers);
5482  return varregs;
5483 }
5484 
5485 static const char *get_name_from_variable(const struct ast_variable *var)
5486 {
5487  /* Don't expect this to return non-NULL. Both NULL and empty
5488  * values can cause the option to get removed from the variable
5489  * list. This is called on ast_variables gotten from both
5490  * ast_load_realtime and ast_load_realtime_multientry.
5491  * - ast_load_realtime removes options with empty values
5492  * - ast_load_realtime_multientry does not!
5493  * For consistent behaviour, we check for the empty name and
5494  * return NULL instead. */
5495  const struct ast_variable *tmp;
5496  for (tmp = var; tmp; tmp = tmp->next) {
5497  if (!strcasecmp(tmp->name, "name")) {
5498  if (!ast_strlen_zero(tmp->value)) {
5499  return tmp->value;
5500  }
5501  break;
5502  }
5503  }
5504  return NULL;
5505 }
5506 
5507 /* If varregs is NULL, we don't use sipregs.
5508  * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
5509 static int realtime_peer_by_name(const char *const *name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
5510 {
5511  /* Peer by name and host=dynamic */
5512  if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
5513  ;
5514  /* Peer by name and host=IP */
5515  } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
5516  ;
5517  /* Peer by name and host=HOSTNAME */
5518  } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
5519  /*!\note
5520  * If this one loaded something, then we need to ensure that the host
5521  * field matched. The only reason why we can't have this as a criteria
5522  * is because we only have the IP address and the host field might be
5523  * set as a name (and the reverse PTR might not match).
5524  */
5525  if (addr) {
5526  struct ast_variable *tmp;
5527  for (tmp = *var; tmp; tmp = tmp->next) {
5528  if (!strcasecmp(tmp->name, "host")) {
5529  struct ast_sockaddr *addrs = NULL;
5530 
5531  if (ast_sockaddr_resolve(&addrs,
5532  tmp->value,
5535  ast_sockaddr_cmp(&addrs[0], addr)) {
5536  /* No match */
5537  ast_variables_destroy(*var);
5538  *var = NULL;
5539  }
5540  ast_free(addrs);
5541  break;
5542  }
5543  }
5544  }
5545  }
5546 
5547  /* Did we find anything? */
5548  if (*var) {
5549  if (varregs) {
5550  *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
5551  }
5552  return 1;
5553  }
5554  return 0;
5555 }
5556 
5557 /* Another little helper function for backwards compatibility: this
5558  * checks/fetches the sippeer that belongs to the sipreg. If none is
5559  * found, we free the sipreg and return false. This way we can do the
5560  * check inside the if-condition below. In the old code, not finding
5561  * the sippeer also had it continue look for another match, so we do
5562  * the same. */
5563 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
5564  struct ast_variable *var = NULL;
5565  const char *old_name = *name;
5566  *name = get_name_from_variable(*varregs);
5567  if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
5568  if (!*name) {
5569  ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
5570  }
5571  ast_variables_destroy(*varregs);
5572  *varregs = NULL;
5573  *name = old_name;
5574  }
5575  return var;
5576 }
5577 
5578 /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
5579  * set. Using empty if-bodies instead of goto's while avoiding unnecessary
5580  * indents. */
5581 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, const char *callbackexten, struct ast_variable **var, struct ast_variable **varregs)
5582 {
5583  char portstring[6]; /* up to 5 digits plus null terminator */
5584  ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
5585 
5586  /* We're not finding this peer by this name anymore. Reset it. */
5587  *name = NULL;
5588 
5589  /* First check for fixed IP hosts with matching callbackextensions, if specified */
5590  if (!ast_strlen_zero(callbackexten) && (*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, "callbackextension", callbackexten, SENTINEL))) {
5591  ;
5592  /* Check for fixed IP hosts */
5593  } else if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
5594  ;
5595  /* Check for registered hosts (in sipregs) */
5596  } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
5597  (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
5598  ;
5599  /* Check for registered hosts (in sippeers) */
5600  } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
5601  ;
5602  /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
5603  } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
5604  ;
5605  /* Same as above, but try the IP address field (in sipregs)
5606  * Observe that it fetches the name/var at the same time, without the
5607  * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
5608  * Avoid sipregs if possible. */
5609  } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
5610  ;
5611  /* Same as above, but try the IP address field (in sippeers) */
5612  } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
5613  ;
5614  }
5615 
5616  /* Nothing found? */
5617  if (!*var) {
5618  return 0;
5619  }
5620 
5621  /* Check peer name. It must not be empty. There may exist a
5622  * different match that does have a name, but it's too late for
5623  * that now. */
5624  if (!*name && !(*name = get_name_from_variable(*var))) {
5625  ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
5626  ast_variables_destroy(*var);
5627  *var = NULL;
5628  if (varregs && *varregs) {
5629  ast_variables_destroy(*varregs);
5630  *varregs = NULL;
5631  }
5632  return 0;
5633  }
5634 
5635  /* Make sure varregs is populated if var is. The inverse,
5636  * ensuring that var is set when varregs is, is taken
5637  * care of by realtime_peer_get_sippeer_helper(). */
5638  if (varregs && !*varregs) {
5639  *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
5640  }
5641  return 1;
5642 }
5643 
5645 {
5646  struct ast_config *cfg;
5647  char *cat = NULL;
5648 
5649  if (!(ast_check_realtime("sippeers"))) {
5650  return 0;
5651  }
5652 
5653  /* This is hacky. We want name to be the cat, so it is the first property */
5654  if (!(cfg = ast_load_realtime_multientry("sippeers", "name LIKE", "%", "callbackextension LIKE", "%", SENTINEL))) {
5655  return -1;
5656  }
5657 
5658  while ((cat = ast_category_browse(cfg, cat))) {
5659  struct sip_peer *peer;
5660  struct ast_variable *var = ast_category_root(cfg, cat);
5661 
5662  if (!(peer = build_peer(cat, var, NULL, TRUE, FALSE))) {
5663  continue;
5664  }
5665  ast_log(LOG_NOTICE, "Created realtime peer '%s' for registration\n", peer->name);
5666 
5667  peer->is_realtime = 1;
5668  sip_unref_peer(peer, "register_realtime_peers: Done registering releasing");
5669  }
5670 
5671  ast_config_destroy(cfg);
5672 
5673  return 0;
5674 }
5675 
5676 /*! \brief realtime_peer: Get peer from realtime storage
5677  * Checks the "sippeers" realtime family from extconfig.conf
5678  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
5679  * This returns a pointer to a peer and because we use build_peer, we can rest
5680  * assured that the refcount is bumped.
5681  *
5682  * \note This is never called with both newpeername and addr at the same time.
5683  * If you do, be prepared to get a peer with a different name than newpeername.
5684  */
5685 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
5686 {
5687  struct sip_peer *peer = NULL;
5688  struct ast_variable *var = NULL;
5689  struct ast_variable *varregs = NULL;
5690  char ipaddr[INET6_ADDRSTRLEN];
5691  int realtimeregs = ast_check_realtime("sipregs");
5692 
5693  if (addr) {
5694  ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
5695  } else {
5696  ipaddr[0] = '\0';
5697  }
5698 
5699  if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
5700  ;
5701  } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, callbackexten, &var, realtimeregs ? &varregs : NULL)) {
5702  ;
5703  } else {
5704  return NULL;
5705  }
5706 
5707  /* If we're looking for users, don't return peers (although this check
5708  * should probably be done in realtime_peer_by_* instead...) */
5709  if (which_objects == FINDUSERS) {
5710  struct ast_variable *tmp;
5711  for (tmp = var; tmp; tmp = tmp->next) {
5712  if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
5713  goto cleanup;
5714  }
5715  }
5716  }
5717 
5718  /* Peer found in realtime, now build it in memory */
5719  peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
5720  if (!peer) {
5721  goto cleanup;
5722  }
5723 
5724  /* Previous versions of Asterisk did not require the type field to be
5725  * set for real time peers. This statement preserves that behavior. */
5726  if (peer->type == 0) {
5727  if (which_objects == FINDUSERS) {
5728  peer->type = SIP_TYPE_USER;
5729  } else if (which_objects == FINDPEERS) {
5730  peer->type = SIP_TYPE_PEER;
5731  } else {
5732  peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
5733  }
5734  }
5735 
5736  ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
5737 
5738  if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
5739  /* Cache peer */
5741  if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
5743  sip_unref_peer(_data, "remove registration ref"),
5744  sip_unref_peer(peer, "remove registration ref"),
5745  sip_ref_peer(peer, "add registration ref"));
5746  }
5747  ao2_t_link(peers, peer, "link peer into peers table");
5748  if (!ast_sockaddr_isnull(&peer->addr)) {
5749  ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
5750  }
5751  }
5752  peer->is_realtime = 1;
5753 
5754 cleanup:
5755  ast_variables_destroy(var);
5756  ast_variables_destroy(varregs);
5757  return peer;
5758 }
5759 
5760 /* Function to assist finding peers by name only */
5761 static int find_by_name(void *obj, void *arg, void *data, int flags)
5762 {
5763  struct sip_peer *search = obj, *match = arg;
5764  int *which_objects = data;
5765 
5766  /* Usernames in SIP uri's are case sensitive. Domains are not */
5767  if (strcmp(search->name, match->name)) {
5768  return 0;
5769  }
5770 
5771  switch (*which_objects) {
5772  case FINDUSERS:
5773  if (!(search->type & SIP_TYPE_USER)) {
5774  return 0;
5775  }
5776  break;
5777  case FINDPEERS:
5778  if (!(search->type & SIP_TYPE_PEER)) {
5779  return 0;
5780  }
5781  break;
5782  case FINDALLDEVICES:
5783  break;
5784  }
5785 
5786  return CMP_MATCH | CMP_STOP;
5787 }
5788 
5789 static struct sip_peer *sip_find_peer_full(const char *peer, struct ast_sockaddr *addr, char *callbackexten, int realtime, int which_objects, int devstate_only, int transport)
5790 {
5791  struct sip_peer *p = NULL;
5792  struct sip_peer tmp_peer;
5793 
5794  if (peer) {
5795  ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
5796  p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
5797  } else if (addr) { /* search by addr? */
5798  ast_sockaddr_copy(&tmp_peer.addr, addr);
5799  tmp_peer.flags[0].flags = 0;
5800  tmp_peer.transports = transport;
5801  p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table");
5802  if (!p) {
5803  ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
5804  p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table 2");
5805  if (p) {
5806  return p;
5807  }
5808  }
5809  }
5810 
5811  if (!p && (realtime || devstate_only)) {
5812  /* realtime_peer will return a peer with matching callbackexten if possible, otherwise one matching
5813  * without the callbackexten */
5814  p = realtime_peer(peer, addr, callbackexten, devstate_only, which_objects);
5815  if (p) {
5816  switch (which_objects) {
5817  case FINDUSERS:
5818  if (!(p->type & SIP_TYPE_USER)) {
5819  sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
5820  return NULL;
5821  }
5822  break;
5823  case FINDPEERS:
5824  if (!(p->type & SIP_TYPE_PEER)) {
5825  sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
5826  return NULL;
5827  }
5828  break;
5829  case FINDALLDEVICES:
5830  break;
5831  }
5832  }
5833  }
5834 
5835  return p;
5836 }
5837 
5838 /*!
5839  * \brief Locate device by name or ip address
5840  * \param peer, addr, realtime, devstate_only, transport
5841  * \param which_objects Define which objects should be matched when doing a lookup
5842  * by name. Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
5843  * Note that this option is not used at all when doing a lookup by IP.
5844  *
5845  * This is used on find matching device on name or ip/port.
5846  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
5847  *
5848  * \note Avoid using this function in new functions if there is a way to avoid it,
5849  * since it might cause a database lookup.
5850  */
5851 struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
5852 {
5853  return sip_find_peer_full(peer, addr, NULL, realtime, which_objects, devstate_only, transport);
5854 }
5855 
5856 static struct sip_peer *sip_find_peer_by_ip_and_exten(struct ast_sockaddr *addr, char *callbackexten, int transport)
5857 {
5858  return sip_find_peer_full(NULL, addr, callbackexten, TRUE, FINDPEERS, FALSE, transport);
5859 }
5860 
5861 /*! \brief Set nat mode on the various data sockets */
5862 static void do_setnat(struct sip_pvt *p)
5863 {
5864  const char *mode;
5865  int natflags;
5866 
5867  natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
5868  mode = natflags ? "On" : "Off";
5869 
5870  if (p->rtp) {
5871  ast_debug(1, "Setting NAT on RTP to %s\n", mode);
5873  }
5874  if (p->vrtp) {
5875  ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
5877  }
5878  if (p->udptl) {
5879  ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
5880  ast_udptl_setnat(p->udptl, natflags);
5881  }
5882  if (p->trtp) {
5883  ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
5885  }
5886 }
5887 
5888 /*! \brief Change the T38 state on a SIP dialog */
5889 static void change_t38_state(struct sip_pvt *p, int state)
5890 {
5891  int old = p->t38.state;
5892  struct ast_channel *chan = p->owner;
5893  struct ast_control_t38_parameters parameters = { .request_response = 0 };
5894 
5895  /* Don't bother changing if we are already in the state wanted */
5896  if (old == state)
5897  return;
5898 
5899  p->t38.state = state;
5900  ast_debug(2, "T38 state changed to %u on channel %s\n", p->t38.state, chan ? ast_channel_name(chan) : "<none>");
5901 
5902  /* If no channel was provided we can't send off a control frame */
5903  if (!chan)
5904  return;
5905 
5906  /* Given the state requested and old state determine what control frame we want to queue up */
5907  switch (state) {
5908  case T38_PEER_REINVITE:
5909  parameters = p->t38.their_parms;
5910  parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
5912  ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
5913  break;
5914  case T38_ENABLED:
5915  parameters = p->t38.their_parms;
5916  parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
5917  parameters.request_response = AST_T38_NEGOTIATED;
5918  ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
5919  break;
5920  case T38_REJECTED:
5921  case T38_DISABLED:
5922  if (old == T38_ENABLED) {
5923  parameters.request_response = AST_T38_TERMINATED;
5924  } else if (old == T38_LOCAL_REINVITE) {
5925  parameters.request_response = AST_T38_REFUSED;
5926  }
5927  break;
5928  case T38_LOCAL_REINVITE:
5929  /* wait until we get a peer response before responding to local reinvite */
5930  break;
5931  }
5932 
5933  /* Woot we got a message, create a control frame and send it on! */
5934  if (parameters.request_response)
5935  ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
5936 }
5937 
5938 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
5939 static void set_t38_capabilities(struct sip_pvt *p)
5940 {
5941  if (p->udptl) {
5948  }
5949  }
5950 }
5951 
5952 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
5953 {
5954  if (to_sock->tcptls_session) {
5955  ao2_ref(to_sock->tcptls_session, -1);
5956  to_sock->tcptls_session = NULL;
5957  } else if (to_sock->ws_session) {
5958  ast_websocket_unref(to_sock->ws_session);
5959  to_sock->ws_session = NULL;
5960  }
5961 
5962  if (from_sock->tcptls_session) {
5963  ao2_ref(from_sock->tcptls_session, +1);
5964  } else if (from_sock->ws_session) {
5965  ast_websocket_ref(from_sock->ws_session);
5966  }
5967 
5968  *to_sock = *from_sock;
5969 }
5970 
5971 /*! Cleanup the RTP and SRTP portions of a dialog
5972  *
5973  * \note This procedure excludes vsrtp as it is initialized differently.
5974  */
5975 static void dialog_clean_rtp(struct sip_pvt *p)
5976 {
5977  if (p->rtp) {
5979  p->rtp = NULL;
5980  }
5981 
5982  if (p->vrtp) {
5984  p->vrtp = NULL;
5985  }
5986 
5987  if (p->trtp) {
5989  p->trtp = NULL;
5990  }
5991 
5992  if (p->srtp) {
5994  p->srtp = NULL;
5995  }
5996 
5997  if (p->tsrtp) {
5999  p->tsrtp = NULL;
6000  }
6001 }
6002 
6003 /*! \brief Initialize DTLS-SRTP support on an RTP instance */
6004 static int dialog_initialize_dtls_srtp(const struct sip_pvt *dialog, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp)
6005 {
6006  struct ast_rtp_engine_dtls *dtls;
6007 
6008  if (!dialog->dtls_cfg.enabled) {
6009  return 0;
6010  }
6011 
6013  ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
6014  return -1;
6015  }
6016 
6017  if (!(dtls = ast_rtp_instance_get_dtls(rtp))) {
6018  ast_log(LOG_ERROR, "No DTLS-SRTP support present on engine for RTP instance '%p', was it compiled with support for it?\n",
6019  rtp);
6020  return -1;
6021  }
6022 
6023  if (dtls->set_configuration(rtp, &dialog->dtls_cfg)) {
6024  ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
6025  rtp);
6026  return -1;
6027  }
6028 
6029  if (!(*srtp = ast_sdp_srtp_alloc())) {
6030  ast_log(LOG_ERROR, "Failed to create required SRTP structure on RTP instance '%p'\n",
6031  rtp);
6032  return -1;
6033  }
6034 
6035  return 0;
6036 }
6037 
6038 /*! \brief Initialize RTP portion of a dialog
6039  * \return -1 on failure, 0 on success
6040  */
6041 static int dialog_initialize_rtp(struct sip_pvt *dialog)
6042 {
6043  struct ast_sockaddr bindaddr_tmp;
6044  struct ast_rtp_engine_ice *ice;
6045 
6046  if (!sip_methods[dialog->method].need_rtp) {
6047  return 0;
6048  }
6049 
6051  ast_sockaddr_copy(&bindaddr_tmp, &rtpbindaddr);
6052  } else {
6053  ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
6054  }
6055 
6056  /* Make sure previous RTP instances/FD's do not leak */
6057  dialog_clean_rtp(dialog);
6058 
6059  if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
6060  return -1;
6061  }
6062 
6063  if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->rtp))) {
6064  ice->stop(dialog->rtp);
6065  }
6066 
6067  if (dialog_initialize_dtls_srtp(dialog, dialog->rtp, &dialog->srtp)) {
6068  return -1;
6069  }
6070 
6073  if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
6074  return -1;
6075  }
6076 
6077  if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->vrtp))) {
6078  ice->stop(dialog->vrtp);
6079  }
6080 
6081  if (dialog_initialize_dtls_srtp(dialog, dialog->vrtp, &dialog->vsrtp)) {
6082  return -1;
6083  }
6084 
6085  ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
6088 
6091  }
6092 
6093  if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
6094  if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
6095  return -1;
6096  }
6097 
6098  if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->trtp))) {
6099  ice->stop(dialog->trtp);
6100  }
6101 
6102  if (dialog_initialize_dtls_srtp(dialog, dialog->trtp, &dialog->tsrtp)) {
6103  return -1;
6104  }
6105 
6106  /* Do not timeout text as its not constant*/
6108 
6110  }
6111 
6112  ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
6115 
6119 
6121 
6122  do_setnat(dialog);
6123 
6124  return 0;
6125 }
6126 
6127 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp);
6128 
6129 /*! \brief Create address structure from peer reference.
6130  * This function copies data from peer to the dialog, so we don't have to look up the peer
6131  * again from memory or database during the life time of the dialog.
6132  *
6133  * \return -1 on error, 0 on success.
6134  *
6135  */
6136 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
6137 {
6138  struct sip_auth_container *credentials;
6139 
6140  /* this checks that the dialog is contacting the peer on a valid
6141  * transport type based on the peers transport configuration,
6142  * otherwise, this function bails out */
6143  if (dialog->socket.type && check_request_transport(peer, dialog))
6144  return -1;
6145  copy_socket_data(&dialog->socket, &peer->socket);
6146 
6147  if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
6148  (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
6149  dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
6150  dialog->recv = dialog->sa;
6151  } else
6152  return -1;
6153 
6154  /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
6155  ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
6156  ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
6157  ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
6158  /* Take the peer's caps */
6159  if (peer->caps) {
6162  }
6163  dialog->amaflags = peer->amaflags;
6164 
6165  ast_string_field_set(dialog, engine, peer->engine);
6166 
6167  ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &dialog->dtls_cfg);
6168 
6169  dialog->rtptimeout = peer->rtptimeout;
6170  dialog->rtpholdtimeout = peer->rtpholdtimeout;
6171  dialog->rtpkeepalive = peer->rtpkeepalive;
6172  sip_route_copy(&dialog->route, &peer->path);
6173  if (!sip_route_empty(&dialog->route)) {
6174  /* Parse SIP URI of first route-set hop and use it as target address */
6175  __set_address_from_contact(sip_route_first_uri(&dialog->route), &dialog->sa, dialog->socket.type == AST_TRANSPORT_TLS ? 1 : 0);
6176  }
6177 
6178  if (dialog_initialize_rtp(dialog)) {
6179  return -1;
6180  }
6181 
6182  if (dialog->rtp) { /* Audio */
6185  /* Set Frame packetization */
6186  dialog->autoframing = peer->autoframing;
6188  }
6189 
6190  /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
6191  ast_string_field_set(dialog, peername, peer->name);
6192  ast_string_field_set(dialog, authname, peer->username);
6193  ast_string_field_set(dialog, username, peer->username);
6194  ast_string_field_set(dialog, peersecret, peer->secret);
6195  ast_string_field_set(dialog, peermd5secret, peer->md5secret);
6196  ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
6198  ast_string_field_set(dialog, tohost, peer->tohost);
6199  ast_string_field_set(dialog, fullcontact, peer->fullcontact);
6201  ast_string_field_set(dialog, context, peer->context);
6202  ast_string_field_set(dialog, cid_num, peer->cid_num);
6203  ast_string_field_set(dialog, cid_name, peer->cid_name);
6204  ast_string_field_set(dialog, cid_tag, peer->cid_tag);
6205  ast_string_field_set(dialog, mwi_from, peer->mwi_from);
6206  if (!ast_strlen_zero(peer->parkinglot)) {
6207  ast_string_field_set(dialog, parkinglot, peer->parkinglot);
6208  }
6209  ast_string_field_set(dialog, engine, peer->engine);
6210  ref_proxy(dialog, obproxy_get(dialog, peer));
6211  dialog->callgroup = peer->callgroup;
6212  dialog->pickupgroup = peer->pickupgroup;
6217  ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
6218  dialog->allowtransfer = peer->allowtransfer;
6219  dialog->jointnoncodeccapability = dialog->noncodeccapability;
6220 
6221  /* Update dialog authorization credentials */
6222  ao2_lock(peer);
6223  credentials = peer->auth;
6224  if (credentials) {
6225  ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
6226  }
6227  ao2_unlock(peer);
6228  ao2_lock(dialog);
6229  if (dialog->peerauth) {
6230  ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
6231  }
6232  dialog->peerauth = credentials;
6233  ao2_unlock(dialog);
6234 
6235  dialog->maxcallbitrate = peer->maxcallbitrate;
6236  dialog->disallowed_methods = peer->disallowed_methods;
6238  if (ast_strlen_zero(dialog->tohost))
6239  ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
6240  if (!ast_strlen_zero(peer->fromdomain)) {
6241  ast_string_field_set(dialog, fromdomain, peer->fromdomain);
6242  if (!dialog->initreq.headers) {
6243  char *new_callid;
6244  char *tmpcall = ast_strdupa(dialog->callid);
6245  /* this sure looks to me like we are going to change the callid on this dialog!! */
6246  new_callid = strchr(tmpcall, '@');
6247  if (new_callid) {
6248  int callid_size;
6249 
6250  *new_callid = '\0';
6251 
6252  /* Change the dialog callid. */
6253  callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
6254  new_callid = ast_alloca(callid_size);
6255  snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
6256  change_callid_pvt(dialog, new_callid);
6257  }
6258  }
6259  }
6260  if (!ast_strlen_zero(peer->fromuser)) {
6261  ast_string_field_set(dialog, fromuser, peer->fromuser);
6262  }
6263  if (!ast_strlen_zero(peer->language)) {
6264  ast_string_field_set(dialog, language, peer->language);
6265  }
6266  /* Set timer T1 to RTT for this peer (if known by qualify=) */
6267  /* Minimum is settable or default to 100 ms */
6268  /* If there is a maxms and lastms from a qualify use that over a manual T1
6269  value. Otherwise, use the peer's T1 value. */
6270  if (peer->maxms && peer->lastms) {
6271  dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
6272  } else {
6273  dialog->timer_t1 = peer->timer_t1;
6274  }
6275 
6276  /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
6277  the known timer */
6278  if (peer->timer_b) {
6279  dialog->timer_b = peer->timer_b;
6280  } else {
6281  dialog->timer_b = 64 * dialog->timer_t1;
6282  }
6283 
6284  if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
6285  (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
6286  dialog->noncodeccapability |= AST_RTP_DTMF;
6287  } else {
6288  dialog->noncodeccapability &= ~AST_RTP_DTMF;
6289  }
6290 
6292 
6293  if (peer->call_limit) {
6294  ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
6295  }
6296  if (!dialog->portinuri) {
6297  dialog->portinuri = peer->portinuri;
6298  }
6299  dialog->chanvars = copy_vars(peer->chanvars);
6300  if (peer->fromdomainport) {
6301  dialog->fromdomainport = peer->fromdomainport;
6302  }
6303  dialog->callingpres = peer->callingpres;
6304 
6305  return 0;
6306 }
6307 
6308 /*! \brief The default sip port for the given transport */
6309 static inline int default_sip_port(enum ast_transport type)
6310 {
6312 }
6313 
6314 /*! \brief create address structure from device name
6315  * Or, if peer not found, find it in the global DNS
6316  * returns TRUE (-1) on failure, FALSE on success */
6317 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
6318 {
6319  struct sip_peer *peer;
6320  char *peername, *peername2, *hostn;
6321  char host[MAXHOSTNAMELEN];
6322  char service[MAXHOSTNAMELEN];
6323  int srv_ret = 0;
6324  int tportno;
6325 
6326  AST_DECLARE_APP_ARGS(hostport,
6327  AST_APP_ARG(host);
6328  AST_APP_ARG(port);
6329  );
6330 
6331  peername = ast_strdupa(opeer);
6332  peername2 = ast_strdupa(opeer);
6333  AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
6334 
6335  if (hostport.port)
6336  dialog->portinuri = 1;
6337 
6338  dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
6339  dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
6340  peer = sip_find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
6341 
6342  if (peer) {
6343  int res;
6344  if (newdialog) {
6345  set_socket_transport(&dialog->socket, 0);
6346  }
6347  res = create_addr_from_peer(dialog, peer);
6348  dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
6349  sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
6350  return res;
6351  } else if (ast_check_digits(peername)) {
6352  /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
6353  * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
6354  * almost certainly not intended. It is much better to just reject purely numeric hostnames */
6355  ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
6356  return -1;
6357  } else {
6358  dialog->rtptimeout = global_rtptimeout;
6361  if (dialog_initialize_rtp(dialog)) {
6362  return -1;
6363  }
6364  }
6365 
6366  ast_string_field_set(dialog, tohost, hostport.host);
6368 
6369  /* Get the outbound proxy information */
6370  ref_proxy(dialog, obproxy_get(dialog, NULL));
6371 
6372  if (addr) {
6373  /* This address should be updated using dnsmgr */
6374  ast_sockaddr_copy(&dialog->sa, addr);
6375  } else {
6376 
6377  /* Let's see if we can find the host in DNS. First try DNS SRV records,
6378  then hostname lookup */
6379  /*! \todo Fix this function. When we ask for SRV, we should check all transports
6380  In the future, we should first check NAPTR to find out transport preference
6381  */
6382  hostn = peername;
6383  /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
6384  * an A record lookup should be used instead of SRV.
6385  */
6386  if (!hostport.port && sip_cfg.srvlookup) {
6387  snprintf(service, sizeof(service), "_%s._%s.%s",
6388  get_srv_service(dialog->socket.type),
6389  get_srv_protocol(dialog->socket.type), peername);
6390  if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
6391  service)) > 0) {
6392  hostn = host;
6393  }
6394  }
6395 
6396  if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : AST_TRANSPORT_UDP)) {
6397  ast_log(LOG_WARNING, "No such host: %s\n", peername);
6398  return -1;
6399  }
6400 
6401  if (srv_ret > 0) {
6402  ast_sockaddr_set_port(&dialog->sa, tportno);
6403  }
6404  }
6405 
6406  if (!dialog->socket.type) {
6408  }
6409 
6410  if (!ast_sockaddr_port(&dialog->sa)) {
6411  ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
6412  }
6413  ast_sockaddr_copy(&dialog->recv, &dialog->sa);
6414  return 0;
6415 }
6416 
6417 /*! \brief Scheduled congestion on a call.
6418  * Only called by the scheduler, must return the reference when done.
6419  */
6420 static int auto_congest(const void *arg)
6421 {
6422  struct sip_pvt *p = (struct sip_pvt *)arg;
6423 
6424  sip_pvt_lock(p);
6425  p->initid = -1; /* event gone, will not be rescheduled */
6426  if (p->owner) {
6427  /* XXX fails on possible deadlock */
6428  if (!ast_channel_trylock(p->owner)) {
6429  append_history(p, "Cong", "Auto-congesting (timer)");
6432  }
6433 
6434  /* Give the channel a chance to act before we proceed with destruction */
6436  }
6437  sip_pvt_unlock(p);
6438  dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
6439  return 0;
6440 }
6441 
6442 
6443 /*! \brief Initiate SIP call from PBX
6444  * used from the dial() application */
6445 static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
6446 {
6447  int res;
6448  struct sip_pvt *p = ast_channel_tech_pvt(ast); /* chan is locked, so the reference cannot go away */
6449  struct varshead *headp;
6450  struct ast_var_t *current;
6451  const char *referer = NULL; /* SIP referrer */
6452  int cc_core_id;
6453  char uri[SIPBUFSIZE] = "";
6454 
6456  ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
6457  return -1;
6458  }
6459 
6460  if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
6462  struct ast_cc_monitor *recall_monitor;
6463  struct sip_monitor_instance *monitor_instance;
6464  ast_channel_get_device_name(ast, device_name, sizeof(device_name));
6465  if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
6466  monitor_instance = recall_monitor->private_data;
6467  ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
6468  ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
6469  }
6470  }
6471 
6472  /* Check whether there is vxml_url, distinctive ring variables */
6473  headp = ast_channel_varshead(ast);
6474  AST_LIST_TRAVERSE(headp, current, entries) {
6475  /* Check whether there is a VXML_URL variable */
6476  if (!p->options->vxml_url && !strcmp(ast_var_name(current), "VXML_URL")) {
6477  p->options->vxml_url = ast_var_value(current);
6478  } else if (!p->options->uri_options && !strcmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
6479  p->options->uri_options = ast_var_value(current);
6480  } else if (!p->options->addsipheaders && !strncmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
6481  /* Check whether there is a variable with a name starting with SIPADDHEADER */
6482  p->options->addsipheaders = 1;
6483  } else if (!strcmp(ast_var_name(current), "SIPFROMDOMAIN")) {
6484  ast_string_field_set(p, fromdomain, ast_var_value(current));
6485  } else if (!strcmp(ast_var_name(current), "SIPTRANSFER")) {
6486  /* This is a transferred call */
6487  p->options->transfer = 1;
6488  } else if (!strcmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
6489  /* This is the referrer */
6490  referer = ast_var_value(current);
6491  } else if (!strcmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
6492  /* We're replacing a call. */
6493  p->options->replaces = ast_var_value(current);
6494  } else if (!strcmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
6495  if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
6496  ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
6497  }
6498  }
6499  }
6500 
6501  /* Check to see if we should try to force encryption */
6503  ast_log(LOG_WARNING, "Encrypted signaling is required\n");
6505  return -1;
6506  }
6507 
6508  if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
6509  if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
6510  ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
6512  }
6513 
6514  if (p->rtp && !p->srtp && !(p->srtp = ast_sdp_srtp_alloc())) {
6515  ast_log(LOG_WARNING, "SRTP audio setup failed\n");
6516  return -1;
6517  }
6518 
6519  if (p->vrtp && !p->vsrtp && !(p->vsrtp = ast_sdp_srtp_alloc())) {
6520  ast_log(LOG_WARNING, "SRTP video setup failed\n");
6521  return -1;
6522  }
6523 
6524  if (p->trtp && !p->tsrtp && !(p->tsrtp = ast_sdp_srtp_alloc())) {
6525  ast_log(LOG_WARNING, "SRTP text setup failed\n");
6526  return -1;
6527  }
6528  }
6529 
6530  res = 0;
6531  ast_set_flag(&p->flags[0], SIP_OUTGOING);
6532 
6533  /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
6534  * so ensure it is disabled.
6535  */
6537 
6538  if (p->options->transfer) {
6539  char buf[SIPBUFSIZE / 2];
6540 
6541  if (referer) {
6542  if (sipdebug)
6543  ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
6544  snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
6545  } else
6546  snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
6547  ast_string_field_set(p, cid_name, buf);
6548  }
6549  ast_debug(1, "Outgoing Call for %s\n", p->username);
6550 
6552 
6553  if (res == -1) {
6555  return res;
6556  }
6560 
6561  /* If there are no formats left to offer, punt */
6562  if (ast_format_cap_empty(p->jointcaps)) {
6563  ast_log(LOG_WARNING, "No format found to offer. Cancelling call to %s\n", p->username);
6564  res = -1;
6565  /* If audio was requested (prefcaps) and the [peer] section contains
6566  * audio (caps) the user expects audio. In that case, if jointcaps
6567  * contain no audio, punt. Furthermore, this check allows the [peer]
6568  * section to have no audio. In that case, the user expects no audio
6569  * and we can pass. Finally, this check allows the requester not to
6570  * offer any audio. In that case, the call is expected to have no audio
6571  * and we can pass, as well.
6572  */
6576  ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
6577  res = -1;
6578  } else {
6579  int xmitres;
6581  struct ast_set_party_connected_line update_connected;
6582 
6583  sip_pvt_lock(p);
6584 
6585  /* Supply initial connected line information if available. */
6586  memset(&update_connected, 0, sizeof(update_connected));
6587  ast_party_connected_line_init(&connected);
6588  if (!ast_strlen_zero(p->cid_num)
6590  update_connected.id.number = 1;
6591  connected.id.number.valid = 1;
6592  connected.id.number.str = (char *) p->cid_num;
6593  connected.id.number.presentation = p->callingpres;
6594  }
6595  if (!ast_strlen_zero(p->cid_name)
6597  update_connected.id.name = 1;
6598  connected.id.name.valid = 1;
6599  connected.id.name.str = (char *) p->cid_name;
6600  connected.id.name.presentation = p->callingpres;
6601  }
6602  if (update_connected.id.number || update_connected.id.name) {
6603  /* Invalidate any earlier private connected id representation */
6604  ast_set_party_id_all(&update_connected.priv);
6605 
6606  connected.id.tag = (char *) p->cid_tag;
6608  ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
6609  }
6610 
6611  xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
6612  if (xmitres == XMIT_ERROR) {
6613  sip_pvt_unlock(p);
6614  return -1;
6615  }
6616  p->invitestate = INV_CALLING;
6617 
6618  /* Initialize auto-congest time */
6620  dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
6621  dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
6622  dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
6623  sip_pvt_unlock(p);
6624  }
6625  return res;
6626 }
6627 
6628 /*! \brief Destroy registry object
6629  Objects created with the register= statement in static configuration */
6630 static void sip_registry_destroy(void *obj)
6631 {
6632  struct sip_registry *reg = obj;
6633  /* Really delete */
6634  ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
6635 
6636  if (reg->call) {
6637  /* Clear registry before destroying to ensure
6638  we don't get reentered trying to grab the registry lock */
6639  ao2_t_replace(reg->call->registry, NULL, "destroy reg->call->registry");
6640  ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
6641  dialog_unlink_all(reg->call);
6642  reg->call = dialog_unref(reg->call, "unref reg->call");
6643  /* reg->call = sip_destroy(reg->call); */
6644  }
6645 
6647 }
6648 
6649 /*! \brief Destroy MWI subscription object */
6650 static void sip_subscribe_mwi_destroy(void *data)
6651 {
6652  struct sip_subscription_mwi *mwi = data;
6653 
6654  if (mwi->call) {
6655  mwi->call->mwi = NULL;
6656  mwi->call = dialog_unref(mwi->call, "sip_subscription_mwi destruction");
6657  }
6658 
6660 }
6661 
6662 /*! \brief Destroy SDP media offer list */
6663 static void offered_media_list_destroy(struct sip_pvt *p)
6664 {
6665  struct offered_media *offer;
6666  while ((offer = AST_LIST_REMOVE_HEAD(&p->offered_media, next))) {
6667  ast_free(offer->decline_m_line);
6668  ast_free(offer);
6669  }
6670 }
6671 
6672 /*! \brief ao2 destructor for SIP dialog structure */
6673 static void sip_pvt_dtor(void *vdoomed)
6674 {
6675  struct sip_pvt *p = vdoomed;
6676  struct sip_request *req;
6677 
6678  ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
6679 
6680  /* Destroy Session-Timers if allocated */
6681  ast_free(p->stimer);
6682  p->stimer = NULL;
6683 
6684  if (sip_debug_test_pvt(p))
6685  ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
6686 
6689  ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
6690  }
6691 
6692  /* Unlink us from the owner if we have one */
6693  if (p->owner) {
6694  ast_channel_lock(p->owner);
6695  ast_debug(1, "Detaching from %s\n", ast_channel_name(p->owner));
6697  /* Make sure that the channel knows its backend is going away */
6700  /* Give the channel a chance to react before deallocation */
6701  usleep(1);
6702  }
6703 
6704  /* Remove link from peer to subscription of MWI */
6705  if (p->relatedpeer && p->relatedpeer->mwipvt == p)
6706  p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
6707  if (p->relatedpeer && p->relatedpeer->call == p)
6708  p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
6709 
6710  if (p->relatedpeer)
6711  p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
6712 
6713  if (p->registry) {
6714  if (p->registry->call == p)
6715  p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
6716  ao2_t_replace(p->registry, NULL, "delete p->registry");
6717  }
6718 
6719  if (p->mwi) {
6720  p->mwi->call = NULL;
6721  p->mwi = NULL;
6722  }
6723 
6724  if (dumphistory)
6725  sip_dump_history(p);
6726 
6727  if (p->options) {
6728  if (p->options->outboundproxy) {
6729  ao2_ref(p->options->outboundproxy, -1);
6730  }
6731  ast_free(p->options);
6732  p->options = NULL;
6733  }
6734 
6735  if (p->outboundproxy) {
6736  ref_proxy(p, NULL);
6737  }
6738 
6739  if (p->notify) {
6741  ast_free(p->notify->content);
6742  ast_free(p->notify);
6743  p->notify = NULL;
6744  }
6745 
6746  /* Free RTP and SRTP instances */
6747  dialog_clean_rtp(p);
6748 
6749  if (p->udptl) {
6751  p->udptl = NULL;
6752  }
6753  sip_refer_destroy(p);
6754  sip_route_clear(&p->route);
6755  deinit_req(&p->initreq);
6756 
6757  /* Clear history */
6758  if (p->history) {
6759  struct sip_history *hist;
6760  while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
6761  ast_free(hist);
6762  p->history_entries--;
6763  }
6764  ast_free(p->history);
6765  p->history = NULL;
6766  }
6767 
6768  while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
6769  ast_free(req);
6770  }
6771 
6773 
6774  if (p->chanvars) {
6776  p->chanvars = NULL;
6777  }
6778 
6780 
6781  if (p->vsrtp) {
6783  p->vsrtp = NULL;
6784  }
6785 
6786  if (p->directmediaacl) {
6788  }
6789 
6791 
6793  p->cc_params = NULL;
6794 
6795  if (p->epa_entry) {
6796  ao2_ref(p->epa_entry, -1);
6797  p->epa_entry = NULL;
6798  }
6799 
6800  if (p->socket.tcptls_session) {
6801  ao2_ref(p->socket.tcptls_session, -1);
6802  p->socket.tcptls_session = NULL;
6803  } else if (p->socket.ws_session) {
6805  p->socket.ws_session = NULL;
6806  }
6807 
6808  if (p->peerauth) {
6809  ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
6810  p->peerauth = NULL;
6811  }
6812 
6815 
6816  ao2_cleanup(p->caps);
6817  ao2_cleanup(p->jointcaps);
6818  ao2_cleanup(p->peercaps);
6819  ao2_cleanup(p->redircaps);
6820  ao2_cleanup(p->prefcaps);
6821 
6823 
6824  if (p->last_device_state_info) {
6827  }
6828 }
6829 
6830 /*! \brief update_call_counter: Handle call_limit for SIP devices
6831  * Setting a call-limit will cause calls above the limit not to be accepted.
6832  *
6833  * Remember that for a type=friend, there's one limit for the user and
6834  * another for the peer, not a combined call limit.
6835  * This will cause unexpected behaviour in subscriptions, since a "friend"
6836  * is *two* devices in Asterisk, not one.
6837  *
6838  * Thought: For realtime, we should probably update storage with inuse counter...
6839  *
6840  * \return 0 if call is ok (no call limit, below threshold)
6841  * -1 on rejection of call
6842  *
6843  */
6844 static int update_call_counter(struct sip_pvt *fup, int event)
6845 {
6846  char name[256];
6847  int *inuse = NULL, *call_limit = NULL, *ringing = NULL;
6848  int outgoing = fup->outgoing_call;
6849  struct sip_peer *p = NULL;
6850 
6851  ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
6852 
6853 
6854  /* Test if we need to check call limits, in order to avoid
6855  realtime lookups if we do not need it */
6857  return 0;
6858 
6859  ast_copy_string(name, fup->username, sizeof(name));
6860 
6861  /* Check the list of devices */
6862  if (fup->relatedpeer) {
6863  p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
6864  inuse = &p->inuse;
6865  call_limit = &p->call_limit;
6866  ringing = &p->ringing;
6867  ast_copy_string(name, fup->peername, sizeof(name));
6868  }
6869  if (!p) {
6870  ast_debug(2, "%s is not a local device, no call limit\n", name);
6871  return 0;
6872  }
6873 
6874  switch(event) {
6875  /* incoming and outgoing affects the inuse counter */
6876  case DEC_CALL_LIMIT:
6877  /* Decrement inuse count if applicable */
6878  if (inuse) {
6879  sip_pvt_lock(fup);
6880  ao2_lock(p);
6881  if (*inuse > 0) {
6882  if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
6883  (*inuse)--;
6884  ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
6885  }
6886  } else {
6887  *inuse = 0;
6888  }
6889  ao2_unlock(p);
6890  sip_pvt_unlock(fup);
6891  }
6892 
6893  /* Decrement ringing count if applicable */
6894  if (ringing) {
6895  sip_pvt_lock(fup);
6896  ao2_lock(p);
6897  if (*ringing > 0) {
6898  if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6899  (*ringing)--;
6901  }
6902  } else {
6903  *ringing = 0;
6904  }
6905  ao2_unlock(p);
6906  sip_pvt_unlock(fup);
6907  }
6908 
6909  /* Decrement onhold count if applicable */
6910  sip_pvt_lock(fup);
6911  ao2_lock(p);
6914  ao2_unlock(p);
6915  sip_pvt_unlock(fup);
6916  sip_peer_hold(fup, FALSE);
6917  } else {
6918  ao2_unlock(p);
6919  sip_pvt_unlock(fup);
6920  }
6921  if (sipdebug)
6922  ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
6923  break;
6924 
6925  case INC_CALL_RINGING:
6926  case INC_CALL_LIMIT:
6927  /* If call limit is active and we have reached the limit, reject the call */
6928  if (*call_limit > 0 ) {
6929  if (*inuse >= *call_limit) {
6930  ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
6931  sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
6932  return -1;
6933  }
6934  }
6935  if (ringing && (event == INC_CALL_RINGING)) {
6936  sip_pvt_lock(fup);
6937  ao2_lock(p);
6938  if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6939  (*ringing)++;
6940  ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
6941  }
6942  ao2_unlock(p);
6943  sip_pvt_unlock(fup);
6944  }
6945  if (inuse) {
6946  sip_pvt_lock(fup);
6947  ao2_lock(p);
6948  if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
6949  (*inuse)++;
6950  ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
6951  }
6952  ao2_unlock(p);
6953  sip_pvt_unlock(fup);
6954  }
6955  if (sipdebug) {
6956  ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
6957  }
6958  break;
6959 
6960  case DEC_CALL_RINGING:
6961  if (ringing) {
6962  sip_pvt_lock(fup);
6963  ao2_lock(p);
6964  if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
6965  if (*ringing > 0) {
6966  (*ringing)--;
6967  }
6969  }
6970  ao2_unlock(p);
6971  sip_pvt_unlock(fup);
6972  }
6973  break;
6974 
6975  default:
6976  ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
6977  }
6978 
6980  sip_unref_peer(p, "update_call_counter: sip_unref_peer from call counter");
6981 
6982  return 0;
6983 }
6984 
6985 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
6986 int hangup_sip2cause(int cause)
6987 {
6988  /* Possible values taken from causes.h */
6989 
6990  switch(cause) {
6991  case 401: /* Unauthorized */
6992  return AST_CAUSE_CALL_REJECTED;
6993  case 403: /* Not found */
6994  return AST_CAUSE_CALL_REJECTED;
6995  case 404: /* Not found */
6996  return AST_CAUSE_UNALLOCATED;
6997  case 405: /* Method not allowed */
6998  return AST_CAUSE_INTERWORKING;
6999  case 407: /* Proxy authentication required */
7000  return AST_CAUSE_CALL_REJECTED;
7001  case 408: /* No reaction */
7003  case 409: /* Conflict */
7005  case 410: /* Gone */
7006  return AST_CAUSE_NUMBER_CHANGED;
7007  case 411: /* Length required */
7008  return AST_CAUSE_INTERWORKING;
7009  case 413: /* Request entity too large */
7010  return AST_CAUSE_INTERWORKING;
7011  case 414: /* Request URI too large */
7012  return AST_CAUSE_INTERWORKING;
7013  case 415: /* Unsupported media type */
7014  return AST_CAUSE_INTERWORKING;
7015  case 420: /* Bad extension */
7017  case 480: /* No answer */
7018  return AST_CAUSE_NO_ANSWER;
7019  case 481: /* No answer */
7020  return AST_CAUSE_INTERWORKING;
7021  case 482: /* Loop detected */
7022  return AST_CAUSE_INTERWORKING;
7023  case 483: /* Too many hops */
7024  return AST_CAUSE_NO_ANSWER;
7025  case 484: /* Address incomplete */
7027  case 485: /* Ambiguous */
7028  return AST_CAUSE_UNALLOCATED;
7029  case 486: /* Busy everywhere */
7030  return AST_CAUSE_BUSY;
7031  case 487: /* Request terminated */
7032  return AST_CAUSE_INTERWORKING;
7033  case 488: /* No codecs approved */
7035  case 491: /* Request pending */
7036  return AST_CAUSE_INTERWORKING;
7037  case 493: /* Undecipherable */
7038  return AST_CAUSE_INTERWORKING;
7039  case 500: /* Server internal failure */
7040  return AST_CAUSE_FAILURE;
7041  case 501: /* Call rejected */
7043  case 502:
7045  case 503: /* Service unavailable */
7046  return AST_CAUSE_CONGESTION;
7047  case 504: /* Gateway timeout */
7049  case 505: /* SIP version not supported */
7050  return AST_CAUSE_INTERWORKING;
7051  case 600: /* Busy everywhere */
7052  return AST_CAUSE_USER_BUSY;
7053  case 603: /* Decline */
7054  return AST_CAUSE_CALL_REJECTED;
7055  case 604: /* Does not exist anywhere */
7056  return AST_CAUSE_UNALLOCATED;
7057  case 606: /* Not acceptable */
7059  default:
7060  if (cause < 500 && cause >= 400) {
7061  /* 4xx class error that is unknown - someting wrong with our request */
7062  return AST_CAUSE_INTERWORKING;
7063  } else if (cause < 600 && cause >= 500) {
7064  /* 5xx class error - problem in the remote end */
7065  return AST_CAUSE_CONGESTION;
7066  } else if (cause < 700 && cause >= 600) {
7067  /* 6xx - global errors in the 4xx class */
7068  return AST_CAUSE_INTERWORKING;
7069  }
7070  return AST_CAUSE_NORMAL;
7071  }
7072  /* Never reached */
7073  return 0;
7074 }
7075 
7076 /*! \brief Convert Asterisk hangup causes to SIP codes
7077 \verbatim
7078  Possible values from causes.h
7079  AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
7080  AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
7081 
7082  In addition to these, a lot of PRI codes is defined in causes.h
7083  ...should we take care of them too ?
7084 
7085  Quote RFC 3398
7086 
7087  ISUP Cause value SIP response
7088  ---------------- ------------
7089  1 unallocated number 404 Not Found
7090  2 no route to network 404 Not found
7091  3 no route to destination 404 Not found
7092  16 normal call clearing --- (*)
7093  17 user busy 486 Busy here
7094  18 no user responding 408 Request Timeout
7095  19 no answer from the user 480 Temporarily unavailable
7096  20 subscriber absent 480 Temporarily unavailable
7097  21 call rejected 403 Forbidden (+)
7098  22 number changed (w/o diagnostic) 410 Gone
7099  22 number changed (w/ diagnostic) 301 Moved Permanently
7100  23 redirection to new destination 410 Gone
7101  26 non-selected user clearing 404 Not Found (=)
7102  27 destination out of order 502 Bad Gateway
7103  28 address incomplete 484 Address incomplete
7104  29 facility rejected 501 Not implemented
7105  31 normal unspecified 480 Temporarily unavailable
7106 \endverbatim
7107 */
7108 const char *hangup_cause2sip(int cause)
7109 {
7110  switch (cause) {
7111  case AST_CAUSE_UNALLOCATED: /* 1 */
7112  case AST_CAUSE_NO_ROUTE_DESTINATION: /* 3 IAX2: Can't find extension in context */
7113  case AST_CAUSE_NO_ROUTE_TRANSIT_NET: /* 2 */
7114  return "404 Not Found";
7115  case AST_CAUSE_CONGESTION: /* 34 */
7116  case AST_CAUSE_SWITCH_CONGESTION: /* 42 */
7117  return "503 Service Unavailable";
7118  case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
7119  return "408 Request Timeout";
7120  case AST_CAUSE_NO_ANSWER: /* 19 */
7121  case AST_CAUSE_UNREGISTERED: /* 20 */
7122  return "480 Temporarily unavailable";
7123  case AST_CAUSE_CALL_REJECTED: /* 21 */
7124  return "403 Forbidden";
7125  case AST_CAUSE_NUMBER_CHANGED: /* 22 */
7126  return "410 Gone";
7127  case AST_CAUSE_NORMAL_UNSPECIFIED: /* 31 */
7128  return "480 Temporarily unavailable";
7130  return "484 Address incomplete";
7131  case AST_CAUSE_USER_BUSY:
7132  return "486 Busy here";
7133  case AST_CAUSE_FAILURE:
7134  return "500 Server internal failure";
7135  case AST_CAUSE_FACILITY_REJECTED: /* 29 */
7136  return "501 Not Implemented";
7138  return "503 Service Unavailable";
7139  /* Used in chan_iax2 */
7141  return "502 Bad Gateway";
7142  case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
7143  return "488 Not Acceptable Here";
7144  case AST_CAUSE_INTERWORKING: /* Unspecified Interworking issues */
7145  return "500 Network error";
7146 
7147  case AST_CAUSE_NOTDEFINED:
7148  default:
7149  ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
7150  return NULL;
7151  }
7152 
7153  /* Never reached */
7154  return 0;
7155 }
7156 
7157 /* Run by the sched thread. */
7158 static int reinvite_timeout(const void *data)
7159 {
7160  struct sip_pvt *dialog = (struct sip_pvt *) data;
7161  struct ast_channel *owner;
7162 
7163  owner = sip_pvt_lock_full(dialog);
7164  dialog->reinviteid = -1;
7165  check_pendings(dialog);
7166  if (owner) {
7167  ast_channel_unlock(owner);
7168  ast_channel_unref(owner);
7169  }
7170  sip_pvt_unlock(dialog);
7171  dialog_unref(dialog, "reinviteid complete");
7172  return 0;
7173 }
7174 
7175 /* Run by the sched thread. */
7176 static int __stop_reinviteid(const void *data)
7177 {
7178  struct sip_pvt *pvt = (void *) data;
7179 
7180  AST_SCHED_DEL_UNREF(sched, pvt->reinviteid,
7181  dialog_unref(pvt, "Stop scheduled reinviteid"));
7182  dialog_unref(pvt, "Stop reinviteid action");
7183  return 0;
7184 }
7185 
7186 static void stop_reinviteid(struct sip_pvt *pvt)
7187 {
7188  dialog_ref(pvt, "Stop reinviteid action");
7189  if (ast_sched_add(sched, 0, __stop_reinviteid, pvt) < 0) {
7190  /* Uh Oh. Expect bad behavior. */
7191  dialog_unref(pvt, "Failed to schedule stop reinviteid action");
7192  }
7193 }
7194 
7195 /*! \brief sip_hangup: Hangup SIP call
7196  * Part of PBX interface, called from ast_hangup */
7197 static int sip_hangup(struct ast_channel *ast)
7198 {
7199  struct sip_pvt *p = ast_channel_tech_pvt(ast);
7200  int needcancel = FALSE;
7201  int needdestroy = 0;
7202  struct ast_channel *oldowner = ast;
7203 
7204  if (!p) {
7205  ast_debug(1, "Asked to hangup channel that was not connected\n");
7206  return 0;
7207  }
7209  ast_debug(1, "This call was answered elsewhere\n");
7210  append_history(p, "Cancel", "Call answered elsewhere");
7211  p->answered_elsewhere = TRUE;
7212  }
7213 
7214  /* Store hangupcause locally in PVT so we still have it before disconnect */
7215  if (p->owner)
7217 
7220  if (sipdebug)
7221  ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
7223  }
7224  ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
7226  ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
7227  if (p->owner) {
7228  sip_pvt_lock(p);
7229  oldowner = p->owner;
7230  sip_set_owner(p, NULL); /* Owner will be gone after we return, so take it away */
7231  sip_pvt_unlock(p);
7232  ast_channel_tech_pvt_set(oldowner, dialog_unref(ast_channel_tech_pvt(oldowner), "unref oldowner->tech_pvt"));
7233  }
7235  return 0;
7236  }
7237 
7238  ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
7239 
7240  sip_pvt_lock(p);
7242  if (sipdebug)
7243  ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
7245  }
7246 
7247  /* Determine how to disconnect */
7248  if (p->owner != ast) {
7249  ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
7250  sip_pvt_unlock(p);
7251  return 0;
7252  }
7253  /* If the call is not UP, we need to send CANCEL instead of BYE */
7254  /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
7256  needcancel = TRUE;
7257  ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast_channel_state(ast)));
7258  }
7259 
7260  stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
7261 
7262  append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", ast_cause2str(p->hangupcause));
7263 
7264  /* Disconnect */
7265  disable_dsp_detect(p);
7266 
7267  sip_set_owner(p, NULL);
7269 
7271  /* Do not destroy this pvt until we have timeout or
7272  get an answer to the BYE or INVITE/CANCEL
7273  If we get no answer during retransmit period, drop the call anyway.
7274  (Sorry, mother-in-law, you can't deny a hangup by sending
7275  603 declined to BYE...)
7276  */
7277  if (p->alreadygone)
7278  needdestroy = 1; /* Set destroy flag at end of this function */
7279  else if (p->invitestate != INV_CALLING)
7281 
7282  /* Start the process if it's not already started */
7283  if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
7284  if (needcancel) { /* Outgoing call, not up */
7285  if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7286  /* if we can't send right now, mark it pending */
7287  if (p->invitestate == INV_CALLING) {
7288  /* We can't send anything in CALLING state */
7290  /* Do we need a timer here if we don't hear from them at all? Yes we do or else we will get hung dialogs and those are no fun. */
7292  append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
7293  } else {
7294  struct sip_pkt *cur;
7295 
7296  for (cur = p->packets; cur; cur = cur->next) {
7297  __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
7298  }
7300  /* Send a new request: CANCEL */
7302  /* Actually don't destroy us yet, wait for the 487 on our original
7303  INVITE, but do set an autodestruct just in case we never get it. */
7304  needdestroy = 0;
7306  }
7307  } else { /* Incoming call, not up */
7308  const char *res;
7309 
7311  if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
7312  transmit_response_reliable(p, res, &p->initreq);
7313  else
7314  transmit_response_reliable(p, "603 Declined", &p->initreq);
7316  }
7317  } else { /* Call is in UP state, send BYE */
7318  if (p->stimer) {
7319  stop_session_timer(p);
7320  }
7321 
7322  if (!p->pendinginvite) {
7323  char *quality;
7324  char quality_buf[AST_MAX_USER_FIELD];
7325 
7326  if (p->rtp) {
7327  struct ast_rtp_instance *p_rtp;
7328 
7329  p_rtp = p->rtp;
7330  ao2_ref(p_rtp, +1);
7331  ast_channel_unlock(oldowner);
7332  sip_pvt_unlock(p);
7333  ast_rtp_instance_set_stats_vars(oldowner, p_rtp);
7334  ao2_ref(p_rtp, -1);
7335  ast_channel_lock(oldowner);
7336  sip_pvt_lock(p);
7337  }
7338 
7339  /*
7340  * The channel variables are set below just to get the AMI
7341  * VarSet event because the channel is being hungup.
7342  */
7343  if (p->rtp || p->vrtp || p->trtp) {
7344  ast_channel_stage_snapshot(oldowner);
7345  }
7346  if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
7347  if (p->do_history) {
7348  append_history(p, "RTCPaudio", "Quality:%s", quality);
7349  }
7350  pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
7351  }
7352  if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
7353  if (p->do_history) {
7354  append_history(p, "RTCPvideo", "Quality:%s", quality);
7355  }
7356  pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
7357  }
7358  if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
7359  if (p->do_history) {
7360  append_history(p, "RTCPtext", "Quality:%s", quality);
7361  }
7362  pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
7363  }
7364  if (p->rtp || p->vrtp || p->trtp) {
7366  }
7367 
7368  /* Send a hangup */
7369  if (ast_channel_state(oldowner) == AST_STATE_UP) {
7371  }
7372 
7373  } else {
7374  /* Note we will need a BYE when this all settles out
7375  but we can't send one while we have "INVITE" outstanding. */
7379  sip_cancel_destroy(p);
7380 
7381  /* If we have an ongoing reinvite, there is a chance that we have gotten a provisional
7382  * response, but something weird has happened and we will never receive a final response.
7383  * So, just in case, check for pending actions after a bit of time to trigger the pending
7384  * bye that we are setting above */
7385  if (p->ongoing_reinvite && p->reinviteid < 0) {
7386  p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1,
7387  reinvite_timeout, dialog_ref(p, "Schedule reinviteid"));
7388  if (p->reinviteid < 0) {
7389  /* Uh Oh. Expect bad behavior. */
7390  dialog_unref(p, "Failed to schedule reinviteid");
7391  }
7392  }
7393  }
7394  }
7395  }
7396  if (needdestroy) {
7397  pvt_set_needdestroy(p, "hangup");
7398  }
7399  sip_pvt_unlock(p);
7400  dialog_unref(p, "unref ast->tech_pvt");
7401  return 0;
7402 }
7403 
7404 /*! \brief Try setting the codecs suggested by the SIP_CODEC channel variable */
7405 static void try_suggested_sip_codec(struct sip_pvt *p)
7406 {
7407  const char *codec_list;
7408  char *codec_list_copy;
7409  struct ast_format_cap *original_jointcaps;
7410  char *codec;
7411  int first_codec = 1;
7412 
7413  char *strtok_ptr;
7414 
7415  if (p->outgoing_call) {
7416  codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
7417  } else if (!(codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
7418  codec_list = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
7419  }
7420 
7421  if (ast_strlen_zero(codec_list)) {
7422  return;
7423  }
7424 
7425  codec_list_copy = ast_strdupa(codec_list);
7426 
7427  original_jointcaps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
7428  if (!original_jointcaps) {
7429  return;
7430  }
7432 
7433  for (codec = strtok_r(codec_list_copy, ",", &strtok_ptr); codec; codec = strtok_r(NULL, ",", &strtok_ptr)) {
7434  struct ast_format *fmt;
7435 
7436  codec = ast_strip(codec);
7437 
7438  fmt = ast_format_cache_get(codec);
7439  if (!fmt) {
7440  ast_log(AST_LOG_NOTICE, "Ignoring ${SIP_CODEC*} variable because of unrecognized/not configured codec %s (check allow/disallow in sip.conf)\n", codec);
7441  continue;
7442  }
7443  if (ast_format_cap_iscompatible_format(original_jointcaps, fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
7444  if (first_codec) {
7445  ast_verb(4, "Set codec to '%s' for this call because of ${SIP_CODEC*} variable\n", codec);
7447  ast_format_cap_append(p->jointcaps, fmt, 0);
7449  ast_format_cap_append(p->caps, fmt, 0);
7450  first_codec = 0;
7451  } else {
7452  ast_verb(4, "Add codec to '%s' for this call because of ${SIP_CODEC*} variable\n", codec);
7453  /* Add the format to the capabilities structure */
7454  ast_format_cap_append(p->jointcaps, fmt, 0);
7455  ast_format_cap_append(p->caps, fmt, 0);
7456  }
7457  } else {
7458  ast_log(AST_LOG_NOTICE, "Ignoring ${SIP_CODEC*} variable because it is not shared by both ends: %s\n", codec);
7459  }
7460 
7461  ao2_ref(fmt, -1);
7462  }
7463 
7464  /* The original joint formats may have contained negotiated parameters (fmtp)
7465  * like the Opus Codec or iLBC 20. The cached formats contain the default
7466  * parameters, which could be different than the negotiated (joint) result. */
7468 
7469  ao2_ref(original_jointcaps, -1);
7470  return;
7471  }
7472 
7473 
7474 /*! \brief sip_answer: Answer SIP call , send 200 OK on Invite
7475  * Part of PBX interface */
7476 static int sip_answer(struct ast_channel *ast)
7477 {
7478  int res = 0;
7479  struct sip_pvt *p = ast_channel_tech_pvt(ast);
7480  int oldsdp = FALSE;
7481 
7482  if (!p) {
7483  ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
7484  ast_channel_name(ast));
7485  return res;
7486  }
7487  sip_pvt_lock(p);
7488  if (ast_channel_state(ast) != AST_STATE_UP) {
7490 
7491  if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
7492  oldsdp = TRUE;
7493  }
7494 
7495  ast_setstate(ast, AST_STATE_UP);
7496  ast_debug(1, "SIP answering channel: %s\n", ast_channel_name(ast));
7498  res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
7500  /* RFC says the session timer starts counting on 200,
7501  * not on INVITE. */
7502  if (p->stimer) {
7504  }
7505  }
7506  sip_pvt_unlock(p);
7507  return res;
7508 }
7509 
7510 /*! \brief Send frame to media channel (rtp) */
7511 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
7512 {
7513  struct sip_pvt *p = ast_channel_tech_pvt(ast);
7514  int res = 0;
7515 
7516  switch (frame->frametype) {
7517  case AST_FRAME_VOICE:
7519  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
7520  ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
7525  return 0;
7526  }
7527  if (p) {
7528  sip_pvt_lock(p);
7529  if (p->t38.state == T38_ENABLED) {
7530  /* drop frame, can't sent VOICE frames while in T.38 mode */
7531  sip_pvt_unlock(p);
7532  break;
7533  } else if (p->rtp) {
7534  /* If channel is not up, activate early media session */
7535  if ((ast_channel_state(ast) != AST_STATE_UP) &&
7537  !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7541  transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
7543  }
7544  }
7547  p->lastrtptx = time(NULL);
7548  res = ast_rtp_instance_write(p->rtp, frame);
7549  }
7550  }
7551  sip_pvt_unlock(p);
7552  }
7553  break;
7554  case AST_FRAME_VIDEO:
7555  if (p) {
7556  sip_pvt_lock(p);
7557  if (p->vrtp) {
7558  /* Activate video early media */
7559  if ((ast_channel_state(ast) != AST_STATE_UP) &&
7561  !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7563  transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
7565  }
7568  p->lastrtptx = time(NULL);
7569  res = ast_rtp_instance_write(p->vrtp, frame);
7570  }
7571  }
7572  sip_pvt_unlock(p);
7573  }
7574  break;
7575  case AST_FRAME_TEXT:
7576  if (p) {
7577  sip_pvt_lock(p);
7578  if (p->red) {
7579  ast_rtp_red_buffer(p->trtp, frame);
7580  } else {
7581  if (p->trtp) {
7582  /* Activate text early media */
7583  if ((ast_channel_state(ast) != AST_STATE_UP) &&
7585  !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
7587  transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
7589  }
7592  p->lastrtptx = time(NULL);
7593  res = ast_rtp_instance_write(p->trtp, frame);
7594  }
7595  }
7596  }
7597  sip_pvt_unlock(p);
7598  }
7599  break;
7600  case AST_FRAME_IMAGE:
7601  return 0;
7602  break;
7603  case AST_FRAME_MODEM:
7604  if (p) {
7605  sip_pvt_lock(p);
7606  /* UDPTL requires two-way communication, so early media is not needed here.
7607  we simply forget the frames if we get modem frames before the bridge is up.
7608  Fax will re-transmit.
7609  */
7610  if ((ast_channel_state(ast) == AST_STATE_UP) &&
7611  p->udptl &&
7612  (p->t38.state == T38_ENABLED)) {
7613  res = ast_udptl_write(p->udptl, frame);
7614  }
7615  sip_pvt_unlock(p);
7616  }
7617  break;
7618  default:
7619  ast_log(LOG_WARNING, "Can't send %u type frames with SIP write\n", frame->frametype);
7620  return 0;
7621  }
7622 
7623  return res;
7624 }
7625 
7626 /*! \brief sip_fixup: Fix up a channel: If a channel is consumed, this is called.
7627  Basically update any ->owner links */
7628 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
7629 {
7630  int ret = -1;
7631  struct sip_pvt *p;
7632 
7633  if (newchan && ast_test_flag(ast_channel_flags(newchan), AST_FLAG_ZOMBIE))
7634  ast_debug(1, "New channel is zombie\n");
7635  if (oldchan && ast_test_flag(ast_channel_flags(oldchan), AST_FLAG_ZOMBIE))
7636  ast_debug(1, "Old channel is zombie\n");
7637 
7638  if (!newchan || !ast_channel_tech_pvt(newchan)) {
7639  if (!newchan)
7640  ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
7641  else
7642  ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", ast_channel_name(oldchan));
7643  return -1;
7644  }
7645  p = ast_channel_tech_pvt(newchan);
7646 
7647  sip_pvt_lock(p);
7648  append_history(p, "Masq", "Old channel: %s\n", ast_channel_name(oldchan));
7649  append_history(p, "Masq (cont)", "...new owner: %s\n", ast_channel_name(newchan));
7650  if (p->owner != oldchan)
7651  ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
7652  else {
7653  sip_set_owner(p, newchan);
7654  /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
7655  RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
7656  able to do this if the masquerade happens before the bridge breaks (e.g., AMI
7657  redirect of both channels). Note that a channel can not be masqueraded *into*
7658  a native bridge. So there is no danger that this breaks a native bridge that
7659  should stay up. */
7660  sip_set_rtp_peer(newchan, NULL, NULL, NULL, NULL, 0);
7661  ret = 0;
7662  }
7663  ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, ast_channel_name(p->owner), ast_channel_name(oldchan));
7664 
7665  sip_pvt_unlock(p);
7666  return ret;
7667 }
7668 
7669 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
7670 {
7671  struct sip_pvt *p = ast_channel_tech_pvt(ast);
7672  int res = 0;
7673 
7674  if (!p) {
7675  ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
7676  ast_channel_name(ast));
7677  return res;
7678  }
7679 
7680  sip_pvt_lock(p);
7681  switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
7682  case SIP_DTMF_INBAND:
7683  res = -1; /* Tell Asterisk to generate inband indications */
7684  break;
7685  case SIP_DTMF_RFC2833:
7686  if (p->rtp)
7687  ast_rtp_instance_dtmf_begin(p->rtp, digit);
7688  break;
7689  default:
7690  break;
7691  }
7692  sip_pvt_unlock(p);
7693 
7694  return res;
7695 }
7696 
7697 /*! \brief Send DTMF character on SIP channel
7698  within one call, we're able to transmit in many methods simultaneously */
7699 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
7700 {
7701  struct sip_pvt *p = ast_channel_tech_pvt(ast);
7702  int res = 0;
7703 
7704  if (!p) {
7705  ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
7706  ast_channel_name(ast));
7707  return res;
7708  }
7709 
7710  sip_pvt_lock(p);
7711  switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
7712  case SIP_DTMF_INFO:
7713  case SIP_DTMF_SHORTINFO:
7714  transmit_info_with_digit(p, digit, duration);
7715  break;
7716  case SIP_DTMF_RFC2833:
7717  if (p->rtp)
7718  ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
7719  break;
7720  case SIP_DTMF_INBAND:
7721  res = -1; /* Tell Asterisk to stop inband indications */
7722  break;
7723  }
7724  sip_pvt_unlock(p);
7725 
7726  return res;
7727 }
7728 
7729 /*! \brief Transfer SIP call */
7730 static int sip_transfer(struct ast_channel *ast, const char *dest)
7731 {
7732  struct sip_pvt *p = ast_channel_tech_pvt(ast);
7733  int res;
7734 
7735  if (!p) {
7736  ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
7737  ast_channel_name(ast));
7738  return -1;
7739  }
7740 
7741  if (dest == NULL) /* functions below do not take a NULL */
7742  dest = "";
7743  sip_pvt_lock(p);
7744  if (ast_channel_state(ast) == AST_STATE_RING)
7745  res = sip_sipredirect(p, dest);
7746  else
7747  res = transmit_refer(p, dest);
7748  sip_pvt_unlock(p);
7749  return res;
7750 }
7751 
7752 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
7753 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
7754 {
7755  int res = 0;
7756 
7757  if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
7758  return -1;
7759  }
7760  switch (parameters->request_response) {
7761  case AST_T38_NEGOTIATED:
7762  case AST_T38_REQUEST_NEGOTIATE: /* Request T38 */
7763  /* Negotiation can not take place without a valid max_ifp value. */
7764  if (!parameters->max_ifp) {
7765  if (p->t38.state == T38_PEER_REINVITE) {
7767  transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
7768  }
7770  break;
7771  } else if (p->t38.state == T38_PEER_REINVITE) {
7773  p->t38.our_parms = *parameters;
7774  /* modify our parameters to conform to the peer's parameters,
7775  * based on the rules in the ITU T.38 recommendation
7776  */
7777  if (!p->t38.their_parms.fill_bit_removal) {
7779  }
7780  if (!p->t38.their_parms.transcoding_mmr) {
7782  }
7783  if (!p->t38.their_parms.transcoding_jbig) {
7785  }
7791  } else if ((p->t38.state != T38_ENABLED) || ((p->t38.state == T38_ENABLED) &&
7792  (parameters->request_response == AST_T38_REQUEST_NEGOTIATE))) {
7793  p->t38.our_parms = *parameters;
7796  if (!p->pendinginvite) {
7798  } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
7800  }
7801  }
7802  break;
7803  case AST_T38_TERMINATED:
7804  case AST_T38_REFUSED:
7805  case AST_T38_REQUEST_TERMINATE: /* Shutdown T38 */
7806  if (p->t38.state == T38_PEER_REINVITE) {
7809  transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
7810  } else if (p->t38.state == T38_ENABLED) {
7813  }
7814  break;
7815  case AST_T38_REQUEST_PARMS: { /* Application wants remote's parameters re-sent */
7816  struct ast_control_t38_parameters parameters = p->t38.their_parms;
7817 
7818  if (p->t38.state == T38_PEER_REINVITE) {
7820  parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
7822  if (p->owner) {
7823  ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
7824  }
7825  /* we need to return a positive value here, so that applications that
7826  * send this request can determine conclusively whether it was accepted or not...
7827  * older versions of chan_sip would just silently accept it and return zero.
7828  */
7829  res = AST_T38_REQUEST_PARMS;
7830  }
7831  break;
7832  }
7833  default:
7834  res = -1;
7835  break;
7836  }
7837 
7838  return res;
7839 }
7840 
7848 };
7849 
7850 /*!
7851  * \internal
7852  * \brief Create and initialize UDPTL for the specified dialog
7853  *
7854  * \param p SIP private structure to create UDPTL object for
7855  * \pre p is locked
7856  * \pre p->owner is locked
7857  *
7858  * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
7859  *
7860  * \return 0 on success, any other value on failure
7861  */
7862 static int initialize_udptl(struct sip_pvt *p)
7863 {
7864  int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
7865 
7866  if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
7867  return 1;
7868  }
7869 
7870  /* If we've already initialized T38, don't take any further action */
7871  if (p->udptl) {
7872  return 0;
7873  }
7874 
7875  /* T38 can be supported by this dialog, create it and set the derived properties */
7876  if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
7877  if (p->owner) {
7879  }
7880 
7884 
7885  ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
7886  ast_udptl_setnat(p->udptl, natflags);
7887  } else {
7888  ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
7890  return 1;
7891  }
7892 
7893  return 0;
7894 }
7895 
7896 
7897 static int sipinfo_send(
7898  struct ast_channel *chan,
7899  struct ast_variable *headers,
7900  const char *content_type,
7901  const char *content,
7902  const char *useragent_filter)
7903 {
7904  struct sip_pvt *p;
7905  struct ast_variable *var;
7906  struct sip_request req;
7907  int res = -1;
7908 
7909  ast_channel_lock(chan);
7910 
7911  if (ast_channel_tech(chan) != &sip_tech) {
7912  ast_log(LOG_WARNING, "Attempted to send a custom INFO on a non-SIP channel %s\n", ast_channel_name(chan));
7913  ast_channel_unlock(chan);
7914  return res;
7915  }
7916 
7917  p = ast_channel_tech_pvt(chan);
7918  sip_pvt_lock(p);
7919 
7920  if (!(ast_strlen_zero(useragent_filter))) {
7921  int match = (strstr(p->useragent, useragent_filter)) ? 1 : 0;
7922  if (!match) {
7923  goto cleanup;
7924  }
7925  }
7926 
7927  reqprep(&req, p, SIP_INFO, 0, 1);
7928  for (var = headers; var; var = var->next) {
7929  add_header(&req, var->name, var->value);
7930  }
7931  if (!ast_strlen_zero(content) && !ast_strlen_zero(content_type)) {
7932  add_header(&req, "Content-Type", content_type);
7933  add_content(&req, content);
7934  }
7935 
7936  res = send_request(p, &req, XMIT_RELIABLE, p->ocseq);
7937 
7938 cleanup:
7939  sip_pvt_unlock(p);
7940  ast_channel_unlock(chan);
7941  return res;
7942 }
7943 /*! \brief Play indication to user
7944  * With SIP a lot of indications is sent as messages, letting the device play
7945  the indication - busy signal, congestion etc
7946  \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
7947 */
7948 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
7949 {
7950  struct sip_pvt *p = ast_channel_tech_pvt(ast);
7951  int res = 0;
7952 
7953  if (!p) {
7954  ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
7955  ast_channel_name(ast));
7956  return res;
7957  }
7958 
7959  sip_pvt_lock(p);
7960  switch(condition) {
7961  case AST_CONTROL_RINGING:
7962  if (ast_channel_state(ast) == AST_STATE_RING) {
7964  if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
7966  /* Send 180 ringing if out-of-band seems reasonable */
7967  transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
7968  ast_set_flag(&p->flags[0], SIP_RINGING);
7970  break;
7971  } else {
7972  /* Well, if it's not reasonable, just send in-band */
7973  }
7974  }
7975  res = -1;
7976  break;
7977  case AST_CONTROL_BUSY:
7978  if (ast_channel_state(ast) != AST_STATE_UP) {
7979  transmit_response_reliable(p, "486 Busy Here", &p->initreq);
7981  sip_alreadygone(p);
7983  break;
7984  }
7985  res = -1;
7986  break;
7988  if (ast_channel_state(ast) != AST_STATE_UP) {
7989  transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
7991  sip_alreadygone(p);
7993  break;
7994  }
7995  res = -1;
7996  break;
7998  if (ast_channel_state(ast) != AST_STATE_UP) {
7999  switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
8001  transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
8003  sip_alreadygone(p);
8005  break;
8007  /* Just wait for inband DTMF digits */
8008  break;
8009  default:
8010  /* it actually means no support for overlap */
8011  transmit_response_reliable(p, "404 Not Found", &p->initreq);
8013  sip_alreadygone(p);
8015  break;
8016  }
8017  }
8018  break;
8020  if ((ast_channel_state(ast) != AST_STATE_UP) &&
8022  !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
8023  transmit_response(p, "100 Trying", &p->initreq);
8025  break;
8026  }
8027  res = -1;
8028  break;
8029  case AST_CONTROL_PROGRESS:
8030  if ((ast_channel_state(ast) != AST_STATE_UP) &&
8032  !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
8034  /* SIP_PROG_INBAND_NEVER means sending 180 ringing in place of a 183 */
8036  transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
8038  } else if (ast_channel_state(ast) == AST_STATE_RING && !ast_test_flag(&p->flags[0], SIP_RINGING)) {
8039  transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
8040  ast_set_flag(&p->flags[0], SIP_RINGING);
8041  }
8042  break;
8043  }
8044  res = -1;
8045  break;
8046  case AST_CONTROL_HOLD:
8048  ast_moh_start(ast, data, p->mohinterpret);
8049  break;
8050  case AST_CONTROL_UNHOLD:
8052  ast_moh_stop(ast);
8053  break;
8054  case AST_CONTROL_VIDUPDATE: /* Request a video frame update */
8055  if (p->vrtp && !p->novideo) {
8056  /* FIXME: Only use this for VP8. Additional work would have to be done to
8057  * fully support other video codecs */
8059  /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
8060  * RTP engine would provide a way to externally write/schedule RTCP
8061  * packets */
8062  struct ast_frame fr;
8065  res = ast_rtp_instance_write(p->vrtp, &fr);
8066  } else {
8068  }
8069  } else {
8070  res = -1;
8071  }
8072  break;
8074  res = -1;
8075  if (datalen != sizeof(struct ast_control_t38_parameters)) {
8076  ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);
8077  } else {
8078  const struct ast_control_t38_parameters *parameters = data;
8079  if (!initialize_udptl(p)) {
8080  res = interpret_t38_parameters(p, parameters);
8081  }
8082  }
8083  break;
8084  case AST_CONTROL_SRCUPDATE:
8086  break;
8087  case AST_CONTROL_SRCCHANGE:
8089  break;
8091  update_connectedline(p, data, datalen);
8092  break;
8094  update_redirecting(p, data, datalen);
8095  break;
8096  case AST_CONTROL_AOC:
8097  {
8098  struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
8099  if (!decoded) {
8100  ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
8101  res = -1;
8102  break;
8103  }
8104  switch (ast_aoc_get_msg_type(decoded)) {
8105  case AST_AOC_REQUEST:
8106  if (ast_aoc_get_termination_request(decoded)) {
8107  /* TODO, once there is a way to get AOC-E on hangup, attempt that here
8108  * before hanging up the channel.*/
8109 
8110  /* The other side has already initiated the hangup. This frame
8111  * just says they are waiting to get AOC-E before completely tearing
8112  * the call down. Since SIP does not support this at the moment go
8113  * ahead and terminate the call here to avoid an unnecessary timeout. */
8114  ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", ast_channel_name(p->owner));
8116  }
8117  break;
8118  case AST_AOC_D:
8119  case AST_AOC_E:
8120  if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
8121  transmit_info_with_aoc(p, decoded);
8122  }
8123  break;
8124  case AST_AOC_S: /* S not supported yet */
8125  default:
8126  break;
8127  }
8128  ast_aoc_destroy_decoded(decoded);
8129  }
8130  break;
8131  case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
8132  break;
8133  case AST_CONTROL_FLASH: /* We don't currently handle AST_CONTROL_FLASH here, but it is expected, so we don't need to warn either. */
8134  res = -1;
8135  break;
8136  case AST_CONTROL_PVT_CAUSE_CODE: /* these should be handled by the code in channel.c */
8138  case -1:
8139  res = -1;
8140  break;
8141  default:
8142  ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
8143  res = -1;
8144  break;
8145  }
8146  sip_pvt_unlock(p);
8147  return res;
8148 }
8149 
8150 /*!
8151  * \brief Initiate a call in the SIP channel
8152  *
8153  * \note called from sip_request_call (calls from the pbx ) for
8154  * outbound channels and from handle_request_invite for inbound
8155  * channels
8156  *
8157  * \pre i is locked
8158  *
8159  * \return New ast_channel locked.
8160  */
8161 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, ast_callid callid)
8162 {
8163  struct ast_format_cap *caps;
8164  struct ast_channel *tmp;
8165  struct ast_variable *v = NULL;
8166  struct ast_format *fmt;
8167  struct ast_format_cap *what = NULL; /* SHALLOW COPY DO NOT DESTROY! */
8168  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
8169  int needvideo = 0;
8170  int needtext = 0;
8171  char *exten;
8172 
8174  if (!caps) {
8175  return NULL;
8176  }
8177 
8178  {
8179  const char *my_name; /* pick a good name */
8180 
8181  if (title) {
8182  my_name = title;
8183  } else {
8184  my_name = ast_strdupa(i->fromdomain);
8185  }
8186 
8187  /* Don't hold a sip pvt lock while we allocate a channel */
8188  sip_pvt_unlock(i);
8189 
8190  if (i->relatedpeer && i->relatedpeer->endpoint) {
8191  tmp = ast_channel_alloc_with_endpoint(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, assignedids, requestor, i->amaflags, i->relatedpeer->endpoint, "SIP/%s-%08x", my_name, (unsigned)ast_atomic_fetchadd_int((int *)&chan_idx, +1));
8192  } else {
8193  tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, assignedids, requestor, i->amaflags, "SIP/%s-%08x", my_name, (unsigned)ast_atomic_fetchadd_int((int *)&chan_idx, +1));
8194  }
8195  }
8196  if (!tmp) {
8197  ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
8198  ao2_ref(caps, -1);
8199  sip_pvt_lock(i);
8200  return NULL;
8201  }
8202 
8204 
8205  /* If we sent in a callid, bind it to the channel. */
8206  if (callid) {
8207  ast_channel_callid_set(tmp, callid);
8208  }
8209 
8210  sip_pvt_lock(i);
8213 
8215 
8216  /* Select our native format based on codec preference until we receive
8217  something from another device to the contrary. */
8218  if (ast_format_cap_count(i->jointcaps)) { /* The joint capabilities of us and peer */
8219  what = i->jointcaps;
8220  } else if (ast_format_cap_count(i->caps)) { /* Our configured capability for this peer */
8221  what = i->caps;
8222  } else {
8223  what = sip_cfg.caps;
8224  }
8225 
8226  /* Set the native formats */
8228  /* Use only the preferred audio format, which is stored at the '0' index */
8229  fmt = ast_format_cap_get_best_by_type(what, AST_MEDIA_TYPE_AUDIO); /* get the best audio format */
8230  if (fmt) {
8231  int framing;
8232 
8233  ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_AUDIO); /* remove only the other audio formats */
8234  framing = ast_format_cap_get_format_framing(what, fmt);
8235  ast_format_cap_append(caps, fmt, framing); /* add our best choice back */
8236  } else {
8237  /* If we don't have an audio format, try to get something */
8238  fmt = ast_format_cap_get_format(caps, 0);
8239  if (!fmt) {
8240  ast_log(LOG_WARNING, "No compatible formats could be found for %s\n", ast_channel_name(tmp));
8241  ao2_ref(caps, -1);
8243  ast_channel_unlock(tmp);
8244  ast_hangup(tmp);
8245  return NULL;
8246  }
8247  }
8248  ast_channel_nativeformats_set(tmp, caps);
8249  ao2_ref(caps, -1);
8250 
8251  ast_debug(3, "*** Our native formats are %s \n", ast_format_cap_get_names(ast_channel_nativeformats(tmp), &codec_buf));
8252  ast_debug(3, "*** Joint capabilities are %s \n", ast_format_cap_get_names(i->jointcaps, &codec_buf));
8253  ast_debug(3, "*** Our capabilities are %s \n", ast_format_cap_get_names(i->caps, &codec_buf));
8254  ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_format_get_name(fmt));
8255  if (ast_format_cap_count(i->prefcaps)) {
8256  ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_format_cap_get_names(i->prefcaps, &codec_buf));
8257  }
8258 
8259  /* If we have a prefcodec setting, we have an inbound channel that set a
8260  preferred format for this call. Otherwise, we check the jointcapability
8261  We also check for vrtp. If it's not there, we are not allowed do any video anyway.
8262  */
8263  if (i->vrtp) {
8265  needvideo = 1;
8266  else if (ast_format_cap_count(i->prefcaps))
8267  needvideo = ast_format_cap_has_type(i->prefcaps, AST_MEDIA_TYPE_VIDEO); /* Outbound call */
8268  else
8269  needvideo = ast_format_cap_has_type(i->jointcaps, AST_MEDIA_TYPE_VIDEO); /* Inbound call */
8270 
8271  if (!needvideo) {
8273  i->vrtp = NULL;
8274  }
8275  }
8276 
8277  if (i->trtp) {
8279  needtext = ast_format_cap_has_type(i->prefcaps, AST_MEDIA_TYPE_TEXT); /* Outbound call */
8280  else
8281  needtext = ast_format_cap_has_type(i->jointcaps, AST_MEDIA_TYPE_TEXT); /* Inbound call */
8282  }
8283 
8284  if (needvideo) {
8285  ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
8286  } else {
8287  ast_debug(3, "This channel will not be able to handle video.\n");
8288  }
8289 
8290  enable_dsp_detect(i);
8291 
8292  if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
8293  (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
8294  if (i->rtp) {
8296  }
8297  } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
8298  if (i->rtp) {
8300  }
8301  }
8302 
8303  /* Set file descriptors for audio, video, and realtime text. Since
8304  * UDPTL is created as needed in the lifetime of a dialog, its file
8305  * descriptor is set in initialize_udptl */
8306  if (i->rtp) {
8308  if (ast_test_flag(&i->flags[2], SIP_PAGE3_RTCP_MUX)) {
8310  } else {
8312  }
8315  }
8316  if (needvideo && i->vrtp) {
8318  if (ast_test_flag(&i->flags[2], SIP_PAGE3_RTCP_MUX)) {
8320  } else {
8322  }
8323  }
8324  if (needtext && i->trtp) {
8326  }
8327  if (i->udptl) {
8329  }
8330 
8331  if (state == AST_STATE_RING) {
8332  ast_channel_rings_set(tmp, 1);
8333  }
8335 
8336  ast_channel_set_writeformat(tmp, fmt);
8338 
8339  ast_channel_set_readformat(tmp, fmt);
8341 
8342  ao2_ref(fmt, -1);
8343 
8344  ast_channel_tech_pvt_set(tmp, dialog_ref(i, "sip_new: set chan->tech_pvt to i"));
8345 
8348 
8351 
8354  if (!ast_strlen_zero(i->parkinglot)) {
8355  ast_channel_parkinglot_set(tmp, i->parkinglot);
8356  }
8357  if (!ast_strlen_zero(i->accountcode)) {
8358  ast_channel_accountcode_set(tmp, i->accountcode);
8359  }
8360  if (i->amaflags) {
8362  }
8363  if (!ast_strlen_zero(i->language)) {
8364  ast_channel_language_set(tmp, i->language);
8365  }
8366  if (!ast_strlen_zero(i->zone)) {
8367  struct ast_tone_zone *zone;
8368  if (!(zone = ast_get_indication_zone(i->zone))) {
8369  ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", i->zone);
8370  }
8371  ast_channel_zone_set(tmp, zone);
8372  }
8373  sip_set_owner(i, tmp);
8376  /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
8377  * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
8378  * structure so that there aren't issues when forming URI's
8379  */
8380  exten = ast_strdupa(i->exten);
8381  sip_pvt_unlock(i);
8382  ast_channel_unlock(tmp);
8383  if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
8385  }
8386  ast_channel_lock(tmp);
8387  sip_pvt_lock(i);
8388  ast_channel_exten_set(tmp, exten);
8389 
8390  /* Don't use ast_set_callerid() here because it will
8391  * generate an unnecessary NewCallerID event */
8392  if (!ast_strlen_zero(i->cid_num)) {
8393  ast_channel_caller(tmp)->ani.number.valid = 1;
8395  }
8396  if (!ast_strlen_zero(i->rdnis)) {
8399  }
8400 
8401  if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
8403  }
8404 
8405  ast_channel_priority_set(tmp, 1);
8406  if (!ast_strlen_zero(i->uri)) {
8407  pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
8408  }
8409  if (!ast_strlen_zero(i->domain)) {
8410  pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
8411  }
8413  pbx_builtin_setvar_helper(tmp, "SIPURIPHONECONTEXT", i->tel_phone_context);
8414  }
8415  if (!ast_strlen_zero(i->callid)) {
8416  pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
8417  }
8418  if (i->rtp) {
8420  }
8421 
8422  if (!i->relatedpeer) {
8424  }
8425  /* Set channel variables for this call from configuration */
8426  for (v = i->chanvars ; v ; v = v->next) {
8427  char valuebuf[1024];
8428  pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
8429  }
8430 
8431  if (i->do_history) {
8432  append_history(i, "NewChan", "Channel %s - from %s", ast_channel_name(tmp), i->callid);
8433  }
8434 
8436 
8437  return tmp;
8438 }
8439 
8440 /*! \brief Lookup 'name' in the SDP starting
8441  * at the 'start' line. Returns the matching line, and 'start'
8442  * is updated with the next line number.
8443  */
8444 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
8445 {
8446  int len = strlen(name);
8447  const char *line;
8448 
8449  while (*start < (req->sdp_start + req->sdp_count)) {
8450  line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
8451  if (!strncasecmp(line, name, len) && line[len] == '=') {
8452  return ast_skip_blanks(line + len + 1);
8453  }
8454  }
8455 
8456  /* if the line was not found, ensure that *start points past the SDP */
8457  (*start)++;
8458 
8459  return "";
8460 }
8461 
8462 /*! \brief Fetches the next valid SDP line between the 'start' line
8463  * (inclusive) and the 'stop' line (exclusive). Returns the type
8464  * ('a', 'c', ...) and matching line in reference 'start' is updated
8465  * with the next line number.
8466  */
8467 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
8468 {
8469  char type = '\0';
8470  const char *line = NULL;
8471 
8472  if (stop > (req->sdp_start + req->sdp_count)) {
8473  stop = req->sdp_start + req->sdp_count;
8474  }
8475 
8476  while (*start < stop) {
8477  line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
8478  if (line[1] == '=') {
8479  type = line[0];
8480  *value = ast_skip_blanks(line + 2);
8481  break;
8482  }
8483  }
8484 
8485  return type;
8486 }
8487 
8488 /*! \brief Get a specific line from the message content */
8489 static char *get_content_line(struct sip_request *req, char *name, char delimiter)
8490 {
8491  int i;
8492  int len = strlen(name);
8493  const char *line;
8494 
8495  for (i = 0; i < req->lines; i++) {
8496  line = REQ_OFFSET_TO_STR(req, line[i]);
8497  if (!strncasecmp(line, name, len) && line[len] == delimiter) {
8498  return ast_skip_blanks(line + len + 1);
8499  }
8500  }
8501 
8502  return "";
8503 }
8504 
8505 /*! \brief Structure for conversion between compressed SIP and "normal" SIP headers */
8506 struct cfalias {
8507  const char *fullname;
8508  const char *shortname;
8509 };
8510 static const struct cfalias aliases[] = {
8511  { "Content-Type", "c" },
8512  { "Content-Encoding", "e" },
8513  { "From", "f" },
8514  { "Call-ID", "i" },
8515  { "Contact", "m" },
8516  { "Content-Length", "l" },
8517  { "Subject", "s" },
8518  { "To", "t" },
8519  { "Supported", "k" },
8520  { "Refer-To", "r" },
8521  { "Referred-By", "b" },
8522  { "Allow-Events", "u" },
8523  { "Event", "o" },
8524  { "Via", "v" },
8525  { "Accept-Contact", "a" },
8526  { "Reject-Contact", "j" },
8527  { "Request-Disposition", "d" },
8528  { "Session-Expires", "x" },
8529  { "Identity", "y" },
8530  { "Identity-Info", "n" },
8531 };
8532 
8533 /*! \brief Find compressed SIP alias */
8534 static const char *find_alias(const char *name, const char *_default)
8535 {
8536  int x;
8537 
8538  for (x = 0; x < ARRAY_LEN(aliases); x++) {
8539  if (!strcasecmp(aliases[x].fullname, name))
8540  return aliases[x].shortname;
8541  }
8542 
8543  return _default;
8544 }
8545 
8546 /*! \brief Find full SIP alias */
8547 static const char *find_full_alias(const char *name, const char *_default)
8548 {
8549  int x;
8550 
8551  if (strlen(name) == 1) {
8552  /* We have a short header name to convert. */
8553  for (x = 0; x < ARRAY_LEN(aliases); ++x) {
8554  if (!strcasecmp(aliases[x].shortname, name))
8555  return aliases[x].fullname;
8556  }
8557  }
8558 
8559  return _default;
8560 }
8561 
8562 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
8563 {
8564  /*
8565  * Technically you can place arbitrary whitespace both before and after the ':' in
8566  * a header, although RFC3261 clearly says you shouldn't before, and place just
8567  * one afterwards. If you shouldn't do it, what absolute idiot decided it was
8568  * a good idea to say you can do it, and if you can do it, why in the hell would.
8569  * you say you shouldn't.
8570  */
8571  const char *sname = find_alias(name, NULL);
8572  int x, len = strlen(name), slen = (sname ? 1 : 0);
8573  for (x = *start; x < req->headers; x++) {
8574  const char *header = REQ_OFFSET_TO_STR(req, header[x]);
8575  int smatch = 0, match = !strncasecmp(header, name, len);
8576  if (slen) {
8577  smatch = !strncasecmp(header, sname, slen);
8578  }
8579  if (match || smatch) {
8580  /* skip name */
8581  const char *r = header + (match ? len : slen );
8582  /* HCOLON has optional SP/HTAB; skip past those */
8583  while (*r == ' ' || *r == '\t') {
8584  ++r;
8585  }
8586  if (*r == ':') {
8587  *start = x+1;
8588  return ast_skip_blanks(r+1);
8589  }
8590  }
8591  }
8592 
8593  /* Don't return NULL, so sip_get_header is always a valid pointer */
8594  return "";
8595 }
8596 
8597 /*! \brief Get header from SIP request
8598  \return Always return something, so don't check for NULL because it won't happen :-)
8599 */
8600 const char *sip_get_header(const struct sip_request *req, const char *name)
8601 {
8602  int start = 0;
8603  return __get_header(req, name, &start);
8604 }
8605 
8606 
8608 
8609 /*! \brief Get message body content */
8610 static char *get_content(struct sip_request *req)
8611 {
8612  struct ast_str *str;
8613  int i;
8614 
8615  if (!(str = ast_str_thread_get(&sip_content_buf, 128))) {
8616  return NULL;
8617  }
8618 
8619  ast_str_reset(str);
8620 
8621  for (i = 0; i < req->lines; i++) {
8622  if (ast_str_append(&str, 0, "%s\n", REQ_OFFSET_TO_STR(req, line[i])) < 0) {
8623  return NULL;
8624  }
8625  }
8626 
8627  return ast_str_buffer(str);
8628 }
8629 
8630 /*! \brief Read RTP from network */
8631 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
8632 {
8633  /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
8634  struct ast_frame *f;
8635 
8636  if (!p->rtp) {
8637  /* We have no RTP allocated for this channel */
8638  return &ast_null_frame;
8639  }
8640 
8641  switch(ast_channel_fdno(ast)) {
8642  case 0:
8643  f = ast_rtp_instance_read(p->rtp, 0); /* RTP Audio */
8644  break;
8645  case 1:
8646  f = ast_rtp_instance_read(p->rtp, 1); /* RTCP Control Channel */
8647  break;
8648  case 2:
8649  f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
8650  break;
8651  case 3:
8652  f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
8653  break;
8654  case 4:
8655  f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
8656  if (sipdebug_text) {
8657  struct ast_str *out = ast_str_create(f->datalen * 4 + 6);
8658  int i;
8659  unsigned char* arr = f->data.ptr;
8660  do {
8661  if (!out) {
8662  break;
8663  }
8664  for (i = 0; i < f->datalen; i++) {
8665  ast_str_append(&out, 0, "%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
8666  }
8667  ast_str_append(&out, 0, " -> ");
8668  for (i = 0; i < f->datalen; i++) {
8669  ast_str_append(&out, 0, "%02hhX ", arr[i]);
8670  }
8671  ast_verb(0, "%s\n", ast_str_buffer(out));
8672  ast_free(out);
8673  } while (0);
8674  }
8675  break;
8676  case 5:
8677  f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
8678  break;
8679  default:
8680  f = &ast_null_frame;
8681  }
8682  /* Don't forward RFC2833 if we're not supposed to */
8683  if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
8684  (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
8685  ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
8686  ast_frfree(f);
8687  return &ast_null_frame;
8688  }
8689 
8690  /* We already hold the channel lock */
8691  if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
8692  return f;
8693  }
8694 
8696  struct ast_format_cap *caps;
8697 
8699  ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
8701  ast_frfree(f);
8702  return &ast_null_frame;
8703  }
8704  ast_debug(1, "Oooh, format changed to %s\n",
8706 
8708  if (caps) {
8711  ast_format_cap_append(caps, f->subclass.format, 0);
8713  ao2_ref(caps, -1);
8714  }
8717  }
8718 
8719  if (f && p->dsp) {
8720  f = ast_dsp_process(p->owner, p->dsp, f);
8721  if (f && f->frametype == AST_FRAME_DTMF) {
8722  if (f->subclass.integer == 'f') {
8723  ast_debug(1, "Fax CNG detected on %s\n", ast_channel_name(ast));
8724  *faxdetect = 1;
8725  /* If we only needed this DSP for fax detection purposes we can just drop it now */
8726  if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
8728  } else {
8729  ast_dsp_free(p->dsp);
8730  p->dsp = NULL;
8731  }
8732  } else {
8733  ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
8734  }
8735  }
8736  }
8737 
8738  return f;
8739 }
8740 
8741 /*! \brief Read SIP RTP from channel */
8742 static struct ast_frame *sip_read(struct ast_channel *ast)
8743 {
8744  struct ast_frame *fr;
8745  struct sip_pvt *p = ast_channel_tech_pvt(ast);
8746  int faxdetected = FALSE;
8747 
8748  sip_pvt_lock(p);
8749  fr = sip_rtp_read(ast, p, &faxdetected);
8750  p->lastrtprx = time(NULL);
8751 
8752  /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
8753  if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
8754  if (strcmp(ast_channel_exten(ast), "fax")) {
8755  const char *target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
8756  /*
8757  * We need to unlock 'ast' here because
8758  * ast_exists_extension has the potential to start and
8759  * stop an autoservice on the channel. Such action is
8760  * prone to deadlock if the channel is locked.
8761  *
8762  * ast_async_goto() has its own restriction on not holding
8763  * the channel lock.
8764  */
8765  sip_pvt_unlock(p);
8766  ast_channel_unlock(ast);
8767  ast_frfree(fr);
8768  fr = &ast_null_frame;
8769  if (ast_exists_extension(ast, target_context, "fax", 1,
8770  S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, NULL))) {
8771  ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
8772  pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
8773  if (ast_async_goto(ast, target_context, "fax", 1)) {
8774  ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
8775  }
8776  } else {
8777  ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
8778  }
8779  ast_channel_lock(ast);
8780  sip_pvt_lock(p);
8781  }
8782  }
8783 
8784  /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
8785  if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast_channel_state(ast) != AST_STATE_UP) {
8786  ast_frfree(fr);
8787  fr = &ast_null_frame;
8788  }
8789 
8790  sip_pvt_unlock(p);
8791 
8792  return fr;
8793 }
8794 
8795 
8796 /*! \brief Generate 32 byte random string for callid's etc */
8797 static char *generate_random_string(char *buf, size_t size)
8798 {
8799  long val[4];
8800  int x;
8801 
8802  for (x=0; x<4; x++)
8803  val[x] = ast_random();
8804  snprintf(buf, size, "%08lx%08lx%08lx%08lx", (unsigned long)val[0], (unsigned long)val[1], (unsigned long)val[2], (unsigned long)val[3]);
8805 
8806  return buf;
8807 }
8808 
8809 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
8810 {
8811  struct ast_str *uri = ast_str_alloca(size);
8812  ast_str_set(&uri, 0, "%s", pvt->socket.type == AST_TRANSPORT_TLS ? "sips:" : "sip:");
8813  /* Here would be a great place to generate a UUID, but for now we'll
8814  * use the handy random string generation function we already have
8815  */
8816  ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
8817  ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
8818  ast_copy_string(buf, ast_str_buffer(uri), size);
8819  return buf;
8820 }
8821 
8822 /*!
8823  * \brief Build SIP Call-ID value for a non-REGISTER transaction
8824  *
8825  * \note The passed in pvt must not be in a dialogs container
8826  * since this function changes the hash key used by the
8827  * container.
8828  */
8829 static void build_callid_pvt(struct sip_pvt *pvt)
8830 {
8831  char buf[33];
8832  const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
8833 
8834  ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
8835 }
8836 
8837 /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
8838 #define CONTAINER_UNLINK(container, obj, tag) \
8839  ({ \
8840  int found = 0; \
8841  typeof((obj)) __removed_obj; \
8842  __removed_obj = ao2_t_callback((container), \
8843  OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
8844  if (__removed_obj) { \
8845  ao2_ref(__removed_obj, -1); \
8846  found = 1; \
8847  } \
8848  found; \
8849  })
8850 
8851 /*!
8852  * \internal
8853  * \brief Safely change the callid of the given SIP dialog.
8854  *
8855  * \param pvt SIP private structure to change callid
8856  * \param callid Specified new callid to use. NULL if generate new callid.
8857  *
8858  * \return Nothing
8859  */
8860 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
8861 {
8862  int in_dialog_container;
8863  int in_rtp_container;
8864  char *oldid = ast_strdupa(pvt->callid);
8865 
8866  ao2_lock(dialogs);
8867  ao2_lock(dialogs_rtpcheck);
8868  in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
8869  "About to change the callid -- remove the old name");
8870  in_rtp_container = CONTAINER_UNLINK(dialogs_rtpcheck, pvt,
8871  "About to change the callid -- remove the old name");
8872  if (callid) {
8873  ast_string_field_set(pvt, callid, callid);
8874  } else {
8875  build_callid_pvt(pvt);
8876  }
8877  if (in_dialog_container) {
8878  ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
8879  }
8880  if (in_rtp_container) {
8881  ao2_t_link(dialogs_rtpcheck, pvt, "New dialog callid -- inserted back into table");
8882  }
8883  ao2_unlock(dialogs_rtpcheck);
8884  ao2_unlock(dialogs);
8885 
8886  if (strcmp(oldid, pvt->callid)) {
8887  ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
8888  }
8889 }
8890 
8891 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
8892 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
8893 {
8894  char buf[33];
8895 
8896  const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
8897 
8898  ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
8899 }
8900 
8901 /*! \brief Build SIP From tag value for REGISTER */
8902 static void build_localtag_registry(struct sip_registry *reg)
8903 {
8904  ast_string_field_build(reg, localtag, "as%08lx", (unsigned long)ast_random());
8905 }
8906 
8907 /*! \brief Make our SIP dialog tag */
8908 static void make_our_tag(struct sip_pvt *pvt)
8909 {
8910  ast_string_field_build(pvt, tag, "as%08lx", (unsigned long)ast_random());
8911 }
8912 
8913 /*! \brief Allocate Session-Timers struct w/in dialog */
8914 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
8915 {
8916  struct sip_st_dlg *stp;
8917 
8918  if (p->stimer) {
8919  ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
8920  return p->stimer;
8921  }
8922 
8923  if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg)))) {
8924  return NULL;
8925  }
8926  stp->st_schedid = -1; /* Session-Timers ast_sched scheduler id */
8927 
8928  p->stimer = stp;
8929 
8930  return p->stimer;
8931 }
8932 
8933 static void sip_pvt_callid_set(struct sip_pvt *pvt, ast_callid callid)
8934 {
8935  pvt->logger_callid = callid;
8936 }
8937 
8938 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
8939  * Returns a reference to the object so whoever uses it later must
8940  * remember to release the reference.
8941  */
8942 struct sip_pvt *__sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
8943  int useglobal_nat, const int intended_method, struct sip_request *req, ast_callid logger_callid,
8944  const char *file, int line, const char *func)
8945 {
8946  struct sip_pvt *p;
8947 
8948  p = __ao2_alloc(sizeof(*p), sip_pvt_dtor,
8949  AO2_ALLOC_OPT_LOCK_MUTEX, "allocate a dialog(pvt) struct",
8950  file, line, func);
8951  if (!p) {
8952  return NULL;
8953  }
8954 
8955  if (ast_string_field_init(p, 512)) {
8956  ao2_t_ref(p, -1, "failed to string_field_init, drop p");
8957  return NULL;
8958  }
8959 
8960  if (!(p->cc_params = ast_cc_config_params_init())) {
8961  ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
8962  return NULL;
8963  }
8964 
8965  if (logger_callid) {
8966  sip_pvt_callid_set(p, logger_callid);
8967  }
8968 
8974 
8975  if (!p->caps|| !p->jointcaps || !p->peercaps || !p->redircaps || !p->prefcaps) {
8976  ao2_cleanup(p->caps);
8977  ao2_cleanup(p->jointcaps);
8978  ao2_cleanup(p->peercaps);
8979  ao2_cleanup(p->redircaps);
8980  ao2_cleanup(p->prefcaps);
8981  ao2_t_ref(p, -1, "Yuck, couldn't allocate format capabilities. Get rid o' p");
8982  return NULL;
8983  }
8984 
8985 
8986  /* If this dialog is created as a result of a request or response, lets store
8987  * some information about it in the dialog. */
8988  if (req) {
8989  struct sip_via *via;
8990  const char *cseq = sip_get_header(req, "Cseq");
8991  uint32_t seqno;
8992 
8993  /* get branch parameter from initial Request that started this dialog */
8994  via = parse_via(sip_get_header(req, "Via"));
8995  if (via) {
8996  /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
8997  * it is not useful to us to have it */
8998  if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
8999  ast_string_field_set(p, initviabranch, via->branch);
9000  ast_string_field_set(p, initviasentby, via->sent_by);
9001  }
9002  free_via(via);
9003  }
9004 
9005  /* Store initial incoming cseq. An error in sscanf here is ignored. There is no approperiate
9006  * except not storing the number. CSeq validation must take place before dialog creation in find_call */
9007  if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
9008  p->init_icseq = seqno;
9009  }
9010  /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
9012  } else {
9014  }
9015 
9016  p->socket.fd = -1;
9017  p->method = intended_method;
9018  p->initid = -1;
9019  p->waitid = -1;
9020  p->reinviteid = -1;
9021  p->autokillid = -1;
9022  p->request_queue_sched_id = -1;
9024  p->t38id = -1;
9025  p->subscribed = NONE;
9026  p->stateid = -1;
9027  p->sessionversion_remote = -1;
9028  p->session_modify = TRUE;
9029  p->stimer = NULL;
9030  ast_copy_string(p->zone, default_zone, sizeof(p->zone));
9032 
9033  if (intended_method != SIP_OPTIONS) { /* Peerpoke has it's own system */
9034  p->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
9035  p->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
9036  }
9037 
9038  if (!addr) {
9039  p->ourip = internip;
9040  } else {
9041  ast_sockaddr_copy(&p->sa, addr);
9042  ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
9043  }
9044 
9045  /* Copy global flags to this PVT at setup. */
9046  ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
9047  ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
9048  ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
9049 
9051 
9052  p->branch = ast_random();
9053  make_our_tag(p);
9054  p->ocseq = INITIAL_CSEQ;
9055  p->allowed_methods = UINT_MAX;
9056 
9057  if (sip_methods[intended_method].need_rtp) {
9060  }
9061 
9062  if (useglobal_nat && addr) {
9063  /* Setup NAT structure according to global settings if we have an address */
9064  ast_sockaddr_copy(&p->recv, addr);
9065  check_via(p, req);
9066  do_setnat(p);
9067  }
9068 
9069  if (p->method != SIP_REGISTER) {
9070  ast_string_field_set(p, fromdomain, default_fromdomain);
9072  }
9073  build_via(p);
9074  if (!callid)
9075  build_callid_pvt(p);
9076  else
9077  ast_string_field_set(p, callid, callid);
9078  /* Assign default music on hold class */
9083  if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
9084  (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
9086  }
9090 
9093 
9094  /* Add to active dialog list */
9095 
9096  ao2_t_link(dialogs, p, "link pvt into dialogs table");
9097 
9098  ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
9099  return p;
9100 }
9101 
9102 /*!
9103  * \brief Process the Via header according to RFC 3261 section 18.2.2.
9104  * \param p a sip_pvt structure that will be modified according to the received
9105  * header
9106  * \param req a sip request with a Via header to process
9107  *
9108  * This function will update the destination of the response according to the
9109  * Via header in the request and RFC 3261 section 18.2.2. We do not have a
9110  * transport layer so we ignore certain values like the 'received' param (we
9111  * set the destination address to the address the request came from in the
9112  * respprep() function).
9113  *
9114  * \retval -1 error
9115  * \retval 0 success
9116  */
9117 static int process_via(struct sip_pvt *p, const struct sip_request *req)
9118 {
9119  struct sip_via *via = parse_via(sip_get_header(req, "Via"));
9120 
9121  if (!via) {
9122  ast_log(LOG_ERROR, "error processing via header\n");
9123  return -1;
9124  }
9125 
9126  if (via->maddr) {
9128  ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
9129  ast_log(LOG_ERROR, "error processing via header\n");
9130  free_via(via);
9131  return -1;
9132  }
9133 
9135  setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
9136  }
9137  }
9138 
9139  ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
9140 
9141  free_via(via);
9142  return 0;
9143 }
9144 
9145 /* \brief arguments used for Request/Response to matching */
9147  int method;
9148  const char *callid;
9149  const char *totag;
9150  const char *fromtag;
9151  uint32_t seqno;
9152 
9153  /* Set if this method is a Response */
9154  int respid;
9155 
9156  /* Set if the method is a Request */
9157  const char *ruri;
9158  const char *viabranch;
9159  const char *viasentby;
9160 
9161  /* Set this if the Authentication header is present in the Request. */
9163 };
9164 
9168  SIP_REQ_LOOP_DETECTED, /* multiple incoming requests with same call-id but different branch parameters have been detected */
9169  SIP_REQ_FORKED, /* An outgoing request has been forked as result of receiving two differing 200ok responses. */
9170 };
9171 
9172 /*
9173  * \brief Match a incoming Request/Response to a dialog
9174  *
9175  * \retval enum match_req_res indicating if the dialog matches the arg
9176  */
9177 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
9178 {
9179  const char *init_ruri = NULL;
9180  if (sip_pvt_ptr->initreq.headers) {
9181  init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlpart2);
9182  }
9183 
9184  /*
9185  * Match Tags and call-id to Dialog
9186  */
9187  if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
9188  /* call-id does not match. */
9189  return SIP_REQ_NOT_MATCH;
9190  }
9191  if (arg->method == SIP_RESPONSE) {
9192  /* Verify fromtag of response matches the tag we gave them. */
9193  if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
9194  /* fromtag from response does not match our tag */
9195  return SIP_REQ_NOT_MATCH;
9196  }
9197 
9198  /* Verify totag if we have one stored for this dialog, but never be strict about this for
9199  * a response until the dialog is established */
9200  if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
9201  if (ast_strlen_zero(arg->totag)) {
9202  /* missing totag when they already gave us one earlier */
9203  return SIP_REQ_NOT_MATCH;
9204  }
9205  /* compare the totag of response with the tag we have stored for them */
9206  if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
9207  /* totag did not match what we had stored for them. */
9208  char invite_branch[32] = { 0, };
9209  if (sip_pvt_ptr->invite_branch) {
9210  snprintf(invite_branch, sizeof(invite_branch), "z9hG4bK%08x", (unsigned)sip_pvt_ptr->invite_branch);
9211  }
9212  /* Forked Request Detection
9213  *
9214  * If this is a 200ok response and the totags do not match, this
9215  * might be a forked response to an outgoing Request. Detection of
9216  * a forked response must meet the criteria below.
9217  *
9218  * 1. must be a 2xx Response
9219  * 2. call-d equal to call-id of Request. this is done earlier
9220  * 3. from-tag equal to from-tag of Request. this is done earlier
9221  * 4. branch parameter equal to branch of inital Request
9222  * 5. to-tag _NOT_ equal to previous 2xx response that already established the dialog.
9223  */
9224  if ((arg->respid == 200) &&
9225  !ast_strlen_zero(invite_branch) &&
9226  !ast_strlen_zero(arg->viabranch) &&
9227  !strcmp(invite_branch, arg->viabranch)) {
9228  return SIP_REQ_FORKED;
9229  }
9230 
9231  /* The totag did not match the one we had stored, and this is not a Forked Request. */
9232  return SIP_REQ_NOT_MATCH;
9233  }
9234  }
9235  } else {
9236  /* Verify the fromtag of Request matches the tag they provided earlier.
9237  * If this is a Request with authentication credentials, forget their old
9238  * tag as it is not valid after the 401 or 407 response. */
9239  if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
9240  /* their tag does not match the one was have stored for them */
9241  return SIP_REQ_NOT_MATCH;
9242  }
9243  /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
9244  if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
9245  /* totag from Request does not match our tag */
9246  return SIP_REQ_NOT_MATCH;
9247  }
9248  }
9249 
9250  /*
9251  * Compare incoming request against initial transaction.
9252  *
9253  * This is a best effort attempt at distinguishing forked requests from
9254  * our initial transaction. If all the elements are NOT in place to evaluate
9255  * this, this block is ignored and the dialog match is made regardless.
9256  * Once the totag is established after the dialog is confirmed, this is not necessary.
9257  *
9258  * CRITERIA required for initial transaction matching.
9259  *
9260  * 1. Is a Request
9261  * 2. Callid and theirtag match (this is done in the dialog matching block)
9262  * 3. totag is NOT present
9263  * 4. CSeq matchs our initial transaction's cseq number
9264  * 5. pvt has init via branch parameter stored
9265  */
9266  if ((arg->method != SIP_RESPONSE) && /* must be a Request */
9267  ast_strlen_zero(arg->totag) && /* must not have a totag */
9268  (sip_pvt_ptr->init_icseq == arg->seqno) && /* the cseq must be the same as this dialogs initial cseq */
9269  !ast_strlen_zero(sip_pvt_ptr->initviabranch) && /* The dialog must have started with a RFC3261 compliant branch tag */
9270  init_ruri) { /* the dialog must have an initial request uri associated with it */
9271  /* This Request matches all the criteria required for Loop/Merge detection.
9272  * Now we must go down the path of comparing VIA's and RURIs. */
9273  if (ast_strlen_zero(arg->viabranch) ||
9274  strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
9275  ast_strlen_zero(arg->viasentby) ||
9276  strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
9277  /* At this point, this request does not match this Dialog.*/
9278 
9279  /* if methods are different this is just a mismatch */
9280  if ((sip_pvt_ptr->method != arg->method)) {
9281  return SIP_REQ_NOT_MATCH;
9282  }
9283 
9284  /* If RUIs are different, this is a forked request to a separate URI.
9285  * Returning a mismatch allows this Request to be processed separately. */
9286  if (sip_uri_cmp(init_ruri, arg->ruri)) {
9287  /* not a match, request uris are different */
9288  return SIP_REQ_NOT_MATCH;
9289  }
9290 
9291  /* Loop/Merge Detected
9292  *
9293  * ---Current Matches to Initial Request---
9294  * request uri
9295  * Call-id
9296  * their-tag
9297  * no totag present
9298  * method
9299  * cseq
9300  *
9301  * --- Does not Match Initial Request ---
9302  * Top Via
9303  *
9304  * Without the same Via, this can not match our initial transaction for this dialog,
9305  * but given that this Request matches everything else associated with that initial
9306  * Request this is most certainly a Forked request in which we have already received
9307  * part of the fork.
9308  */
9309  return SIP_REQ_LOOP_DETECTED;
9310  }
9311  } /* end of Request Via check */
9312 
9313  /* Match Authentication Request.
9314  *
9315  * A Request with an Authentication header must come back with the
9316  * same Request URI. Otherwise it is not a match.
9317  */
9318  if ((arg->method != SIP_RESPONSE) && /* Must be a Request type to even begin checking this */
9319  ast_strlen_zero(arg->totag) && /* no totag is present to match */
9320  arg->authentication_present && /* Authentication header is present in Request */
9321  sip_uri_cmp(init_ruri, arg->ruri)) { /* Compare the Request URI of both the last Request and this new one */
9322 
9323  /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
9324  return SIP_REQ_NOT_MATCH;
9325  }
9326 
9327  return SIP_REQ_MATCH;
9328 }
9329 
9330 /*! \brief This function creates a dialog to handle a forked request. This dialog
9331  * exists only to properly terminiate the forked request immediately.
9332  */
9333 static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
9334 {
9335  struct sip_pvt *p;
9336  const char *callid;
9337  ast_callid logger_callid;
9338 
9339  sip_pvt_lock(original);
9340  callid = ast_strdupa(original->callid);
9341  logger_callid = original->logger_callid;
9342  sip_pvt_unlock(original);
9343 
9344  p = sip_alloc(callid, addr, 1, SIP_INVITE, req, logger_callid);
9345  if (!p) {
9346  return; /* alloc error */
9347  }
9348 
9349  /* Lock p and original private structures. */
9350  sip_pvt_lock(p);
9351  while (sip_pvt_trylock(original)) {
9352  /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
9353  sip_pvt_unlock(p);
9354  sched_yield();
9355  sip_pvt_lock(p);
9356  }
9357 
9359  p->ocseq = original->ocseq;
9360  p->branch = original->branch;
9361 
9362  memcpy(&p->flags, &original->flags, sizeof(p->flags));
9363  copy_request(&p->initreq, &original->initreq);
9364  ast_string_field_set(p, theirtag, new_theirtag);
9365  ast_string_field_set(p, tag, original->tag);
9366  ast_string_field_set(p, uri, original->uri);
9367  ast_string_field_set(p, our_contact, original->our_contact);
9368  ast_string_field_set(p, fullcontact, original->fullcontact);
9369 
9370  sip_pvt_unlock(original);
9371 
9372  parse_ok_contact(p, req);
9373  build_route(p, req, 1, 0);
9374 
9377 
9378  pvt_set_needdestroy(p, "forked request"); /* this dialog will terminate once the BYE is responed to or times out. */
9379  sip_pvt_unlock(p);
9380  dialog_unref(p, "setup forked invite termination");
9381 }
9382 
9383 /*! \internal
9384  *
9385  * \brief Locks both pvt and pvt owner if owner is present.
9386  *
9387  * \note This function gives a ref to pvt->owner if it is present and locked.
9388  * This reference must be decremented after pvt->owner is unlocked.
9389  *
9390  * \note This function will never give you up,
9391  * \note This function will never let you down.
9392  * \note This function will run around and desert you.
9393  *
9394  * \pre pvt is not locked
9395  * \post pvt is locked
9396  * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
9397  *
9398  * \return a pointer to the locked and reffed pvt->owner channel if it exists.
9399  */
9400 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
9401 {
9402  struct ast_channel *chan;
9403 
9404  /* Locking is simple when it is done right. If you see a deadlock resulting
9405  * in this function, it is not this function's fault, Your problem exists elsewhere.
9406  * This function is perfect... seriously. */
9407  for (;;) {
9408  /* First, get the channel and grab a reference to it */
9409  sip_pvt_lock(pvt);
9410  chan = pvt->owner;
9411  if (chan) {
9412  /* The channel can not go away while we hold the pvt lock.
9413  * Give the channel a ref so it will not go away after we let
9414  * the pvt lock go. */
9415  ast_channel_ref(chan);
9416  } else {
9417  /* no channel, return pvt locked */
9418  return NULL;
9419  }
9420 
9421  /* We had to hold the pvt lock while getting a ref to the owner channel
9422  * but now we have to let this lock go in order to preserve proper
9423  * locking order when grabbing the channel lock */
9424  sip_pvt_unlock(pvt);
9425 
9426  /* Look, no deadlock avoidance, hooray! */
9427  ast_channel_lock(chan);
9428  sip_pvt_lock(pvt);
9429 
9430  if (pvt->owner == chan) {
9431  /* done */
9432  break;
9433  }
9434 
9435  /* If the owner changed while everything was unlocked, no problem,
9436  * just start over and everthing will work. This is rare, do not be
9437  * confused by this loop and think this it is an expensive operation.
9438  * The majority of the calls to this function will never involve multiple
9439  * executions of this loop. */
9440  ast_channel_unlock(chan);
9441  ast_channel_unref(chan);
9442  sip_pvt_unlock(pvt);
9443  }
9444 
9445  /* If owner exists, it is locked and reffed */
9446  return pvt->owner;
9447 }
9448 
9449 /*! \brief Set the owning channel on the \ref sip_pvt object */
9450 static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan)
9451 {
9452  p->owner = chan;
9453  if (p->rtp) {
9455  }
9456  if (p->vrtp) {
9458  }
9459  if (p->trtp) {
9461  }
9462 }
9463 
9464 /*! \brief find or create a dialog structure for an incoming SIP message.
9465  * Connect incoming SIP message to current dialog or create new dialog structure
9466  * Returns a reference to the sip_pvt object, remember to give it back once done.
9467  * Called by handle_request_do
9468  */
9469 static struct sip_pvt *__find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method,
9470  const char *file, int line, const char *func)
9471 {
9472  char totag[128];
9473  char fromtag[128];
9474  const char *callid = sip_get_header(req, "Call-ID");
9475  const char *from = sip_get_header(req, "From");
9476  const char *to = sip_get_header(req, "To");
9477  const char *cseq = sip_get_header(req, "Cseq");
9478  struct sip_pvt *sip_pvt_ptr;
9479  uint32_t seqno;
9480  /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
9481  /* sip_get_header always returns non-NULL so we must use ast_strlen_zero() */
9482  if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
9483  ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
9484  (sscanf(cseq, "%30u", &seqno) != 1)) {
9485 
9486  /* RFC 3261 section 24.4.1. Send a 400 Bad Request if the request is malformed. */
9487  if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
9488  transmit_response_using_temp(callid, addr, 1, intended_method,
9489  req, "400 Bad Request");
9490  }
9491  return NULL; /* Invalid packet */
9492  }
9493 
9495  /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
9496  we need more to identify a branch - so we have to check branch, from
9497  and to tags to identify a call leg.
9498  For Asterisk to behave correctly, you need to turn on pedanticsipchecking
9499  in sip.conf
9500  */
9501  if (gettag(req, "To", totag, sizeof(totag)))
9502  req->has_to_tag = 1; /* Used in handle_request/response */
9503  gettag(req, "From", fromtag, sizeof(fromtag));
9504 
9505  ast_debug(5, "= Looking for Call ID: %s (Checking %s) --From tag %s --To-tag %s \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
9506 
9507  /* All messages must always have From: tag */
9508  if (ast_strlen_zero(fromtag)) {
9509  ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
9510  return NULL;
9511  }
9512  /* reject requests that must always have a To: tag */
9513  if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
9514  if (req->method != SIP_ACK) {
9515  transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
9516  }
9517  ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
9518  return NULL;
9519  }
9520  }
9521 
9522  /* match on callid only for REGISTERs */
9523  if (!sip_cfg.pedanticsipchecking || req->method == SIP_REGISTER) {
9524  struct sip_pvt tmp_dialog = {
9525  .callid = callid,
9526  };
9527  sip_pvt_ptr = __ao2_find(dialogs, &tmp_dialog, OBJ_POINTER,
9528  "find_call in dialogs", file, line, func);
9529  if (sip_pvt_ptr) { /* well, if we don't find it-- what IS in there? */
9530  /* Found the call */
9531  return sip_pvt_ptr;
9532  }
9533  } else { /* in pedantic mode! -- do the fancy search */
9534  struct sip_pvt tmp_dialog = {
9535  .callid = callid,
9536  };
9537  /* if a Outbound forked Request is detected, this pvt will point
9538  * to the dialog the Request is forking off of. */
9539  struct sip_pvt *fork_pvt = NULL;
9540  struct match_req_args args = { 0, };
9541  int found;
9542  struct ao2_iterator *iterator = __ao2_callback(dialogs,
9545  &tmp_dialog,
9546  "pedantic ao2_find in dialogs",
9547  file, line, func);
9548  struct sip_via *via = NULL;
9549 
9550  args.method = req->method;
9551  args.callid = NULL; /* we already matched this. */
9552  args.totag = totag;
9553  args.fromtag = fromtag;
9554  args.seqno = seqno;
9555  /* get via header information. */
9556  args.ruri = REQ_OFFSET_TO_STR(req, rlpart2);
9557  via = parse_via(sip_get_header(req, "Via"));
9558  if (via) {
9559  args.viasentby = via->sent_by;
9560  args.viabranch = via->branch;
9561  }
9562  /* determine if this is a Request with authentication credentials. */
9563  if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
9564  !ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
9565  args.authentication_present = 1;
9566  }
9567  /* if it is a response, get the response code */
9568  if (req->method == SIP_RESPONSE) {
9569  const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
9570  int respid;
9571  if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
9572  args.respid = respid;
9573  }
9574  }
9575 
9576  /* Iterate a list of dialogs already matched by Call-id */
9577  while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
9578  sip_pvt_lock(sip_pvt_ptr);
9579  found = match_req_to_dialog(sip_pvt_ptr, &args);
9580  sip_pvt_unlock(sip_pvt_ptr);
9581 
9582  switch (found) {
9583  case SIP_REQ_MATCH:
9584  sip_pvt_lock(sip_pvt_ptr);
9585  if (args.method != SIP_RESPONSE && args.authentication_present
9586  && strcmp(args.fromtag, sip_pvt_ptr->theirtag)) {
9587  /* If we have a request that uses athentication and the fromtag is
9588  * different from that in the original call dialog, update the
9589  * fromtag in the saved call dialog */
9590  ast_string_field_set(sip_pvt_ptr, theirtag, args.fromtag);
9591  }
9592  sip_pvt_unlock(sip_pvt_ptr);
9593  ao2_iterator_destroy(iterator);
9594  dialog_unref(fork_pvt, "unref fork_pvt");
9595  free_via(via);
9596  return sip_pvt_ptr; /* return pvt with ref */
9597  case SIP_REQ_LOOP_DETECTED:
9598  /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
9599  * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
9600  transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
9601  __ao2_ref(sip_pvt_ptr, -1, "pvt did not match incoming SIP msg, unref from search.",
9602  file, line, func);
9603  ao2_iterator_destroy(iterator);
9604  dialog_unref(fork_pvt, "unref fork_pvt");
9605  free_via(via);
9606  return NULL;
9607  case SIP_REQ_FORKED:
9608  dialog_unref(fork_pvt, "throwing way pvt to fork off of.");
9609  fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
9610  /* fall through */
9611  case SIP_REQ_NOT_MATCH:
9612  default:
9613  __ao2_ref(sip_pvt_ptr, -1, "pvt did not match incoming SIP msg, unref from search",
9614  file, line, func);
9615  break;
9616  }
9617  }
9618  if (iterator) {
9619  ao2_iterator_destroy(iterator);
9620  }
9621 
9622  /* Handle any possible forked requests. This must be done only after transaction matching is complete. */
9623  if (fork_pvt) {
9624  /* XXX right now we only support handling forked INVITE Requests. Any other
9625  * forked request type must be added here. */
9626  if (fork_pvt->method == SIP_INVITE) {
9627  forked_invite_init(req, args.totag, fork_pvt, addr);
9628  dialog_unref(fork_pvt, "throwing way old forked pvt");
9629  free_via(via);
9630  return NULL;
9631  }
9632  fork_pvt = dialog_unref(fork_pvt, "throwing way pvt to fork off of");
9633  }
9634 
9635  free_via(via);
9636  } /* end of pedantic mode Request/Reponse to Dialog matching */
9637 
9638  /* See if the method is capable of creating a dialog */
9639  if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
9640  struct sip_pvt *p = NULL;
9641  ast_callid logger_callid = 0;
9642 
9643  if (intended_method == SIP_INVITE) {
9644  logger_callid = ast_create_callid();
9645  }
9646 
9647  /* Ok, time to create a new SIP dialog object, a pvt */
9648  if (!(p = sip_alloc(callid, addr, 1, intended_method, req, logger_callid))) {
9649  /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
9650  getting a dialog from sip_alloc.
9651 
9652  Without a dialog we can't retransmit and handle ACKs and all that, but at least
9653  send an error message.
9654 
9655  Sorry, we apologize for the inconvienience
9656  */
9657  transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
9658  ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
9659  }
9660  return p; /* can be NULL */
9661  } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
9662  /* A method we do not support, let's take it on the volley */
9663  transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
9664  ast_debug(2, "Got a request with unsupported SIP method.\n");
9665  } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
9666  /* This is a request outside of a dialog that we don't know about */
9667  transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
9668  ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
9669  }
9670  /* We do not respond to responses for dialogs that we don't know about, we just drop
9671  the session quickly */
9672  if (intended_method == SIP_RESPONSE)
9673  ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
9674 
9675  return NULL;
9676 }
9677 
9678 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
9679 static int sip_register(const char *value, int lineno)
9680 {
9681  struct sip_registry *reg;
9682 
9683  reg = ao2_t_find(registry_list, value, OBJ_SEARCH_KEY, "check for existing registry");
9684  if (reg) {
9685  ao2_t_ref(reg, -1, "throw away found registry");
9686  return 0;
9687  }
9688 
9689  if (!(reg = ao2_t_alloc(sizeof(*reg), sip_registry_destroy, "allocate a registry struct"))) {
9690  ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
9691  return -1;
9692  }
9693 
9694  reg->expire = -1;
9695  reg->timeout = -1;
9696 
9697  if (ast_string_field_init(reg, 256)) {
9698  ao2_t_ref(reg, -1, "failed to string_field_init, drop reg");
9699  return -1;
9700  }
9701 
9702  ast_string_field_set(reg, configvalue, value);
9703  if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
9704  ao2_t_ref(reg, -1, "failure to parse, unref the reg pointer");
9705  return -1;
9706  }
9707 
9708  /* set default expiry if necessary */
9709  if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
9710  reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
9711  }
9712 
9713  ao2_t_link(registry_list, reg, "link reg to registry_list");
9714  ao2_t_ref(reg, -1, "unref the reg pointer");
9715 
9716  return 0;
9717 }
9718 
9719 /*! \brief Parse mwi=> line in sip.conf and add to list */
9720 static int sip_subscribe_mwi(const char *value, int lineno)
9721 {
9722  struct sip_subscription_mwi *mwi;
9723  int portnum = 0;
9724  enum ast_transport transport = AST_TRANSPORT_UDP;
9725  char buf[256] = "";
9726  char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
9727 
9728  if (!value) {
9729  return -1;
9730  }
9731 
9732  ast_copy_string(buf, value, sizeof(buf));
9733 
9734  username = buf;
9735 
9736  if ((hostname = strrchr(buf, '@'))) {
9737  *hostname++ = '\0';
9738  } else {
9739  return -1;
9740  }
9741 
9742  if ((secret = strchr(username, ':'))) {
9743  *secret++ = '\0';
9744  if ((authuser = strchr(secret, ':'))) {
9745  *authuser++ = '\0';
9746  }
9747  }
9748 
9749  if ((mailbox = strchr(hostname, '/'))) {
9750  *mailbox++ = '\0';
9751  }
9752 
9753  if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
9754  ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
9755  return -1;
9756  }
9757 
9758  if ((porta = strchr(hostname, ':'))) {
9759  *porta++ = '\0';
9760  if (!(portnum = atoi(porta))) {
9761  ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
9762  return -1;
9763  }
9764  }
9765 
9766  if (!(mwi = ao2_t_alloc(sizeof(*mwi), sip_subscribe_mwi_destroy, "allocate an mwi struct"))) {
9767  return -1;
9768  }
9769 
9770  mwi->resub = -1;
9771 
9772  if (ast_string_field_init(mwi, 256)) {
9773  ao2_t_ref(mwi, -1, "failed to string_field_init, drop mwi");
9774  return -1;
9775  }
9776 
9777  ast_string_field_set(mwi, username, username);
9778  if (secret) {
9779  ast_string_field_set(mwi, secret, secret);
9780  }
9781  if (authuser) {
9782  ast_string_field_set(mwi, authuser, authuser);
9783  }
9784  ast_string_field_set(mwi, hostname, hostname);
9785  ast_string_field_set(mwi, mailbox, mailbox);
9786  mwi->portno = portnum;
9787  mwi->transport = transport;
9788 
9789  ao2_t_link(subscription_mwi_list, mwi, "link new mwi object");
9790  ao2_t_ref(mwi, -1, "unref to match ao2_t_alloc");
9791 
9792  return 0;
9793 }
9794 
9795 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
9796 {
9797  (*allowed_methods) |= (1 << method);
9798 }
9799 
9800 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
9801 {
9802  (*allowed_methods) &= ~(1 << method);
9803 }
9804 
9805 /*! \brief Check if method is allowed for a device or a dialog */
9806 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
9807 {
9808  return ((*allowed_methods) >> method) & 1;
9809 }
9810 
9811 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
9812 {
9813  char *method;
9814  for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
9815  int id = find_sip_method(ast_skip_blanks(method));
9816  if (id == SIP_UNKNOWN) {
9817  continue;
9818  }
9819  mark_method_allowed(methods, id);
9820  }
9821 }
9822 /*!
9823  * \brief parse the Allow header to see what methods the endpoint we
9824  * are communicating with allows.
9825  *
9826  * We parse the allow header on incoming Registrations and save the
9827  * result to the SIP peer that is registering. When the registration
9828  * expires, we clear what we know about the peer's allowed methods.
9829  * When the peer re-registers, we once again parse to see if the
9830  * list of allowed methods has changed.
9831  *
9832  * For peers that do not register, we parse the first message we receive
9833  * during a call to see what is allowed, and save the information
9834  * for the duration of the call.
9835  * \param req The SIP request we are parsing
9836  * \retval The methods allowed
9837  */
9838 static unsigned int parse_allowed_methods(struct sip_request *req)
9839 {
9840  char *allow = ast_strdupa(sip_get_header(req, "Allow"));
9841  unsigned int allowed_methods = SIP_UNKNOWN;
9842 
9843  if (ast_strlen_zero(allow)) {
9844  /* I have witnessed that REGISTER requests from Polycom phones do not
9845  * place the phone's allowed methods in an Allow header. Instead, they place the
9846  * allowed methods in a methods= parameter in the Contact header.
9847  */
9848  char *contact = ast_strdupa(sip_get_header(req, "Contact"));
9849  char *methods = strstr(contact, ";methods=");
9850 
9851  if (ast_strlen_zero(methods)) {
9852  /* RFC 3261 states:
9853  *
9854  * "The absence of an Allow header field MUST NOT be
9855  * interpreted to mean that the UA sending the message supports no
9856  * methods. Rather, it implies that the UA is not providing any
9857  * information on what methods it supports."
9858  *
9859  * For simplicity, we'll assume that the peer allows all known
9860  * SIP methods if they have no Allow header. We can then clear out the necessary
9861  * bits if the peer lets us know that we have sent an unsupported method.
9862  */
9863  return UINT_MAX;
9864  }
9865  allow = ast_strip_quoted(methods + 9, "\"", "\"");
9866  }
9867  mark_parsed_methods(&allowed_methods, allow);
9868  return allowed_methods;
9869 }
9870 
9871 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
9872  *
9873  * This function, in addition to setting the allowed methods for a sip_pvt
9874  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
9875  *
9876  * \param pvt The sip_pvt we are setting the allowed_methods for
9877  * \param req The request which we are parsing
9878  * \retval The methods alloweded by the sip_pvt
9879  */
9880 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
9881 {
9883 
9884  if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
9886  }
9887  pvt->allowed_methods &= ~(pvt->disallowed_methods);
9888 
9889  return pvt->allowed_methods;
9890 }
9891 
9892 /*! \brief Parse multiline SIP headers into one header
9893  This is enabled if pedanticsipchecking is enabled */
9894 static void lws2sws(struct ast_str *data)
9895 {
9896  char *msgbuf = ast_str_buffer(data);
9897  int len = ast_str_strlen(data);
9898  int h = 0, t = 0;
9899  int lws = 0;
9900  int just_read_eol = 0;
9901  int done_with_headers = 0;
9902 
9903  while (h < len) {
9904  /* Eliminate all CRs */
9905  if (msgbuf[h] == '\r') {
9906  h++;
9907  continue;
9908  }
9909  /* Check for end-of-line */
9910  if (msgbuf[h] == '\n') {
9911  if (just_read_eol) {
9912  done_with_headers = 1;
9913  } else {
9914  just_read_eol = 1;
9915  }
9916  /* Check for end-of-message */
9917  if (h + 1 == len)
9918  break;
9919  /* Check for a continuation line */
9920  if (!done_with_headers
9921  && (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t')) {
9922  /* Merge continuation line */
9923  h++;
9924  continue;
9925  }
9926  /* Propagate LF and start new line */
9927  msgbuf[t++] = msgbuf[h++];
9928  lws = 0;
9929  continue;
9930  } else {
9931  just_read_eol = 0;
9932  }
9933  if (!done_with_headers
9934  && (msgbuf[h] == ' ' || msgbuf[h] == '\t')) {
9935  if (lws) {
9936  h++;
9937  continue;
9938  }
9939  msgbuf[t++] = msgbuf[h++];
9940  lws = 1;
9941  continue;
9942  }
9943  msgbuf[t++] = msgbuf[h++];
9944  if (lws)
9945  lws = 0;
9946  }
9947  msgbuf[t] = '\0';
9948  ast_str_update(data);
9949 }
9950 
9951 /*! \brief Parse a SIP message
9952  \note this function is used both on incoming and outgoing packets
9953 */
9954 static int parse_request(struct sip_request *req)
9955 {
9956  char *c = ast_str_buffer(req->data);
9957  ptrdiff_t *dst = req->header;
9958  int i = 0;
9959  unsigned int lim = SIP_MAX_HEADERS - 1;
9960  unsigned int skipping_headers = 0;
9961  ptrdiff_t current_header_offset = 0;
9962  char *previous_header = "";
9963 
9964  req->header[0] = 0;
9965  req->headers = -1; /* mark that we are working on the header */
9966  for (; *c; c++) {
9967  if (*c == '\r') { /* remove \r */
9968  *c = '\0';
9969  } else if (*c == '\n') { /* end of this line */
9970  *c = '\0';
9971  current_header_offset = (c + 1) - ast_str_buffer(req->data);
9972  previous_header = ast_str_buffer(req->data) + dst[i];
9973  if (skipping_headers) {
9974  /* check to see if this line is blank; if so, turn off
9975  the skipping flag, so the next line will be processed
9976  as a body line */
9977  if (ast_strlen_zero(previous_header)) {
9978  skipping_headers = 0;
9979  }
9980  dst[i] = current_header_offset; /* record start of next line */
9981  continue;
9982  }
9983  if (sipdebug) {
9984  ast_debug(4, "%7s %2d [%3d]: %s\n",
9985  req->headers < 0 ? "Header" : "Body",
9986  i, (int) strlen(previous_header), previous_header);
9987  }
9988  if (ast_strlen_zero(previous_header) && req->headers < 0) {
9989  req->headers = i; /* record number of header lines */
9990  dst = req->line; /* start working on the body */
9991  i = 0;
9992  lim = SIP_MAX_LINES - 1;
9993  } else { /* move to next line, check for overflows */
9994  if (i++ == lim) {
9995  /* if we're processing headers, then skip any remaining
9996  headers and move on to processing the body, otherwise
9997  we're done */
9998  if (req->headers != -1) {
9999  break;
10000  } else {
10001  req->headers = i;
10002  dst = req->line;
10003  i = 0;
10004  lim = SIP_MAX_LINES - 1;
10005  skipping_headers = 1;
10006  }
10007  }
10008  }
10009  dst[i] = current_header_offset; /* record start of next line */
10010  }
10011  }
10012 
10013  /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
10014  but since some devices send without, we'll be generous in what we accept. However,
10015  if we've already reached the maximum number of lines for portion of the message
10016  we were parsing, we can't accept any more, so just ignore it.
10017  */
10018  previous_header = ast_str_buffer(req->data) + dst[i];
10019  if ((i < lim) && !ast_strlen_zero(previous_header)) {
10020  if (sipdebug) {
10021  ast_debug(4, "%7s %2d [%3d]: %s\n",
10022  req->headers < 0 ? "Header" : "Body",
10023  i, (int) strlen(previous_header), previous_header );
10024  }
10025  i++;
10026  }
10027 
10028  /* update count of header or body lines */
10029  if (req->headers >= 0) { /* we are in the body */
10030  req->lines = i;
10031  } else { /* no body */
10032  req->headers = i;
10033  req->lines = 0;
10034  /* req->data->used will be a NULL byte */
10035  req->line[0] = ast_str_strlen(req->data);
10036  }
10037 
10038  if (*c) {
10039  ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
10040  }
10041 
10042  /* Split up the first line parts */
10043  return determine_firstline_parts(req);
10044 }
10045 
10046 /*!
10047  \brief Determine whether a SIP message contains an SDP in its body
10048  \param req the SIP request to process
10049  \return 1 if SDP found, 0 if not found
10050 
10051  Also updates req->sdp_start and req->sdp_count to indicate where the SDP
10052  lives in the message body.
10053 */
10054 static int find_sdp(struct sip_request *req)
10055 {
10056  const char *content_type;
10057  const char *content_length;
10058  const char *search;
10059  char *boundary;
10060  unsigned int x;
10061  int boundaryisquoted = FALSE;
10062  int found_application_sdp = FALSE;
10063  int found_end_of_headers = FALSE;
10064 
10065  content_length = sip_get_header(req, "Content-Length");
10066 
10067  if (!ast_strlen_zero(content_length)) {
10068  if (sscanf(content_length, "%30u", &x) != 1) {
10069  ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
10070  return 0;
10071  }
10072 
10073  /* Content-Length of zero means there can't possibly be an
10074  SDP here, even if the Content-Type says there is */
10075  if (x == 0)
10076  return 0;
10077  }
10078 
10079  content_type = sip_get_header(req, "Content-Type");
10080 
10081  /* if the body contains only SDP, this is easy */
10082  if (!strncasecmp(content_type, "application/sdp", 15)) {
10083  req->sdp_start = 0;
10084  req->sdp_count = req->lines;
10085  return req->lines ? 1 : 0;
10086  }
10087 
10088  /* if it's not multipart/mixed, there cannot be an SDP */
10089  if (strncasecmp(content_type, "multipart/mixed", 15))
10090  return 0;
10091 
10092  /* if there is no boundary marker, it's invalid */
10093  if ((search = strcasestr(content_type, ";boundary=")))
10094  search += 10;
10095  else if ((search = strcasestr(content_type, "; boundary=")))
10096  search += 11;
10097  else
10098  return 0;
10099 
10100  if (ast_strlen_zero(search))
10101  return 0;
10102 
10103  /* If the boundary is quoted with ", remove quote */
10104  if (*search == '\"') {
10105  search++;
10106  boundaryisquoted = TRUE;
10107  }
10108 
10109  /* make a duplicate of the string, with two extra characters
10110  at the beginning */
10111  boundary = ast_strdupa(search - 2);
10112  boundary[0] = boundary[1] = '-';
10113  /* Remove final quote */
10114  if (boundaryisquoted)
10115  boundary[strlen(boundary) - 1] = '\0';
10116 
10117  /* search for the boundary marker, the empty line delimiting headers from
10118  sdp part and the end boundry if it exists */
10119 
10120  for (x = 0; x < (req->lines); x++) {
10121  const char *line = REQ_OFFSET_TO_STR(req, line[x]);
10122  if (!strncasecmp(line, boundary, strlen(boundary))){
10123  if (found_application_sdp && found_end_of_headers) {
10124  req->sdp_count = (x - 1) - req->sdp_start;
10125  return 1;
10126  }
10127  found_application_sdp = FALSE;
10128  }
10129  if (!strcasecmp(line, "Content-Type: application/sdp"))
10130  found_application_sdp = TRUE;
10131 
10132  if (ast_strlen_zero(line)) {
10133  if (found_application_sdp && !found_end_of_headers){
10134  req->sdp_start = x;
10135  found_end_of_headers = TRUE;
10136  }
10137  }
10138  }
10139  if (found_application_sdp && found_end_of_headers) {
10140  req->sdp_count = x - req->sdp_start;
10141  return TRUE;
10142  }
10143  return FALSE;
10144 }
10145 
10146 /*! \brief Change hold state for a call */
10147 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
10148 {
10149  if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD))) {
10150  sip_peer_hold(dialog, holdstate);
10151  }
10152  append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
10153  if (!holdstate) { /* Put off remote hold */
10154  ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
10155  return;
10156  }
10157  /* No address for RTP, we're on hold */
10158 
10159  /* Ensure hold flags are cleared so that overlapping flags do not conflict */
10161 
10162  if (sendonly == 1) /* One directional hold (sendonly/recvonly) */
10164  else if (sendonly == 2) /* Inactive stream */
10166  else
10168  return;
10169 }
10170 
10171 /*! \internal
10172  * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
10173  * \retval TRUE if the address is null or any
10174  * \retval FALSE if the address it not null or any
10175  * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
10176  */
10177 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
10178 {
10179  return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
10180 }
10181 
10182 /*! \brief Check the media stream list to see if the given type already exists */
10183 static int has_media_stream(struct sip_pvt *p, enum media_type m)
10184 {
10185  struct offered_media *offer = NULL;
10186  AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
10187  if (m == offer->type) {
10188  return 1;
10189  }
10190  }
10191  return 0;
10192 }
10193 
10194 static void configure_rtcp(struct sip_pvt *p, struct ast_rtp_instance *instance, int which, int remote_rtcp_mux)
10195 {
10196  int local_rtcp_mux = ast_test_flag(&p->flags[2], SIP_PAGE3_RTCP_MUX);
10197  int fd = -1;
10198 
10199  if (local_rtcp_mux && remote_rtcp_mux) {
10201  } else {
10203  fd = ast_rtp_instance_fd(instance, 1);
10204  }
10205 
10206  if (p->owner) {
10207  ast_channel_set_fd(p->owner, which, fd);
10208  }
10209 }
10210 
10211 static void set_ice_components(struct sip_pvt *p, struct ast_rtp_instance *instance, int remote_rtcp_mux)
10212 {
10213  struct ast_rtp_engine_ice *ice;
10214  int local_rtcp_mux = ast_test_flag(&p->flags[2], SIP_PAGE3_RTCP_MUX);
10215 
10216  ice = ast_rtp_instance_get_ice(instance);
10217  if (!ice) {
10218  return;
10219  }
10220 
10221  if (local_rtcp_mux && remote_rtcp_mux) {
10222  /* We both support RTCP mux. Only one ICE component necessary */
10223  ice->change_components(instance, 1);
10224  } else {
10225  /* They either don't support RTCP mux or we don't know if they do yet. */
10226  ice->change_components(instance, 2);
10227  }
10228 }
10229 
10230 static int has_media_level_attribute(int start, struct sip_request *req, const char *attr)
10231 {
10232  int next = start;
10233  char type;
10234  const char *value;
10235 
10236  /* We don't care about the return result here */
10237  get_sdp_iterate(&next, req, "m");
10238 
10239  while ((type = get_sdp_line(&start, next, req, &value)) != '\0') {
10240  if (type == 'a' && !strcasecmp(value, attr)) {
10241  return 1;
10242  }
10243  }
10244 
10245  return 0;
10246 }
10247 
10248 /*! \brief Process SIP SDP offer, select formats and activate media channels
10249  If offer is rejected, we will not change any properties of the call
10250  Return 0 on success, a negative value on errors.
10251  Must be called after find_sdp().
10252 */
10253 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action, int is_offer)
10254 {
10255  int res = 0;
10256 
10257  /* Iterators for SDP parsing */
10258  int start = req->sdp_start;
10259  int next = start;
10260  int iterator = start;
10261 
10262  /* Temporary vars for SDP parsing */
10263  char type = '\0';
10264  const char *value = NULL;
10265  const char *m = NULL; /* SDP media offer */
10266  const char *nextm = NULL;
10267  int len = -1;
10268  struct offered_media *offer;
10269 
10270  /* Host information */
10271  struct ast_sockaddr sessionsa;
10272  struct ast_sockaddr audiosa;
10273  struct ast_sockaddr videosa;
10274  struct ast_sockaddr textsa;
10275  struct ast_sockaddr imagesa;
10276  struct ast_sockaddr *sa = NULL; /*!< RTP audio destination IP address */
10277  struct ast_sockaddr *vsa = NULL; /*!< RTP video destination IP address */
10278  struct ast_sockaddr *tsa = NULL; /*!< RTP text destination IP address */
10279  struct ast_sockaddr *isa = NULL; /*!< UDPTL image destination IP address */
10280  int portno = -1; /*!< RTP audio destination port number */
10281  int vportno = -1; /*!< RTP video destination port number */
10282  int tportno = -1; /*!< RTP text destination port number */
10283  int udptlportno = -1; /*!< UDPTL image destination port number */
10284 
10285  /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
10289 
10290  int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
10291 
10292  struct ast_rtp_codecs newaudiortp = AST_RTP_CODECS_NULL_INIT;
10293  struct ast_rtp_codecs newvideortp = AST_RTP_CODECS_NULL_INIT;
10294  struct ast_rtp_codecs newtextrtp = AST_RTP_CODECS_NULL_INIT;
10295  struct ast_format_cap *newjointcapability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT); /* Negotiated capability */
10297  int newnoncodeccapability;
10298 
10299  const char *codecs;
10300  unsigned int codec;
10301 
10302  /* SRTP */
10303  int secure_audio = FALSE;
10304  int secure_video = FALSE;
10305 
10306  /* RTCP Multiplexing */
10307  int remote_rtcp_mux_audio = FALSE;
10308  int remote_rtcp_mux_video = FALSE;
10309 
10310  /* Others */
10311  int sendonly = -1;
10312  unsigned int numberofports;
10313  int last_rtpmap_codec = 0;
10314  int red_data_pt[10]; /* For T.140 RED */
10315  int red_num_gen = 0; /* For T.140 RED */
10316  char red_fmtp[100] = "empty"; /* For T.140 RED */
10317  int debug = sip_debug_test_pvt(p);
10318 
10319  /* START UNKNOWN */
10320  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10321  struct ast_format *tmp_fmt;
10322  /* END UNKNOWN */
10323 
10324  /* Initial check */
10325  if (!p->rtp) {
10326  ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
10327  res = -1;
10328  goto process_sdp_cleanup;
10329  }
10330  if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
10331  res = -1;
10332  goto process_sdp_cleanup;
10333  }
10334 
10335  if (ast_rtp_codecs_payloads_initialize(&newaudiortp) || ast_rtp_codecs_payloads_initialize(&newvideortp) ||
10336  ast_rtp_codecs_payloads_initialize(&newtextrtp)) {
10337  res = -1;
10338  goto process_sdp_cleanup;
10339  }
10340 
10341  /* Update our last rtprx when we receive an SDP, too */
10342  p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10343 
10345 
10346  /* Scan for the first media stream (m=) line to limit scanning of globals */
10347  nextm = get_sdp_iterate(&next, req, "m");
10348  if (ast_strlen_zero(nextm)) {
10349  ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
10350  res = -1;
10351  goto process_sdp_cleanup;
10352  }
10353 
10354  /* Scan session level SDP parameters (lines before first media stream) */
10355  while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
10356  int processed = FALSE;
10357  switch (type) {
10358  case 'o':
10359  /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
10360  * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
10361  */
10362  if (!process_sdp_o(value, p)) {
10363  res = (p->session_modify == FALSE) ? 0 : -1;
10364  goto process_sdp_cleanup;
10365  }
10366  processed = TRUE;
10367  break;
10368  case 'c':
10369  if (process_sdp_c(value, &sessionsa)) {
10370  processed = TRUE;
10371  sa = &sessionsa;
10372  vsa = sa;
10373  tsa = sa;
10374  isa = sa;
10375  }
10376  break;
10377  case 'a':
10378  if (process_sdp_a_sendonly(value, &sendonly)) {
10379  processed = TRUE;
10380  }
10381  else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
10382  processed = TRUE;
10383  else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
10384  processed = TRUE;
10385  else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
10386  processed = TRUE;
10387  else if (process_sdp_a_image(value, p))
10388  processed = TRUE;
10389 
10390  if (process_sdp_a_ice(value, p, p->rtp, 0)) {
10391  processed = TRUE;
10392  }
10393  if (process_sdp_a_ice(value, p, p->vrtp, 0)) {
10394  processed = TRUE;
10395  }
10396  if (process_sdp_a_ice(value, p, p->trtp, 0)) {
10397  processed = TRUE;
10398  }
10399 
10400  if (process_sdp_a_dtls(value, p, p->rtp)) {
10401  processed = TRUE;
10402  if (p->srtp) {
10404  }
10405  }
10406  if (process_sdp_a_dtls(value, p, p->vrtp)) {
10407  processed = TRUE;
10408  if (p->vsrtp) {
10410  }
10411  }
10412  if (process_sdp_a_dtls(value, p, p->trtp)) {
10413  processed = TRUE;
10414  if (p->tsrtp) {
10416  }
10417  }
10418 
10419  break;
10420  }
10421 
10422  ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
10423  }
10424 
10425  /* default: novideo and notext set */
10426  p->novideo = TRUE;
10427  p->notext = TRUE;
10428 
10429  /* Scan media stream (m=) specific parameters loop */
10430  while (!ast_strlen_zero(nextm)) {
10431  int audio = FALSE;
10432  int video = FALSE;
10433  int image = FALSE;
10434  int text = FALSE;
10435  int processed_crypto = FALSE;
10436  int rtcp_mux_offered = 0;
10437  char protocol[18] = {0,};
10438  unsigned int x;
10439  struct ast_rtp_engine_dtls *dtls;
10440 
10441  numberofports = 0;
10442  len = -1;
10443  start = next;
10444  m = nextm;
10445  iterator = next;
10446  nextm = get_sdp_iterate(&next, req, "m");
10447 
10448  if (!(offer = ast_calloc(1, sizeof(*offer)))) {
10449  ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer list\n");
10450  res = -1;
10451  goto process_sdp_cleanup;
10452  }
10453  AST_LIST_INSERT_TAIL(&p->offered_media, offer, next);
10454  offer->type = SDP_UNKNOWN;
10455 
10456  /* We need to check for this ahead of time */
10457  rtcp_mux_offered = has_media_level_attribute(iterator, req, "rtcp-mux");
10458 
10459  /* Check for 'audio' media offer */
10460  if (p->rtp && strncmp(m, "audio ", 6) == 0) {
10461  if ((sscanf(m, "audio %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10462  (sscanf(m, "audio %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10463  codecs = m + len;
10464  /* produce zero-port m-line since it may be needed later
10465  * length is "m=audio 0 " + protocol + " " + codecs + "\r\n\0" */
10466  if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10467  ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10468  res = -1;
10469  goto process_sdp_cleanup;
10470  }
10471  /* guaranteed to be exactly the right length */
10472  sprintf(offer->decline_m_line, "m=audio 0 %s %s\r\n", protocol, codecs);
10473 
10474  if (x == 0) {
10475  ast_debug(1, "Ignoring audio media offer because port number is zero\n");
10476  continue;
10477  }
10478 
10479  if (has_media_stream(p, SDP_AUDIO)) {
10480  ast_log(LOG_WARNING, "Declining non-primary audio stream: %s\n", m);
10481  continue;
10482  }
10483 
10484  /* Check number of ports offered for stream */
10485  if (numberofports > 1) {
10486  ast_log(LOG_WARNING, "%u ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
10487  }
10488 
10489  if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10490  if (req->method != SIP_RESPONSE) {
10491  ast_log(LOG_NOTICE, "Received SAVPF profle in audio offer but AVPF is not enabled, enabling: %s\n", m);
10492  secure_audio = 1;
10494  }
10495  else {
10496 
10497  ast_log(LOG_WARNING, "Received SAVPF profle in audio answer but AVPF is not enabled: %s\n", m);
10498  continue;
10499  }
10500  } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10501  if (req->method != SIP_RESPONSE) {
10502  ast_log(LOG_NOTICE, "Received SAVP profle in audio offer but AVPF is enabled, disabling: %s\n", m);
10503  secure_audio = 1;
10505  }
10506  else {
10507  ast_log(LOG_WARNING, "Received SAVP profile in audio offer but AVPF is enabled: %s\n", m);
10508  continue;
10509  }
10510  } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
10511  secure_audio = 1;
10512 
10513  processed_crypto = 1;
10514  if (p->srtp) {
10516  }
10517  } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
10518  secure_audio = 1;
10519  } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10520  if (req->method != SIP_RESPONSE) {
10521  ast_log(LOG_NOTICE, "Received AVPF profile in audio offer but AVPF is not enabled, enabling: %s\n", m);
10523  }
10524  else {
10525  ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
10526  continue;
10527  }
10528  } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10529  if (req->method != SIP_RESPONSE) {
10530  ast_log(LOG_NOTICE, "Received AVP profile in audio answer but AVPF is enabled, disabling: %s\n", m);
10532  }
10533  else {
10534  ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
10535  continue;
10536  }
10537  } else if ((!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) &&
10538  (!(dtls = ast_rtp_instance_get_dtls(p->rtp)) || !dtls->active(p->rtp))) {
10539  ast_log(LOG_WARNING, "Received UDP/TLS in audio offer but DTLS is not enabled: %s\n", m);
10540  continue;
10541  } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10542  ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
10543  continue;
10544  }
10545 
10546  audio = TRUE;
10547  offer->type = SDP_AUDIO;
10548  portno = x;
10549 
10550  /* Scan through the RTP payload types specified in a "m=" line: */
10551  for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10552  if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10553  ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
10554  res = -1;
10555  goto process_sdp_cleanup;
10556  }
10557  if (debug) {
10558  ast_verbose("Found RTP audio format %u\n", codec);
10559  }
10560 
10561  ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
10562  }
10563  } else {
10564  ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
10565  res = -1;
10566  goto process_sdp_cleanup;
10567  }
10568  }
10569  /* Check for 'video' media offer */
10570  else if (p->vrtp && strncmp(m, "video ", 6) == 0) {
10571  if ((sscanf(m, "video %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10572  (sscanf(m, "video %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10573  codecs = m + len;
10574  /* produce zero-port m-line since it may be needed later
10575  * length is "m=video 0 " + protocol + " " + codecs + "\r\n\0" */
10576  if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10577  ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10578  res = -1;
10579  goto process_sdp_cleanup;
10580  }
10581  /* guaranteed to be exactly the right length */
10582  sprintf(offer->decline_m_line, "m=video 0 %s %s\r\n", protocol, codecs);
10583 
10584  if (x == 0) {
10585  ast_debug(1, "Ignoring video stream offer because port number is zero\n");
10586  continue;
10587  }
10588 
10589  /* Check number of ports offered for stream */
10590  if (numberofports > 1) {
10591  ast_log(LOG_WARNING, "%u ports offered for video stream, not supported by Asterisk. Will try anyway...\n", numberofports);
10592  }
10593 
10594  if (has_media_stream(p, SDP_VIDEO)) {
10595  ast_log(LOG_WARNING, "Declining non-primary video stream: %s\n", m);
10596  continue;
10597  }
10598 
10599  if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10600  ast_log(LOG_WARNING, "Received SAVPF profle in video offer but AVPF is not enabled: %s\n", m);
10601  continue;
10602  } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10603  ast_log(LOG_WARNING, "Received SAVP profile in video offer but AVPF is enabled: %s\n", m);
10604  continue;
10605  } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
10606  secure_video = 1;
10607 
10608  processed_crypto = 1;
10609  if (p->vsrtp || (p->vsrtp = ast_sdp_srtp_alloc())) {
10611  }
10612  } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
10613  secure_video = 1;
10614  } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10615  ast_log(LOG_WARNING, "Received AVPF profile in video offer but AVPF is not enabled: %s\n", m);
10616  continue;
10617  } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10618  ast_log(LOG_WARNING, "Received AVP profile in video offer but AVPF is enabled: %s\n", m);
10619  continue;
10620  } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10621  ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
10622  continue;
10623  }
10624 
10625  video = TRUE;
10626  p->novideo = FALSE;
10627  offer->type = SDP_VIDEO;
10628  vportno = x;
10629 
10630  /* Scan through the RTP payload types specified in a "m=" line: */
10631  for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10632  if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10633  ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
10634  res = -1;
10635  goto process_sdp_cleanup;
10636  }
10637  if (debug) {
10638  ast_verbose("Found RTP video format %u\n", codec);
10639  }
10640  ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
10641  }
10642  } else {
10643  ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
10644  res = -1;
10645  goto process_sdp_cleanup;
10646  }
10647  }
10648  /* Check for 'text' media offer */
10649  else if (p->trtp && strncmp(m, "text ", 5) == 0) {
10650  if ((sscanf(m, "text %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10651  (sscanf(m, "text %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10652  codecs = m + len;
10653  /* produce zero-port m-line since it may be needed later
10654  * length is "m=text 0 " + protocol + " " + codecs + "\r\n\0" */
10655  if (!(offer->decline_m_line = ast_malloc(9 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10656  ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10657  res = -1;
10658  goto process_sdp_cleanup;
10659  }
10660  /* guaranteed to be exactly the right length */
10661  sprintf(offer->decline_m_line, "m=text 0 %s %s\r\n", protocol, codecs);
10662 
10663  if (x == 0) {
10664  ast_debug(1, "Ignoring text stream offer because port number is zero\n");
10665  continue;
10666  }
10667 
10668  /* Check number of ports offered for stream */
10669  if (numberofports > 1) {
10670  ast_log(LOG_WARNING, "%u ports offered for text stream, not supported by Asterisk. Will try anyway...\n", numberofports);
10671  }
10672 
10673  if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10674  ast_log(LOG_WARNING, "Received AVPF profile in text offer but AVPF is not enabled: %s\n", m);
10675  continue;
10676  } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10677  ast_log(LOG_WARNING, "Received AVP profile in text offer but AVPF is enabled: %s\n", m);
10678  continue;
10679  } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10680  ast_log(LOG_WARNING, "Unknown RTP profile in text offer: %s\n", m);
10681  continue;
10682  }
10683 
10684  if (has_media_stream(p, SDP_TEXT)) {
10685  ast_log(LOG_WARNING, "Declining non-primary text stream: %s\n", m);
10686  continue;
10687  }
10688 
10689  text = TRUE;
10690  p->notext = FALSE;
10691  offer->type = SDP_TEXT;
10692  tportno = x;
10693 
10694  /* Scan through the RTP payload types specified in a "m=" line: */
10695  for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10696  if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10697  ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
10698  res = -1;
10699  goto process_sdp_cleanup;
10700  }
10701  if (debug) {
10702  ast_verbose("Found RTP text format %u\n", codec);
10703  }
10704  ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
10705  }
10706  } else {
10707  ast_log(LOG_WARNING, "Rejecting text stream offer due to invalid or unsupported syntax: %s\n", m);
10708  res = -1;
10709  goto process_sdp_cleanup;
10710  }
10711  }
10712  /* Check for 'image' media offer */
10713  else if (strncmp(m, "image ", 6) == 0) {
10714  if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
10715  (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
10716  /* produce zero-port m-line since it may be needed later
10717  * length is "m=image 0 udptl t38" + "\r\n\0" */
10718  if (!(offer->decline_m_line = ast_malloc(22))) {
10719  ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10720  res = -1;
10721  goto process_sdp_cleanup;
10722  }
10723  /* guaranteed to be exactly the right length */
10724  strcpy(offer->decline_m_line, "m=image 0 udptl t38\r\n");
10725 
10726  if (x == 0) {
10727  ast_debug(1, "Ignoring image stream offer because port number is zero\n");
10728  continue;
10729  }
10730 
10731  if (initialize_udptl(p)) {
10732  ast_log(LOG_WARNING, "Failed to initialize UDPTL, declining image stream\n");
10733  continue;
10734  }
10735 
10736  if (has_media_stream(p, SDP_IMAGE)) {
10737  ast_log(LOG_WARNING, "Declining non-primary image stream: %s\n", m);
10738  continue;
10739  }
10740 
10741  image = TRUE;
10742  if (debug) {
10743  ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
10744  }
10745 
10746  offer->type = SDP_IMAGE;
10747  udptlportno = x;
10748 
10749  if (p->t38.state != T38_ENABLED) {
10750  memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
10751 
10752  /* default EC to none, the remote end should
10753  * respond with the EC they want to use */
10755  }
10756  } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
10757  ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
10758  /* produce zero-port m-line since this is guaranteed to be declined
10759  * length is "m=image 0 strlen(protocol) t38" + "\r\n\0" */
10760  if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 7))) {
10761  ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10762  res = -1;
10763  goto process_sdp_cleanup;
10764  }
10765  /* guaranteed to be exactly the right length */
10766  sprintf(offer->decline_m_line, "m=image 0 %s t38\r\n", protocol);
10767  continue;
10768  } else {
10769  ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
10770  res = -1;
10771  goto process_sdp_cleanup;
10772  }
10773  } else {
10774  char type[20] = {0,};
10775  if ((sscanf(m, "%19s %30u/%30u %n", type, &x, &numberofports, &len) == 3 && len > 0) ||
10776  (sscanf(m, "%19s %30u %n", type, &x, &len) == 2 && len > 0)) {
10777  /* produce zero-port m-line since it may be needed later
10778  * length is "m=" + type + " 0 " + remainder + "\r\n\0" */
10779  if (!(offer->decline_m_line = ast_malloc(2 + strlen(type) + 3 + strlen(m + len) + 3))) {
10780  ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10781  res = -1;
10782  goto process_sdp_cleanup;
10783  }
10784  /* guaranteed to be long enough */
10785  sprintf(offer->decline_m_line, "m=%s 0 %s\r\n", type, m + len);
10786  continue;
10787  } else {
10788  ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
10789  res = -1;
10790  goto process_sdp_cleanup;
10791  }
10792  }
10793 
10794  /* Media stream specific parameters */
10795  while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
10796  int processed = FALSE;
10797 
10798  switch (type) {
10799  case 'c':
10800  if (audio) {
10801  if (process_sdp_c(value, &audiosa)) {
10802  processed = TRUE;
10803  sa = &audiosa;
10804  }
10805  } else if (video) {
10806  if (process_sdp_c(value, &videosa)) {
10807  processed = TRUE;
10808  vsa = &videosa;
10809  }
10810  } else if (text) {
10811  if (process_sdp_c(value, &textsa)) {
10812  processed = TRUE;
10813  tsa = &textsa;
10814  }
10815  } else if (image) {
10816  if (process_sdp_c(value, &imagesa)) {
10817  processed = TRUE;
10818  isa = &imagesa;
10819  }
10820  }
10821  break;
10822  case 'a':
10823  /* Audio specific scanning */
10824  if (audio) {
10825  if (process_sdp_a_ice(value, p, p->rtp, rtcp_mux_offered)) {
10826  processed = TRUE;
10827  } else if (process_sdp_a_dtls(value, p, p->rtp)) {
10828  processed_crypto = TRUE;
10829  processed = TRUE;
10830  if (p->srtp) {
10832  }
10833  } else if (process_sdp_a_sendonly(value, &sendonly)) {
10834  processed = TRUE;
10835  } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
10836  processed_crypto = TRUE;
10837  processed = TRUE;
10838  if (secure_audio == FALSE) {
10839  ast_log(AST_LOG_NOTICE, "Processed audio crypto attribute without SAVP specified; accepting anyway\n");
10840  secure_audio = TRUE;
10841  }
10842  } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
10843  processed = TRUE;
10844  } else if (process_sdp_a_rtcp_mux(value, p, &remote_rtcp_mux_audio)) {
10845  processed = TRUE;
10846  }
10847  }
10848  /* Video specific scanning */
10849  else if (video) {
10850  if (process_sdp_a_ice(value, p, p->vrtp, rtcp_mux_offered)) {
10851  processed = TRUE;
10852  } else if (process_sdp_a_dtls(value, p, p->vrtp)) {
10853  processed_crypto = TRUE;
10854  processed = TRUE;
10855  if (p->vsrtp) {
10857  }
10858  } else if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
10859  processed_crypto = TRUE;
10860  processed = TRUE;
10861  if (secure_video == FALSE) {
10862  ast_log(AST_LOG_NOTICE, "Processed video crypto attribute without SAVP specified; accepting anyway\n");
10863  secure_video = TRUE;
10864  }
10865  } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
10866  processed = TRUE;
10867  } else if (process_sdp_a_rtcp_mux(value, p, &remote_rtcp_mux_video)) {
10868  processed = TRUE;
10869  }
10870  }
10871  /* Text (T.140) specific scanning */
10872  else if (text) {
10873  if (process_sdp_a_ice(value, p, p->trtp, rtcp_mux_offered)) {
10874  processed = TRUE;
10875  } else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
10876  processed = TRUE;
10877  } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
10878  processed_crypto = TRUE;
10879  processed = TRUE;
10880  }
10881  }
10882  /* Image (T.38 FAX) specific scanning */
10883  else if (image) {
10884  if (process_sdp_a_image(value, p))
10885  processed = TRUE;
10886  }
10887  break;
10888  }
10889 
10890  ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
10891  (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
10892  type, value,
10893  (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
10894  }
10895 
10896  /* Ensure crypto lines are provided where necessary */
10897  if (audio && secure_audio && !processed_crypto) {
10898  ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
10899  res = -1;
10900  goto process_sdp_cleanup;
10901  } else if (video && secure_video && !processed_crypto) {
10902  ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
10903  res = -1;
10904  goto process_sdp_cleanup;
10905  }
10906  }
10907 
10908  /* Sanity checks */
10909  if (!sa && !vsa && !tsa && !isa) {
10910  ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
10911  res = -1;
10912  goto process_sdp_cleanup;
10913  }
10914 
10915  if ((portno == -1) &&
10916  (vportno == -1) &&
10917  (tportno == -1) &&
10918  (udptlportno == -1)) {
10919  ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
10920  res = -1;
10921  goto process_sdp_cleanup;
10922  }
10923 
10924  if (p->srtp && p->udptl && udptlportno != -1) {
10925  ast_debug(1, "Terminating SRTP due to T.38 UDPTL\n");
10927  p->srtp = NULL;
10928  }
10929 
10930  if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, AST_SRTP_CRYPTO_OFFER_OK)))) {
10931  ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
10932  res = -1;
10933  goto process_sdp_cleanup;
10934  }
10935 
10936  if (!secure_audio && p->srtp) {
10937  ast_log(LOG_WARNING, "Failed to receive SDP offer/answer with required SRTP crypto attributes for audio\n");
10938  res = -1;
10939  goto process_sdp_cleanup;
10940  }
10941 
10942  if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, AST_SRTP_CRYPTO_OFFER_OK)))) {
10943  ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
10944  res = -1;
10945  goto process_sdp_cleanup;
10946  }
10947 
10948  if (!p->novideo && !secure_video && p->vsrtp) {
10949  ast_log(LOG_WARNING, "Failed to receive SDP offer/answer with required SRTP crypto attributes for video\n");
10950  res = -1;
10951  goto process_sdp_cleanup;
10952  }
10953 
10954  if (!(secure_audio || secure_video || (p->udptl && udptlportno != -1)) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
10955  ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
10956  res = -1;
10957  goto process_sdp_cleanup;
10958  }
10959 
10960  if (udptlportno == -1) {
10962  }
10963 
10964  if (is_offer) {
10965  /*
10966  * Setup rx payload type mapping to prefer the mapping
10967  * from the peer that the RFC says we SHOULD use.
10968  */
10969  ast_rtp_codecs_payloads_xover(&newaudiortp, &newaudiortp, NULL);
10970  ast_rtp_codecs_payloads_xover(&newvideortp, &newvideortp, NULL);
10971  ast_rtp_codecs_payloads_xover(&newtextrtp, &newtextrtp, NULL);
10972  }
10973 
10974  /* Now gather all of the codecs that we are asked for: */
10975  ast_rtp_codecs_payload_formats(&newaudiortp, peercapability, &peernoncodeccapability);
10976  ast_rtp_codecs_payload_formats(&newvideortp, vpeercapability, &vpeernoncodeccapability);
10977  ast_rtp_codecs_payload_formats(&newtextrtp, tpeercapability, &tpeernoncodeccapability);
10978 
10979  ast_format_cap_append_from_cap(newpeercapability, peercapability, AST_MEDIA_TYPE_AUDIO);
10980  ast_format_cap_append_from_cap(newpeercapability, vpeercapability, AST_MEDIA_TYPE_VIDEO);
10981  ast_format_cap_append_from_cap(newpeercapability, tpeercapability, AST_MEDIA_TYPE_TEXT);
10982 
10983  ast_format_cap_get_compatible(p->caps, newpeercapability, newjointcapability);
10984  if (!ast_format_cap_count(newjointcapability) && udptlportno == -1) {
10985  ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
10986  /* Do NOT Change current setting */
10987  res = -1;
10988  goto process_sdp_cleanup;
10989  }
10990 
10991  newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
10992 
10993  if (debug) {
10994  /* shame on whoever coded this.... */
10995  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10996  struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10997  struct ast_str *vpeer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10998  struct ast_str *tpeer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10999  struct ast_str *joint_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11000  struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
11001  struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
11002  struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
11003 
11004  ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
11005  ast_format_cap_get_names(p->caps, &cap_buf),
11006  ast_format_cap_get_names(peercapability, &peer_buf),
11007  ast_format_cap_get_names(vpeercapability, &vpeer_buf),
11008  ast_format_cap_get_names(tpeercapability, &tpeer_buf),
11009  ast_format_cap_get_names(newjointcapability, &joint_buf));
11010 
11011  ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
11013  ast_rtp_lookup_mime_multiple2(s2, NULL, peernoncodeccapability, 0, 0),
11014  ast_rtp_lookup_mime_multiple2(s3, NULL, newnoncodeccapability, 0, 0));
11015  }
11016 
11017  /* When UDPTL is negotiated it is expected that there are no compatible codecs as audio or
11018  * video is not being transported, thus we continue in this function further up if that is
11019  * the case. If we receive an SDP answer containing both a UDPTL stream and another media
11020  * stream however we need to check again to ensure that there is at least one joint codec
11021  * instead of assuming there is one.
11022  */
11023  if ((portno != -1 || vportno != -1 || tportno != -1) && ast_format_cap_count(newjointcapability)) {
11024  /* We are now ready to change the sip session and RTP structures with the offered codecs, since
11025  they are acceptable */
11026  unsigned int framing;
11028  ast_format_cap_append_from_cap(p->jointcaps, newjointcapability, AST_MEDIA_TYPE_UNKNOWN); /* Our joint codec profile for this call */
11030  ast_format_cap_append_from_cap(p->peercaps, newpeercapability, AST_MEDIA_TYPE_UNKNOWN); /* The other side's capability in latest offer */
11031  p->jointnoncodeccapability = newnoncodeccapability; /* DTMF capabilities */
11032 
11033  tmp_fmt = ast_format_cap_get_format(p->jointcaps, 0);
11034  framing = ast_format_cap_get_format_framing(p->jointcaps, tmp_fmt);
11035  /* respond with single most preferred joint codec, limiting the other side's choice */
11038  ast_format_cap_append(p->jointcaps, tmp_fmt, framing);
11039  }
11040  if (!ast_rtp_codecs_get_framing(&newaudiortp)) {
11041  /* Peer did not force us to use a specific framing, so use our own */
11042  ast_rtp_codecs_set_framing(&newaudiortp, framing);
11043  }
11044  ao2_ref(tmp_fmt, -1);
11045  }
11046 
11047  /* Setup audio address and port */
11048  if (p->rtp) {
11049  if (sa && portno > 0) {
11050  /* Start ICE negotiation here, only when it is response, and setting that we are conrolling agent,
11051  as we are offerer */
11052  set_ice_components(p, p->rtp, remote_rtcp_mux_audio);
11053  if (req->method == SIP_RESPONSE) {
11054  start_ice(p->rtp, 1);
11055  }
11056  ast_sockaddr_set_port(sa, portno);
11058  if (debug) {
11059  ast_verbose("Peer audio RTP is at port %s\n",
11061  }
11062 
11064  /* Ensure RTCP is enabled since it may be inactive
11065  if we're coming back from a T.38 session */
11066  configure_rtcp(p, p->rtp, SIP_AUDIO_RTCP_FD, remote_rtcp_mux_audio);
11067 
11068  if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
11069  ast_clear_flag(&p->flags[0], SIP_DTMF);
11070  if (newnoncodeccapability & AST_RTP_DTMF) {
11071  /* XXX Would it be reasonable to drop the DSP at this point? XXX */
11073  /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
11076  } else {
11078  }
11079  }
11080  } else if (udptlportno > 0) {
11081  if (debug)
11082  ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
11083 
11084  /* Force media to go through us for T.38. */
11085  memset(&p->redirip, 0, sizeof(p->redirip));
11086 
11087  /* Prevent audio RTCP reads */
11088  if (p->owner) {
11090  }
11091  /* Silence RTCP while audio RTP is inactive */
11093  } else {
11095  if (debug)
11096  ast_verbose("Peer doesn't provide audio\n");
11097  }
11098  }
11099 
11100  /* Setup video address and port */
11101  if (p->vrtp) {
11102  if (vsa && vportno > 0) {
11103  set_ice_components(p, p->vrtp, remote_rtcp_mux_video);
11104  start_ice(p->vrtp, (req->method != SIP_RESPONSE) ? 0 : 1);
11105  ast_sockaddr_set_port(vsa, vportno);
11107  if (debug) {
11108  ast_verbose("Peer video RTP is at port %s\n",
11109  ast_sockaddr_stringify(vsa));
11110  }
11112  configure_rtcp(p, p->vrtp, SIP_VIDEO_RTCP_FD, remote_rtcp_mux_video);
11113  } else {
11115  if (debug)
11116  ast_verbose("Peer doesn't provide video\n");
11117  }
11118  }
11119 
11120  /* Setup text address and port */
11121  if (p->trtp) {
11122  if (tsa && tportno > 0) {
11123  start_ice(p->trtp, (req->method != SIP_RESPONSE) ? 0 : 1);
11124  ast_sockaddr_set_port(tsa, tportno);
11126  if (debug) {
11127  ast_verbose("Peer T.140 RTP is at port %s\n",
11128  ast_sockaddr_stringify(tsa));
11129  }
11131  p->red = 1;
11132  ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
11133  } else {
11134  p->red = 0;
11135  }
11137  } else {
11139  if (debug)
11140  ast_verbose("Peer doesn't provide T.140\n");
11141  }
11142  }
11143 
11144  /* Setup image address and port */
11145  if (p->udptl) {
11146  if (isa && udptlportno > 0) {
11149  if (!ast_sockaddr_isnull(isa) && debug) {
11150  ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
11151  }
11152  }
11153  ast_sockaddr_set_port(isa, udptlportno);
11154  ast_udptl_set_peer(p->udptl, isa);
11155  if (debug)
11156  ast_debug(1, "Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
11157 
11158  /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
11160  /* setting to zero will force a default if none was provided by the SDP */
11162  }
11163 
11164  /* Remote party offers T38, we need to update state */
11165  if ((t38action == SDP_T38_ACCEPT) &&
11166  (p->t38.state == T38_LOCAL_REINVITE)) {
11168  } else if ((t38action == SDP_T38_INITIATE) &&
11169  p->owner && p->lastinvite) {
11170  change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
11171  /* If fax detection is enabled then send us off to the fax extension */
11173  ast_channel_lock(p->owner);
11174  if (strcmp(ast_channel_exten(p->owner), "fax")) {
11175  const char *target_context = S_OR(ast_channel_macrocontext(p->owner), ast_channel_context(p->owner));
11177  if (ast_exists_extension(p->owner, target_context, "fax", 1,
11179  ast_verb(2, "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", ast_channel_name(p->owner));
11181  if (ast_async_goto(p->owner, target_context, "fax", 1)) {
11182  ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(p->owner), target_context);
11183  }
11184  } else {
11185  ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
11186  }
11187  } else {
11189  }
11190  }
11191  }
11192  } else {
11194  ast_udptl_stop(p->udptl);
11195  if (debug)
11196  ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
11197  }
11198  }
11199 
11200  if ((portno == -1) && (p->t38.state != T38_DISABLED) && (p->t38.state != T38_REJECTED)) {
11201  ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
11202  res = 0;
11203  goto process_sdp_cleanup;
11204  }
11205 
11206  /* Ok, we're going with this offer */
11207  ast_debug(2, "We're settling with these formats: %s\n", ast_format_cap_get_names(p->jointcaps, &codec_buf));
11208 
11209  if (!p->owner) { /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
11210  res = 0;
11211  goto process_sdp_cleanup;
11212  }
11213 
11214  ast_debug(4, "We have an owner, now see if we need to change this call\n");
11216  struct ast_format_cap *caps;
11217  unsigned int framing;
11218 
11219  if (debug) {
11220  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11221  struct ast_str *joint_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11222 
11223  ast_debug(1, "Setting native formats after processing SDP. peer joint formats %s, old nativeformats %s\n",
11224  ast_format_cap_get_names(p->jointcaps, &joint_buf),
11226  }
11227 
11229  if (caps) {
11230  tmp_fmt = ast_format_cap_get_format(p->jointcaps, 0);
11231  framing = ast_format_cap_get_format_framing(p->jointcaps, tmp_fmt);
11232  ast_format_cap_append(caps, tmp_fmt, framing);
11233  ast_format_cap_append_from_cap(caps, vpeercapability, AST_MEDIA_TYPE_VIDEO);
11234  ast_format_cap_append_from_cap(caps, tpeercapability, AST_MEDIA_TYPE_TEXT);
11236  ao2_ref(caps, -1);
11237  ao2_ref(tmp_fmt, -1);
11238  }
11239 
11242  }
11243 
11244  if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && (!ast_sockaddr_isnull(sa) || !ast_sockaddr_isnull(vsa) || !ast_sockaddr_isnull(tsa) || !ast_sockaddr_isnull(isa)) && (!sendonly || sendonly == -1)) {
11246  ast_queue_unhold(p->owner);
11247  }
11248  /* Activate a re-invite */
11250  change_hold_state(p, req, FALSE, sendonly);
11251  } else if ((sockaddr_is_null_or_any(sa) && sockaddr_is_null_or_any(vsa) && sockaddr_is_null_or_any(tsa) && sockaddr_is_null_or_any(isa)) || (sendonly && sendonly != -1)) {
11254  }
11255  if (sendonly)
11257  /* RTCP needs to go ahead, even if we're on hold!!! */
11258  /* Activate a re-invite */
11260  change_hold_state(p, req, TRUE, sendonly);
11261  }
11262 
11263 process_sdp_cleanup:
11264  if (res) {
11266  }
11267  ast_rtp_codecs_payloads_destroy(&newtextrtp);
11268  ast_rtp_codecs_payloads_destroy(&newvideortp);
11269  ast_rtp_codecs_payloads_destroy(&newaudiortp);
11270  ao2_cleanup(peercapability);
11271  ao2_cleanup(vpeercapability);
11272  ao2_cleanup(tpeercapability);
11273  ao2_cleanup(newjointcapability);
11274  ao2_cleanup(newpeercapability);
11275  return res;
11276 }
11277 
11278 static int process_sdp_o(const char *o, struct sip_pvt *p)
11279 {
11280  const char *o_copy_start;
11281  char *o_copy;
11282  char *token;
11283  int offset;
11284  int64_t sess_version;
11285  char unique[128];
11286 
11287  /* Store the SDP version number of remote UA. This will allow us to
11288  distinguish between session modifications and session refreshes. If
11289  the remote UA does not send an incremented SDP version number in a
11290  subsequent RE-INVITE then that means its not changing media session.
11291  The RE-INVITE may have been sent to update connected party, remote
11292  target or to refresh the session (Session-Timers). Asterisk must not
11293  change media session and increment its own version number in answer
11294  SDP in this case. */
11295 
11296  p->session_modify = TRUE;
11297 
11298  if (ast_strlen_zero(o)) {
11299  ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
11300  return FALSE;
11301  }
11302 
11303  /* o=<username> <sess-id> <sess-version> <nettype> <addrtype>
11304  <unicast-address> */
11305 
11306  o_copy_start = o_copy = ast_strdupa(o);
11307  token = strsep(&o_copy, " "); /* Skip username */
11308  if (!o_copy) {
11309  ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
11310  return FALSE;
11311  }
11312  token = strsep(&o_copy, " "); /* sess-id */
11313  if (!o_copy) {
11314  ast_log(LOG_WARNING, "SDP syntax error in o= line sess-id\n");
11315  return FALSE;
11316  }
11317  token = strsep(&o_copy, " "); /* sess-version */
11318  if (!o_copy || !sscanf(token, "%30" SCNd64, &sess_version)) {
11319  ast_log(LOG_WARNING, "SDP syntax error in o= line sess-version\n");
11320  return FALSE;
11321  }
11322 
11323  /* Copy all after sess-version on top of sess-version into unique.
11324  * <sess-id> is a numeric string such that the tuple of <username>,
11325  * <sess-id>, <nettype>, <addrtype>, and <unicast-address> forms a
11326  * globally unique identifier for the session.
11327  * I.e. all except the <sess-version> */
11328  ast_copy_string(unique, o, sizeof(unique)); /* copy all of o= contents */
11329  offset = (o_copy - o_copy_start); /* after sess-version */
11330  if (offset < sizeof(unique)) {
11331  /* copy all after sess-version on top of sess-version */
11332  int sess_version_start = token - o_copy_start;
11333  ast_copy_string(unique + sess_version_start, o + offset, sizeof(unique) - sess_version_start);
11334  }
11335 
11336  /* We need to check the SDP version number the other end sent us;
11337  * our rules for deciding what to accept are a bit complex.
11338  *
11339  * 1) if 'ignoresdpversion' has been set for this dialog, then
11340  * we will just accept whatever they sent and assume it is
11341  * a modification of the session, even if it is not
11342  * 2) otherwise, if this is the first SDP we've seen from them
11343  * we accept it;
11344  * note that _them_ may change, in which case the
11345  * sessionunique_remote will be different
11346  * 3) otherwise, if the new SDP version number is higher than the
11347  * old one, we accept it
11348  * 4) otherwise, if this SDP is in response to us requesting a switch
11349  * to T.38, we accept the SDP, but also generate a warning message
11350  * that this peer should have the 'ignoresdpversion' option set,
11351  * because it is not following the SDP offer/answer RFC; if we did
11352  * not request a switch to T.38, then we stop parsing the SDP, as it
11353  * has not changed from the previous version
11354  */
11355  if (sip_debug_test_pvt(p)) {
11357  ast_verbose("Got SDP version %" PRId64 " and unique parts [%s]\n",
11358  sess_version, unique);
11359  } else {
11360  ast_verbose("Comparing SDP version %" PRId64 " -> %" PRId64 " and unique parts [%s] -> [%s]\n",
11361  p->sessionversion_remote, sess_version, p->sessionunique_remote, unique);
11362  }
11363  }
11364 
11366  sess_version > p->sessionversion_remote ||
11367  strcmp(unique, S_OR(p->sessionunique_remote, ""))) {
11368  p->sessionversion_remote = sess_version;
11369  ast_string_field_set(p, sessionunique_remote, unique);
11370  } else {
11371  if (p->t38.state == T38_LOCAL_REINVITE) {
11372  p->sessionversion_remote = sess_version;
11373  ast_string_field_set(p, sessionunique_remote, unique);
11374  ast_log(LOG_WARNING, "Call %s responded to our T.38 reinvite without changing SDP version; 'ignoresdpversion' should be set for this peer.\n", p->callid);
11375  } else {
11376  p->session_modify = FALSE;
11377  ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
11378  return FALSE;
11379  }
11380  }
11381 
11382  return TRUE;
11383 }
11384 
11385 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
11386 {
11387  char proto[4], host[258];
11388  int af;
11389 
11390  /* Check for Media-description-level-address */
11391  if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
11392  if (!strcmp("IP4", proto)) {
11393  af = AF_INET;
11394  } else if (!strcmp("IP6", proto)) {
11395  af = AF_INET6;
11396  } else {
11397  ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
11398  return FALSE;
11399  }
11400  if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
11401  ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
11402  return FALSE;
11403  }
11404  return TRUE;
11405  } else {
11406  ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
11407  return FALSE;
11408  }
11409  return FALSE;
11410 }
11411 
11412 static int process_sdp_a_sendonly(const char *a, int *sendonly)
11413 {
11414  int found = FALSE;
11415 
11416  if (!strcasecmp(a, "sendonly")) {
11417  if (*sendonly == -1)
11418  *sendonly = 1;
11419  found = TRUE;
11420  } else if (!strcasecmp(a, "inactive")) {
11421  if (*sendonly == -1)
11422  *sendonly = 2;
11423  found = TRUE;
11424  } else if (!strcasecmp(a, "sendrecv")) {
11425  if (*sendonly == -1)
11426  *sendonly = 0;
11427  found = TRUE;
11428  }
11429  return found;
11430 }
11431 
11432 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance, int rtcp_mux_offered)
11433 {
11434  struct ast_rtp_engine_ice *ice;
11435  int found = FALSE;
11436  char ufrag[256], pwd[256], foundation[33], transport[4], address[46], cand_type[6], relay_address[46] = "";
11437  struct ast_rtp_engine_ice_candidate candidate = { 0, };
11438  unsigned int port, relay_port = 0;
11439 
11440  if (!instance || !(ice = ast_rtp_instance_get_ice(instance))) {
11441  return found;
11442  }
11443 
11444  if (sscanf(a, "ice-ufrag: %255s", ufrag) == 1) {
11445  ice->set_authentication(instance, ufrag, NULL);
11446  found = TRUE;
11447  } else if (sscanf(a, "ice-pwd: %255s", pwd) == 1) {
11448  ice->set_authentication(instance, NULL, pwd);
11449  found = TRUE;
11450  } else if (sscanf(a, "candidate: %32s %30u %3s %30u %23s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport, (unsigned *)&candidate.priority,
11451  address, &port, cand_type, relay_address, &relay_port) >= 7) {
11452 
11453  if (rtcp_mux_offered && ast_test_flag(&p->flags[2], SIP_PAGE3_RTCP_MUX) && candidate.id > 1) {
11454  /* If we support RTCP-MUX and they offered it, don't consider RTCP candidates */
11455  return TRUE;
11456  }
11457 
11458  candidate.foundation = foundation;
11459  candidate.transport = transport;
11460 
11461  ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
11462  ast_sockaddr_set_port(&candidate.address, port);
11463 
11464  if (!strcasecmp(cand_type, "host")) {
11466  } else if (!strcasecmp(cand_type, "srflx")) {
11468  } else if (!strcasecmp(cand_type, "relay")) {
11470  } else {
11471  return found;
11472  }
11473 
11474  if (!ast_strlen_zero(relay_address)) {
11475  ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
11476  }
11477 
11478  if (relay_port) {
11479  ast_sockaddr_set_port(&candidate.relay_address, relay_port);
11480  }
11481 
11482  ice->add_remote_candidate(instance, &candidate);
11483 
11484  found = TRUE;
11485  } else if (!strcasecmp(a, "ice-lite")) {
11486  ice->ice_lite(instance);
11487  found = TRUE;
11488  }
11489 
11490  return found;
11491 }
11492 
11493 static int process_sdp_a_rtcp_mux(const char *a, struct sip_pvt *p, int *requested)
11494 {
11495  int found = FALSE;
11496 
11497  if (!strncasecmp(a, "rtcp-mux", 8)) {
11498  *requested = TRUE;
11499  found = TRUE;
11500  }
11501 
11502  return found;
11503 }
11504 
11505 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
11506 {
11507  struct ast_rtp_engine_dtls *dtls;
11508  int found = FALSE;
11509  char value[256], hash[32];
11510 
11511  if (!instance || !p->dtls_cfg.enabled || !(dtls = ast_rtp_instance_get_dtls(instance))) {
11512  return found;
11513  }
11514 
11515  if (sscanf(a, "setup: %255s", value) == 1) {
11516  found = TRUE;
11517 
11518  if (!strcasecmp(value, "active")) {
11519  dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTIVE);
11520  } else if (!strcasecmp(value, "passive")) {
11521  dtls->set_setup(instance, AST_RTP_DTLS_SETUP_PASSIVE);
11522  } else if (!strcasecmp(value, "actpass")) {
11523  dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTPASS);
11524  } else if (!strcasecmp(value, "holdconn")) {
11525  dtls->set_setup(instance, AST_RTP_DTLS_SETUP_HOLDCONN);
11526  } else {
11527  ast_log(LOG_WARNING, "Unsupported setup attribute value '%s' received on dialog '%s'\n",
11528  value, p->callid);
11529  }
11530  } else if (sscanf(a, "connection: %255s", value) == 1) {
11531  found = TRUE;
11532 
11533  if (!strcasecmp(value, "new")) {
11534  dtls->reset(instance);
11535  } else if (!strcasecmp(value, "existing")) {
11536  /* Since they want to just use what already exists we go on as if nothing happened */
11537  } else {
11538  ast_log(LOG_WARNING, "Unsupported connection attribute value '%s' received on dialog '%s'\n",
11539  value, p->callid);
11540  }
11541  } else if (sscanf(a, "fingerprint: %31s %255s", hash, value) == 2) {
11542  found = TRUE;
11543 
11544  if (!strcasecmp(hash, "sha-1")) {
11545  dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA1, value);
11546  } else if (!strcasecmp(hash, "sha-256")) {
11547  dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA256, value);
11548  } else {
11549  ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s' received on dialog '%s'\n",
11550  hash, p->callid);
11551  }
11552  }
11553 
11554  return found;
11555 }
11556 
11557 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
11558 {
11559  int found = FALSE;
11560  unsigned int codec;
11561  char mimeSubtype[128];
11562  char fmtp_string[256];
11563  unsigned int sample_rate;
11564  int debug = sip_debug_test_pvt(p);
11565 
11566  if (!strncasecmp(a, "ptime", 5)) {
11567  char *tmp = strrchr(a, ':');
11568  long int framing = 0;
11569  if (tmp) {
11570  tmp++;
11571  framing = strtol(tmp, NULL, 10);
11572  if (framing == LONG_MIN || framing == LONG_MAX) {
11573  framing = 0;
11574  ast_debug(1, "Can't read framing from SDP: %s\n", a);
11575  }
11576  }
11577 
11578  if (framing && p->autoframing) {
11579  ast_debug(1, "Setting framing to %ld\n", framing);
11580  ast_format_cap_set_framing(p->caps, framing);
11581  ast_rtp_codecs_set_framing(newaudiortp, framing);
11582  }
11583  found = TRUE;
11584  } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11585  /* We have a rtpmap to handle */
11586  if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11587  if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
11588  ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
11589  if (debug)
11590  ast_verbose("Found audio description format %s for ID %u\n", mimeSubtype, codec);
11591  //found_rtpmap_codecs[last_rtpmap_codec] = codec;
11592  (*last_rtpmap_codec)++;
11593  found = TRUE;
11594  } else {
11595  ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11596  if (debug)
11597  ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
11598  }
11599  } else {
11600  if (debug)
11601  ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
11602  }
11603  } else if (sscanf(a, "fmtp: %30u %255[^\t\n]", &codec, fmtp_string) == 2) {
11604  struct ast_format *format;
11605 
11606  if ((format = ast_rtp_codecs_get_payload_format(newaudiortp, codec))) {
11607  unsigned int bit_rate;
11608  struct ast_format *format_parsed;
11609 
11610  format_parsed = ast_format_parse_sdp_fmtp(format, fmtp_string);
11611  if (format_parsed) {
11612  ast_rtp_codecs_payload_replace_format(newaudiortp, codec, format_parsed);
11613  ao2_replace(format, format_parsed);
11614  ao2_ref(format_parsed, -1);
11615  found = TRUE;
11616  } else {
11617  ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11618  }
11619 
11621  if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11622  if (bit_rate != 64000) {
11623  ast_log(LOG_WARNING, "Got G.719 offer at %u bps, but only 64000 bps supported; ignoring.\n", bit_rate);
11624  ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11625  } else {
11626  found = TRUE;
11627  }
11628  }
11629  }
11630  ao2_ref(format, -1);
11631  }
11632  }
11633 
11634  return found;
11635 }
11636 
11637 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
11638 {
11639  int found = FALSE;
11640  unsigned int codec;
11641  char mimeSubtype[128];
11642  unsigned int sample_rate;
11643  int debug = sip_debug_test_pvt(p);
11644  char fmtp_string[256];
11645 
11646  if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11647  /* We have a rtpmap to handle */
11648  if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11649  /* Note: should really look at the '#chans' params too */
11650  if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)
11651  || !strncasecmp(mimeSubtype, "VP8", 3)) {
11652  if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
11653  if (debug)
11654  ast_verbose("Found video description format %s for ID %u\n", mimeSubtype, codec);
11655  //found_rtpmap_codecs[last_rtpmap_codec] = codec;
11656  (*last_rtpmap_codec)++;
11657  found = TRUE;
11658  } else {
11659  ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
11660  if (debug)
11661  ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
11662  }
11663  }
11664  } else {
11665  if (debug)
11666  ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
11667  }
11668  } else if (sscanf(a, "fmtp: %30u %255[^\t\n]", &codec, fmtp_string) == 2) {
11669  struct ast_format *format;
11670 
11671  if ((format = ast_rtp_codecs_get_payload_format(newvideortp, codec))) {
11672  struct ast_format *format_parsed;
11673 
11674  format_parsed = ast_format_parse_sdp_fmtp(format, fmtp_string);
11675 
11676  if (format_parsed) {
11677  ast_rtp_codecs_payload_replace_format(newvideortp, codec, format_parsed);
11678  ao2_replace(format, format_parsed);
11679  ao2_ref(format_parsed, -1);
11680  found = TRUE;
11681  } else {
11682  ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
11683  }
11684  ao2_ref(format, -1);
11685  }
11686  }
11687 
11688  return found;
11689 }
11690 
11691 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec)
11692 {
11693  int found = FALSE;
11694  unsigned int codec;
11695  char mimeSubtype[128];
11696  unsigned int sample_rate;
11697  char *red_cp;
11698  int debug = sip_debug_test_pvt(p);
11699 
11700  if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11701  /* We have a rtpmap to handle */
11702  if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11703  if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
11704  if (p->trtp) {
11705  /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
11706  ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
11707  found = TRUE;
11708  }
11709  } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
11710  if (p->trtp) {
11711  ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
11712  sprintf(red_fmtp, "fmtp:%u ", codec);
11713  if (debug)
11714  ast_verbose("RED submimetype has payload type: %u\n", codec);
11715  found = TRUE;
11716  }
11717  }
11718  } else {
11719  if (debug)
11720  ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
11721  }
11722  } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
11723  char *rest = NULL;
11724  /* count numbers of generations in fmtp */
11725  red_cp = &red_fmtp[strlen(red_fmtp)];
11726  strncpy(red_fmtp, a, 100);
11727 
11728  sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
11729  red_cp = strtok_r(red_cp, "/", &rest);
11730  while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
11731  sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
11732  red_cp = strtok_r(NULL, "/", &rest);
11733  }
11734  red_cp = red_fmtp;
11735  found = TRUE;
11736  }
11737 
11738  return found;
11739 }
11740 
11741 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
11742 {
11743  int found = FALSE;
11744  char s[256];
11745  unsigned int x;
11746  char *attrib = ast_strdupa(a);
11747  char *pos;
11748 
11749  if (initialize_udptl(p)) {
11750  return found;
11751  }
11752 
11753  /* Due to a typo in an IANA registration of one of the T.38 attributes,
11754  * RFC5347 section 2.5.2 recommends that all T.38 attributes be parsed in
11755  * a case insensitive manner. Hence, the importance of proof reading (and
11756  * code reviews).
11757  */
11758  for (pos = attrib; *pos; ++pos) {
11759  *pos = tolower(*pos);
11760  }
11761 
11762  if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
11763  ast_debug(3, "MaxBufferSize:%u\n", x);
11764  found = TRUE;
11765  } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
11766  ast_debug(3, "T38MaxBitRate: %u\n", x);
11767  switch (x) {
11768  case 14400:
11770  break;
11771  case 12000:
11773  break;
11774  case 9600:
11776  break;
11777  case 7200:
11779  break;
11780  case 4800:
11782  break;
11783  case 2400:
11785  break;
11786  }
11787  found = TRUE;
11788  } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
11789  ast_debug(3, "FaxVersion: %u\n", x);
11790  p->t38.their_parms.version = x;
11791  found = TRUE;
11792  } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
11793  /* override the supplied value if the configuration requests it */
11794  if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
11795  ast_debug(1, "Overriding T38FaxMaxDatagram '%u' with '%d'\n", x, p->t38_maxdatagram);
11796  x = p->t38_maxdatagram;
11797  }
11798  ast_debug(3, "FaxMaxDatagram: %u\n", x);
11800  found = TRUE;
11801  } else if ((strncmp(attrib, "t38faxfillbitremoval", sizeof("t38faxfillbitremoval") - 1) == 0)) {
11802  if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
11803  ast_debug(3, "FillBitRemoval: %u\n", x);
11804  if (x == 1) {
11806  }
11807  } else {
11808  ast_debug(3, "FillBitRemoval\n");
11810  }
11811  found = TRUE;
11812  } else if ((strncmp(attrib, "t38faxtranscodingmmr", sizeof("t38faxtranscodingmmr") - 1) == 0)) {
11813  if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
11814  ast_debug(3, "Transcoding MMR: %u\n", x);
11815  if (x == 1) {
11817  }
11818  } else {
11819  ast_debug(3, "Transcoding MMR\n");
11821  }
11822  found = TRUE;
11823  } else if ((strncmp(attrib, "t38faxtranscodingjbig", sizeof("t38faxtranscodingjbig") - 1) == 0)) {
11824  if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
11825  ast_debug(3, "Transcoding JBIG: %u\n", x);
11826  if (x == 1) {
11828  }
11829  } else {
11830  ast_debug(3, "Transcoding JBIG\n");
11832  }
11833  found = TRUE;
11834  } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
11835  ast_debug(3, "RateManagement: %s\n", s);
11836  if (!strcasecmp(s, "localTCF"))
11838  else if (!strcasecmp(s, "transferredTCF"))
11840  found = TRUE;
11841  } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
11842  ast_debug(3, "UDP EC: %s\n", s);
11843  if (!strcasecmp(s, "t38UDPRedundancy")) {
11845  } else if (!strcasecmp(s, "t38UDPFEC")) {
11847  } else {
11849  }
11850  found = TRUE;
11851  }
11852 
11853  return found;
11854 }
11855 
11856 /*! \brief Add "Supported" header to sip message. Since some options may
11857  * be disabled in the config, the sip_pvt must be inspected to determine what
11858  * is supported for this dialog. */
11859 static int add_supported(struct sip_pvt *pvt, struct sip_request *req)
11860 {
11861  char supported_value[SIPBUFSIZE];
11862  int res;
11863 
11864  sprintf(supported_value, "replaces%s%s",
11865  (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) ? ", timer" : "",
11866  ast_test_flag(&pvt->flags[0], SIP_USEPATH) ? ", path" : "");
11867  res = add_header(req, "Supported", supported_value);
11868 
11869  return res;
11870 }
11871 
11872 /*! \brief Add header to SIP message */
11873 static int add_header(struct sip_request *req, const char *var, const char *value)
11874 {
11875  if (req->headers == SIP_MAX_HEADERS) {
11876  ast_log(LOG_WARNING, "Out of SIP header space\n");
11877  return -1;
11878  }
11879 
11880  if (req->lines) {
11881  ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
11882  return -1;
11883  }
11884 
11885  if (sip_cfg.compactheaders) {
11886  var = find_alias(var, var);
11887  }
11888 
11889  ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
11890  req->header[req->headers] = ast_str_strlen(req->data);
11891 
11892  req->headers++;
11893 
11894  return 0;
11895 }
11896 
11897 /*!
11898  * \pre dialog is assumed to be locked while calling this function
11899  * \brief Add 'Max-Forwards' header to SIP message
11900  */
11901 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
11902 {
11903  char clen[10];
11904 
11905  snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
11906 
11907  return add_header(req, "Max-Forwards", clen);
11908 }
11909 
11910 /*! \brief Add 'Content-Length' header and content to SIP message */
11911 static int finalize_content(struct sip_request *req)
11912 {
11913  char clen[10];
11914 
11915  if (req->lines) {
11916  ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
11917  return -1;
11918  }
11919 
11920  snprintf(clen, sizeof(clen), "%zu", ast_str_strlen(req->content));
11921  add_header(req, "Content-Length", clen);
11922 
11923  if (ast_str_strlen(req->content)) {
11924  ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
11925  }
11926  req->lines = ast_str_strlen(req->content) ? 1 : 0;
11927  return 0;
11928 }
11929 
11930 /*! \brief Add content (not header) to SIP message */
11931 static int add_content(struct sip_request *req, const char *line)
11932 {
11933  if (req->lines) {
11934  ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
11935  return -1;
11936  }
11937 
11938  ast_str_append(&req->content, 0, "%s", line);
11939  return 0;
11940 }
11941 
11942 /*! \brief Copy one header field from one request to another */
11943 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
11944 {
11945  const char *tmp = sip_get_header(orig, field);
11946 
11947  if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
11948  return add_header(req, field, tmp);
11949  ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
11950  return -1;
11951 }
11952 
11953 /*! \brief Copy all headers from one request to another */
11954 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
11955 {
11956  int start = 0;
11957  int copied = 0;
11958  for (;;) {
11959  const char *tmp = __get_header(orig, field, &start);
11960 
11961  if (ast_strlen_zero(tmp))
11962  break;
11963  /* Add what we're responding to */
11964  add_header(req, field, tmp);
11965  copied++;
11966  }
11967  return copied ? 0 : -1;
11968 }
11969 
11970 /*! \brief Copy SIP VIA Headers from the request to the response
11971 \note If the client indicates that it wishes to know the port we received from,
11972  it adds ;rport without an argument to the topmost via header. We need to
11973  add the port number (from our point of view) to that parameter.
11974 \verbatim
11975  We always add ;received=<ip address> to the topmost via header.
11976 \endverbatim
11977  Received: RFC 3261, rport RFC 3581 */
11978 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
11979 {
11980  int copied = 0;
11981  int start = 0;
11982 
11983  for (;;) {
11984  char new[512];
11985  const char *oh = __get_header(orig, field, &start);
11986 
11987  if (ast_strlen_zero(oh))
11988  break;
11989 
11990  if (!copied) { /* Only check for empty rport in topmost via header */
11991  char leftmost[512], *others, *rport;
11992 
11993  /* Only work on leftmost value */
11994  ast_copy_string(leftmost, oh, sizeof(leftmost));
11995  others = strchr(leftmost, ',');
11996  if (others)
11997  *others++ = '\0';
11998 
11999  /* Find ;rport; (empty request) */
12000  rport = strstr(leftmost, ";rport");
12001  if (rport && *(rport+6) == '=')
12002  rport = NULL; /* We already have a parameter to rport */
12003 
12004  if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
12005  /* We need to add received port - rport */
12006  char *end;
12007 
12008  rport = strstr(leftmost, ";rport");
12009 
12010  if (rport) {
12011  end = strchr(rport + 1, ';');
12012  if (end)
12013  memmove(rport, end, strlen(end) + 1);
12014  else
12015  *rport = '\0';
12016  }
12017 
12018  /* Add rport to first VIA header if requested */
12019  snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
12021  ast_sockaddr_port(&p->recv),
12022  others ? "," : "", others ? others : "");
12023  } else {
12024  /* We should *always* add a received to the topmost via */
12025  snprintf(new, sizeof(new), "%s;received=%s%s%s",
12027  others ? "," : "", others ? others : "");
12028  }
12029  oh = new; /* the header to copy */
12030  } /* else add the following via headers untouched */
12031  add_header(req, field, oh);
12032  copied++;
12033  }
12034  if (!copied) {
12035  ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
12036  return -1;
12037  }
12038  return 0;
12039 }
12040 
12041 /*! \brief Add route header into request per learned route */
12042 static void add_route(struct sip_request *req, struct sip_route *route, int skip)
12043 {
12044  struct ast_str *r;
12045 
12046  if (sip_route_empty(route)) {
12047  return;
12048  }
12049 
12050  if ((r = sip_route_list(route, 0, skip))) {
12051  if (ast_str_strlen(r)) {
12052  add_header(req, "Route", ast_str_buffer(r));
12053  }
12054  ast_free(r);
12055  }
12056 }
12057 
12058 /*! \brief Set destination from SIP URI
12059  *
12060  * Parse uri to h (host) and port - uri is already just the part inside the <>
12061  * general form we are expecting is \verbatim sip[s]:username[:password][;parameter]@host[:port][;...] \endverbatim
12062  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
12063  * for SIP: uri's
12064  *
12065  * If there's a sips: uri scheme, TLS will be required.
12066  */
12067 static void set_destination(struct sip_pvt *p, const char *uri)
12068 {
12069  char *trans, *maddr, hostname[256];
12070  const char *h;
12071  int hn;
12072  int debug=sip_debug_test_pvt(p);
12073  int tls_on = FALSE;
12074 
12075  if (debug)
12076  ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
12077 
12078  if ((trans = strcasestr(uri, ";transport="))) {
12079  trans += strlen(";transport=");
12080 
12081  if (!strncasecmp(trans, "ws", 2)) {
12082  if (debug)
12083  ast_verbose("set_destination: URI is for WebSocket, we can't set destination\n");
12084  return;
12085  }
12086  }
12087 
12088  /* Find and parse hostname */
12089  h = strchr(uri, '@');
12090  if (h)
12091  ++h;
12092  else {
12093  h = uri;
12094  if (!strncasecmp(h, "sip:", 4)) {
12095  h += 4;
12096  } else if (!strncasecmp(h, "sips:", 5)) {
12097  h += 5;
12098  tls_on = TRUE;
12099  }
12100  }
12101  hn = strcspn(h, ";>") + 1;
12102  if (hn > sizeof(hostname))
12103  hn = sizeof(hostname);
12104  ast_copy_string(hostname, h, hn);
12105  /* XXX bug here if string has been trimmed to sizeof(hostname) */
12106  h += hn - 1;
12107 
12108  /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
12109  * otherwise, just look for A records */
12110  if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
12111  ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
12112  return;
12113  }
12114 
12115  /* Got the hostname - but maybe there's a "maddr=" to override address? */
12116  maddr = strstr(h, "maddr=");
12117  if (maddr) {
12118  int port;
12119 
12120  maddr += 6;
12121  hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
12122  "0123456789-.:[]") + 1;
12123  if (hn > sizeof(hostname))
12124  hn = sizeof(hostname);
12125  ast_copy_string(hostname, maddr, hn);
12126 
12127  port = ast_sockaddr_port(&p->sa);
12128 
12129  /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
12130  * NAPTR/SRV, otherwise, just look for A records */
12132  ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
12133  return;
12134  }
12135 
12136  ast_sockaddr_set_port(&p->sa, port);
12137  }
12138 
12139  if (!ast_sockaddr_port(&p->sa)) {
12140  ast_sockaddr_set_port(&p->sa, tls_on ?
12142  }
12143 
12144  if (debug) {
12145  ast_verbose("set_destination: set destination to %s\n",
12146  ast_sockaddr_stringify(&p->sa));
12147  }
12148 }
12149 
12150 /*! \brief Initialize SIP response, based on SIP request */
12151 static int init_resp(struct sip_request *resp, const char *msg)
12152 {
12153  /* Initialize a response */
12154  memset(resp, 0, sizeof(*resp));
12155  resp->method = SIP_RESPONSE;
12156  if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
12157  goto e_return;
12158  if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
12159  goto e_free_data;
12160  resp->header[0] = 0;
12161  ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
12162  resp->headers++;
12163  return 0;
12164 
12165 e_free_data:
12166  ast_free(resp->data);
12167  resp->data = NULL;
12168 e_return:
12169  return -1;
12170 }
12171 
12172 /*! \brief Initialize SIP request */
12173 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
12174 {
12175  /* Initialize a request */
12176  memset(req, 0, sizeof(*req));
12177  if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
12178  goto e_return;
12179  if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
12180  goto e_free_data;
12181  req->method = sipmethod;
12182  req->header[0] = 0;
12183  ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
12184  req->headers++;
12185  return 0;
12186 
12187 e_free_data:
12188  ast_free(req->data);
12189  req->data = NULL;
12190 e_return:
12191  return -1;
12192 }
12193 
12194 /*! \brief Deinitialize SIP response/request */
12195 static void deinit_req(struct sip_request *req)
12196 {
12197  if (req->data) {
12198  ast_free(req->data);
12199  req->data = NULL;
12200  }
12201  if (req->content) {
12202  ast_free(req->content);
12203  req->content = NULL;
12204  }
12205 }
12206 
12207 
12208 /*! \brief Test if this response needs a contact header */
12209 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
12210  /* Requirements for Contact header inclusion in responses generated
12211  * from the header tables found in the following RFCs. Where the
12212  * Contact header was marked mandatory (m) or optional (o) this
12213  * function returns 1.
12214  *
12215  * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
12216  * - RFC 2976 (INFO)
12217  * - RFC 3262 (PRACK)
12218  * - RFC 3265 (SUBSCRIBE, NOTIFY)
12219  * - RFC 3311 (UPDATE)
12220  * - RFC 3428 (MESSAGE)
12221  * - RFC 3515 (REFER)
12222  * - RFC 3903 (PUBLISH)
12223  */
12224 
12225  switch (method) {
12226  /* 1xx, 2xx, 3xx, 485 */
12227  case SIP_INVITE:
12228  case SIP_UPDATE:
12229  case SIP_SUBSCRIBE:
12230  case SIP_NOTIFY:
12231  if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
12232  return 1;
12233  break;
12234 
12235  /* 2xx, 3xx, 485 */
12236  case SIP_REGISTER:
12237  case SIP_OPTIONS:
12238  if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
12239  return 1;
12240  break;
12241 
12242  /* 3xx, 485 */
12243  case SIP_BYE:
12244  case SIP_PRACK:
12245  case SIP_MESSAGE:
12246  case SIP_PUBLISH:
12247  if (msg[0] == '3' || !strncmp(msg, "485", 3))
12248  return 1;
12249  break;
12250 
12251  /* 2xx, 3xx, 4xx, 5xx, 6xx */
12252  case SIP_REFER:
12253  if (msg[0] >= '2' && msg[0] <= '6')
12254  return 1;
12255  break;
12256 
12257  /* contact will not be included for everything else */
12258  case SIP_ACK:
12259  case SIP_CANCEL:
12260  case SIP_INFO:
12261  case SIP_PING:
12262  default:
12263  return 0;
12264  }
12265  return 0;
12266 }
12267 
12268 /*! \brief Prepare SIP response packet */
12269 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
12270 {
12271  char newto[256];
12272  const char *ot;
12273 
12274  init_resp(resp, msg);
12275  copy_via_headers(p, resp, req, "Via");
12276  if (msg[0] == '1' || msg[0] == '2')
12277  copy_all_header(resp, req, "Record-Route");
12278  copy_header(resp, req, "From");
12279  ot = sip_get_header(req, "To");
12280  if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
12281  /* Add the proper tag if we don't have it already. If they have specified
12282  their tag, use it. Otherwise, use our own tag */
12284  snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
12285  else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
12286  snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
12287  else
12288  ast_copy_string(newto, ot, sizeof(newto));
12289  ot = newto;
12290  }
12291  add_header(resp, "To", ot);
12292  copy_header(resp, req, "Call-ID");
12293  copy_header(resp, req, "CSeq");
12295  add_header(resp, "Server", global_useragent);
12296  add_header(resp, "Allow", ALLOWED_METHODS);
12297  add_supported(p, resp);
12298 
12299  /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
12300  if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
12301  char se_hdr[256];
12302  snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
12303  p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
12304  add_header(resp, "Session-Expires", se_hdr);
12305  /* RFC 2048, Section 9
12306  * If the refresher parameter in the Session-Expires header field in the
12307  * 2xx response has a value of 'uac', the UAS MUST place a Require
12308  * header field into the response with the value 'timer'.
12309  * ...
12310  * If the refresher parameter in
12311  * the 2xx response has a value of 'uas' and the Supported header field
12312  * in the request contained the value 'timer', the UAS SHOULD place a
12313  * Require header field into the response with the value 'timer'
12314  */
12317  p->stimer->st_active_peer_ua == TRUE)) {
12318  resp->reqsipoptions |= SIP_OPT_TIMER;
12319  }
12320  }
12321 
12322  if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
12323  /* For registration responses, we also need expiry and
12324  contact info */
12325  add_expires(resp, p->expiry);
12326  if (p->expiry) { /* Only add contact if we have an expiry time */
12327  char contact[SIPBUFSIZE];
12328  const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
12329  char *brackets = strchr(contact_uri, '<');
12330  snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
12331  add_header(resp, "Contact", contact); /* Not when we unregister */
12332  }
12333  if (p->method == SIP_REGISTER && ast_test_flag(&p->flags[0], SIP_USEPATH)) {
12334  copy_header(resp, req, "Path");
12335  }
12336  } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
12337  add_header(resp, "Contact", p->our_contact);
12338  }
12339 
12340  if (!ast_strlen_zero(p->url)) {
12341  add_header(resp, "Access-URL", p->url);
12343  }
12344 
12345  /* default to routing the response to the address where the request
12346  * came from. Since we don't have a transport layer, we do this here.
12347  * The process_via() function will update the port to either the port
12348  * specified in the via header or the default port later on (per RFC
12349  * 3261 section 18.2.2).
12350  */
12351  p->sa = p->recv;
12352 
12353  if (process_via(p, req)) {
12354  ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
12355  }
12356 
12357  return 0;
12358 }
12359 
12360 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
12361 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
12362 {
12363  struct sip_request *orig = &p->initreq;
12364  char stripped[80];
12365  char tmp[80];
12366  char newto[256];
12367  const char *c;
12368  const char *ot, *of;
12369  int is_strict = FALSE; /*!< Strict routing flag */
12370  int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING); /* Session direction */
12371 
12372  snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
12373 
12374  if (!seqno) {
12375  p->ocseq++;
12376  seqno = p->ocseq;
12377  }
12378 
12379  /* A CANCEL must have the same branch as the INVITE that it is canceling. */
12380  if (sipmethod == SIP_CANCEL) {
12381  p->branch = p->invite_branch;
12382  build_via(p);
12383  } else if (newbranch && (sipmethod == SIP_INVITE)) {
12384  p->branch ^= ast_random();
12385  p->invite_branch = p->branch;
12386  build_via(p);
12387  } else if (newbranch) {
12388  p->branch ^= ast_random();
12389  build_via(p);
12390  }
12391 
12392  /* Check for strict or loose router */
12393  if (sip_route_is_strict(&p->route)) {
12394  is_strict = TRUE;
12395  if (sipdebug)
12396  ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
12397  }
12398 
12399  if (sipmethod == SIP_CANCEL) {
12400  c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2); /* Use original URI */
12401  } else if (sipmethod == SIP_ACK) {
12402  /* Use URI from Contact: in 200 OK (if INVITE)
12403  (we only have the contacturi on INVITEs) */
12404  if (!ast_strlen_zero(p->okcontacturi)) {
12405  c = is_strict ? sip_route_first_uri(&p->route) : p->okcontacturi;
12406  } else {
12407  c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
12408  }
12409  } else if (!ast_strlen_zero(p->okcontacturi)) {
12410  /* Use for BYE or REINVITE */
12411  c = is_strict ? sip_route_first_uri(&p->route) : p->okcontacturi;
12412  } else if (!ast_strlen_zero(p->uri)) {
12413  c = p->uri;
12414  } else {
12415  char *n;
12416  /* We have no URI, use To: or From: header as URI (depending on direction) */
12417  ast_copy_string(stripped, sip_get_header(orig, is_outbound ? "To" : "From"),
12418  sizeof(stripped));
12419  n = get_in_brackets(stripped);
12420  c = remove_uri_parameters(n);
12421  }
12422  init_req(req, sipmethod, c);
12423 
12424  snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
12425 
12426  add_header(req, "Via", p->via);
12427  /*
12428  * Use the learned route set unless this is a CANCEL or an ACK for a non-2xx
12429  * final response. For a CANCEL or ACK, we have to send to the same destination
12430  * as the original INVITE.
12431  * Send UPDATE to the same destination as CANCEL, if call is not in final state.
12432  */
12433  if (!sip_route_empty(&p->route) &&
12434  !(sipmethod == SIP_CANCEL ||
12435  (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)) ||
12436  (sipmethod == SIP_UPDATE && (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)))) {
12438  /* For TCP/TLS sockets that are connected we won't need
12439  * to do any hostname/IP lookups */
12440  } else if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
12441  /* For NATed traffic, we ignore the contact/route and
12442  * simply send to the received-from address. No need
12443  * for lookups. */
12444  } else {
12446  }
12447  add_route(req, &p->route, is_strict ? 1 : 0);
12448  }
12449  add_max_forwards(p, req);
12450 
12451  ot = sip_get_header(orig, "To");
12452  of = sip_get_header(orig, "From");
12453 
12454  /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
12455  as our original request, including tag (or presumably lack thereof) */
12456  if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
12457  /* Add the proper tag if we don't have it already. If they have specified
12458  their tag, use it. Otherwise, use our own tag */
12459  if (is_outbound && !ast_strlen_zero(p->theirtag))
12460  snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
12461  else if (!is_outbound)
12462  snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
12463  else
12464  snprintf(newto, sizeof(newto), "%s", ot);
12465  ot = newto;
12466  }
12467 
12468  if (is_outbound) {
12469  add_header(req, "From", of);
12470  add_header(req, "To", ot);
12471  } else {
12472  add_header(req, "From", ot);
12473  add_header(req, "To", of);
12474  }
12475  /* Do not add Contact for MESSAGE, BYE and Cancel requests */
12476  if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
12477  add_header(req, "Contact", p->our_contact);
12478 
12479  copy_header(req, orig, "Call-ID");
12480  add_header(req, "CSeq", tmp);
12481 
12483  add_header(req, "User-Agent", global_useragent);
12484 
12485  if (!ast_strlen_zero(p->url)) {
12486  add_header(req, "Access-URL", p->url);
12488  }
12489 
12490  /* Add Session-Timers related headers if the feature is active for this session.
12491  An exception to this behavior is the ACK request. Since Asterisk never requires
12492  session-timers support from a remote end-point (UAS) in an INVITE, it must
12493  not send 'Require: timer' header in the ACK request.
12494  This should only be added in the INVITE transactions, not MESSAGE or REFER or other
12495  in-dialog messages.
12496  */
12497  if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
12498  && sipmethod == SIP_INVITE) {
12499  char se_hdr[256];
12500  snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
12501  p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
12502  add_header(req, "Session-Expires", se_hdr);
12503  snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
12504  add_header(req, "Min-SE", se_hdr);
12505  }
12506 
12507  return 0;
12508 }
12509 
12510 /*! \brief Base transmit response function */
12511 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
12512 {
12513  struct sip_request resp;
12514  uint32_t seqno = 0;
12515 
12516  if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
12517  ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
12518  return -1;
12519  }
12520  respprep(&resp, p, msg, req);
12521 
12522  if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
12524  && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
12526  add_rpid(&resp, p);
12527  }
12528  if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12529  add_cc_call_info_to_response(p, &resp);
12530  }
12531 
12532  /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
12533  if (!strncmp(msg, "302", 3)) {
12534  add_diversion(&resp, p);
12535  }
12536 
12537  /* If we are cancelling an incoming invite for some reason, add information
12538  about the reason why we are doing this in clear text */
12539  if (p->method == SIP_INVITE && msg[0] != '1') {
12540  char buf[20];
12541 
12542  if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
12543  int hangupcause = 0;
12544 
12545  if (p->owner && ast_channel_hangupcause(p->owner)) {
12546  hangupcause = ast_channel_hangupcause(p->owner);
12547  } else if (p->hangupcause) {
12548  hangupcause = p->hangupcause;
12549  } else {
12550  int respcode;
12551  if (sscanf(msg, "%30d ", &respcode))
12552  hangupcause = hangup_sip2cause(respcode);
12553  }
12554 
12555  if (hangupcause) {
12556  sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
12557  add_header(&resp, "Reason", buf);
12558  }
12559  }
12560 
12561  if (p->owner && ast_channel_hangupcause(p->owner)) {
12562  add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(ast_channel_hangupcause(p->owner)));
12563  snprintf(buf, sizeof(buf), "%d", ast_channel_hangupcause(p->owner));
12564  add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12565  }
12566  }
12567  return send_response(p, &resp, reliable, seqno);
12568 }
12569 
12570 static int transmit_response_with_sip_etag(struct sip_pvt *p, const char *msg, const struct sip_request *req, struct sip_esc_entry *esc_entry, int need_new_etag)
12571 {
12572  struct sip_request resp;
12573 
12574  if (need_new_etag) {
12575  create_new_sip_etag(esc_entry, 1);
12576  }
12577  respprep(&resp, p, msg, req);
12578  add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
12579 
12580  return send_response(p, &resp, 0, 0);
12581 }
12582 
12583 static int temp_pvt_init(void *data)
12584 {
12585  struct sip_pvt *p = data;
12586 
12587  p->do_history = 0; /* XXX do we need it ? isn't already all 0 ? */
12588  return ast_string_field_init(p, 512);
12589 }
12590 
12591 static void temp_pvt_cleanup(void *data)
12592 {
12593  struct sip_pvt *p = data;
12594 
12596 
12597  ast_free(data);
12598 }
12599 
12600 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
12601 static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
12602 {
12603  struct sip_pvt *p = NULL;
12604 
12605  if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
12606  ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
12607  return -1;
12608  }
12609 
12610  /* XXX the structure may be dirty from previous usage.
12611  * Here we should state clearly how we should reinitialize it
12612  * before using it.
12613  * E.g. certainly the threadstorage should be left alone,
12614  * but other thihngs such as flags etc. maybe need cleanup ?
12615  */
12616 
12617  /* Initialize the bare minimum */
12618  p->method = intended_method;
12619 
12620  if (!addr) {
12622  } else {
12623  ast_sockaddr_copy(&p->sa, addr);
12624  ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
12625  }
12626 
12627  p->branch = ast_random();
12628  make_our_tag(p);
12629  p->ocseq = INITIAL_CSEQ;
12630 
12631  if (useglobal_nat && addr) {
12632  ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
12633  ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT);
12634  ast_sockaddr_copy(&p->recv, addr);
12635  check_via(p, req);
12636  }
12637 
12638  ast_string_field_set(p, fromdomain, default_fromdomain);
12640  build_via(p);
12641  ast_string_field_set(p, callid, callid);
12642 
12643  copy_socket_data(&p->socket, &req->socket);
12644 
12645  /* Use this temporary pvt structure to send the message */
12646  __transmit_response(p, msg, req, XMIT_UNRELIABLE);
12647 
12648  /* Free the string fields, but not the pool space */
12649  ast_string_field_init(p, 0);
12650 
12651  return 0;
12652 }
12653 
12654 /*! \brief Transmit response, no retransmits */
12655 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12656 {
12657  return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
12658 }
12659 
12660 /*! \brief Transmit response, no retransmits */
12661 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
12662 {
12663  struct sip_request resp;
12664  respprep(&resp, p, msg, req);
12665  add_date(&resp);
12666  add_header(&resp, "Unsupported", unsupported);
12667  return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12668 }
12669 
12670 /*! \brief Transmit 422 response with Min-SE header (Session-Timers) */
12671 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
12672 {
12673  struct sip_request resp;
12674  char minse_str[20];
12675 
12676  respprep(&resp, p, msg, req);
12677  add_date(&resp);
12678 
12679  snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
12680  add_header(&resp, "Min-SE", minse_str);
12681  return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12682 }
12683 
12684 
12685 /*! \brief Transmit response, Make sure you get an ACK
12686  This is only used for responses to INVITEs, where we need to make sure we get an ACK
12687 */
12688 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12689 {
12690  return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
12691 }
12692 
12693 /*! \brief Add date header to SIP message */
12694 static void add_date(struct sip_request *req)
12695 {
12696  char tmp[256];
12697  struct tm tm;
12698  time_t t = time(NULL);
12699 
12700  gmtime_r(&t, &tm);
12701  strftime(tmp, sizeof(tmp), "%a, %d %b %Y %T GMT", &tm);
12702  add_header(req, "Date", tmp);
12703 }
12704 
12705 /*! \brief Add Expires header to SIP message */
12706 static void add_expires(struct sip_request *req, int expires)
12707 {
12708  char tmp[32];
12709 
12710  snprintf(tmp, sizeof(tmp), "%d", expires);
12711  add_header(req, "Expires", tmp);
12712 }
12713 
12714 /*! \brief Append Retry-After header field when transmitting response */
12715 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
12716 {
12717  struct sip_request resp;
12718  respprep(&resp, p, msg, req);
12719  add_header(&resp, "Retry-After", seconds);
12720  return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12721 }
12722 
12723 /*! \brief Add date before transmitting response */
12724 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12725 {
12726  struct sip_request resp;
12727  respprep(&resp, p, msg, req);
12728  add_date(&resp);
12729  return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12730 }
12731 
12732 /*! \brief Append Accept header, content length before transmitting response */
12733 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
12734 {
12735  struct sip_request resp;
12736  respprep(&resp, p, msg, req);
12737  add_header(&resp, "Accept", "application/sdp");
12738  return send_response(p, &resp, reliable, 0);
12739 }
12740 
12741 /*! \brief Append Min-Expires header, content length before transmitting response */
12742 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minexpires)
12743 {
12744  struct sip_request resp;
12745  char tmp[32];
12746 
12747  snprintf(tmp, sizeof(tmp), "%d", minexpires);
12748  respprep(&resp, p, msg, req);
12749  add_header(&resp, "Min-Expires", tmp);
12750  return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12751 }
12752 
12753 /*! \brief Respond with authorization request */
12754 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *nonce, enum xmittype reliable, const char *header, int stale)
12755 {
12756  struct sip_request resp;
12757  char tmp[512];
12758  uint32_t seqno = 0;
12759 
12760  if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
12761  ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
12762  return -1;
12763  }
12764  /* Choose Realm */
12765  get_realm(p, req);
12766 
12767  /* Stale means that they sent us correct authentication, but
12768  based it on an old challenge (nonce) */
12769  snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, nonce, stale ? ", stale=true" : "");
12770  respprep(&resp, p, msg, req);
12771  add_header(&resp, header, tmp);
12772  append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
12773  return send_response(p, &resp, reliable, seqno);
12774 }
12775 
12776 /*!
12777  \brief Extract domain from SIP To/From header
12778  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
12779  \note TODO: Such code is all over SIP channel, there is a sense to organize
12780  this patern in one function
12781 */
12782 static int get_domain(const char *str, char *domain, int len)
12783 {
12784  char tmpf[256];
12785  char *a, *from;
12786 
12787  *domain = '\0';
12788  ast_copy_string(tmpf, str, sizeof(tmpf));
12789  from = get_in_brackets(tmpf);
12790  if (!ast_strlen_zero(from)) {
12791  if (strncasecmp(from, "sip:", 4)) {
12792  ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
12793  return -1;
12794  }
12795  from += 4;
12796  } else
12797  from = NULL;
12798 
12799  if (from) {
12800  int bracket = 0;
12801 
12802  /* Strip any params or options from user */
12803  if ((a = strchr(from, ';')))
12804  *a = '\0';
12805  /* Strip port from domain if present */
12806  for (a = from; *a != '\0'; ++a) {
12807  if (*a == ':' && bracket == 0) {
12808  *a = '\0';
12809  break;
12810  } else if (*a == '[') {
12811  ++bracket;
12812  } else if (*a == ']') {
12813  --bracket;
12814  }
12815  }
12816  if ((a = strchr(from, '@'))) {
12817  *a = '\0';
12818  ast_copy_string(domain, a + 1, len);
12819  } else
12820  ast_copy_string(domain, from, len);
12821  }
12822 
12823  return ast_strlen_zero(domain);
12824 }
12825 
12826 /*!
12827  \brief Choose realm based on From header and then To header or use globaly configured realm.
12828  Realm from From/To header should be listed among served domains in config file: domain=...
12829 */
12830 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
12831 {
12832  char domain[MAXHOSTNAMELEN];
12833 
12834  if (!ast_strlen_zero(p->realm))
12835  return;
12836 
12837  if (sip_cfg.domainsasrealm &&
12839  {
12840  /* Check From header first */
12841  if (!get_domain(sip_get_header(req, "From"), domain, sizeof(domain))) {
12842  if (check_sip_domain(domain, NULL, 0)) {
12843  ast_string_field_set(p, realm, domain);
12844  return;
12845  }
12846  }
12847  /* Check To header */
12848  if (!get_domain(sip_get_header(req, "To"), domain, sizeof(domain))) {
12849  if (check_sip_domain(domain, NULL, 0)) {
12850  ast_string_field_set(p, realm, domain);
12851  return;
12852  }
12853  }
12854  }
12855 
12856  /* Use default realm from config file */
12857  ast_string_field_set(p, realm, sip_cfg.realm);
12858 }
12859 
12860 /*!
12861  * \internal
12862  *
12863  * \arg msg Only use a string constant for the msg, here, it is shallow copied
12864  *
12865  * \note assumes the sip_pvt is locked.
12866  */
12867 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
12868 {
12869  int res;
12870 
12871  if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
12872  p->last_provisional = msg;
12873  update_provisional_keepalive(p, with_sdp);
12874  }
12875 
12876  return res;
12877 }
12878 
12879 /*!
12880  * \internal
12881  * \brief Destroy all additional MESSAGE headers.
12882  *
12883  * \param pvt SIP private dialog struct.
12884  *
12885  * \return Nothing
12886  */
12887 static void destroy_msg_headers(struct sip_pvt *pvt)
12888 {
12889  struct sip_msg_hdr *doomed;
12890 
12891  while ((doomed = AST_LIST_REMOVE_HEAD(&pvt->msg_headers, next))) {
12892  ast_free(doomed);
12893  }
12894 }
12895 
12896 /*!
12897  * \internal
12898  * \brief Add a MESSAGE header to the dialog.
12899  *
12900  * \param pvt SIP private dialog struct.
12901  * \param hdr_name Name of header for MESSAGE.
12902  * \param hdr_value Value of header for MESSAGE.
12903  *
12904  * \return Nothing
12905  */
12906 static void add_msg_header(struct sip_pvt *pvt, const char *hdr_name, const char *hdr_value)
12907 {
12908  size_t hdr_len_name;
12909  size_t hdr_len_value;
12910  struct sip_msg_hdr *node;
12911  char *pos;
12912 
12913  hdr_len_name = strlen(hdr_name) + 1;
12914  hdr_len_value = strlen(hdr_value) + 1;
12915 
12916  node = ast_calloc(1, sizeof(*node) + hdr_len_name + hdr_len_value);
12917  if (!node) {
12918  return;
12919  }
12920  pos = node->stuff;
12921  node->name = pos;
12922  strcpy(pos, hdr_name);
12923  pos += hdr_len_name;
12924  node->value = pos;
12925  strcpy(pos, hdr_value);
12926 
12927  AST_LIST_INSERT_TAIL(&pvt->msg_headers, node, next);
12928 }
12929 
12930 /*! \brief Add text body to SIP message */
12931 static int add_text(struct sip_request *req, struct sip_pvt *p)
12932 {
12933  const char *content_type = NULL;
12934  struct sip_msg_hdr *node;
12935 
12936  /* Add any additional MESSAGE headers. */
12937  AST_LIST_TRAVERSE(&p->msg_headers, node, next) {
12938  if (!strcasecmp(node->name, "Content-Type")) {
12939  /* Save content type */
12940  content_type = node->value;
12941  } else {
12942  add_header(req, node->name, node->value);
12943  }
12944  }
12945  if (ast_strlen_zero(content_type)) {
12946  /* "Content-Type" not set - use default value */
12947  content_type = "text/plain;charset=UTF-8";
12948  }
12949  add_header(req, "Content-Type", content_type);
12950 
12951  /* XXX Convert \n's to \r\n's XXX */
12952  add_content(req, p->msg_body);
12953  return 0;
12954 }
12955 
12956 /*! \brief Add DTMF INFO tone to sip message
12957  Mode = 0 for application/dtmf-relay (Cisco)
12958  1 for application/dtmf
12959 */
12960 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
12961 {
12962  char tmp[256];
12963  int event;
12964  if (mode) {
12965  /* Application/dtmf short version used by some implementations */
12966  if ('0' <= digit && digit <= '9') {
12967  event = digit - '0';
12968  } else if (digit == '*') {
12969  event = 10;
12970  } else if (digit == '#') {
12971  event = 11;
12972  } else if ('A' <= digit && digit <= 'D') {
12973  event = 12 + digit - 'A';
12974  } else if ('a' <= digit && digit <= 'd') {
12975  event = 12 + digit - 'a';
12976  } else {
12977  /* Unknown digit */
12978  event = 0;
12979  }
12980  snprintf(tmp, sizeof(tmp), "%d\r\n", event);
12981  add_header(req, "Content-Type", "application/dtmf");
12982  add_content(req, tmp);
12983  } else {
12984  /* Application/dtmf-relay as documented by Cisco */
12985  snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
12986  add_header(req, "Content-Type", "application/dtmf-relay");
12987  add_content(req, tmp);
12988  }
12989  return 0;
12990 }
12991 
12992 /*!
12993  * \pre if p->owner exists, it must be locked
12994  * \brief Add Remote-Party-ID header to SIP message
12995  */
12996 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
12997 {
12998  struct ast_str *tmp = ast_str_alloca(256);
12999  char tmp2[256];
13000  char lid_name_buf[128];
13001  char *lid_num;
13002  char *lid_name;
13003  int lid_pres;
13004  const char *fromdomain;
13005  const char *privacy = NULL;
13006  const char *screen = NULL;
13007  struct ast_party_id connected_id;
13008  const char *anonymous_string = "\"Anonymous\" <sip:[email protected]>";
13009 
13010  if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
13011  return 0;
13012  }
13013 
13014  if (!p->owner) {
13015  return 0;
13016  }
13017  connected_id = ast_channel_connected_effective_id(p->owner);
13018  lid_num = S_COR(connected_id.number.valid, connected_id.number.str, NULL);
13019  if (!lid_num) {
13020  return 0;
13021  }
13022  lid_name = S_COR(connected_id.name.valid, connected_id.name.str, NULL);
13023  if (!lid_name) {
13024  lid_name = lid_num;
13025  }
13026  ast_escape_quoted(lid_name, lid_name_buf, sizeof(lid_name_buf));
13027  lid_pres = ast_party_id_presentation(&connected_id);
13028 
13029  if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
13031  /* If pres is not allowed and we don't trust the peer, we don't apply an RPID header */
13032  return 0;
13033  }
13034 
13035  fromdomain = p->fromdomain;
13036  if (!fromdomain ||
13038  !strcmp("anonymous.invalid", fromdomain))) {
13039  /* If the fromdomain is NULL or if it was set to anonymous.invalid due to privacy settings and we trust the peer,
13040  * use the host IP address */
13041  fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
13042  }
13043 
13044  lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), ast_uri_sip_user);
13045 
13046  if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
13048  /* trust_id_outbound = yes - Always give full information even if it's private, but append a privacy header
13049  * When private data is included */
13050  ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
13051  if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
13052  add_header(req, "Privacy", "id");
13053  }
13054  } else {
13055  /* trust_id_outbound = legacy - behave in a non RFC-3325 compliant manner and send anonymized data when
13056  * when handling private data. */
13057  if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
13058  ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
13059  } else {
13060  ast_str_set(&tmp, -1, "%s", anonymous_string);
13061  }
13062  }
13063  add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
13064  } else {
13065  ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name_buf, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
13066 
13067  switch (lid_pres) {
13070  privacy = "off";
13071  screen = "no";
13072  break;
13075  privacy = "off";
13076  screen = "yes";
13077  break;
13080  privacy = "full";
13081  screen = "no";
13082  break;
13085  privacy = "full";
13086  screen = "yes";
13087  break;
13089  break;
13090  default:
13091  if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
13092  privacy = "full";
13093  }
13094  else
13095  privacy = "off";
13096  screen = "no";
13097  break;
13098  }
13099 
13100  if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
13101  ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
13102  }
13103 
13104  add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
13105  }
13106  return 0;
13107 }
13108 
13109 /*! \brief add XML encoded media control with update
13110  \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
13111 static int add_vidupdate(struct sip_request *req)
13112 {
13113  const char *xml_is_a_huge_waste_of_space =
13114  "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
13115  " <media_control>\r\n"
13116  " <vc_primitive>\r\n"
13117  " <to_encoder>\r\n"
13118  " <picture_fast_update>\r\n"
13119  " </picture_fast_update>\r\n"
13120  " </to_encoder>\r\n"
13121  " </vc_primitive>\r\n"
13122  " </media_control>\r\n";
13123  add_header(req, "Content-Type", "application/media_control+xml");
13124  add_content(req, xml_is_a_huge_waste_of_space);
13125  return 0;
13126 }
13127 
13128 /*! \brief Add ICE attributes to SDP */
13129 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
13130 {
13131  struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
13132  const char *username, *password;
13133  struct ao2_container *candidates;
13134  struct ao2_iterator i;
13135  struct ast_rtp_engine_ice_candidate *candidate;
13136 
13137  /* If no ICE support is present we can't very well add the attributes */
13138  if (!ice || !(candidates = ice->get_local_candidates(instance))) {
13139  return;
13140  }
13141 
13142  if ((username = ice->get_ufrag(instance))) {
13143  ast_str_append(a_buf, 0, "a=ice-ufrag:%s\r\n", username);
13144  }
13145  if ((password = ice->get_password(instance))) {
13146  ast_str_append(a_buf, 0, "a=ice-pwd:%s\r\n", password);
13147  }
13148 
13149  i = ao2_iterator_init(candidates, 0);
13150 
13151  while ((candidate = ao2_iterator_next(&i))) {
13152  ast_str_append(a_buf, 0, "a=candidate:%s %u %s %d ", candidate->foundation, candidate->id, candidate->transport, candidate->priority);
13153  ast_str_append(a_buf, 0, "%s ", ast_sockaddr_stringify_addr_remote(&candidate->address));
13154 
13155  ast_str_append(a_buf, 0, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
13156 
13157  if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
13158  ast_str_append(a_buf, 0, "host");
13159  } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
13160  ast_str_append(a_buf, 0, "srflx");
13161  } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
13162  ast_str_append(a_buf, 0, "relay");
13163  }
13164 
13165  if (!ast_sockaddr_isnull(&candidate->relay_address)) {
13166  ast_str_append(a_buf, 0, " raddr %s ", ast_sockaddr_stringify_addr_remote(&candidate->relay_address));
13167  ast_str_append(a_buf, 0, "rport %s", ast_sockaddr_stringify_port(&candidate->relay_address));
13168  }
13169 
13170  ast_str_append(a_buf, 0, "\r\n");
13171  ao2_ref(candidate, -1);
13172  }
13173 
13175 
13176  ao2_ref(candidates, -1);
13177 }
13178 
13179 /*! \brief Start ICE negotiation on an RTP instance */
13180 static void start_ice(struct ast_rtp_instance *instance, int offer)
13181 {
13182  struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
13183 
13184  if (!ice) {
13185  return;
13186  }
13187 
13188  /* If we are the offerer then we are the controlling agent, otherwise they are */
13190  ice->start(instance);
13191 }
13192 
13193 /*! \brief Add DTLS attributes to SDP */
13194 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
13195 {
13196  struct ast_rtp_engine_dtls *dtls;
13197  enum ast_rtp_dtls_hash hash;
13198  const char *fingerprint;
13199 
13200  if (!instance || !(dtls = ast_rtp_instance_get_dtls(instance)) || !dtls->active(instance)) {
13201  return;
13202  }
13203 
13204  switch (dtls->get_connection(instance)) {
13206  ast_str_append(a_buf, 0, "a=connection:new\r\n");
13207  break;
13209  ast_str_append(a_buf, 0, "a=connection:existing\r\n");
13210  break;
13211  default:
13212  break;
13213  }
13214 
13215  switch (dtls->get_setup(instance)) {
13217  ast_str_append(a_buf, 0, "a=setup:active\r\n");
13218  break;
13220  ast_str_append(a_buf, 0, "a=setup:passive\r\n");
13221  break;
13223  ast_str_append(a_buf, 0, "a=setup:actpass\r\n");
13224  break;
13226  ast_str_append(a_buf, 0, "a=setup:holdconn\r\n");
13227  break;
13228  default:
13229  break;
13230  }
13231 
13232  hash = dtls->get_fingerprint_hash(instance);
13233  fingerprint = dtls->get_fingerprint(instance);
13234  if (fingerprint && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
13235  ast_str_append(a_buf, 0, "a=fingerprint:%s %s\r\n", hash == AST_RTP_DTLS_HASH_SHA1 ? "SHA-1" : "SHA-256",
13236  fingerprint);
13237  }
13238 }
13239 
13240 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
13241 static void add_codec_to_sdp(const struct sip_pvt *p,
13242  struct ast_format *format,
13243  struct ast_str **m_buf,
13244  struct ast_str **a_buf,
13245  int debug,
13246  int *min_packet_size,
13247  int *max_packet_size)
13248 {
13249  int rtp_code;
13250  const char *mime;
13251  unsigned int rate, framing;
13252 
13253  if (debug)
13254  ast_verbose("Adding codec %s to SDP\n", ast_format_get_name(format));
13255 
13256  if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, format, 0)) == -1) ||
13258  !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
13259  return;
13260  }
13261 
13262  ast_str_append(m_buf, 0, " %d", rtp_code);
13263  /* Opus mandates 2 channels in rtpmap */
13265  ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u/2\r\n", rtp_code, mime, rate);
13266  } else if ((AST_RTP_PT_LAST_STATIC < rtp_code) || !(sip_cfg.compactheaders)) {
13267  ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code, mime, rate);
13268  }
13269 
13270  ast_format_generate_sdp_fmtp(format, rtp_code, a_buf);
13271 
13272  framing = ast_format_cap_get_format_framing(p->caps, format);
13273 
13275  /* Indicate that we don't support VAD (G.723.1 annex A) */
13276  ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
13277  } else if (ast_format_cmp(format, ast_format_g719) == AST_FORMAT_CMP_EQUAL) {
13278  /* Indicate that we only expect 64Kbps */
13279  ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
13280  }
13281 
13282  if (max_packet_size && ast_format_get_maximum_ms(format) &&
13283  (ast_format_get_maximum_ms(format) < *max_packet_size)) {
13284  *max_packet_size = ast_format_get_maximum_ms(format);
13285  }
13286 
13287  if (framing && (framing < *min_packet_size)) {
13288  *min_packet_size = framing;
13289  }
13290 
13291  /* Our first codec packetization processed cannot be zero */
13292  if ((*min_packet_size) == 0 && framing) {
13293  *min_packet_size = framing;
13294  }
13295 
13296  if ((*max_packet_size) == 0 && ast_format_get_maximum_ms(format)) {
13297  *max_packet_size = ast_format_get_maximum_ms(format);
13298  }
13299 }
13300 
13301 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
13302 /* This is different to the audio one now so we can add more caps later */
13303 static void add_vcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
13304  struct ast_str **m_buf, struct ast_str **a_buf,
13305  int debug, int *min_packet_size)
13306 {
13307  int rtp_code;
13308  const char *subtype;
13309  unsigned int rate;
13310 
13311  if (!p->vrtp)
13312  return;
13313 
13314  if (debug)
13315  ast_verbose("Adding video codec %s to SDP\n", ast_format_get_name(format));
13316 
13317  if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, format, 0)) == -1) ||
13318  !(subtype = ast_rtp_lookup_mime_subtype2(1, format, 0, 0)) ||
13319  !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
13320  return;
13321  }
13322 
13323  ast_str_append(m_buf, 0, " %d", rtp_code);
13324  ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code, subtype, rate);
13325  /* VP8: add RTCP FIR support */
13327  ast_str_append(a_buf, 0, "a=rtcp-fb:* ccm fir\r\n");
13328  }
13329 
13330  ast_format_generate_sdp_fmtp(format, rtp_code, a_buf);
13331 }
13332 
13333 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
13334 static void add_tcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
13335  struct ast_str **m_buf, struct ast_str **a_buf,
13336  int debug, int *min_packet_size)
13337 {
13338  int rtp_code;
13339 
13340  if (!p->trtp)
13341  return;
13342 
13343  if (debug)
13344  ast_verbose("Adding text codec %s to SDP\n", ast_format_get_name(format));
13345 
13346  if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, format, 0)) == -1)
13347  return;
13348 
13349  ast_str_append(m_buf, 0, " %d", rtp_code);
13350  ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
13351  ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
13352  ast_rtp_lookup_sample_rate2(1, format, 0));
13353  /* Add fmtp code here */
13354 
13357  ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
13358  t140code,
13359  t140code,
13360  t140code);
13361 
13362  }
13363 }
13364 
13365 
13366 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
13367 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
13368 {
13369  switch (rate) {
13370  case AST_T38_RATE_2400:
13371  return 2400;
13372  case AST_T38_RATE_4800:
13373  return 4800;
13374  case AST_T38_RATE_7200:
13375  return 7200;
13376  case AST_T38_RATE_9600:
13377  return 9600;
13378  case AST_T38_RATE_12000:
13379  return 12000;
13380  case AST_T38_RATE_14400:
13381  return 14400;
13382  default:
13383  return 0;
13384  }
13385 }
13386 
13387 /*! \brief Add RFC 2833 DTMF offer to SDP */
13388 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
13389  struct ast_str **m_buf, struct ast_str **a_buf,
13390  int debug)
13391 {
13392  int rtp_code;
13393 
13394  if (debug)
13395  ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", (unsigned)format, ast_rtp_lookup_mime_subtype2(0, NULL, format, 0));
13396  if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, NULL, format)) == -1)
13397  return;
13398 
13399  ast_str_append(m_buf, 0, " %d", rtp_code);
13400  ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
13401  ast_rtp_lookup_mime_subtype2(0, NULL, format, 0),
13402  ast_rtp_lookup_sample_rate2(0, NULL, format));
13403  if (format == AST_RTP_DTMF) /* Indicate we support DTMF and FLASH... */
13404  ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
13405 }
13406 
13407 /*! \brief Set all IP media addresses for this call
13408  \note called from add_sdp()
13409 */
13410 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
13411  struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
13412  struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
13413  struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
13414 {
13415  int use_externip = 0;
13416 
13417  /* First, get our address */
13419  if (p->vrtp) {
13421  }
13422  if (p->trtp) {
13424  }
13425 
13426  /* If our real IP differs from the local address returned by the RTP engine, use it. */
13427  /* The premise is that if we are already using that IP to communicate with the client, */
13428  /* we should be using it for RTP too. */
13429  use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
13430 
13431  /* Now, try to figure out where we want them to send data */
13432  /* Is this a re-invite to move the media out, then use the original offer from caller */
13433  if (!ast_sockaddr_isnull(&p->redirip)) { /* If we have a redirection IP, use it */
13434  ast_sockaddr_copy(dest, &p->redirip);
13435  } else {
13436  /*
13437  * Audio Destination IP:
13438  *
13439  * 1. Specifically configured media address.
13440  * 2. Local address as specified by the RTP engine.
13441  * 3. The local IP as defined by chan_sip.
13442  *
13443  * Audio Destination Port:
13444  *
13445  * 1. Provided by the RTP engine.
13446  */
13447  ast_sockaddr_copy(dest,
13449  !ast_sockaddr_is_any(addr) && !use_externip ? addr :
13450  &p->ourip);
13452  }
13453 
13454  if (needvideo) {
13455  /* Determine video destination */
13456  if (!ast_sockaddr_isnull(&p->vredirip)) {
13457  ast_sockaddr_copy(vdest, &p->vredirip);
13458  } else {
13459  /*
13460  * Video Destination IP:
13461  *
13462  * 1. Specifically configured media address.
13463  * 2. Local address as specified by the RTP engine.
13464  * 3. The local IP as defined by chan_sip.
13465  *
13466  * Video Destination Port:
13467  *
13468  * 1. Provided by the RTP engine.
13469  */
13470  ast_sockaddr_copy(vdest,
13472  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
13473  &p->ourip);
13475  }
13476  }
13477 
13478  if (needtext) {
13479  /* Determine text destination */
13480  if (!ast_sockaddr_isnull(&p->tredirip)) {
13481  ast_sockaddr_copy(tdest, &p->tredirip);
13482  } else {
13483  /*
13484  * Text Destination IP:
13485  *
13486  * 1. Specifically configured media address.
13487  * 2. Local address as specified by the RTP engine.
13488  * 3. The local IP as defined by chan_sip.
13489  *
13490  * Text Destination Port:
13491  *
13492  * 1. Provided by the RTP engine.
13493  */
13494  ast_sockaddr_copy(tdest,
13496  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
13497  &p->ourip);
13499  }
13500  }
13501 }
13502 
13503 static char *crypto_get_attrib(struct ast_sdp_srtp *srtp, int dtls_enabled, int default_taglen_32)
13504 {
13505  struct ast_sdp_srtp *tmp = srtp;
13506  char *a_crypto;
13507 
13508  if (!tmp || dtls_enabled) {
13509  return NULL;
13510  }
13511 
13512  a_crypto = ast_strdup("");
13513  if (!a_crypto) {
13514  return NULL;
13515  }
13516 
13517  do {
13518  char *copy = a_crypto;
13519  const char *orig_crypto = ast_sdp_srtp_get_attrib(tmp, dtls_enabled, default_taglen_32);
13520 
13521  if (ast_strlen_zero(orig_crypto)) {
13522  ast_free(copy);
13523  return NULL;
13524  }
13525  if (ast_asprintf(&a_crypto, "%sa=crypto:%s\r\n", copy, orig_crypto) == -1) {
13526  ast_free(copy);
13527  return NULL;
13528  }
13529 
13530  ast_free(copy);
13531  } while ((tmp = AST_LIST_NEXT(tmp, sdp_srtp_list)));
13532 
13533  return a_crypto;
13534 }
13535 
13536 /*! \brief Add Session Description Protocol message
13537 
13538  If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
13539  is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
13540  without modifying the media session in any way.
13541 */
13542 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
13543 {
13546  int res = AST_SUCCESS;
13547  int doing_directmedia = FALSE;
13548  struct ast_sockaddr addr = { {0,} };
13549  struct ast_sockaddr vaddr = { {0,} };
13550  struct ast_sockaddr taddr = { {0,} };
13551  struct ast_sockaddr udptladdr = { {0,} };
13552  struct ast_sockaddr dest = { {0,} };
13553  struct ast_sockaddr vdest = { {0,} };
13554  struct ast_sockaddr tdest = { {0,} };
13555  struct ast_sockaddr udptldest = { {0,} };
13556 
13557  /* SDP fields */
13558  struct offered_media *offer;
13559  char *version = "v=0\r\n"; /* Protocol version */
13560  char subject[256]; /* Subject of the session */
13561  char owner[256]; /* Session owner/creator */
13562  char connection[256]; /* Connection data */
13563  char *session_time = "t=0 0\r\n"; /* Time the session is active */
13564  char bandwidth[256] = ""; /* Max bitrate */
13565  char *hold = "";
13566  struct ast_str *m_audio = ast_str_alloca(256); /* Media declaration line for audio */
13567  struct ast_str *m_video = ast_str_alloca(256); /* Media declaration line for video */
13568  struct ast_str *m_text = ast_str_alloca(256); /* Media declaration line for text */
13569  struct ast_str *m_modem = ast_str_alloca(256); /* Media declaration line for modem */
13570  struct ast_str *a_audio = ast_str_create(256); /* Attributes for audio */
13571  struct ast_str *a_video = ast_str_create(256); /* Attributes for video */
13572  struct ast_str *a_text = ast_str_create(256); /* Attributes for text */
13573  struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
13574  RAII_VAR(char *, a_crypto, NULL, ast_free);
13575  RAII_VAR(char *, v_a_crypto, NULL, ast_free);
13576  RAII_VAR(char *, t_a_crypto, NULL, ast_free);
13577 
13578  int x;
13579  struct ast_format *tmp_fmt;
13580  int needaudio = FALSE;
13581  int needvideo = FALSE;
13582  int needtext = FALSE;
13583  int debug = sip_debug_test_pvt(p);
13584  int min_audio_packet_size = 0;
13585  int max_audio_packet_size = 0;
13586  int min_video_packet_size = 0;
13587  int min_text_packet_size = 0;
13588 
13589  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
13590 
13591  /* Set the SDP session name */
13592  snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
13593 
13594  if (!alreadysent || !tmpcap) {
13595  res = AST_FAILURE;
13596  goto add_sdp_cleanup;
13597  }
13598  if (!p->rtp) {
13599  ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
13600  res = AST_FAILURE;
13601  goto add_sdp_cleanup;
13602 
13603  }
13604  /* XXX We should not change properties in the SIP dialog until
13605  we have acceptance of the offer if this is a re-invite */
13606 
13607  /* Set RTP Session ID and version */
13608  if (!p->sessionid) {
13609  p->sessionid = (int)ast_random();
13610  p->sessionversion = p->sessionid;
13611  } else {
13612  if (oldsdp == FALSE)
13613  p->sessionversion++;
13614  }
13615 
13616  if (add_audio) {
13617  doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && (ast_format_cap_count(p->redircaps))) ? TRUE : FALSE;
13618 
13619  if (doing_directmedia) {
13621  ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_format_cap_get_names(tmpcap, &codec_buf));
13622  } else {
13624  }
13625 
13626  /* Check if we need audio in this call */
13627  needaudio = ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_AUDIO);
13628 
13629  /* Check if we need video in this call */
13630  if ((ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_VIDEO)) && !p->novideo) {
13631  if (doing_directmedia && !ast_format_cap_has_type(tmpcap, AST_MEDIA_TYPE_VIDEO)) {
13632  ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
13633  } else if (p->vrtp) {
13634  needvideo = TRUE;
13635  ast_debug(2, "This call needs video offers!\n");
13636  } else {
13637  ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
13638  }
13639  }
13640 
13641  /* Check if we need text in this call */
13643  if (sipdebug_text)
13644  ast_verbose("We think we can do text\n");
13645  if (p->trtp) {
13646  if (sipdebug_text) {
13647  ast_verbose("And we have a text rtp object\n");
13648  }
13649  needtext = TRUE;
13650  ast_debug(2, "This call needs text offers! \n");
13651  } else {
13652  ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
13653  }
13654  }
13655 
13656  /* XXX note, Video and Text are negated - 'true' means 'no' */
13657  ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n",
13658  ast_format_cap_get_names(tmpcap, &codec_buf),
13659  p->novideo ? "True" : "False", p->notext ? "True" : "False");
13660  ast_debug(1, "** Our prefcodec: %s \n", ast_format_cap_get_names(p->prefcaps, &codec_buf));
13661  }
13662 
13663  get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
13664 
13665  /* We don't use dest here but p->ourip because address in o= field must not change in reINVITE */
13666  snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
13668  p->sessionid, p->sessionversion,
13670  "IP6" : "IP4",
13672 
13673  snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
13675  "IP6" : "IP4",
13677 
13678  if (add_audio) {
13680  hold = "a=recvonly\r\n";
13681  doing_directmedia = FALSE;
13683  hold = "a=inactive\r\n";
13684  doing_directmedia = FALSE;
13685  } else {
13686  hold = "a=sendrecv\r\n";
13687  }
13688 
13689  if (debug) {
13690  ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
13691  }
13692 
13693  /* Ok, we need video. Let's add what we need for video and set codecs.
13694  Video is handled differently than audio since we can not transcode. */
13695  if (needvideo) {
13696  v_a_crypto = crypto_get_attrib(p->vsrtp, p->dtls_cfg.enabled,
13698  ast_str_append(&m_video, 0, "m=video %d %s", ast_sockaddr_port(&vdest),
13699  ast_sdp_get_rtp_profile(v_a_crypto ? 1 : 0, p->vrtp,
13702 
13703  /* Build max bitrate string */
13704  if (p->maxcallbitrate)
13705  snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
13706  if (debug) {
13707  ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
13708  }
13709 
13710  if (!doing_directmedia) {
13711  if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13712  add_ice_to_sdp(p->vrtp, &a_video);
13713  }
13714 
13715  add_dtls_to_sdp(p->vrtp, &a_video);
13716  }
13717  }
13718 
13719  /* Ok, we need text. Let's add what we need for text and set codecs.
13720  Text is handled differently than audio since we can not transcode. */
13721  if (needtext) {
13722  if (sipdebug_text)
13723  ast_verbose("Lets set up the text sdp\n");
13724  t_a_crypto = crypto_get_attrib(p->tsrtp, p->dtls_cfg.enabled,
13726  ast_str_append(&m_text, 0, "m=text %d %s", ast_sockaddr_port(&tdest),
13727  ast_sdp_get_rtp_profile(t_a_crypto ? 1 : 0, p->trtp,
13730  if (debug) { /* XXX should I use tdest below ? */
13731  ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
13732  }
13733 
13734  if (!doing_directmedia) {
13735  if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13736  add_ice_to_sdp(p->trtp, &a_text);
13737  }
13738 
13739  add_dtls_to_sdp(p->trtp, &a_text);
13740  }
13741  }
13742 
13743  /* Start building generic SDP headers */
13744 
13745  /* We break with the "recommendation" and send our IP, in order that our
13746  peer doesn't have to ast_gethostbyname() us */
13747 
13748  a_crypto = crypto_get_attrib(p->srtp, p->dtls_cfg.enabled,
13750  ast_str_append(&m_audio, 0, "m=audio %d %s", ast_sockaddr_port(&dest),
13751  ast_sdp_get_rtp_profile(a_crypto ? 1 : 0, p->rtp,
13754 
13755  /* Now, start adding audio codecs. These are added in this order:
13756  - First what was requested by the calling channel
13757  - Then our mutually shared capabilities, determined previous in tmpcap
13758  */
13759 
13760 
13761  /* Unless otherwise configured, the prefcaps is added before the peer's
13762  * configured codecs.
13763  */
13765  for (x = 0; x < ast_format_cap_count(p->prefcaps); x++) {
13766  tmp_fmt = ast_format_cap_get_format(p->prefcaps, x);
13767 
13768  if ((ast_format_get_type(tmp_fmt) != AST_MEDIA_TYPE_AUDIO) ||
13770  ao2_ref(tmp_fmt, -1);
13771  continue;
13772  }
13773 
13774  add_codec_to_sdp(p, tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size, &max_audio_packet_size);
13775  ast_format_cap_append(alreadysent, tmp_fmt, 0);
13776  ao2_ref(tmp_fmt, -1);
13777  }
13778  }
13779 
13780  /* Now send any other common codecs */
13781  for (x = 0; x < ast_format_cap_count(tmpcap); x++) {
13782  tmp_fmt = ast_format_cap_get_format(tmpcap, x);
13783 
13784  if (ast_format_cap_iscompatible_format(alreadysent, tmp_fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
13785  ao2_ref(tmp_fmt, -1);
13786  continue;
13787  }
13788 
13789  if (ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_AUDIO) {
13790  add_codec_to_sdp(p, tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size, &max_audio_packet_size);
13791  } else if (needvideo && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_VIDEO) {
13792  add_vcodec_to_sdp(p, tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
13793  } else if (needtext && ast_format_get_type(tmp_fmt) == AST_MEDIA_TYPE_TEXT) {
13794  add_tcodec_to_sdp(p, tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
13795  }
13796 
13797  ast_format_cap_append(alreadysent, tmp_fmt, 0);
13798  ao2_ref(tmp_fmt, -1);
13799  }
13800 
13801  /* Now add DTMF RFC2833 telephony-event as a codec */
13802  for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
13803  if (!(p->jointnoncodeccapability & x))
13804  continue;
13805 
13806  add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
13807  }
13808 
13809  ast_debug(3, "-- Done with adding codecs to SDP\n");
13810 
13811  if (!p->owner || ast_channel_timingfd(p->owner) == -1) {
13812  ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
13813  }
13814 
13815  if (min_audio_packet_size) {
13816  ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
13817  }
13818 
13819  /* XXX don't think you can have ptime for video */
13820  if (min_video_packet_size) {
13821  ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
13822  }
13823 
13824  /* XXX don't think you can have ptime for text */
13825  if (min_text_packet_size) {
13826  ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
13827  }
13828 
13829  if (max_audio_packet_size) {
13830  ast_str_append(&a_audio, 0, "a=maxptime:%d\r\n", max_audio_packet_size);
13831  }
13832 
13833  if (!ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13834  ast_debug(1, "Setting framing on incoming call: %u\n", min_audio_packet_size);
13835  ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(p->rtp), min_audio_packet_size);
13836  }
13837 
13838  if (!doing_directmedia) {
13839  if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13840  add_ice_to_sdp(p->rtp, &a_audio);
13841  /* Start ICE negotiation, and setting that we are controlled agent,
13842  as this is response to offer */
13843  if (resp->method == SIP_RESPONSE) {
13844  start_ice(p->rtp, 0);
13845  }
13846  }
13847 
13848  add_dtls_to_sdp(p->rtp, &a_audio);
13849  }
13850 
13851  /* If we've got rtcp-mux enabled, just unconditionally offer it in all SDPs */
13852  if (ast_test_flag(&p->flags[2], SIP_PAGE3_RTCP_MUX)) {
13853  ast_str_append(&a_audio, 0, "a=rtcp-mux\r\n");
13854  ast_str_append(&a_video, 0, "a=rtcp-mux\r\n");
13855  }
13856  }
13857 
13858  if (add_t38) {
13859  /* Our T.38 end is */
13860  ast_udptl_get_us(p->udptl, &udptladdr);
13861 
13862  /* We don't use directmedia for T.38, so keep the destination the same as our IP address. */
13863  ast_sockaddr_copy(&udptldest, &p->ourip);
13864  ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
13865 
13866  if (debug) {
13867  ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
13868  }
13869 
13870  /* We break with the "recommendation" and send our IP, in order that our
13871  peer doesn't have to ast_gethostbyname() us */
13872 
13873  ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
13874 
13875  if (ast_sockaddr_cmp_addr(&udptldest, &dest)) {
13876  ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
13877  (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
13878  "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
13879  }
13880 
13881  ast_str_append(&a_modem, 0, "a=T38FaxVersion:%u\r\n", p->t38.our_parms.version);
13882  ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%u\r\n", t38_get_rate(p->t38.our_parms.rate));
13883  if (p->t38.our_parms.fill_bit_removal) {
13884  ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
13885  }
13886  if (p->t38.our_parms.transcoding_mmr) {
13887  ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
13888  }
13889  if (p->t38.our_parms.transcoding_jbig) {
13890  ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
13891  }
13892  switch (p->t38.our_parms.rate_management) {
13894  ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
13895  break;
13897  ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
13898  break;
13899  }
13900  ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
13903  break;
13905  ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
13906  break;
13908  ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
13909  break;
13910  }
13911  }
13912 
13913  if (needaudio)
13914  ast_str_append(&m_audio, 0, "\r\n");
13915  if (needvideo)
13916  ast_str_append(&m_video, 0, "\r\n");
13917  if (needtext)
13918  ast_str_append(&m_text, 0, "\r\n");
13919 
13920  add_header(resp, "Content-Type", "application/sdp");
13921  add_content(resp, version);
13922  add_content(resp, owner);
13923  add_content(resp, subject);
13924  add_content(resp, connection);
13925  /* only if video response is appropriate */
13926  if (needvideo) {
13927  add_content(resp, bandwidth);
13928  }
13929  add_content(resp, session_time);
13930  /* if this is a response to an invite, order our offers properly */
13931  if (!AST_LIST_EMPTY(&p->offered_media)) {
13932  AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
13933  switch (offer->type) {
13934  case SDP_AUDIO:
13935  if (needaudio) {
13936  add_content(resp, ast_str_buffer(m_audio));
13937  if (a_crypto) {
13938  add_content(resp, a_crypto);
13939  }
13940  add_content(resp, ast_str_buffer(a_audio));
13941  add_content(resp, hold);
13942  } else {
13943  add_content(resp, offer->decline_m_line);
13944  }
13945  break;
13946  case SDP_VIDEO:
13947  if (needvideo) { /* only if video response is appropriate */
13948  add_content(resp, ast_str_buffer(m_video));
13949  add_content(resp, ast_str_buffer(a_video));
13950  add_content(resp, hold); /* Repeat hold for the video stream */
13951  if (v_a_crypto) {
13952  add_content(resp, v_a_crypto);
13953  }
13954  } else {
13955  add_content(resp, offer->decline_m_line);
13956  }
13957  break;
13958  case SDP_TEXT:
13959  if (needtext) { /* only if text response is appropriate */
13960  add_content(resp, ast_str_buffer(m_text));
13961  add_content(resp, ast_str_buffer(a_text));
13962  add_content(resp, hold); /* Repeat hold for the text stream */
13963  if (t_a_crypto) {
13964  add_content(resp, t_a_crypto);
13965  }
13966  } else {
13967  add_content(resp, offer->decline_m_line);
13968  }
13969  break;
13970  case SDP_IMAGE:
13971  if (add_t38) {
13972  add_content(resp, ast_str_buffer(m_modem));
13973  add_content(resp, ast_str_buffer(a_modem));
13974  } else {
13975  add_content(resp, offer->decline_m_line);
13976  }
13977  break;
13978  case SDP_UNKNOWN:
13979  add_content(resp, offer->decline_m_line);
13980  break;
13981  }
13982  }
13983  } else {
13984  /* generate new SDP from scratch, no offers */
13985  if (needaudio) {
13986  add_content(resp, ast_str_buffer(m_audio));
13987  if (a_crypto) {
13988  add_content(resp, a_crypto);
13989  }
13990  add_content(resp, ast_str_buffer(a_audio));
13991  add_content(resp, hold);
13992  }
13993  if (needvideo) { /* only if video response is appropriate */
13994  add_content(resp, ast_str_buffer(m_video));
13995  add_content(resp, ast_str_buffer(a_video));
13996  add_content(resp, hold); /* Repeat hold for the video stream */
13997  if (v_a_crypto) {
13998  add_content(resp, v_a_crypto);
13999  }
14000  }
14001  if (needtext) { /* only if text response is appropriate */
14002  add_content(resp, ast_str_buffer(m_text));
14003  add_content(resp, ast_str_buffer(a_text));
14004  add_content(resp, hold); /* Repeat hold for the text stream */
14005  if (t_a_crypto) {
14006  add_content(resp, t_a_crypto);
14007  }
14008  }
14009  if (add_t38) {
14010  add_content(resp, ast_str_buffer(m_modem));
14011  add_content(resp, ast_str_buffer(a_modem));
14012  }
14013  }
14014 
14015  /* Update lastrtprx when we send our SDP */
14016  p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
14017 
14018  /*
14019  * We unlink this dialog and link again into the
14020  * dialogs_rtpcheck container so its not in there twice.
14021  */
14022  ao2_lock(dialogs_rtpcheck);
14023  ao2_t_unlink(dialogs_rtpcheck, p, "unlink pvt into dialogs_rtpcheck container");
14024  ao2_t_link(dialogs_rtpcheck, p, "link pvt into dialogs_rtpcheck container");
14025  ao2_unlock(dialogs_rtpcheck);
14026 
14027  ast_debug(3, "Done building SDP. Settling with this capability: %s\n",
14028  ast_format_cap_get_names(tmpcap, &codec_buf));
14029 
14030 add_sdp_cleanup:
14031  ast_free(a_text);
14032  ast_free(a_video);
14033  ast_free(a_audio);
14034  ao2_cleanup(alreadysent);
14035  ao2_cleanup(tmpcap);
14036 
14037  return res;
14038 }
14039 
14040 /*! \brief Used for 200 OK and 183 early media */
14041 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
14042 {
14043  struct sip_request resp;
14044  uint32_t seqno;
14045 
14046  if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
14047  ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
14048  return -1;
14049  }
14050  respprep(&resp, p, msg, req);
14051  if (p->udptl) {
14052  add_sdp(&resp, p, 0, 0, 1);
14053  } else
14054  ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
14055  if (retrans && !p->pendinginvite)
14056  p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
14057  return send_response(p, &resp, retrans, seqno);
14058 }
14059 
14060 /*! \brief copy SIP request (mostly used to save request for responses) */
14061 static void copy_request(struct sip_request *dst, const struct sip_request *src)
14062 {
14063  /* XXX this function can encounter memory allocation errors, perhaps it
14064  * should return a value */
14065 
14066  struct ast_str *duplicate = dst->data;
14067  struct ast_str *duplicate_content = dst->content;
14068 
14069  /* copy the entire request then restore the original data and content
14070  * members from the dst request */
14071  *dst = *src;
14072  dst->data = duplicate;
14073  dst->content = duplicate_content;
14074 
14075  /* copy the data into the dst request */
14076  if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
14077  return;
14078  }
14079  ast_str_copy_string(&dst->data, src->data);
14080 
14081  /* copy the content into the dst request (if it exists) */
14082  if (src->content) {
14083  if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
14084  return;
14085  }
14086  ast_str_copy_string(&dst->content, src->content);
14087  }
14088 }
14089 
14090 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
14091 {
14092  char uri[SIPBUFSIZE];
14095  struct sip_cc_agent_pvt *agent_pvt;
14096 
14097  if (!agent) {
14098  /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
14099  * agent? Oh well, we'll just warn and return without adding the header.
14100  */
14101  ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
14102  return;
14103  }
14104 
14105  agent_pvt = agent->private_data;
14106 
14107  if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
14108  ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
14109  } else {
14110  generate_uri(p, uri, sizeof(uri));
14111  ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
14112  }
14113  /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
14114  * to be more accurate. This parameter has no bearing on the actual operation
14115  * of the feature; it's just there for informational purposes.
14116  */
14117  ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
14118  add_header(resp, "Call-Info", ast_str_buffer(header));
14119  ao2_ref(agent, -1);
14120 }
14121 
14122 /*! \brief Used for 200 OK and 183 early media
14123  \return Will return XMIT_ERROR for network errors.
14124 */
14125 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid)
14126 {
14127  struct sip_request resp;
14128  uint32_t seqno;
14129  if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
14130  ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
14131  return -1;
14132  }
14133  respprep(&resp, p, msg, req);
14134  if (rpid == TRUE) {
14135  add_rpid(&resp, p);
14136  }
14137  if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
14138  add_cc_call_info_to_response(p, &resp);
14139  }
14140  if (p->rtp) {
14143  if (p->t38.state == T38_ENABLED) {
14144  add_sdp(&resp, p, oldsdp, TRUE, TRUE);
14145  } else {
14146  add_sdp(&resp, p, oldsdp, TRUE, FALSE);
14147  }
14148  } else
14149  ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
14150  if (reliable && !p->pendinginvite)
14151  p->pendinginvite = seqno; /* Buggy clients sends ACK on RINGING too */
14152  add_required_respheader(&resp);
14153  return send_response(p, &resp, reliable, seqno);
14154 }
14155 
14156 /*! \brief Parse first line of incoming SIP request */
14158 {
14159  char *e = ast_skip_blanks(ast_str_buffer(req->data)); /* there shouldn't be any */
14160  char *local_rlpart1;
14161 
14162  if (!*e)
14163  return -1;
14164  req->rlpart1 = e - ast_str_buffer(req->data); /* method or protocol */
14165  local_rlpart1 = e;
14166  e = ast_skip_nonblanks(e);
14167  if (*e)
14168  *e++ = '\0';
14169  /* Get URI or status code */
14170  e = ast_skip_blanks(e);
14171  if ( !*e )
14172  return -1;
14173  ast_trim_blanks(e);
14174 
14175  if (!strcasecmp(local_rlpart1, "SIP/2.0") ) { /* We have a response */
14176  if (strlen(e) < 3) /* status code is 3 digits */
14177  return -1;
14178  req->rlpart2 = e - ast_str_buffer(req->data);
14179  } else { /* We have a request */
14180  if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
14181  ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
14182  e++;
14183  if (!*e)
14184  return -1;
14185  }
14186  req->rlpart2 = e - ast_str_buffer(req->data); /* URI */
14187  e = ast_skip_nonblanks(e);
14188  if (*e)
14189  *e++ = '\0';
14190  e = ast_skip_blanks(e);
14191  if (strcasecmp(e, "SIP/2.0") ) {
14192  ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
14193  return -1;
14194  }
14195  }
14196  return 1;
14197 }
14198 
14199 /*! \brief Transmit reinvite with SDP
14200 \note A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
14201  INVITE that opened the SIP dialogue
14202  We reinvite so that the audio stream (RTP) go directly between
14203  the SIP UAs. SIP Signalling stays with * in the path.
14204 
14205  If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
14206  T38 UDPTL transmission on the channel
14207 
14208  If oldsdp is TRUE then the SDP version number is not incremented. This
14209  is needed for Session-Timers so we can send a re-invite to refresh the
14210  SIP session without modifying the media session.
14211 */
14212 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
14213 {
14214  struct sip_request req;
14215 
14216  if (t38version) {
14217  /* Force media to go through us for T.38. */
14218  memset(&p->redirip, 0, sizeof(p->redirip));
14219  }
14220  if (p->rtp) {
14221  if (t38version) {
14222  /* Silence RTCP while audio RTP is inactive */
14224  if (p->owner) {
14225  /* Prevent audio RTCP reads */
14227  }
14228  } else if (ast_sockaddr_isnull(&p->redirip)) {
14229  /* Enable RTCP since it will be inactive if we're coming back
14230  * with this reinvite */
14232  if (p->owner) {
14233  /* Enable audio RTCP reads */
14235  }
14236  }
14237  }
14238 
14239  reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
14240 
14241  add_header(&req, "Allow", ALLOWED_METHODS);
14242  add_supported(p, &req);
14243  if (sipdebug) {
14244  if (oldsdp == TRUE)
14245  add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
14246  else
14247  add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
14248  }
14249 
14250  if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
14251  add_rpid(&req, p);
14252 
14253  if (p->do_history) {
14254  append_history(p, "ReInv", "Re-invite sent");
14255  }
14256 
14258 
14260  if (t38version) {
14261  add_sdp(&req, p, oldsdp, FALSE, TRUE);
14262  } else {
14263  add_sdp(&req, p, oldsdp, TRUE, FALSE);
14264  }
14265 
14266  /* Use this as the basis */
14267  initialize_initreq(p, &req);
14268  p->lastinvite = p->ocseq;
14269  ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Change direction of this dialog */
14270  p->ongoing_reinvite = 1;
14271  return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
14272 }
14273 
14274 /* \brief Remove URI parameters at end of URI, not in username part though */
14275 static char *remove_uri_parameters(char *uri)
14276 {
14277  char *atsign;
14278  atsign = strchr(uri, '@'); /* First, locate the at sign */
14279  if (!atsign) {
14280  atsign = uri; /* Ok hostname only, let's stick with the rest */
14281  }
14282  atsign = strchr(atsign, ';'); /* Locate semi colon */
14283  if (atsign)
14284  *atsign = '\0'; /* Kill at the semi colon */
14285  return uri;
14286 }
14287 
14288 /*! \brief Check Contact: URI of SIP message */
14289 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
14290 {
14291  char stripped[SIPBUFSIZE];
14292  char *c;
14293 
14294  ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
14295  c = get_in_brackets(stripped);
14296  /* Cut the URI at the at sign after the @, not in the username part */
14297  c = remove_uri_parameters(c);
14298  if (!ast_strlen_zero(c)) {
14299  ast_string_field_set(p, uri, c);
14300  }
14301 }
14302 
14303 /*!
14304  * \brief Determine if, as a UAS, we need to use a SIPS Contact.
14305  *
14306  * This uses the rules defined in RFC 3261 section 12.1.1 to
14307  * determine if a SIPS URI should be used as the Contact header
14308  * when responding to incoming SIP requests.
14309  *
14310  * \param req The incoming SIP request
14311  * \retval 0 SIPS is not required
14312  * \retval 1 SIPS is required
14313  */
14314 static int uas_sips_contact(struct sip_request *req)
14315 {
14316  const char *record_route = sip_get_header(req, "Record-Route");
14317 
14318  if (!strncmp(REQ_OFFSET_TO_STR(req, rlpart2), "sips:", 5)) {
14319  return 1;
14320  }
14321 
14322  if (record_route) {
14323  char *record_route_uri = get_in_brackets(ast_strdupa(record_route));
14324 
14325  if (!strncmp(record_route_uri, "sips:", 5)) {
14326  return 1;
14327  }
14328  } else {
14329  const char *contact = sip_get_header(req, "Contact");
14330  char *contact_uri = get_in_brackets(ast_strdupa(contact));
14331 
14332  if (!strncmp(contact_uri, "sips:", 5)) {
14333  return 1;
14334  }
14335  }
14336 
14337  return 0;
14338 }
14339 
14340 /*!
14341  * \brief Determine if, as a UAC, we need to use a SIPS Contact.
14342  *
14343  * This uses the rules defined in RFC 3621 section 8.1.1.8 to
14344  * determine if a SIPS URI should be used as the Contact header
14345  * on our outgoing request.
14346  *
14347  * \param req The outgoing SIP request
14348  * \retval 0 SIPS is not required
14349  * \retval 1 SIPS is required
14350  */
14351 static int uac_sips_contact(struct sip_request *req)
14352 {
14353  const char *route = sip_get_header(req, "Route");
14354 
14355  if (!strncmp(REQ_OFFSET_TO_STR(req, rlpart2), "sips:", 5)) {
14356  return 1;
14357  }
14358 
14359  if (route) {
14360  char *route_uri = get_in_brackets(ast_strdupa(route));
14361 
14362  if (!strncmp(route_uri, "sips:", 5)) {
14363  return 1;
14364  }
14365  }
14366 
14367  return 0;
14368 }
14369 
14370 /*!
14371  * \brief Build contact header
14372  *
14373  * This is the Contact header that we send out in SIP requests and responses
14374  * involving this sip_pvt.
14375  *
14376  * The incoming parameter is used to tell if we are building the request parameter
14377  * is an incoming SIP request that we are building the Contact header in response to,
14378  * or if the req parameter is an outbound SIP request that we will later be adding
14379  * the Contact header to.
14380  *
14381  * \param p The sip_pvt where the built Contact will be saved.
14382  * \param req The request that triggered the creation of a Contact header.
14383  * \param incoming Indicates if the Contact header is being created for a response to an incoming request
14384  */
14385 static void build_contact(struct sip_pvt *p, struct sip_request *req, int incoming)
14386 {
14387  char tmp[SIPBUFSIZE];
14388  char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), ast_uri_sip_user);
14389  int use_sips;
14390  char *transport = ast_strdupa(sip_get_transport(p->socket.type));
14391 
14392  if (incoming) {
14393  use_sips = uas_sips_contact(req);
14394  } else {
14395  use_sips = uac_sips_contact(req);
14396  }
14397 
14398  if (p->socket.type == AST_TRANSPORT_UDP) {
14399  ast_string_field_build(p, our_contact, "<%s:%s%s%s>", use_sips ? "sips" : "sip",
14400  user, ast_strlen_zero(user) ? "" : "@",
14402  } else {
14403  ast_string_field_build(p, our_contact, "<%s:%s%s%s;transport=%s>",
14404  use_sips ? "sips" : "sip", user, ast_strlen_zero(user) ? "" : "@",
14406  }
14407 }
14408 
14409 /*! \brief Initiate new SIP request to peer/user */
14410 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
14411 {
14412 #define SIPHEADER 256
14413  struct ast_str *invite = ast_str_create(SIPHEADER);
14414  struct ast_str *from = ast_str_create(SIPHEADER);
14415  struct ast_str *to = ast_str_create(SIPHEADER);
14416  char tmp_n[SIPBUFSIZE/2]; /* build a local copy of 'n' if needed */
14417  char tmp_l[SIPBUFSIZE/2]; /* build a local copy of 'l' if needed */
14418  const char *l = NULL; /* XXX what is this, exactly ? */
14419  const char *n = NULL; /* XXX what is this, exactly ? */
14420  const char *d = NULL; /* domain in from header */
14421  const char *urioptions = "";
14422  int ourport;
14423  int cid_has_name = 1;
14424  int cid_has_num = 1;
14425  struct ast_party_id connected_id;
14426  int ret;
14427 
14428  if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
14429  const char *s = p->username; /* being a string field, cannot be NULL */
14430 
14431  /* Test p->username against allowed characters in AST_DIGIT_ANY
14432  If it matches the allowed characters list, then sipuser = ";user=phone"
14433  If not, then sipuser = ""
14434  */
14435  /* + is allowed in first position in a tel: uri */
14436  if (*s == '+')
14437  s++;
14438  for (; *s; s++) {
14439  if (!strchr(AST_DIGIT_ANYNUM, *s) )
14440  break;
14441  }
14442  /* If we have only digits, add ;user=phone to the uri */
14443  if (!*s)
14444  urioptions = ";user=phone";
14445  }
14446 
14447 
14448  snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
14449 
14450  if (ast_strlen_zero(p->fromdomain)) {
14452  }
14453  if (p->owner) {
14454  connected_id = ast_channel_connected_effective_id(p->owner);
14455 
14457  if (connected_id.number.valid) {
14458  l = connected_id.number.str;
14459  }
14460  if (connected_id.name.valid) {
14461  n = connected_id.name.str;
14462  }
14463  } else {
14464  /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
14465  * their callerid restricted */
14466  l = "anonymous";
14467  n = CALLERID_UNKNOWN;
14468  d = FROMDOMAIN_INVALID;
14469  }
14470  }
14471 
14472  /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
14473  * XXX Right now, this logic works because the only place that mwi_from
14474  * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
14475  * we might end up putting the mwi_from setting into other types of NOTIFY
14476  * messages as well.
14477  */
14478  if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
14479  l = p->mwi_from;
14480  }
14481 
14482  if (ast_strlen_zero(l)) {
14483  cid_has_num = 0;
14484  l = default_callerid;
14485  }
14486  if (ast_strlen_zero(n)) {
14487  cid_has_name = 0;
14488  n = l;
14489  }
14490 
14491  /* Allow user to be overridden */
14492  if (!ast_strlen_zero(p->fromuser))
14493  l = p->fromuser;
14494  else /* Save for any further attempts */
14495  ast_string_field_set(p, fromuser, l);
14496 
14497  /* Allow user to be overridden */
14498  if (!ast_strlen_zero(p->fromname))
14499  n = p->fromname;
14500  else /* Save for any further attempts */
14501  ast_string_field_set(p, fromname, n);
14502 
14503  /* Allow domain to be overridden */
14504  if (!ast_strlen_zero(p->fromdomain))
14505  d = p->fromdomain;
14506  else /* Save for any further attempts */
14507  ast_string_field_set(p, fromdomain, d);
14508 
14509  ast_copy_string(tmp_l, l, sizeof(tmp_l));
14511  ast_uri_encode(l, tmp_l, sizeof(tmp_l), ast_uri_sip_user);
14512  }
14513 
14515 
14516  if (!sip_standard_port(p->socket.type, ourport)) {
14517  ret = ast_str_set(&from, 0, "<sip:%s@%s:%d>;tag=%s", tmp_l, d, ourport, p->tag);
14518  } else {
14519  ret = ast_str_set(&from, 0, "<sip:%s@%s>;tag=%s", tmp_l, d, p->tag);
14520  }
14521  if (ret == AST_DYNSTR_BUILD_FAILED) {
14522  /* We don't have an escape path from here... */
14523  ast_log(LOG_ERROR, "The From header was truncated in call '%s'. This call setup will fail.\n", p->callid);
14524  /* Make sure that the field contains something non-broken.
14525  See https://issues.asterisk.org/jira/browse/ASTERISK-26069
14526  */
14527  ast_str_set(&from, 3, "<>");
14528 
14529  }
14530 
14531  /* If a caller id name was specified, prefix a display name, if there is enough room. */
14532  if (cid_has_name || !cid_has_num) {
14533  size_t written = ast_str_strlen(from);
14534  size_t name_len;
14536  ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
14537  n = tmp_n;
14538  }
14539  name_len = strlen(n);
14540  ret = ast_str_make_space(&from, name_len + written + 4);
14541 
14542  if (ret == 0) {
14543  /* needed again, as ast_str_make_space coud've changed the pointer */
14544  char *from_buf = ast_str_buffer(from);
14545 
14546  memmove(from_buf + name_len + 3, from_buf, written + 1);
14547  from_buf[0] = '"';
14548  memcpy(from_buf + 1, n, name_len);
14549  from_buf[name_len + 1] = '"';
14550  from_buf[name_len + 2] = ' ';
14551  }
14552  }
14553 
14554  if (!ast_strlen_zero(explicit_uri)) {
14555  ast_str_set(&invite, 0, "%s", explicit_uri);
14556  } else {
14557  /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
14558  if (!ast_strlen_zero(p->fullcontact)) {
14559  /* If we have full contact, trust it */
14560  ast_str_append(&invite, 0, "%s", p->fullcontact);
14561  } else {
14562  /* Otherwise, use the username while waiting for registration */
14563  ast_str_append(&invite, 0, "sip:");
14564  if (!ast_strlen_zero(p->username)) {
14565  n = p->username;
14567  ast_uri_encode(n, tmp_n, sizeof(tmp_n), ast_uri_sip_user);
14568  n = tmp_n;
14569  }
14570  ast_str_append(&invite, 0, "%s@", n);
14571  }
14572  ast_str_append(&invite, 0, "%s", p->tohost);
14573  if (p->portinuri) {
14574  ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
14575  }
14576  ast_str_append(&invite, 0, "%s", urioptions);
14577  }
14578  }
14579 
14580  /* If custom URI options have been provided, append them */
14581  if (p->options && !ast_strlen_zero(p->options->uri_options))
14582  ast_str_append(&invite, 0, ";%s", p->options->uri_options);
14583 
14584  /* This is the request URI, which is the next hop of the call
14585  which may or may not be the destination of the call
14586  */
14587  ast_string_field_set(p, uri, ast_str_buffer(invite));
14588 
14589  if (!ast_strlen_zero(p->todnid)) {
14590  /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
14591  if (!strchr(p->todnid, '@')) {
14592  /* We have no domain in the dnid */
14593  ret = ast_str_set(&to, 0, "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
14594  } else {
14595  ret = ast_str_set(&to, 0, "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
14596  }
14597  } else {
14598  if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
14599  /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
14600  ret = ast_str_set(&to, 0, "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
14601  } else if (p->options && p->options->vxml_url) {
14602  /* If there is a VXML URL append it to the SIP URL */
14603  ret = ast_str_set(&to, 0, "<%s>;%s", p->uri, p->options->vxml_url);
14604  } else {
14605  ret = ast_str_set(&to, 0, "<%s>", p->uri);
14606  }
14607  }
14608  if (ret == AST_DYNSTR_BUILD_FAILED) {
14609  /* We don't have an escape path from here... */
14610  ast_log(LOG_ERROR, "The To header was truncated in call '%s'. This call setup will fail.\n", p->callid);
14611  /* Make sure that the field contains something non-broken.
14612  See https://issues.asterisk.org/jira/browse/ASTERISK-26069
14613  */
14614  ast_str_set(&to, 3, "<>");
14615  }
14616 
14617  init_req(req, sipmethod, p->uri);
14618  /* now tmp_n is available so reuse it to build the CSeq */
14619  snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
14620 
14621  add_header(req, "Via", p->via);
14622  add_max_forwards(p, req);
14623  /* This will be a no-op most of the time. However, under certain circumstances,
14624  * NOTIFY messages will use this function for preparing the request and should
14625  * have Route headers present.
14626  */
14627  add_route(req, &p->route, 0);
14628 
14629  add_header(req, "From", ast_str_buffer(from));
14630  add_header(req, "To", ast_str_buffer(to));
14631  ast_string_field_set(p, exten, l);
14632  build_contact(p, req, 0);
14633  add_header(req, "Contact", p->our_contact);
14634  add_header(req, "Call-ID", p->callid);
14635  add_header(req, "CSeq", tmp_n);
14637  add_header(req, "User-Agent", global_useragent);
14638  }
14639 
14640  ast_free(from);
14641  ast_free(to);
14642  ast_free(invite);
14643 }
14644 
14645 /*! \brief Add "Diversion" header to outgoing message
14646  *
14647  * We need to add a Diversion header if the owner channel of
14648  * this dialog has redirecting information associated with it.
14649  *
14650  * \param req The request/response to which we will add the header
14651  * \param pvt The sip_pvt which represents the call-leg
14652  */
14653 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt)
14654 {
14655  struct ast_party_id diverting_from;
14656  const char *reason;
14657  const char *quote_str;
14658  char header_text[256];
14659  char encoded_number[SIPBUFSIZE/2];
14660 
14661  /* We skip this entirely if the configuration doesn't allow diversion headers */
14662  if (!sip_cfg.send_diversion) {
14663  return;
14664  }
14665 
14666  if (!pvt->owner) {
14667  return;
14668  }
14669 
14670  diverting_from = ast_channel_redirecting_effective_from(pvt->owner);
14671  if (!diverting_from.number.valid
14672  || ast_strlen_zero(diverting_from.number.str)) {
14673  return;
14674  }
14675 
14677  ast_uri_encode(diverting_from.number.str, encoded_number, sizeof(encoded_number), ast_uri_sip_user);
14678  } else {
14679  ast_copy_string(encoded_number, diverting_from.number.str, sizeof(encoded_number));
14680  }
14681 
14683 
14684  /* Reason is either already quoted or it is a token to not need quotes added. */
14685  quote_str = *reason == '\"' || sip_is_token(reason) ? "" : "\"";
14686 
14687  /* We at least have a number to place in the Diversion header, which is enough */
14688  if (!diverting_from.name.valid
14689  || ast_strlen_zero(diverting_from.name.str)) {
14690  snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s%s%s",
14691  encoded_number,
14693  quote_str, reason, quote_str);
14694  } else {
14695  char escaped_name[SIPBUFSIZE/2];
14697  ast_escape_quoted(diverting_from.name.str, escaped_name, sizeof(escaped_name));
14698  } else {
14699  ast_copy_string(escaped_name, diverting_from.name.str, sizeof(escaped_name));
14700  }
14701  snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s%s%s",
14702  escaped_name,
14703  encoded_number,
14705  quote_str, reason, quote_str);
14706  }
14707 
14708  add_header(req, "Diversion", header_text);
14709 }
14710 
14711 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
14712 {
14713  struct sip_pvt *pvt;
14714  int expires;
14715 
14716  epa_entry->publish_type = publish_type;
14717 
14718  if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL, 0))) {
14719  return -1;
14720  }
14721 
14722  sip_pvt_lock(pvt);
14723 
14724  if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
14725  sip_pvt_unlock(pvt);
14726  dialog_unlink_all(pvt);
14727  dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
14728  return -1;
14729  }
14730  ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
14731  ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
14732  expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
14733  pvt->expiry = expires;
14734 
14735  /* Bump refcount for sip_pvt's reference */
14736  ao2_ref(epa_entry, +1);
14737  pvt->epa_entry = epa_entry;
14738 
14739  transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
14740  sip_pvt_unlock(pvt);
14742  dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
14743  return 0;
14744 }
14745 
14746 /*!
14747  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
14748  * \param p sip_pvt structure
14749  * \param sipmethod
14750  * \param sdp unknown
14751  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
14752  * 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
14753  * \param explicit_uri
14754 */
14755 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
14756 {
14757  struct sip_request req;
14758  struct ast_variable *var;
14759 
14760  if (init) {/* Bump branch even on initial requests */
14761  p->branch ^= ast_random();
14762  p->invite_branch = p->branch;
14763  build_via(p);
14764  }
14765  if (init > 1) {
14766  initreqprep(&req, p, sipmethod, explicit_uri);
14767  } else {
14768  /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
14769  reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
14770  }
14771 
14772  if (p->options && p->options->auth) {
14773  add_header(&req, p->options->authheader, p->options->auth);
14774  }
14775  add_date(&req);
14776  if (sipmethod == SIP_REFER && p->refer) { /* Call transfer */
14777  if (!ast_strlen_zero(p->refer->refer_to)) {
14778  add_header(&req, "Refer-To", p->refer->refer_to);
14779  }
14780  if (!ast_strlen_zero(p->refer->referred_by)) {
14781  add_header(&req, "Referred-By", p->refer->referred_by);
14782  }
14783  } else if (sipmethod == SIP_SUBSCRIBE) {
14784  if (p->subscribed == MWI_NOTIFICATION) {
14785  add_header(&req, "Event", "message-summary");
14786  add_header(&req, "Accept", "application/simple-message-summary");
14787  } else if (p->subscribed == CALL_COMPLETION) {
14788  add_header(&req, "Event", "call-completion");
14789  add_header(&req, "Accept", "application/call-completion");
14790  }
14791  add_expires(&req, p->expiry);
14792  }
14793 
14794  /* This new INVITE is part of an attended transfer. Make sure that the
14795  other end knows and replace the current call with this new call */
14796  if (p->options && !ast_strlen_zero(p->options->replaces)) {
14797  add_header(&req, "Replaces", p->options->replaces);
14798  add_header(&req, "Require", "replaces");
14799  }
14800 
14801  /* Add Session-Timers related headers if not already there */
14802  if (ast_strlen_zero(sip_get_header(&req, "Session-Expires")) &&
14803  (sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) &&
14806  && st_get_se(p, FALSE) != DEFAULT_MIN_SE))) {
14807  char i2astr[10];
14808 
14809  if (!p->stimer->st_interval) {
14810  p->stimer->st_interval = st_get_se(p, TRUE);
14811  }
14812 
14813  p->stimer->st_active = TRUE;
14815  snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
14816  add_header(&req, "Session-Expires", i2astr);
14817  }
14818 
14819  snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
14820  add_header(&req, "Min-SE", i2astr);
14821  }
14822 
14823  add_header(&req, "Allow", ALLOWED_METHODS);
14824  add_supported(p, &req);
14825 
14826  if (p->owner && ((p->options && p->options->addsipheaders)
14827  || (p->refer && global_refer_addheaders))) {
14828  struct ast_channel *chan = p->owner; /* The owner channel */
14829  struct varshead *headp;
14830 
14831  ast_channel_lock(chan);
14832 
14833  headp = ast_channel_varshead(chan);
14834 
14835  if (!headp) {
14836  ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
14837  } else {
14838  const struct ast_var_t *current;
14839  AST_LIST_TRAVERSE(headp, current, entries) {
14840  /* SIPADDHEADER: Add SIP header to outgoing call */
14841  if (!strncmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
14842  char *content, *end;
14843  const char *header = ast_var_value(current);
14844  char *headdup = ast_strdupa(header);
14845 
14846  /* Strip of the starting " (if it's there) */
14847  if (*headdup == '"') {
14848  headdup++;
14849  }
14850  if ((content = strchr(headdup, ':'))) {
14851  *content++ = '\0';
14852  content = ast_skip_blanks(content); /* Skip white space */
14853  /* Strip the ending " (if it's there) */
14854  end = content + strlen(content) -1;
14855  if (*end == '"') {
14856  *end = '\0';
14857  }
14858 
14859  add_header(&req, headdup, content);
14860  if (sipdebug) {
14861  ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
14862  }
14863  }
14864  }
14865  }
14866  }
14867 
14868  ast_channel_unlock(chan);
14869  }
14870  if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
14871  add_rpid(&req, p);
14872  if (sipmethod == SIP_INVITE) {
14873  add_diversion(&req, p);
14874  }
14875  if (sdp) {
14877  if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
14878  ast_debug(1, "T38 is in state %u on channel %s\n", p->t38.state, p->owner ? ast_channel_name(p->owner) : "<none>");
14879  add_sdp(&req, p, FALSE, FALSE, TRUE);
14880  } else if (p->rtp) {
14882  add_sdp(&req, p, FALSE, TRUE, FALSE);
14883  }
14884  } else if (sipmethod == SIP_NOTIFY && p->notify) {
14885  for (var = p->notify->headers; var; var = var->next) {
14886  add_header(&req, var->name, var->value);
14887  }
14888  if (ast_str_strlen(p->notify->content)) {
14890  }
14891  } else if (sipmethod == SIP_PUBLISH) {
14892  switch (p->epa_entry->static_data->event) {
14893  case CALL_COMPLETION:
14894  add_header(&req, "Event", "call-completion");
14895  add_expires(&req, p->expiry);
14897  add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
14898  }
14899 
14900  if (!ast_strlen_zero(p->epa_entry->body)) {
14901  add_header(&req, "Content-Type", "application/pidf+xml");
14902  add_content(&req, p->epa_entry->body);
14903  }
14904  default:
14905  break;
14906  }
14907  }
14908 
14909  if (!p->initreq.headers || init > 2) {
14910  initialize_initreq(p, &req);
14911  }
14912  if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
14913  p->lastinvite = p->ocseq;
14914  }
14915  return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
14916 }
14917 
14918 /*!
14919  * \brief Send a subscription or resubscription for MWI
14920  *
14921  * \note Run by the sched thread.
14922  */
14923 static int sip_subscribe_mwi_do(const void *data)
14924 {
14925  struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi *) data;
14926 
14927  mwi->resub = -1;
14929  ao2_t_ref(mwi, -1, "Scheduled mwi resub complete");
14930 
14931  return 0;
14932 }
14933 
14934 /* Run by the sched thread. */
14935 static int __shutdown_mwi_subscription(const void *data)
14936 {
14937  struct sip_subscription_mwi *mwi = (void *) data;
14938 
14939  AST_SCHED_DEL_UNREF(sched, mwi->resub,
14940  ao2_t_ref(mwi, -1, "Stop scheduled mwi resub"));
14941 
14942  if (mwi->dnsmgr) {
14943  ast_dnsmgr_release(mwi->dnsmgr);
14944  mwi->dnsmgr = NULL;
14945  ao2_t_ref(mwi, -1, "dnsmgr release");
14946  }
14947 
14948  ao2_t_ref(mwi, -1, "Shutdown MWI subscription action");
14949  return 0;
14950 }
14951 
14953 {
14954  ao2_t_ref(mwi, +1, "Shutdown MWI subscription action");
14955  if (ast_sched_add(sched, 0, __shutdown_mwi_subscription, mwi) < 0) {
14956  /* Uh Oh. Expect bad behavior. */
14957  ao2_t_ref(mwi, -1, "Failed to schedule shutdown MWI subscription action");
14958  }
14959 }
14960 
14963  int ms;
14964 };
14965 
14966 /* Run by the sched thread. */
14967 static int __start_mwi_subscription(const void *data)
14968 {
14969  struct mwi_subscription_data *sched_data = (void *) data;
14970  struct sip_subscription_mwi *mwi = sched_data->mwi;
14971  int ms = sched_data->ms;
14972 
14973  ast_free(sched_data);
14974 
14975  AST_SCHED_DEL_UNREF(sched, mwi->resub,
14976  ao2_t_ref(mwi, -1, "Stop scheduled mwi resub"));
14977 
14978  ao2_t_ref(mwi, +1, "Schedule mwi resub");
14979  mwi->resub = ast_sched_add(sched, ms, sip_subscribe_mwi_do, mwi);
14980  if (mwi->resub < 0) {
14981  /* Uh Oh. Expect bad behavior. */
14982  ao2_t_ref(mwi, -1, "Failed to schedule mwi resub");
14983  }
14984 
14985  ao2_t_ref(mwi, -1, "Start MWI subscription action");
14986  return 0;
14987 }
14988 
14989 static void start_mwi_subscription(struct sip_subscription_mwi *mwi, int ms)
14990 {
14991  struct mwi_subscription_data *sched_data;
14992 
14993  sched_data = ast_malloc(sizeof(*sched_data));
14994  if (!sched_data) {
14995  /* Uh Oh. Expect bad behavior. */
14996  return;
14997  }
14998  sched_data->mwi = mwi;
14999  sched_data->ms = ms;
15000  ao2_t_ref(mwi, +1, "Start MWI subscription action");
15001  if (ast_sched_add(sched, 0, __start_mwi_subscription, sched_data) < 0) {
15002  /* Uh Oh. Expect bad behavior. */
15003  ao2_t_ref(mwi, -1, "Failed to schedule start MWI subscription action");
15004  ast_free(sched_data);
15005  }
15006 }
15007 
15008 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
15009 {
15010  struct sip_registry *reg = data;
15011  const char *old_str;
15012 
15013  /* This shouldn't happen, but just in case */
15014  if (ast_sockaddr_isnull(new)) {
15015  ast_debug(1, "Empty sockaddr change...ignoring!\n");
15016  return;
15017  }
15018 
15019  if (!ast_sockaddr_port(new)) {
15020  ast_sockaddr_set_port(new, reg->portno);
15021  }
15022 
15023  old_str = ast_strdupa(ast_sockaddr_stringify(old));
15024 
15025  ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
15026  ast_sockaddr_copy(&reg->us, new);
15027 }
15028 
15029 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
15030 {
15031  struct sip_peer *peer = data;
15032  const char *old_str;
15033 
15034  /* This shouldn't happen, but just in case */
15035  if (ast_sockaddr_isnull(new)) {
15036  ast_debug(1, "Empty sockaddr change...ignoring!\n");
15037  return;
15038  }
15039 
15040  if (!ast_sockaddr_isnull(&peer->addr)) {
15041  ao2_unlink(peers_by_ip, peer);
15042  }
15043 
15044  if (!ast_sockaddr_port(new)) {
15046  }
15047 
15048  old_str = ast_strdupa(ast_sockaddr_stringify(old));
15049  ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
15050 
15051  ao2_lock(peer);
15052  ast_sockaddr_copy(&peer->addr, new);
15053  ao2_unlock(peer);
15054 
15055  ao2_link(peers_by_ip, peer);
15056 }
15057 
15058 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
15059 {
15060  struct sip_subscription_mwi *mwi = data;
15061  const char *old_str;
15062 
15063  /* This shouldn't happen, but just in case */
15064  if (ast_sockaddr_isnull(new)) {
15065  ast_debug(1, "Empty sockaddr change...ignoring!\n");
15066  return;
15067  }
15068 
15069  old_str = ast_strdupa(ast_sockaddr_stringify(old));
15070  ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
15071  ast_sockaddr_copy(&mwi->us, new);
15072 }
15073 
15074 /*! \brief Actually setup an MWI subscription or resubscribe */
15076 {
15077  /* If we have no DNS manager let's do a lookup */
15078  if (!mwi->dnsmgr) {
15079  char transport[MAXHOSTNAMELEN];
15080  snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
15081 
15082  mwi->us.ss.ss_family = get_address_family_filter(mwi->transport); /* Filter address family */
15083  ao2_t_ref(mwi, +1, "dnsmgr reference to mwi");
15084  ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, mwi);
15085  if (!mwi->dnsmgr) {
15086  ao2_t_ref(mwi, -1, "dnsmgr disabled, remove reference");
15087  }
15088  }
15089 
15090  /* If we already have a subscription up simply send a resubscription */
15091  if (mwi->call) {
15092  transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
15093  return 0;
15094  }
15095 
15096  /* Create a dialog that we will use for the subscription */
15097  if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, 0))) {
15098  return -1;
15099  }
15100 
15101  ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
15102 
15103  if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
15104  ast_sockaddr_set_port(&mwi->us, mwi->portno);
15105  }
15106 
15107  /* Setup the destination of our subscription */
15108  if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
15109  dialog_unlink_all(mwi->call);
15110  mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
15111  return 0;
15112  }
15113 
15114  mwi->call->expiry = mwi_expiry;
15115 
15116  if (!mwi->dnsmgr && mwi->portno) {
15117  ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
15118  ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
15119  } else {
15120  mwi->portno = ast_sockaddr_port(&mwi->call->sa);
15121  }
15122 
15123  /* Set various other information */
15124  if (!ast_strlen_zero(mwi->authuser)) {
15126  ast_string_field_set(mwi->call, authname, mwi->authuser);
15127  ast_string_field_set(mwi->call, fromuser, mwi->authuser);
15128  } else {
15130  ast_string_field_set(mwi->call, authname, mwi->username);
15131  ast_string_field_set(mwi->call, fromuser, mwi->username);
15132  }
15133  ast_string_field_set(mwi->call, username, mwi->username);
15134  if (!ast_strlen_zero(mwi->secret)) {
15135  ast_string_field_set(mwi->call, peersecret, mwi->secret);
15136  }
15137  set_socket_transport(&mwi->call->socket, mwi->transport);
15138  ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
15139  build_via(mwi->call);
15140 
15141  /* Change the dialog callid. */
15142  change_callid_pvt(mwi->call, NULL);
15143 
15144  ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
15145 
15146  /* Associate the call with us */
15147  mwi->call->mwi = ao2_t_bump(mwi, "Reference mwi from it's call");
15148 
15150 
15151  /* Actually send the packet */
15152  transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
15153 
15154  return 0;
15155 }
15156 
15157 /*!
15158  * \internal
15159  * \brief Find the channel that is causing the RINGING update, ref'd
15160  */
15161 static struct ast_channel *find_ringing_channel(struct ao2_container *device_state_info, struct sip_pvt *p)
15162 {
15163  struct ao2_iterator citer;
15164  struct ast_device_state_info *device_state;
15165  struct ast_channel *c = NULL;
15166  struct timeval tv = {0,};
15167 
15168  /* iterate ringing devices and get the oldest of all causing channels */
15169  citer = ao2_iterator_init(device_state_info, 0);
15170  for (; (device_state = ao2_iterator_next(&citer)); ao2_ref(device_state, -1)) {
15171  if (!device_state->causing_channel || (device_state->device_state != AST_DEVICE_RINGING &&
15172  device_state->device_state != AST_DEVICE_RINGINUSE)) {
15173  continue;
15174  }
15175  ast_channel_lock(device_state->causing_channel);
15176  if (ast_tvzero(tv) || ast_tvcmp(ast_channel_creationtime(device_state->causing_channel), tv) < 0) {
15177  c = device_state->causing_channel;
15178  tv = ast_channel_creationtime(c);
15179  }
15180  ast_channel_unlock(device_state->causing_channel);
15181  }
15182  ao2_iterator_destroy(&citer);
15183  return c ? ast_channel_ref(c) : NULL;
15184 }
15185 
15186 /* XXX Candidate for moving into its own file */
15188 {
15189  return (strstr(p->useragent, "Digium")) ? 1 : 0;
15190 }
15191 
15192 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
15193 static void state_notify_build_xml(struct state_notify_data *data, int full, const char *exten, const char *context, struct ast_str **tmp, struct sip_pvt *p, int subscribed, const char *mfrom, const char *mto)
15194 {
15195  enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
15196  const char *statestring = "terminated";
15197  const char *pidfstate = "--";
15198  const char *pidfnote ="Ready";
15199  char hint[AST_MAX_EXTENSION];
15200 
15201  switch (data->state) {
15203  statestring = (sip_cfg.notifyringing == NOTIFYRINGING_ENABLED) ? "early" : "confirmed";
15204  local_state = NOTIFY_INUSE;
15205  pidfstate = "busy";
15206  pidfnote = "Ringing";
15207  break;
15208  case AST_EXTENSION_RINGING:
15209  statestring = "early";
15210  local_state = NOTIFY_INUSE;
15211  pidfstate = "busy";
15212  pidfnote = "Ringing";
15213  break;
15214  case AST_EXTENSION_INUSE:
15215  statestring = "confirmed";
15216  local_state = NOTIFY_INUSE;
15217  pidfstate = "busy";
15218  pidfnote = "On the phone";
15219  break;
15220  case AST_EXTENSION_BUSY:
15221  statestring = "confirmed";
15222  local_state = NOTIFY_CLOSED;
15223  pidfstate = "busy";
15224  pidfnote = "On the phone";
15225  break;
15227  statestring = "terminated";
15228  local_state = NOTIFY_CLOSED;
15229  pidfstate = "away";
15230  pidfnote = "Unavailable";
15231  break;
15232  case AST_EXTENSION_ONHOLD:
15233  statestring = "confirmed";
15234  local_state = NOTIFY_CLOSED;
15235  pidfstate = "busy";
15236  pidfnote = "On hold";
15237  break;
15239  default:
15240  /* Default setting */
15241  break;
15242  }
15243 
15244  /* Check which device/devices we are watching and if they are registered */
15245  if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
15246  char *hint2;
15247  char *individual_hint = NULL;
15248  int hint_count = 0, unavailable_count = 0;
15249 
15250  /* strip off any possible PRESENCE providers from hint */
15251  if ((hint2 = strrchr(hint, ','))) {
15252  *hint2 = '\0';
15253  }
15254  hint2 = hint;
15255 
15256  while ((individual_hint = strsep(&hint2, "&"))) {
15257  hint_count++;
15258 
15259  if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
15260  unavailable_count++;
15261  }
15262 
15263  /* If none of the hinted devices are registered, we will
15264  * override notification and show no availability.
15265  */
15266  if (hint_count > 0 && hint_count == unavailable_count) {
15267  local_state = NOTIFY_CLOSED;
15268  pidfstate = "away";
15269  pidfnote = "Not online";
15270  }
15271  }
15272 
15273  switch (subscribed) {
15274  case XPIDF_XML:
15275  case CPIM_PIDF_XML:
15276  ast_str_append(tmp, 0,
15277  "<?xml version=\"1.0\"?>\n"
15278  "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
15279  "<presence>\n");
15280  ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
15281  ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
15282  ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
15283  ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
15284  ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
15285  ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
15286  break;
15287  case PIDF_XML: /* Eyebeam supports this format */
15288  ast_str_append(tmp, 0,
15289  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
15290  "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
15291  ast_str_append(tmp, 0, "<pp:person><status>\n");
15292  if (pidfstate[0] != '-') {
15293  ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
15294  }
15295  ast_str_append(tmp, 0, "</status></pp:person>\n");
15296  ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
15297  ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
15298  ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
15299  if (pidfstate[0] == 'b') /* Busy? Still open ... */
15300  ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
15301  else
15302  ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
15303 
15305  && (data->presence_state != AST_PRESENCE_NOT_SET)) {
15306  ast_str_append(tmp, 0, "</tuple>\n");
15307  ast_str_append(tmp, 0, "<tuple id=\"digium-presence\">\n");
15308  ast_str_append(tmp, 0, "<status>\n");
15309  ast_str_append(tmp, 0, "<digium_presence type=\"%s\" subtype=\"%s\">%s</digium_presence>\n",
15311  S_OR(data->presence_subtype, ""),
15312  S_OR(data->presence_message, ""));
15313  ast_str_append(tmp, 0, "</status>\n");
15314  ast_test_suite_event_notify("DIGIUM_PRESENCE_SENT",
15315  "PresenceState: %s\r\n"
15316  "Subtype: %s\r\n"
15317  "Message: %s",
15319  S_OR(data->presence_subtype, ""),
15320  S_OR(data->presence_message, ""));
15321  }
15322  ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
15323  break;
15324  case DIALOG_INFO_XML: /* SNOM subscribes in this format */
15325  ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
15326  ast_str_append(tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%u\" state=\"%s\" entity=\"%s\">\n", p->dialogver, full ? "full" : "partial", mto);
15327  if (data->state > 0 && (data->state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
15328  /* Twice the extension length should be enough for XML encoding */
15329  char local_display[AST_MAX_EXTENSION * 2];
15330  char remote_display[AST_MAX_EXTENSION * 2];
15331  char *local_target = ast_strdupa(mto);
15332  /* It may seem odd to base the remote_target on the To header here,
15333  * but testing by reporters on issue ASTERISK-16735 found that basing
15334  * on the From header would cause ringing state hints to not work
15335  * properly on certain SNOM devices. If you are using notifycid properly
15336  * (i.e. in the same extension and context as the dialed call) then this
15337  * should not be an issue since the data will be overwritten shortly
15338  * with channel caller ID
15339  */
15340  char *remote_target = ast_strdupa(mto);
15341 
15342  ast_xml_escape(exten, local_display, sizeof(local_display));
15343  ast_xml_escape(exten, remote_display, sizeof(remote_display));
15344 
15345  /* There are some limitations to how this works. The primary one is that the
15346  callee must be dialing the same extension that is being monitored. Simply dialing
15347  the hint'd device is not sufficient. */
15348  if (sip_cfg.notifycid) {
15349  struct ast_channel *callee;
15350 
15351  callee = find_ringing_channel(data->device_state_info, p);
15352  if (callee) {
15353  static char *anonymous = "anonymous";
15354  static char *invalid = "anonymous.invalid";
15355  char *cid_num;
15356  char *connected_num;
15357  int need;
15358  int cid_num_restricted, connected_num_restricted;
15359 
15360  ast_channel_lock(callee);
15361 
15362  cid_num_restricted = (ast_channel_caller(callee)->id.number.presentation &
15364  cid_num = S_COR(ast_channel_caller(callee)->id.number.valid,
15365  S_COR(cid_num_restricted, anonymous,
15366  ast_channel_caller(callee)->id.number.str), "");
15367 
15368  need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
15369  strlen(p->fromdomain)) + sizeof("sip:@");
15370  local_target = ast_alloca(need);
15371 
15372  snprintf(local_target, need, "sip:%s@%s", cid_num,
15373  cid_num_restricted ? invalid : p->fromdomain);
15374 
15375  ast_xml_escape(S_COR(ast_channel_caller(callee)->id.name.valid,
15376  S_COR((ast_channel_caller(callee)->id.name.presentation &
15378  ast_channel_caller(callee)->id.name.str), ""),
15379  local_display, sizeof(local_display));
15380 
15381  connected_num_restricted = (ast_channel_connected(callee)->id.number.presentation &
15383  connected_num = S_COR(ast_channel_connected(callee)->id.number.valid,
15384  S_COR(connected_num_restricted, anonymous,
15385  ast_channel_connected(callee)->id.number.str), "");
15386 
15387  need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
15388  strlen(p->fromdomain)) + sizeof("sip:@");
15389  remote_target = ast_alloca(need);
15390 
15391  snprintf(remote_target, need, "sip:%s@%s", connected_num,
15392  connected_num_restricted ? invalid : p->fromdomain);
15393 
15394  ast_xml_escape(S_COR(ast_channel_connected(callee)->id.name.valid,
15395  S_COR((ast_channel_connected(callee)->id.name.presentation &
15396  AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
15397  ast_channel_connected(callee)->id.name.str), ""),
15398  remote_display, sizeof(remote_display));
15399 
15400  ast_channel_unlock(callee);
15401  callee = ast_channel_unref(callee);
15402  }
15403 
15404  /* We create a fake call-id which the phone will send back in an INVITE
15405  Replaces header which we can grab and do some magic with. */
15407  ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
15408  exten, p->callid, p->theirtag, p->tag);
15409  } else {
15410  ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
15411  exten, p->callid);
15412  }
15413  ast_str_append(tmp, 0,
15414  "<remote>\n"
15415  /* See the limitations of this above. Luckily the phone seems to still be
15416  happy when these values are not correct. */
15417  "<identity display=\"%s\">%s</identity>\n"
15418  "<target uri=\"%s\"/>\n"
15419  "</remote>\n"
15420  "<local>\n"
15421  "<identity display=\"%s\">%s</identity>\n"
15422  "<target uri=\"%s\"/>\n"
15423  "</local>\n",
15424  remote_display, remote_target, remote_target, local_display, local_target, local_target);
15425  } else {
15426  ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
15427  }
15428 
15429  } else {
15430  ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
15431  }
15432  ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
15433  if (data->state == AST_EXTENSION_ONHOLD) {
15434  ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
15435  "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
15436  "</target>\n</local>\n", mto);
15437  }
15438  ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
15439  break;
15440  case NONE:
15441  default:
15442  break;
15443  }
15444 }
15445 
15446 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
15447 {
15448  struct sip_request req;
15449  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
15450  char uri[SIPBUFSIZE + sizeof("cc-URI: \r\n") - 1];
15451  char state_str[64];
15452  char subscription_state_hdr[64];
15453 
15455  ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%u)\n", state);
15456  return -1;
15457  }
15458 
15459  reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
15460  snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
15461  add_header(&req, "Event", "call-completion");
15462  add_header(&req, "Content-Type", "application/call-completion");
15463  snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
15464  add_header(&req, "Subscription-State", subscription_state_hdr);
15465  if (state == CC_READY) {
15466  generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
15467  snprintf(uri, sizeof(uri), "cc-URI: %s\r\n", agent_pvt->notify_uri);
15468  }
15469  add_content(&req, state_str);
15470  if (state == CC_READY) {
15471  add_content(&req, uri);
15472  }
15473  return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
15474 }
15475 
15476 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
15477 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout)
15478 {
15479  struct ast_str *tmp = ast_str_alloca(4000);
15480  char from[256], to[256];
15481  char *c, *mfrom, *mto;
15482  struct sip_request req;
15483  const struct cfsubscription_types *subscriptiontype;
15484 
15485  /* If the subscription has not yet been accepted do not send a NOTIFY */
15487  return 0;
15488  }
15489 
15490  memset(from, 0, sizeof(from));
15491  memset(to, 0, sizeof(to));
15492 
15493  subscriptiontype = find_subscription_type(p->subscribed);
15494 
15495  ast_copy_string(from, sip_get_header(&p->initreq, "From"), sizeof(from));
15496  c = get_in_brackets(from);
15497  if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
15498  ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
15499  return -1;
15500  }
15501 
15502  mfrom = remove_uri_parameters(c);
15503 
15504  ast_copy_string(to, sip_get_header(&p->initreq, "To"), sizeof(to));
15505  c = get_in_brackets(to);
15506  if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
15507  ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
15508  return -1;
15509  }
15510  mto = remove_uri_parameters(c);
15511 
15512  reqprep(&req, p, SIP_NOTIFY, 0, 1);
15513 
15514  switch(data->state) {
15516  if (timeout)
15517  add_header(&req, "Subscription-State", "terminated;reason=timeout");
15518  else {
15519  add_header(&req, "Subscription-State", "terminated;reason=probation");
15520  add_header(&req, "Retry-After", "60");
15521  }
15522  break;
15523  case AST_EXTENSION_REMOVED:
15524  add_header(&req, "Subscription-State", "terminated;reason=noresource");
15525  break;
15526  default:
15527  if (p->expiry)
15528  add_header(&req, "Subscription-State", "active");
15529  else /* Expired */
15530  add_header(&req, "Subscription-State", "terminated;reason=timeout");
15531  }
15532 
15533  switch (p->subscribed) {
15534  case XPIDF_XML:
15535  case CPIM_PIDF_XML:
15536  add_header(&req, "Event", subscriptiontype->event);
15537  state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
15538  add_header(&req, "Content-Type", subscriptiontype->mediatype);
15539  p->dialogver++;
15540  break;
15541  case PIDF_XML: /* Eyebeam supports this format */
15542  add_header(&req, "Event", subscriptiontype->event);
15543  state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
15544  add_header(&req, "Content-Type", subscriptiontype->mediatype);
15545  p->dialogver++;
15546  break;
15547  case DIALOG_INFO_XML: /* SNOM subscribes in this format */
15548  add_header(&req, "Event", subscriptiontype->event);
15549  state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
15550  add_header(&req, "Content-Type", subscriptiontype->mediatype);
15551  p->dialogver++;
15552  break;
15553  case NONE:
15554  default:
15555  break;
15556  }
15557 
15558  add_content(&req, ast_str_buffer(tmp));
15559 
15560  p->pendinginvite = p->ocseq; /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
15561 
15562  /* Send as XMIT_CRITICAL as we may never receive a 200 OK Response which clears p->pendinginvite.
15563  *
15564  * extensionstate_update() uses p->pendinginvite for queuing control.
15565  * Updates stall if pendinginvite <> 0.
15566  *
15567  * The most appropriate solution is to remove the subscription when the NOTIFY transaction fails.
15568  * The client will re-subscribe after restarting or maxexpiry timeout.
15569  */
15570 
15571  /* RFC6665 4.2.2. Sending State Information to Subscribers
15572  * If the NOTIFY request fails due to expiration of SIP Timer F (transaction timeout),
15573  * the notifier SHOULD remove the subscription.
15574  */
15575  return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15576 }
15577 
15578 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
15579 \note - Notification only works for registered peers with mailbox= definitions
15580  in sip.conf
15581  - We use the SIP Event package message-summary
15582  MIME type defaults to "application/simple-message-summary";
15583  */
15584 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
15585 {
15586  struct sip_request req;
15587  struct ast_str *out = ast_str_alloca(500);
15589  const char *domain;
15590  const char *exten = S_OR(vmexten, default_vmexten);
15591 
15592  initreqprep(&req, p, SIP_NOTIFY, NULL);
15593  add_header(&req, "Event", "message-summary");
15594  add_header(&req, "Content-Type", default_notifymime);
15595  ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
15596 
15597  /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
15599 
15600  if (!sip_standard_port(p->socket.type, ourport)) {
15601  if (p->socket.type == AST_TRANSPORT_UDP) {
15602  ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
15603  } else {
15604  ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, sip_get_transport(p->socket.type));
15605  }
15606  } else {
15607  if (p->socket.type == AST_TRANSPORT_UDP) {
15608  ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
15609  } else {
15610  ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, sip_get_transport(p->socket.type));
15611  }
15612  }
15613  /* Cisco has a bug in the SIP stack where it can't accept the
15614  (0/0) notification. This can temporarily be disabled in
15615  sip.conf with the "buggymwi" option */
15616  ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
15617  newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
15618 
15619  if (p->subscribed) {
15620  if (p->expiry) {
15621  add_header(&req, "Subscription-State", "active");
15622  } else { /* Expired */
15623  add_header(&req, "Subscription-State", "terminated;reason=timeout");
15624  }
15625  }
15626 
15627  add_content(&req, ast_str_buffer(out));
15628 
15629  if (!p->initreq.headers) {
15630  initialize_initreq(p, &req);
15631  }
15632  return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15633 }
15634 
15635 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
15636 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
15637 {
15638  struct sip_request req;
15639  char tmp[SIPBUFSIZE/2];
15640 
15641  reqprep(&req, p, SIP_NOTIFY, 0, 1);
15642  snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
15643  add_header(&req, "Event", tmp);
15644  add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
15645  add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
15646  add_header(&req, "Allow", ALLOWED_METHODS);
15647  add_supported(p, &req);
15648 
15649  snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
15650  add_content(&req, tmp);
15651 
15652  if (!p->initreq.headers) {
15653  initialize_initreq(p, &req);
15654  }
15655 
15656  return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15657 }
15658 
15659 static int manager_sipnotify(struct mansession *s, const struct message *m)
15660 {
15661  const char *channame = astman_get_header(m, "Channel");
15663  const char *callid = astman_get_header(m, "Call-ID");
15664  struct sip_pvt *p;
15665  struct ast_variable *header, *var;
15666 
15667  if (ast_strlen_zero(channame)) {
15668  astman_send_error(s, m, "SIPNotify requires a channel name");
15669  ast_variables_destroy(vars);
15670  return 0;
15671  }
15672 
15673  if (!strncasecmp(channame, "sip/", 4)) {
15674  channame += 4;
15675  }
15676 
15677  /* check if Call-ID header is set */
15678  if (!ast_strlen_zero(callid)) {
15679  struct sip_pvt tmp_dialog = {
15680  .callid = callid,
15681  };
15682 
15683  p = ao2_find(dialogs, &tmp_dialog, OBJ_SEARCH_OBJECT);
15684  if (!p) {
15685  astman_send_error(s, m, "Call-ID not found");
15686  ast_variables_destroy(vars);
15687  return 0;
15688  }
15689 
15690  if (!(p->notify)) {
15691  sip_notify_alloc(p);
15692  } else {
15694  }
15695  } else {
15696  if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, 0))) {
15697  astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
15698  ast_variables_destroy(vars);
15699  return 0;
15700  }
15701 
15702  if (create_addr(p, channame, NULL, 1)) {
15703  /* Maybe they're not registered, etc. */
15704  dialog_unlink_all(p);
15705  dialog_unref(p, "unref dialog inside for loop" );
15706  /* sip_destroy(p); */
15707  astman_send_error(s, m, "Could not create address");
15708  ast_variables_destroy(vars);
15709  return 0;
15710  }
15711 
15712  /* Notify is outgoing call */
15713  ast_set_flag(&p->flags[0], SIP_OUTGOING);
15714  sip_notify_alloc(p);
15715 
15716  }
15717 
15718  p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
15719 
15720  for (var = vars; var; var = var->next) {
15721  if (!strcasecmp(var->name, "Content")) {
15722  if (ast_str_strlen(p->notify->content))
15723  ast_str_append(&p->notify->content, 0, "\r\n");
15724  ast_str_append(&p->notify->content, 0, "%s", var->value);
15725  } else if (!strcasecmp(var->name, "Content-Length")) {
15726  ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
15727  } else {
15728  header->next = ast_variable_new(var->name, var->value, "");
15729  header = header->next;
15730  }
15731  }
15732 
15733  if (ast_strlen_zero(callid)) {
15734  /* Now that we have the peer's address, set our ip and change callid */
15735  ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
15736  build_via(p);
15737 
15738  change_callid_pvt(p, NULL);
15739 
15741  transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
15742  } else {
15744  transmit_invite(p, SIP_NOTIFY, 0, 1, NULL);
15745  }
15746  dialog_unref(p, "bump down the count of p since we're done with it.");
15747 
15748  astman_send_ack(s, m, "Notify Sent");
15749  ast_variables_destroy(vars);
15750  return 0;
15751 }
15752 
15753 /*! \brief Send a provisional response indicating that a call was redirected
15754  */
15755 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
15756 {
15757  struct sip_request resp;
15758 
15760  return;
15761  }
15762 
15763  respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
15764  add_diversion(&resp, p);
15765  send_response(p, &resp, XMIT_UNRELIABLE, 0);
15766 }
15767 
15768 /*! \brief Notify peer that the connected line has changed */
15769 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
15770 {
15771  struct ast_party_id connected_id = ast_channel_connected_effective_id(p->owner);
15772 
15773  if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
15774  return;
15775  }
15776  if (!connected_id.number.valid
15777  || ast_strlen_zero(connected_id.number.str)) {
15778  return;
15779  }
15780 
15781  append_history(p, "ConnectedLine", "%s party is now %s <%s>",
15782  ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
15783  S_COR(connected_id.name.valid, connected_id.name.str, ""),
15784  S_COR(connected_id.number.valid, connected_id.number.str, ""));
15785 
15787  struct sip_request req;
15788 
15789  if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
15790  reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
15791 
15792  add_header(&req, "Allow", ALLOWED_METHODS);
15793  add_supported(p, &req);
15794  add_rpid(&req, p);
15795  add_sdp(&req, p, FALSE, TRUE, FALSE);
15796 
15797  initialize_initreq(p, &req);
15798  p->lastinvite = p->ocseq;
15799  ast_set_flag(&p->flags[0], SIP_OUTGOING);
15800  send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15802  reqprep(&req, p, SIP_UPDATE, 0, 1);
15803  add_rpid(&req, p);
15804  add_header(&req, "X-Asterisk-rpid-update", "Yes");
15805  send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15806  } else {
15807  /* We cannot send the update yet, so we have to wait until we can */
15809  }
15810  } else {
15813  struct sip_request resp;
15814 
15817  respprep(&resp, p, "180 Ringing", &p->initreq);
15818  add_rpid(&resp, p);
15819  send_response(p, &resp, XMIT_UNRELIABLE, 0);
15820  ast_set_flag(&p->flags[0], SIP_RINGING);
15821  } else if (ast_channel_state(p->owner) == AST_STATE_RINGING) {
15823  respprep(&resp, p, "183 Session Progress", &p->initreq);
15824  add_rpid(&resp, p);
15825  send_response(p, &resp, XMIT_UNRELIABLE, 0);
15827  } else {
15828  ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", ast_channel_name(p->owner), ast_state2str(ast_channel_state(p->owner)));
15829  }
15830  }
15831  }
15832 }
15833 
15834 static const struct _map_x_s regstatestrings[] = {
15835  { REG_STATE_FAILED, "Failed" },
15836  { REG_STATE_UNREGISTERED, "Unregistered"},
15837  { REG_STATE_REGSENT, "Request Sent"},
15838  { REG_STATE_AUTHSENT, "Auth. Sent"},
15839  { REG_STATE_REGISTERED, "Registered"},
15840  { REG_STATE_REJECTED, "Rejected"},
15841  { REG_STATE_TIMEOUT, "Registered"},/* Hidden state. We are renewing registration. */
15842  { REG_STATE_NOAUTH, "No Authentication"},
15843  { -1, NULL } /* terminator */
15844 };
15845 
15846 /*! \brief Convert registration state status to string */
15847 static const char *regstate2str(enum sipregistrystate regstate)
15848 {
15849  return map_x_s(regstatestrings, regstate, "Unknown");
15850 }
15851 
15852 static void sip_publish_registry(const char *username, const char *domain, const char *status)
15853 {
15854  ast_system_publish_registry("SIP", username, domain, status, NULL);
15855 }
15856 
15857 /*!
15858  * \brief Update registration with SIP Proxy.
15859  *
15860  * \details
15861  * Called from the scheduler when the previous registration expires,
15862  * so we don't have to cancel the pending event.
15863  * We assume the reference so the sip_registry is valid, since it
15864  * is stored in the scheduled event anyways.
15865  *
15866  * \note Run by the sched thread.
15867  */
15868 static int sip_reregister(const void *data)
15869 {
15870  /* if we are here, we know that we need to reregister. */
15871  struct sip_registry *r = (struct sip_registry *) data;
15872 
15873  if (r->call && r->call->do_history) {
15874  append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
15875  }
15876  /* Since registry's are only added/removed by the monitor thread, this
15877  may be overkill to reference/dereference at all here */
15878  if (sipdebug) {
15879  ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
15880  }
15881 
15882  r->expire = -1;
15883  r->expiry = r->configured_expiry;
15884  switch (r->regstate) {
15886  case REG_STATE_REGSENT:
15887  case REG_STATE_AUTHSENT:
15888  break;
15889  case REG_STATE_REJECTED:
15890  case REG_STATE_NOAUTH:
15891  case REG_STATE_FAILED:
15892  /* Restarting registration as unregistered */
15894  break;
15895  case REG_STATE_TIMEOUT:
15896  case REG_STATE_REGISTERED:
15897  /* Registration needs to be renewed. */
15899  break;
15900  }
15901  __sip_do_register(r);
15902  ao2_t_ref(r, -1, "Scheduled reregister timeout complete");
15903  return 0;
15904 }
15905 
15906 /*! \brief Register with SIP proxy
15907  \return see \ref __sip_xmit
15908 */
15909 static int __sip_do_register(struct sip_registry *r)
15910 {
15911  int res;
15912 
15914  return res;
15915 }
15916 
15919  int ms;
15920 };
15921 
15922 /* Run by the sched thread. */
15923 static int __start_reregister_timeout(const void *data)
15924 {
15925  struct reregister_data *sched_data = (void *) data;
15926  struct sip_registry *reg = sched_data->reg;
15927  int ms = sched_data->ms;
15928 
15929  ast_free(sched_data);
15930 
15931  AST_SCHED_DEL_UNREF(sched, reg->expire,
15932  ao2_t_ref(reg, -1, "Stop scheduled reregister timeout"));
15933 
15934  ao2_t_ref(reg, +1, "Schedule reregister timeout");
15935  reg->expire = ast_sched_add(sched, ms, sip_reregister, reg);
15936  if (reg->expire < 0) {
15937  /* Uh Oh. Expect bad behavior. */
15938  ao2_t_ref(reg, -1, "Failed to schedule reregister timeout");
15939  }
15940 
15941  ao2_t_ref(reg, -1, "Start reregister timeout action");
15942  return 0;
15943 }
15944 
15945 static void start_reregister_timeout(struct sip_registry *reg, int ms)
15946 {
15947  struct reregister_data *sched_data;
15948 
15949  sched_data = ast_malloc(sizeof(*sched_data));
15950  if (!sched_data) {
15951  /* Uh Oh. Expect bad behavior. */
15952  return;
15953  }
15954  sched_data->reg = reg;
15955  sched_data->ms = ms;
15956  ao2_t_ref(reg, +1, "Start reregister timeout action");
15957  if (ast_sched_add(sched, 0, __start_reregister_timeout, sched_data) < 0) {
15958  /* Uh Oh. Expect bad behavior. */
15959  ao2_t_ref(reg, -1, "Failed to schedule start reregister timeout action");
15960  ast_free(sched_data);
15961  }
15962 }
15963 
15964 /*!
15965  * \brief Registration request timeout, register again
15966  *
15967  * \details
15968  * Registered as a timeout handler during transmit_register(),
15969  * to retransmit the packet if a reply does not come back.
15970  *
15971  * \note This is called by the scheduler so the event is not pending anymore when
15972  * we are called.
15973  *
15974  * \note Run by the sched thread.
15975  */
15976 static int sip_reg_timeout(const void *data)
15977 {
15978  struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
15979  struct sip_pvt *p;
15980 
15981  switch (r->regstate) {
15983  case REG_STATE_REGSENT:
15984  case REG_STATE_AUTHSENT:
15985  case REG_STATE_TIMEOUT:
15986  break;
15987  default:
15988  /*
15989  * Registration completed because we got a request response
15990  * and we couldn't stop the scheduled entry in time.
15991  */
15992  r->timeout = -1;
15993  ao2_t_ref(r, -1, "Scheduled register timeout completed early");
15994  return 0;
15995  }
15996 
15997  if (r->dnsmgr) {
15998  /* If the registration has timed out, maybe the IP changed. Force a refresh. */
16000  }
16001 
16002  /* If the initial tranmission failed, we may not have an existing dialog,
16003  * so it is possible that r->call == NULL.
16004  * Otherwise destroy it, as we have a timeout so we don't want it.
16005  */
16006  if (r->call) {
16007  /* Unlink us, destroy old call. Locking is not relevant here because all this happens
16008  in the single SIP manager thread. */
16009  p = r->call;
16010  sip_pvt_lock(p);
16011  pvt_set_needdestroy(p, "registration timeout");
16012  /* Pretend to ACK anything just in case */
16013  __sip_pretend_ack(p);
16014  sip_pvt_unlock(p);
16015 
16016  /* decouple the two objects */
16017  /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
16018  ao2_t_replace(p->registry, NULL, "p->registry unreffed");
16019  r->call = dialog_unref(r->call, "unrefing r->call");
16020  }
16021  /* If we have a limit, stop registration and give up */
16022  r->timeout = -1;
16024  /* Ok, enough is enough. Don't try any more */
16025  /* We could add an external notification here...
16026  steal it from app_voicemail :-) */
16027  ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
16029  } else {
16032  ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
16033  }
16035  ao2_t_ref(r, -1, "Scheduled register timeout complete");
16036  return 0;
16037 }
16038 
16039 /* Run by the sched thread. */
16040 static int __stop_register_timeout(const void *data)
16041 {
16042  struct sip_registry *reg = (struct sip_registry *) data;
16043 
16044  AST_SCHED_DEL_UNREF(sched, reg->timeout,
16045  ao2_t_ref(reg, -1, "Stop scheduled register timeout"));
16046  ao2_t_ref(reg, -1, "Stop register timeout action");
16047  return 0;
16048 }
16049 
16050 static void stop_register_timeout(struct sip_registry *reg)
16051 {
16052  ao2_t_ref(reg, +1, "Stop register timeout action");
16053  if (ast_sched_add(sched, 0, __stop_register_timeout, reg) < 0) {
16054  /* Uh Oh. Expect bad behavior. */
16055  ao2_t_ref(reg, -1, "Failed to schedule stop register timeout action");
16056  }
16057 }
16058 
16059 /* Run by the sched thread. */
16060 static int __start_register_timeout(const void *data)
16061 {
16062  struct sip_registry *reg = (struct sip_registry *) data;
16063 
16064  AST_SCHED_DEL_UNREF(sched, reg->timeout,
16065  ao2_t_ref(reg, -1, "Stop scheduled register timeout"));
16066 
16067  ao2_t_ref(reg, +1, "Schedule register timeout");
16068  reg->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, reg);
16069  if (reg->timeout < 0) {
16070  /* Uh Oh. Expect bad behavior. */
16071  ao2_t_ref(reg, -1, "Failed to schedule register timeout");
16072  }
16073  ast_debug(1, "Scheduled a registration timeout for %s id #%d \n",
16074  reg->hostname, reg->timeout);
16075 
16076  ao2_t_ref(reg, -1, "Start register timeout action");
16077  return 0;
16078 }
16079 
16080 static void start_register_timeout(struct sip_registry *reg)
16081 {
16082  ao2_t_ref(reg, +1, "Start register timeout action");
16083  if (ast_sched_add(sched, 0, __start_register_timeout, reg) < 0) {
16084  /* Uh Oh. Expect bad behavior. */
16085  ao2_t_ref(reg, -1, "Failed to schedule start register timeout action");
16086  }
16087 }
16088 
16089 static const char *sip_sanitized_host(const char *host)
16090 {
16091  struct ast_sockaddr addr;
16092 
16093  /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
16094  * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
16095  * the original host which is most likely a host name and not an IP. */
16096  memset(&addr, 0, sizeof(addr));
16097  if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
16098  return host;
16099  }
16100  return ast_sockaddr_stringify_host_remote(&addr);
16101 }
16102 
16103 /*! \brief Transmit register to SIP proxy or UA
16104  * auth = NULL on the initial registration (from sip_reregister())
16105  */
16106 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
16107 {
16108  struct sip_request req;
16109  char from[256];
16110  char to[256];
16111  char tmp[80];
16112  char addr[80];
16113  struct sip_pvt *p;
16114  struct sip_peer *peer = NULL;
16115  int res;
16116  int portno = 0;
16117 
16118  /* exit if we are already in process with this registrar ?*/
16119  if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
16120  if (r) {
16121  ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
16122  }
16123  return 0;
16124  }
16125 
16126  if (r->dnsmgr == NULL) {
16127  char transport[MAXHOSTNAMELEN];
16128  peer = sip_find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
16129  snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static sip_get_transport function */
16130  r->us.ss.ss_family = get_address_family_filter(r->transport); /* Filter address family */
16131 
16132  /* No point in doing a DNS lookup of the register hostname if we're just going to
16133  * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
16134  * or peer NULL. Since we're only concerned with its existence, we're not going to
16135  * bother getting a ref to the proxy*/
16136  if (!obproxy_get(r->call, peer)) {
16137  ao2_t_ref(r, +1, "add reg ref for dnsmgr");
16138  ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
16139  if (!r->dnsmgr) {
16140  /*dnsmgr refresh disabled, no reference added! */
16141  ao2_t_ref(r, -1, "remove reg ref, dnsmgr disabled");
16142  }
16143  }
16144  if (peer) {
16145  peer = sip_unref_peer(peer, "removing peer ref for dnsmgr_lookup");
16146  }
16147  }
16148 
16149  if (r->call) { /* We have a registration */
16150  if (!auth) {
16151  ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
16152  return 0;
16153  } else {
16154  p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
16155  ast_string_field_set(p, theirtag, NULL); /* forget their old tag, so we don't match tags when getting response */
16156  }
16157  } else {
16158  /* Build callid for registration if we haven't registered before */
16159  if (!r->callid_valid) {
16162  r->callid_valid = TRUE;
16163  }
16164  /* Allocate SIP dialog for registration */
16165  if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL, 0))) {
16166  ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
16167  return 0;
16168  }
16169 
16170  /* reset tag to consistent value from registry */
16171  ast_string_field_set(p, tag, r->localtag);
16172 
16173  if (p->do_history) {
16174  append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
16175  }
16176 
16177  p->socket.type = r->transport;
16178 
16179  /* Use port number specified if no SRV record was found */
16180  if (!ast_sockaddr_isnull(&r->us)) {
16181  if (!ast_sockaddr_port(&r->us) && r->portno) {
16182  ast_sockaddr_set_port(&r->us, r->portno);
16183  }
16184 
16185  /* It is possible that DNS was unavailable at the time the peer was created.
16186  * Here, if we've updated the address in the registry via manually calling
16187  * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
16188  * call if it was updating a peer's address */
16189  if ((peer = sip_find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
16190  if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
16191  on_dns_update_peer(&peer->addr, &r->us, peer);
16192  }
16193  peer = sip_unref_peer(peer, "unref after sip_find_peer");
16194  }
16195  }
16196 
16197  /* Find address to hostname */
16198  if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
16199  /* we have what we hope is a temporary network error,
16200  * probably DNS. We need to reschedule a registration try */
16201  dialog_unlink_all(p);
16202  p = dialog_unref(p, "unref dialog after unlink_all");
16203  ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n",
16206  r->regattempts++;
16207  return 0;
16208  }
16209 
16210  /* Copy back Call-ID in case create_addr changed it */
16211  ast_string_field_set(r, callid, p->callid);
16212 
16213  if (!r->dnsmgr && r->portno) {
16214  ast_sockaddr_set_port(&p->sa, r->portno);
16216  }
16217  if (!ast_strlen_zero(p->fromdomain)) {
16218  portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
16219  } else if (!ast_strlen_zero(r->regdomain)) {
16220  portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
16221  } else {
16222  portno = ast_sockaddr_port(&p->sa);
16223  }
16224 
16225  ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
16226  r->call = dialog_ref(p, "copying dialog into registry r->call"); /* Save pointer to SIP dialog */
16227  p->registry = ao2_t_bump(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
16228  if (!ast_strlen_zero(r->secret)) { /* Secret (password) */
16229  ast_string_field_set(p, peersecret, r->secret);
16230  }
16231  if (!ast_strlen_zero(r->md5secret))
16232  ast_string_field_set(p, peermd5secret, r->md5secret);
16233  /* User name in this realm
16234  - if authuser is set, use that, otherwise use username */
16235  if (!ast_strlen_zero(r->authuser)) {
16237  ast_string_field_set(p, authname, r->authuser);
16238  } else if (!ast_strlen_zero(r->username)) {
16240  ast_string_field_set(p, authname, r->username);
16241  ast_string_field_set(p, fromuser, r->username);
16242  }
16243  if (!ast_strlen_zero(r->username)) {
16244  ast_string_field_set(p, username, r->username);
16245  }
16246  /* Save extension in packet */
16247  if (!ast_strlen_zero(r->callback)) {
16249  }
16250 
16251  /* Set transport so the correct contact is built */
16253 
16254  /*
16255  check which address we should use in our contact header
16256  based on whether the remote host is on the external or
16257  internal network so we can register through nat
16258  */
16259  ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
16260  }
16261 
16262  /* set up a timeout */
16263  if (auth == NULL) {
16265  }
16266 
16267  snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
16268  if (!ast_strlen_zero(p->theirtag)) {
16269  snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
16270  } else {
16271  snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
16272  }
16273 
16274  /* Fromdomain is what we are registering to, regardless of actual
16275  host name from SRV */
16276  if (portno && portno != STANDARD_SIP_PORT) {
16277  snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
16278  } else {
16279  snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
16280  }
16281 
16282  ast_string_field_set(p, uri, addr);
16283 
16284  p->branch ^= ast_random();
16285 
16286  init_req(&req, sipmethod, addr);
16287 
16288  /* Add to CSEQ */
16289  snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
16290  p->ocseq = r->ocseq;
16291 
16292  build_via(p);
16293  add_header(&req, "Via", p->via);
16294  add_max_forwards(p, &req);
16295  add_header(&req, "From", from);
16296  add_header(&req, "To", to);
16297  add_header(&req, "Call-ID", p->callid);
16298  add_header(&req, "CSeq", tmp);
16299  add_supported(p, &req);
16301  add_header(&req, "User-Agent", global_useragent);
16302 
16303  if (auth) { /* Add auth header */
16304  add_header(&req, authheader, auth);
16305  } else if (!ast_strlen_zero(r->nonce)) {
16306  char digest[1024];
16307 
16308  /* We have auth data to reuse, build a digest header.
16309  * Note, this is not always useful because some parties do not
16310  * like nonces to be reused (for good reasons!) so they will
16311  * challenge us anyways.
16312  */
16313  if (sipdebug) {
16314  ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
16315  }
16316  ast_string_field_set(p, realm, r->realm);
16317  ast_string_field_set(p, nonce, r->nonce);
16319  ast_string_field_set(p, opaque, r->opaque);
16320  ast_string_field_set(p, qop, r->qop);
16321  p->noncecount = ++r->noncecount;
16322 
16323  memset(digest, 0, sizeof(digest));
16324  if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
16325  add_header(&req, "Authorization", digest);
16326  } else {
16327  ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
16328  }
16329  }
16330 
16331  add_expires(&req, r->expiry);
16332  build_contact(p, &req, 0);
16333  add_header(&req, "Contact", p->our_contact);
16334 
16335  initialize_initreq(p, &req);
16336  if (sip_debug_test_pvt(p)) {
16337  ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
16338  }
16340  r->regattempts++; /* Another attempt */
16341  ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
16342  res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
16343  dialog_unref(p, "p is finished here at the end of transmit_register");
16344  return res;
16345 }
16346 
16347 /*!
16348  * \brief Transmit with SIP MESSAGE method
16349  * \note The p->msg_headers and p->msg_body are already setup.
16350  */
16351 static int transmit_message(struct sip_pvt *p, int init, int auth)
16352 {
16353  struct sip_request req;
16354 
16355  if (init) {
16356  initreqprep(&req, p, SIP_MESSAGE, NULL);
16357  initialize_initreq(p, &req);
16358  } else {
16359  reqprep(&req, p, SIP_MESSAGE, 0, 1);
16360  }
16361  if (auth) {
16363  } else {
16364  add_text(&req, p);
16365  return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
16366  }
16367 }
16368 
16369 /*! \brief Allocate SIP refer structure */
16370 static int sip_refer_alloc(struct sip_pvt *p)
16371 {
16372  sip_refer_destroy(p);
16373  p->refer = ast_calloc_with_stringfields(1, struct sip_refer, 512);
16374  return p->refer ? 1 : 0;
16375 }
16376 
16377 /*! \brief Destroy SIP refer structure */
16378 static void sip_refer_destroy(struct sip_pvt *p)
16379 {
16380  if (p->refer) {
16382  ast_free(p->refer);
16383  p->refer = NULL;
16384  }
16385 }
16386 
16387 /*! \brief Allocate SIP refer structure */
16388 static int sip_notify_alloc(struct sip_pvt *p)
16389 {
16390  p->notify = ast_calloc(1, sizeof(struct sip_notify));
16391  if (p->notify) {
16392  p->notify->content = ast_str_create(128);
16393  }
16394  return p->notify ? 1 : 0;
16395 }
16396 
16397 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
16398  \note this is currently broken as we have no way of telling the dialplan
16399  engine whether a transfer succeeds or fails.
16400  \todo Fix the transfer() dialplan function so that a transfer may fail
16401 */
16402 static int transmit_refer(struct sip_pvt *p, const char *dest)
16403 {
16404  char from[256];
16405  const char *of;
16406  char *c;
16407  char referto[256];
16408  int use_tls=FALSE;
16409 
16410  if (sipdebug) {
16411  ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
16412  }
16413 
16414  /* Are we transfering an inbound or outbound call ? */
16415  if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
16416  of = sip_get_header(&p->initreq, "To");
16417  } else {
16418  of = sip_get_header(&p->initreq, "From");
16419  }
16420 
16421  ast_copy_string(from, of, sizeof(from));
16422  of = get_in_brackets(from);
16423  ast_string_field_set(p, from, of);
16424  if (!strncasecmp(of, "sip:", 4)) {
16425  of += 4;
16426  } else if (!strncasecmp(of, "sips:", 5)) {
16427  of += 5;
16428  use_tls = TRUE;
16429  } else {
16430  ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
16431  }
16432  /* Get just the username part */
16433  if (strchr(dest, '@')) {
16434  c = NULL;
16435  } else if ((c = strchr(of, '@'))) {
16436  *c++ = '\0';
16437  }
16438  if (c) {
16439  snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
16440  } else {
16441  snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
16442  }
16443 
16444  /* save in case we get 407 challenge */
16445  sip_refer_alloc(p);
16446  ast_string_field_set(p->refer, refer_to, referto);
16447  ast_string_field_set(p->refer, referred_by, p->our_contact);
16448  p->refer->status = REFER_SENT; /* Set refer status */
16449 
16450  return transmit_invite(p, SIP_REFER, FALSE, 0, NULL);
16451  /* We should propably wait for a NOTIFY here until we ack the transfer */
16452  /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
16453 
16454  /*! \todo In theory, we should hang around and wait for a reply, before
16455  returning to the dial plan here. Don't know really how that would
16456  affect the transfer() app or the pbx, but, well, to make this
16457  useful we should have a STATUS code on transfer().
16458  */
16459 }
16460 
16461 /*! \brief Send SIP INFO advice of charge message */
16462 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
16463 {
16464  struct sip_request req;
16465  struct ast_str *str = ast_str_alloca(512);
16466  const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
16467  enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
16468 
16469  reqprep(&req, p, SIP_INFO, 0, 1);
16470 
16471  if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
16472  ast_str_append(&str, 0, "type=active;");
16473  } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
16474  ast_str_append(&str, 0, "type=terminated;");
16475  } else {
16476  /* unsupported message type */
16477  return -1;
16478  }
16479 
16480  switch (charging) {
16481  case AST_AOC_CHARGE_FREE:
16482  ast_str_append(&str, 0, "free-of-charge;");
16483  break;
16485  ast_str_append(&str, 0, "charging;");
16486  ast_str_append(&str, 0, "charging-info=currency;");
16487  ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
16488  ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
16489  if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
16490  ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
16491  }
16492  break;
16493  case AST_AOC_CHARGE_UNIT:
16494  ast_str_append(&str, 0, "charging;");
16495  ast_str_append(&str, 0, "charging-info=pulse;");
16496  if (unit_entry) {
16497  ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
16498  }
16499  break;
16500  default:
16501  ast_str_append(&str, 0, "not-available;");
16502  };
16503 
16504  add_header(&req, "AOC", ast_str_buffer(str));
16505 
16506  return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
16507 }
16508 
16509 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
16510 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
16511 {
16512  struct sip_request req;
16513 
16514  reqprep(&req, p, SIP_INFO, 0, 1);
16515  add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
16516  return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
16517 }
16518 
16519 /*! \brief Send SIP INFO with video update request */
16521 {
16522  struct sip_request req;
16523 
16524  reqprep(&req, p, SIP_INFO, 0, 1);
16525  add_vidupdate(&req);
16526  return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
16527 }
16528 
16529 /*! \brief Transmit generic SIP request
16530  returns XMIT_ERROR if transmit failed with a critical error (don't retry)
16531 */
16532 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
16533 {
16534  struct sip_request resp;
16535 
16536  reqprep(&resp, p, sipmethod, seqno, newbranch);
16537  if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
16538  add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
16539  }
16540 
16541  if (sipmethod == SIP_ACK) {
16543  }
16544 
16545  return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
16546 }
16547 
16548 /*! \brief return the request and response header for a 401 or 407 code */
16549 void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader)
16550 {
16551  if (code == WWW_AUTH) { /* 401 */
16552  *header = "WWW-Authenticate";
16553  *respheader = "Authorization";
16554  } else if (code == PROXY_AUTH) { /* 407 */
16555  *header = "Proxy-Authenticate";
16556  *respheader = "Proxy-Authorization";
16557  } else {
16558  ast_verbose("-- wrong response code %u\n", code);
16559  *header = *respheader = "Invalid";
16560  }
16561 }
16562 
16563 /*! \brief Transmit SIP request, auth added */
16564 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
16565 {
16566  struct sip_request resp;
16567 
16568  reqprep(&resp, p, sipmethod, seqno, newbranch);
16569  if (!ast_strlen_zero(p->realm)) {
16570  char digest[1024];
16571 
16572  memset(digest, 0, sizeof(digest));
16573  if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
16574  char *dummy, *response;
16575  enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
16576  sip_auth_headers(code, &dummy, &response);
16577  add_header(&resp, response, digest);
16578  } else {
16579  ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
16580  }
16581  }
16582 
16583  switch (sipmethod) {
16584  case SIP_BYE:
16585  {
16586  char buf[20];
16587 
16588  /*
16589  * We are hanging up. If we know a cause for that, send it in
16590  * clear text to make debugging easier.
16591  */
16593  snprintf(buf, sizeof(buf), "Q.850;cause=%d", p->hangupcause & 0x7f);
16594  add_header(&resp, "Reason", buf);
16595  }
16596 
16597  add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
16598  snprintf(buf, sizeof(buf), "%d", p->hangupcause);
16599  add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
16600  break;
16601  }
16602  case SIP_MESSAGE:
16603  add_text(&resp, p);
16604  break;
16605  default:
16606  break;
16607  }
16608 
16609  return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
16610 }
16611 
16612 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
16613 static void destroy_association(struct sip_peer *peer)
16614 {
16615  int realtimeregs = ast_check_realtime("sipregs");
16616  char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
16617 
16618  if (!sip_cfg.ignore_regexpire) {
16619  if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
16620  ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "0", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
16621  } else {
16622  ast_db_del("SIP/Registry", peer->name);
16623  ast_db_del("SIP/RegistryPath", peer->name);
16624  ast_db_del("SIP/PeerMethods", peer->name);
16625  }
16626  }
16627 }
16628 
16629 static void set_socket_transport(struct sip_socket *socket, int transport)
16630 {
16631  /* if the transport type changes, clear all socket data */
16632  if (socket->type != transport) {
16633  socket->fd = -1;
16634  socket->type = transport;
16635  if (socket->tcptls_session) {
16636  ao2_ref(socket->tcptls_session, -1);
16637  socket->tcptls_session = NULL;
16638  } else if (socket->ws_session) {
16640  socket->ws_session = NULL;
16641  }
16642  }
16643 }
16644 
16645 /*! \brief Expire registration of SIP peer */
16646 static int expire_register(const void *data)
16647 {
16648  struct sip_peer *peer = (struct sip_peer *)data;
16649 
16650  if (!peer) { /* Hmmm. We have no peer. Weird. */
16651  return 0;
16652  }
16653 
16654  peer->expire = -1;
16655  peer->portinuri = 0;
16656 
16657  destroy_association(peer); /* remove registration data from storage */
16659 
16660  if (peer->socket.tcptls_session) {
16661  ao2_ref(peer->socket.tcptls_session, -1);
16662  peer->socket.tcptls_session = NULL;
16663  } else if (peer->socket.ws_session) {
16665  peer->socket.ws_session = NULL;
16666  }
16667 
16668  if (peer->endpoint) {
16669  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
16671  blob = ast_json_pack("{s: s, s: s}",
16672  "peer_status", "Unregistered",
16673  "cause", "Expired");
16675  }
16676  register_peer_exten(peer, FALSE); /* Remove regexten */
16678 
16679  /* Do we need to release this peer from memory?
16680  Only for realtime peers and autocreated peers
16681  */
16682  if (peer->is_realtime) {
16683  ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
16684  }
16685 
16686  if (peer->selfdestruct ||
16688  ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
16689  }
16690  if (!ast_sockaddr_isnull(&peer->addr)) {
16691  /* We still need to unlink the peer from the peers_by_ip table,
16692  * otherwise we end up with multiple copies hanging around each
16693  * time a registration expires and the peer re-registers. */
16694  ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
16695  }
16696 
16697  /* Only clear the addr after we check for destruction. The addr must remain
16698  * in order to unlink from the peers_by_ip container correctly */
16699  memset(&peer->addr, 0, sizeof(peer->addr));
16700 
16701  sip_unref_peer(peer, "removing peer ref for expire_register");
16702 
16703  return 0;
16704 }
16705 
16706 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
16707 static int sip_poke_peer_s(const void *data)
16708 {
16709  struct sip_peer *peer = (struct sip_peer *)data;
16710  struct sip_peer *foundpeer;
16711 
16712  peer->pokeexpire = -1;
16713 
16714  foundpeer = ao2_find(peers, peer, OBJ_POINTER);
16715  if (!foundpeer) {
16716  sip_unref_peer(peer, "removing poke peer ref");
16717  return 0;
16718  } else if (foundpeer->name != peer->name) {
16719  sip_unref_peer(foundpeer, "removing above peer ref");
16720  sip_unref_peer(peer, "removing poke peer ref");
16721  return 0;
16722  }
16723 
16724  sip_unref_peer(foundpeer, "removing above peer ref");
16725  sip_poke_peer(peer, 0);
16726  sip_unref_peer(peer, "removing poke peer ref");
16727 
16728  return 0;
16729 }
16730 
16731 static int sip_poke_peer_now(const void *data)
16732 {
16733  struct sip_peer *peer = (struct sip_peer *) data;
16734 
16735  peer->pokeexpire = -1;
16736  sip_poke_peer(peer, 0);
16737  sip_unref_peer(peer, "removing poke peer ref");
16738 
16739  return 0;
16740 }
16741 
16742 /*! \brief Get registration details from Asterisk DB */
16743 static void reg_source_db(struct sip_peer *peer)
16744 {
16745  char data[256];
16746  char path[SIPBUFSIZE * 2];
16747  struct ast_sockaddr sa;
16748  int expire;
16749  char full_addr[128];
16751  AST_APP_ARG(addr);
16752  AST_APP_ARG(port);
16753  AST_APP_ARG(expiry_str);
16754  AST_APP_ARG(username);
16756  );
16757 
16758  /* If read-only RT backend, then refresh from local DB cache */
16759  if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
16760  return;
16761  }
16762  if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
16763  return;
16764  }
16765 
16766  AST_NONSTANDARD_RAW_ARGS(args, data, ':');
16767 
16768  snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
16769 
16770  if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
16771  return;
16772  }
16773 
16774  if (args.expiry_str) {
16775  expire = atoi(args.expiry_str);
16776  } else {
16777  return;
16778  }
16779 
16780  if (args.username) {
16781  ast_string_field_set(peer, username, args.username);
16782  }
16783  if (args.contact) {
16784  ast_string_field_set(peer, fullcontact, args.contact);
16785  }
16786 
16787  ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
16788  peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
16789 
16790  ast_sockaddr_copy(&peer->addr, &sa);
16791  if (peer->maxms) {
16792  /* Don't poke peer immediately, just schedule it within qualifyfreq */
16793  AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
16794  ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
16795  sip_poke_peer_s, peer,
16796  sip_unref_peer(_data, "removing poke peer ref"),
16797  sip_unref_peer(peer, "removing poke peer ref"),
16798  sip_ref_peer(peer, "adding poke peer ref"));
16799  }
16800  AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
16801  sip_unref_peer(_data, "remove registration ref"),
16802  sip_unref_peer(peer, "remove registration ref"),
16803  sip_ref_peer(peer, "add registration ref"));
16804  register_peer_exten(peer, TRUE);
16805  if (!ast_db_get("SIP/RegistryPath", peer->name, path, sizeof(path))) {
16806  build_path(NULL, peer, NULL, path);
16807  }
16808 }
16809 
16810 /*! \brief Save contact header for 200 OK on INVITE */
16811 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
16812 {
16813  char contact[SIPBUFSIZE];
16814  char *c;
16815 
16816  /* Look for brackets */
16817  ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
16818  c = get_in_brackets(contact);
16819 
16820  /* Save full contact to call pvt for later bye or re-invite */
16821  ast_string_field_set(pvt, fullcontact, c);
16822 
16823  /* Save URI for later ACKs, BYE or RE-invites */
16824  ast_string_field_set(pvt, okcontacturi, c);
16825 
16826  /* We should return false for URI:s we can't handle,
16827  like tel:, mailto:,ldap: etc */
16828  return TRUE;
16829 }
16830 
16831 /*!
16832  * \brief Parses SIP reason header according to RFC3326 and sets channel's hangupcause if configured so
16833  * and header present
16834  *
16835  * \note This is used in BYE and CANCEL request and SIP response, but according to RFC3326 it could
16836  * appear in any request, but makes not a lot of sense in others than BYE or CANCEL.
16837  * Currently only implemented for Q.850 status codes.
16838  * \retval 0 success
16839  * \retval -1 on failure or if not configured
16840  */
16841 static int use_reason_header(struct sip_pvt *pvt, struct sip_request *req)
16842 {
16843  int ret, cause;
16844  const char *rp, *rh;
16845 
16846  if (!pvt->owner) {
16847  return -1;
16848  }
16849 
16850  if (!ast_test_flag(&pvt->flags[1], SIP_PAGE2_Q850_REASON) ||
16851  !(rh = sip_get_header(req, "Reason"))) {
16852  return -1;
16853  }
16854 
16855  rh = ast_skip_blanks(rh);
16856  if (strncasecmp(rh, "Q.850", 5)) {
16857  return -1;
16858  }
16859 
16860  ret = -1;
16861  cause = ast_channel_hangupcause(pvt->owner);
16862  rp = strstr(rh, "cause=");
16863  if (rp && sscanf(rp + 6, "%3d", &cause) == 1) {
16864  ret = 0;
16865  ast_channel_hangupcause_set(pvt->owner, cause & 0x7f);
16866  if (req->debug) {
16867  ast_verbose("Using Reason header for cause code: %d\n",
16869  }
16870  }
16871  return ret;
16872 }
16873 
16874 /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
16875  *
16876  * \note This calls parse_uri which has the unexpected property that passing more
16877  * arguments results in more splitting. Most common is to leave out the pass
16878  * argument, causing user to contain user:pass if available.
16879  */
16880 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
16881 {
16882  int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
16883  if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
16884  char *p;
16885  if ((p = strchr(uri, (int)';'))) {
16886  *p = '\0';
16887  }
16888  }
16889  return ret;
16890 }
16891 
16892 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
16893 {
16894  char *hostport, *transport;
16895  char contact_buf[256];
16896  char *contact;
16897 
16898  /* Work on a copy */
16899  ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
16900  contact = contact_buf;
16901 
16902  /*
16903  * We have only the part in <brackets> here so we just need to parse a SIP URI.
16904  *
16905  * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
16906  * We still need to be able to send to the remote agent through the proxy.
16907  */
16908 
16909  if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
16910  &transport)) {
16911  ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
16912  }
16913 
16914  /* XXX This could block for a long time XXX */
16915  /* We should only do this if it's a name, not an IP */
16916  /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
16917  to find transport, port address and hostname. If there's a port number, we have to
16918  assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
16919  */
16920 
16921  /* If we took in an invalid URI, hostport may not have been initialized */
16922  /* ast_sockaddr_resolve requires an initialized hostport string. */
16923  if (ast_strlen_zero(hostport)) {
16924  ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
16925  return -1;
16926  }
16927 
16928  if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
16929  ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
16930  "resolve in DNS) : '%s'\n", hostport);
16931  return -1;
16932  }
16933 
16934  /* set port */
16935  if (!ast_sockaddr_port(addr)) {
16936  ast_sockaddr_set_port(addr,
16937  (get_transport_str2enum(transport) ==
16939  !strncasecmp(fullcontact, "sips", 4)) ?
16941  }
16942 
16943  return 0;
16944 }
16945 
16946 /*! \brief Change the other partys IP address based on given contact */
16947 static int set_address_from_contact(struct sip_pvt *pvt)
16948 {
16949  if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
16950  /* NAT: Don't trust the contact field. Just use what they came to us
16951  with. */
16952  /*! \todo We need to save the TRANSPORT here too */
16953  pvt->sa = pvt->recv;
16954  return 0;
16955  }
16956 
16957  return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == AST_TRANSPORT_TLS ? 1 : 0);
16958 }
16959 
16960 /*! \brief Parse contact header and save registration (peer registration) */
16961 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
16962 {
16963  char contact[SIPBUFSIZE];
16964  char data[SIPBUFSIZE];
16965  const char *expires = sip_get_header(req, "Expires");
16966  int expire = atoi(expires);
16967  char *curi = NULL, *hostport = NULL, *transport = NULL;
16968  int transport_type;
16969  const char *useragent;
16970  struct ast_sockaddr oldsin, testsa;
16971  char *firstcuri = NULL;
16972  int start = 0;
16973  int wildcard_found = 0;
16974  int single_binding_found = 0;
16975 
16976  ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
16977 
16978  if (ast_strlen_zero(expires)) { /* No expires header, try look in Contact: */
16979  char *s = strcasestr(contact, ";expires=");
16980  if (s) {
16981  expires = strsep(&s, ";"); /* trim ; and beyond */
16982  if (sscanf(expires + 9, "%30d", &expire) != 1) {
16983  expire = default_expiry;
16984  }
16985  } else {
16986  /* Nothing has been specified */
16987  expire = default_expiry;
16988  }
16989  }
16990 
16991  if (expire > max_expiry) {
16992  expire = max_expiry;
16993  }
16994  if (expire < min_expiry && expire != 0) {
16995  expire = min_expiry;
16996  }
16997  pvt->expiry = expire;
16998 
16999  copy_socket_data(&pvt->socket, &req->socket);
17000 
17001  do {
17002  /* Look for brackets */
17003  curi = contact;
17004  if (strchr(contact, '<') == NULL) /* No <, check for ; and strip it */
17005  strsep(&curi, ";"); /* This is Header options, not URI options */
17006  curi = get_in_brackets(contact);
17007  if (!firstcuri) {
17008  firstcuri = ast_strdupa(curi);
17009  }
17010 
17011  if (!strcasecmp(curi, "*")) {
17012  wildcard_found = 1;
17013  } else {
17014  single_binding_found = 1;
17015  }
17016 
17017  if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
17018  /* Contact header parameter "*" detected, so punt if: Expires header is missing,
17019  * Expires value is not zero, or another Contact header is present. */
17020  return PARSE_REGISTER_FAILED;
17021  }
17022 
17023  ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
17024  } while (!ast_strlen_zero(contact));
17025  curi = firstcuri;
17026 
17027  /* if they did not specify Contact: or Expires:, they are querying
17028  what we currently have stored as their contact address, so return
17029  it
17030  */
17031  if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
17032  /* If we have an active registration, tell them when the registration is going to expire */
17033  if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
17034  pvt->expiry = ast_sched_when(sched, peer->expire);
17035  }
17036  return PARSE_REGISTER_QUERY;
17037  } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
17038  /* This means remove all registrations and return OK */
17039  AST_SCHED_DEL_UNREF(sched, peer->expire,
17040  sip_unref_peer(peer, "remove register expire ref"));
17041  ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
17042  expire_register(sip_ref_peer(peer,"add ref for explicit expire_register"));
17043  return PARSE_REGISTER_UPDATE;
17044  }
17045 
17046  /* Store whatever we got as a contact from the client */
17047  ast_string_field_set(peer, fullcontact, curi);
17048 
17049  /* For the 200 OK, we should use the received contact */
17050  ast_string_field_build(pvt, our_contact, "<%s>", curi);
17051 
17052  /* Make sure it's a SIP URL */
17053  if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
17054  ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
17055  }
17056 
17057  /* handle the transport type specified in Contact header. */
17058  if (!(transport_type = get_transport_str2enum(transport))) {
17059  transport_type = pvt->socket.type;
17060  }
17061 
17062  /* if the peer's socket type is different than the Registration
17063  * transport type, change it. If it got this far, it is a
17064  * supported type, but check just in case */
17065  if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
17066  set_socket_transport(&peer->socket, transport_type);
17067  }
17068 
17069  oldsin = peer->addr;
17070 
17071  /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
17072  if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
17073  ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
17074  }
17075 
17076  if ((transport_type != AST_TRANSPORT_WS) && (transport_type != AST_TRANSPORT_WSS) &&
17078  /* use the data provided in the Contact header for call routing */
17079  ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
17080  /* XXX This could block for a long time XXX */
17081  /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
17082  if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
17083  ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
17084  ast_string_field_set(peer, fullcontact, "");
17085  ast_string_field_set(pvt, our_contact, "");
17086  return PARSE_REGISTER_FAILED;
17087  }
17088 
17089  /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
17090  The hostport part is actually a host. */
17091  peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
17092 
17093  if (!ast_sockaddr_port(&testsa)) {
17094  ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
17095  }
17096 
17097  ast_sockaddr_copy(&peer->addr, &testsa);
17098  } else {
17099  /* Don't trust the contact field. Just use what they came to us
17100  with */
17101  ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
17102  peer->addr = pvt->recv;
17103  }
17104 
17105  /* Check that they're allowed to register at this IP */
17106  if (ast_apply_acl(sip_cfg.contact_acl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW ||
17107  ast_apply_acl(peer->contactacl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW) {
17108  ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
17110  ast_string_field_set(peer, fullcontact, "");
17111  ast_string_field_set(pvt, our_contact, "");
17112  return PARSE_REGISTER_DENIED;
17113  }
17114 
17115  /* if the Contact header information copied into peer->addr matches the
17116  * received address, and the transport types are the same, then copy socket
17117  * data into the peer struct */
17118  if ((peer->socket.type == pvt->socket.type) &&
17119  !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
17120  copy_socket_data(&peer->socket, &pvt->socket);
17121  }
17122 
17123  /* Now that our address has been updated put ourselves back into the container for lookups */
17124  if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17125  ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
17126  }
17127 
17128  /* Save SIP options profile */
17129  peer->sipoptions = pvt->sipoptions;
17130 
17131  if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
17132  ast_string_field_set(peer, username, curi);
17133  }
17134 
17135  AST_SCHED_DEL_UNREF(sched, peer->expire,
17136  sip_unref_peer(peer, "remove register expire ref"));
17137 
17138  if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17139  peer->expire = -1;
17140  } else {
17141  peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
17142  sip_ref_peer(peer, "add registration ref"));
17143  if (peer->expire == -1) {
17144  sip_unref_peer(peer, "remote registration ref");
17145  }
17146  }
17147  if (!build_path(pvt, peer, req, NULL)) {
17148  /* Tell the dialog to use the Path header in the response */
17149  ast_set2_flag(&pvt->flags[0], 1, SIP_USEPATH);
17150  }
17151  snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
17152  expire, peer->username, peer->fullcontact);
17153  /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
17154  if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate) {
17155  if (!sip_route_empty(&peer->path)) {
17156  struct ast_str *r = sip_route_list(&peer->path, 0, 0);
17157  if (r) {
17158  ast_db_put("SIP/RegistryPath", peer->name, ast_str_buffer(r));
17159  ast_free(r);
17160  }
17161  }
17162  ast_db_put("SIP/Registry", peer->name, data);
17163  }
17164 
17165  if (peer->endpoint) {
17166  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
17168  blob = ast_json_pack("{s: s, s: s}",
17169  "peer_status", "Registered",
17170  "address", ast_sockaddr_stringify(&peer->addr));
17172  }
17173 
17174  /* Is this a new IP address for us? */
17175  if (ast_sockaddr_cmp(&peer->addr, &oldsin)) {
17176  ast_verb(3, "Registered SIP '%s' at %s\n", peer->name,
17177  ast_sockaddr_stringify(&peer->addr));
17178  }
17179  sip_pvt_unlock(pvt);
17180  sip_poke_peer(peer, 0);
17181  sip_pvt_lock(pvt);
17182  register_peer_exten(peer, 1);
17183 
17184  /* Save User agent */
17185  useragent = sip_get_header(req, "User-Agent");
17186  if (strcasecmp(useragent, peer->useragent)) {
17187  ast_string_field_set(peer, useragent, useragent);
17188  ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
17189  }
17190  return PARSE_REGISTER_UPDATE;
17191 }
17192 
17193 /*! \brief Build route list from Record-Route header
17194  *
17195  * \param p
17196  * \param req
17197  * \param backwards
17198  * \param resp the SIP response code or 0 for a request
17199  *
17200  */
17201 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
17202 {
17203  int start = 0;
17204  const char *header;
17205 
17206  /* Once a persistent route is set, don't fool with it */
17207  if (!sip_route_empty(&p->route) && p->route_persistent) {
17208  ast_debug(1, "build_route: Retaining previous route: <%s>\n", sip_route_first_uri(&p->route));
17209  return;
17210  }
17211 
17212  sip_route_clear(&p->route);
17213 
17214  /* We only want to create the route set the first time this is called except
17215  it is called from a provisional response.*/
17216  if ((resp < 100) || (resp > 199)) {
17217  p->route_persistent = 1;
17218  }
17219 
17220  /* Build a tailq, then assign it to p->route when done.
17221  * If backwards, we add entries from the head so they end up
17222  * in reverse order. However, we do need to maintain a correct
17223  * tail pointer because the contact is always at the end.
17224  */
17225  /* 1st we pass through all the hops in any Record-Route headers */
17226  for (;;) {
17227  header = __get_header(req, "Record-Route", &start);
17228  if (*header == '\0') {
17229  break;
17230  }
17231  sip_route_process_header(&p->route, header, backwards);
17232  }
17233 
17234  /* Only append the contact if we are dealing with a strict router or have no route */
17235  if (sip_route_empty(&p->route) || sip_route_is_strict(&p->route)) {
17236  /* 2nd append the Contact: if there is one */
17237  /* Can be multiple Contact headers, comma separated values - we just take the first */
17238  int len;
17239  header = sip_get_header(req, "Contact");
17240  if (strchr(header, '<')) {
17241  get_in_brackets_const(header, &header, &len);
17242  } else {
17243  len = strlen(header);
17244  }
17245  if (header && len) {
17246  sip_route_add(&p->route, header, len, 0);
17247  }
17248  }
17249 
17250  /* For debugging dump what we ended up with */
17251  if (sip_debug_test_pvt(p)) {
17252  sip_route_dump(&p->route);
17253  }
17254 }
17255 
17256 /*! \brief Build route list from Path header
17257  * RFC 3327 requires that the Path header contains SIP URIs with lr paramter.
17258  * Thus, we do not care about strict routing SIP routers
17259  */
17260 static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf)
17261 {
17262  sip_route_clear(&peer->path);
17263 
17264  if (!ast_test_flag(&peer->flags[0], SIP_USEPATH)) {
17265  ast_debug(2, "build_path: do not use Path headers\n");
17266  return -1;
17267  }
17268  ast_debug(2, "build_path: try to build pre-loaded route-set by parsing Path headers\n");
17269 
17270  if (req) {
17271  int start = 0;
17272  const char *header;
17273  for (;;) {
17274  header = __get_header(req, "Path", &start);
17275  if (*header == '\0') {
17276  break;
17277  }
17278  sip_route_process_header(&peer->path, header, 0);
17279  }
17280  } else if (pathbuf) {
17281  sip_route_process_header(&peer->path, pathbuf, 0);
17282  }
17283 
17284  /* Caches result for any dialog->route copied from peer->path */
17285  sip_route_is_strict(&peer->path);
17286 
17287  /* For debugging dump what we ended up with */
17288  if (p && sip_debug_test_pvt(p)) {
17289  sip_route_dump(&peer->path);
17290  }
17291  return 0;
17292 }
17293 
17294 /*! \brief builds the sip_pvt's nonce field which is used for the authentication
17295  * challenge. When forceupdate is not set, the nonce is only updated if
17296  * the current one is stale. In this case, a stalenonce is one which
17297  * has already received a response, if a nonce has not received a response
17298  * it is not always necessary or beneficial to create a new one. */
17299 
17300 static void build_nonce(struct sip_pvt *p, int forceupdate)
17301 {
17302  if (p->stalenonce || forceupdate || ast_strlen_zero(p->nonce)) {
17303  ast_string_field_build(p, nonce, "%08lx", (unsigned long)ast_random()); /* Create nonce for challenge */
17304  p->stalenonce = 0;
17305  }
17306 }
17307 
17308 /*! \brief Takes the digest response and parses it */
17309 void sip_digest_parser(char *c, struct digestkeys *keys)
17310 {
17311  struct digestkeys *i = i;
17312 
17313  while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
17314  for (i = keys; i->key != NULL; i++) {
17315  const char *separator = ","; /* default */
17316 
17317  if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
17318  continue;
17319  }
17320  /* Found. Skip keyword, take text in quotes or up to the separator. */
17321  c += strlen(i->key);
17322  if (*c == '"') { /* in quotes. Skip first and look for last */
17323  c++;
17324  separator = "\"";
17325  }
17326  i->s = c;
17327  strsep(&c, separator);
17328  break;
17329  }
17330  if (i->key == NULL) { /* not found, jump after space or comma */
17331  strsep(&c, " ,");
17332  }
17333  }
17334 }
17335 
17336 /*! \brief Check user authorization from peer definition
17337  Some actions, like REGISTER and INVITEs from peers require
17338  authentication (if peer have secret set)
17339  \return 0 on success, non-zero on error
17340 */
17341 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
17342  const char *secret, const char *md5secret, int sipmethod,
17343  const char *uri, enum xmittype reliable)
17344 {
17345  const char *response;
17346  char *reqheader, *respheader;
17347  const char *authtoken;
17348  char a1_hash[256];
17349  char resp_hash[256]="";
17350  char *c;
17351  int is_bogus_peer = 0;
17352  int wrongnonce = FALSE;
17353  int good_response;
17354  const char *usednonce = p->nonce;
17355  struct ast_str *buf;
17356  int res;
17357 
17358  /* table of recognised keywords, and their value in the digest */
17359  struct digestkeys keys[] = {
17360  [K_RESP] = { "response=", "" },
17361  [K_URI] = { "uri=", "" },
17362  [K_USER] = { "username=", "" },
17363  [K_NONCE] = { "nonce=", "" },
17364  [K_LAST] = { NULL, NULL}
17365  };
17366 
17367  /* Always OK if no secret */
17368  if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)) {
17369  return AUTH_SUCCESSFUL;
17370  }
17371 
17372  /* Always auth with WWW-auth since we're NOT a proxy */
17373  /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
17374  response = "401 Unauthorized";
17375 
17376  /*
17377  * Note the apparent swap of arguments below, compared to other
17378  * usages of sip_auth_headers().
17379  */
17380  sip_auth_headers(WWW_AUTH, &respheader, &reqheader);
17381 
17382  authtoken = sip_get_header(req, reqheader);
17383  if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
17384  /* This is a retransmitted invite/register/etc, don't reconstruct authentication
17385  information */
17386  if (!reliable) {
17387  /* Resend message if this was NOT a reliable delivery. Otherwise the
17388  retransmission should get it */
17389  transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
17390  /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
17392  }
17393  return AUTH_CHALLENGE_SENT;
17394  } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
17395  /* We have no auth, so issue challenge and request authentication */
17396  build_nonce(p, 1); /* Create nonce for challenge */
17397  transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
17398  /* Schedule auto destroy in 32 seconds */
17400  return AUTH_CHALLENGE_SENT;
17401  }
17402 
17403  /* --- We have auth, so check it */
17404 
17405  /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
17406  an example in the spec of just what it is you're doing a hash on. */
17407 
17409  return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
17410  }
17411 
17412  /* Make a copy of the response and parse it */
17413  res = ast_str_set(&buf, 0, "%s", authtoken);
17414 
17415  if (res == AST_DYNSTR_BUILD_FAILED) {
17416  return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
17417  }
17418 
17419  c = ast_str_buffer(buf);
17420 
17421  sip_digest_parser(c, keys);
17422 
17423  /* We cannot rely on the bogus_peer having a bad md5 value. Someone could
17424  * use it to construct valid auth. */
17425  if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
17426  is_bogus_peer = 1;
17427  }
17428 
17429  /* Verify that digest username matches the username we auth as */
17430  if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
17431  ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
17432  username, keys[K_USER].s);
17433  /* Oops, we're trying something here */
17434  return AUTH_USERNAME_MISMATCH;
17435  }
17436 
17437  /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
17438  * If this check fails, send 401 with new nonce */
17439  if (strcasecmp(p->nonce, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
17440  wrongnonce = TRUE;
17441  usednonce = keys[K_NONCE].s;
17442  } else {
17443  p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
17444  }
17445 
17446  if (!ast_strlen_zero(md5secret)) {
17447  ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17448  } else {
17449  char a1[256];
17450 
17451  snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17452  ast_md5_hash(a1_hash, a1);
17453  }
17454 
17455  /* compute the expected response to compare with what we received */
17456  {
17457  char a2[256];
17458  char a2_hash[256];
17459  char resp[256];
17460 
17461  snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
17462  S_OR(keys[K_URI].s, uri));
17463  ast_md5_hash(a2_hash, a2);
17464  snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
17465  ast_md5_hash(resp_hash, resp);
17466  }
17467 
17468  good_response = keys[K_RESP].s &&
17469  !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
17470  !is_bogus_peer; /* lastly, check that the peer isn't the fake peer */
17471  if (wrongnonce) {
17472  if (good_response) {
17473  if (sipdebug)
17474  ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", sip_get_header(req, "From"));
17475  /* We got working auth token, based on stale nonce . */
17476  build_nonce(p, 0);
17477  transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, TRUE);
17478  } else {
17479  /* Everything was wrong, so give the device one more try with a new challenge */
17480  if (!req->ignore) {
17481  if (sipdebug) {
17482  ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", sip_get_header(req, "To"));
17483  }
17484  build_nonce(p, 1);
17485  } else {
17486  if (sipdebug) {
17487  ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", sip_get_header(req, "To"));
17488  }
17489  }
17490  transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
17491  }
17492 
17493  /* Schedule auto destroy in 32 seconds */
17495  return AUTH_CHALLENGE_SENT;
17496  }
17497  if (good_response) {
17498  append_history(p, "AuthOK", "Auth challenge successful for %s", username);
17499  return AUTH_SUCCESSFUL;
17500  }
17501 
17502  /* Ok, we have a bad username/secret pair */
17503  /* Tell the UAS not to re-send this authentication data, because
17504  it will continue to fail
17505  */
17506 
17507  return AUTH_SECRET_FAILED;
17508 }
17509 
17510 /*! \brief Change onhold state of a peer using a pvt structure */
17511 static void sip_peer_hold(struct sip_pvt *p, int hold)
17512 {
17513  if (!p->relatedpeer) {
17514  return;
17515  }
17516 
17517  /* If they put someone on hold, increment the value... otherwise decrement it */
17518  ast_atomic_fetchadd_int(&p->relatedpeer->onhold, (hold ? +1 : -1));
17519 
17520  /* Request device state update */
17522  "SIP/%s", p->relatedpeer->name);
17523 
17524  return;
17525 }
17526 
17527 /*! \brief Receive MWI events that we have subscribed to */
17528 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
17529 {
17530  struct sip_peer *peer = userdata;
17531 
17532  /*
17533  * peer can't be NULL here but the peer can be in the process of being
17534  * destroyed. If it is, we don't want to send any messages. In most cases,
17535  * the peer is actually gone and there's no sense sending NOTIFYs that will
17536  * never be answered.
17537  */
17538  if (stasis_subscription_final_message(sub, msg) || peer_in_destruction(peer)) {
17539  return;
17540  }
17541 
17542  if (ast_mwi_state_type() == stasis_message_type(msg)) {
17543  sip_send_mwi_to_peer(peer, 0);
17544  }
17545 }
17546 
17548 {
17549  if (!network_change_sub) {
17550  network_change_sub = stasis_subscribe(ast_system_topic(),
17554  }
17555 }
17556 
17558 {
17559  network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
17560 }
17561 
17563 {
17564  if (!acl_change_sub) {
17565  acl_change_sub = stasis_subscribe(ast_security_topic(),
17569  }
17570 
17571 }
17572 
17574 {
17575  acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
17576 }
17577 
17578 /* Run by the sched thread. */
17579 static int network_change_sched_cb(const void *data)
17580 {
17584  return 0;
17585 }
17586 
17587 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
17588 {
17589  /* This callback is only concerned with network change messages from the system topic. */
17590  if (stasis_message_type(message) != ast_network_change_type()) {
17591  return;
17592  }
17593 
17594  ast_verb(1, "SIP, got a network change message, renewing all SIP registrations.\n");
17595  if (network_change_sched_id == -1) {
17597  }
17598 }
17599 
17600 static void cb_extensionstate_destroy(int id, void *data)
17601 {
17602  struct sip_pvt *p = data;
17603 
17604  dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
17605 }
17606 
17607 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
17608 \note If you add an "hint" priority to the extension in the dial plan,
17609  you will get notifications on device state changes */
17610 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force)
17611 {
17612  sip_pvt_lock(p);
17613 
17614  switch (data->state) {
17615  case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
17616  case AST_EXTENSION_REMOVED: /* Extension is gone */
17617  sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT); /* Delete subscription in 32 secs */
17618  ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, data->state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
17619  p->subscribed = NONE;
17620  append_history(p, "Subscribestatus", "%s", data->state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
17621  break;
17622  default: /* Tell user */
17623  if (force) {
17624  /* we must skip the next two checks for a queued state change or resubscribe */
17625  } else if ((p->laststate == data->state && (~data->state & AST_EXTENSION_RINGING)) &&
17626  (p->last_presence_state == data->presence_state &&
17627  !strcmp(p->last_presence_subtype, data->presence_subtype) &&
17628  !strcmp(p->last_presence_message, data->presence_message))) {
17629  /* don't notify unchanged state or unchanged early-state causing parties again */
17630  sip_pvt_unlock(p);
17631  return 0;
17632  } else if (data->state & AST_EXTENSION_RINGING) {
17633  /* check if another channel than last time is ringing now to be notified */
17635  if (ringing) {
17637  /* we assume here that no two channels have the exact same creation time */
17638  ao2_ref(ringing, -1);
17639  sip_pvt_unlock(p);
17640  return 0;
17641  } else {
17643  ao2_ref(ringing, -1);
17644  }
17645  }
17646  /* If no ringing channel was found, it doesn't necessarily indicate anything bad.
17647  * Likely, a device state change occurred for a custom device state, which does not
17648  * correspond to any channel. In such a case, just go ahead and pass the notification
17649  * along.
17650  */
17651  }
17652  /* ref before unref because the new could be the same as the old one. Don't risk destruction! */
17653  if (data->device_state_info) {
17654  ao2_ref(data->device_state_info, 1);
17655  }
17658  p->laststate = data->state;
17660  ast_string_field_set(p, last_presence_subtype, S_OR(data->presence_subtype, ""));
17661  ast_string_field_set(p, last_presence_message, S_OR(data->presence_message, ""));
17662  break;
17663  }
17664  if (p->subscribed != NONE) { /* Only send state NOTIFY if we know the format */
17665  if (!p->pendinginvite) {
17666  transmit_state_notify(p, data, 1, FALSE);
17667  if (p->last_device_state_info) {
17668  /* We don't need the saved ref anymore, don't keep channels ref'd. */
17671  }
17672  } else {
17673  /* We already have a NOTIFY sent that is not answered. Queue the state up.
17674  if many state changes happen meanwhile, we will only send a notification of the last one */
17676  }
17677  }
17678 
17679  if (!force) {
17680  ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(data->state), p->username,
17681  ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
17682  }
17683 
17684  sip_pvt_unlock(p);
17685 
17686  return 0;
17687 }
17688 
17689 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
17690 \note If you add an "hint" priority to the extension in the dial plan,
17691  you will get notifications on device state changes */
17692 static int cb_extensionstate(const char *context, const char *exten, struct ast_state_cb_info *info, void *data)
17693 {
17694  struct sip_pvt *p = data;
17695  struct state_notify_data notify_data = {
17696  .state = info->exten_state,
17697  .device_state_info = info->device_state_info,
17698  .presence_state = info->presence_state,
17699  .presence_subtype = info->presence_subtype,
17700  .presence_message = info->presence_message,
17701  };
17702 
17704  /* ignore a presence triggered update if we know the useragent doesn't care */
17705  return 0;
17706  }
17707 
17708  return extensionstate_update(context, exten, &notify_data, p, FALSE);
17709 }
17710 
17711 /*! \brief Send a fake 401 Unauthorized response when the administrator
17712  wants to hide the names of local devices from fishers
17713  */
17714 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
17715 {
17716  /* We have to emulate EXACTLY what we'd get with a good peer
17717  * and a bad password, or else we leak information. */
17718  const char *response = "401 Unauthorized";
17719  const char *reqheader = "Authorization";
17720  const char *respheader = "WWW-Authenticate";
17721  const char *authtoken;
17722  struct ast_str *buf;
17723  char *c;
17724 
17725  /* table of recognised keywords, and their value in the digest */
17726  enum keys { K_NONCE, K_LAST };
17727  struct x {
17728  const char *key;
17729  const char *s;
17730  } *i, keys[] = {
17731  [K_NONCE] = { "nonce=", "" },
17732  [K_LAST] = { NULL, NULL}
17733  };
17734 
17735  authtoken = sip_get_header(req, reqheader);
17736  if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
17737  /* This is a retransmitted invite/register/etc, don't reconstruct authentication
17738  * information */
17739  transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
17740  /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
17742  return;
17743  } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
17744  /* We have no auth, so issue challenge and request authentication */
17745  build_nonce(p, 1);
17746  transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
17747  /* Schedule auto destroy in 32 seconds */
17749  return;
17750  }
17751 
17753  __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
17754  return;
17755  }
17756 
17757  /* Make a copy of the response and parse it */
17758  if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
17759  __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
17760  return;
17761  }
17762 
17763  c = ast_str_buffer(buf);
17764 
17765  while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
17766  for (i = keys; i->key != NULL; i++) {
17767  const char *separator = ","; /* default */
17768 
17769  if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
17770  continue;
17771  }
17772  /* Found. Skip keyword, take text in quotes or up to the separator. */
17773  c += strlen(i->key);
17774  if (*c == '"') { /* in quotes. Skip first and look for last */
17775  c++;
17776  separator = "\"";
17777  }
17778  i->s = c;
17779  strsep(&c, separator);
17780  break;
17781  }
17782  if (i->key == NULL) { /* not found, jump after space or comma */
17783  strsep(&c, " ,");
17784  }
17785  }
17786 
17787  /* Verify nonce from request matches our nonce. If not, send 401 with new nonce */
17788  if (strcasecmp(p->nonce, keys[K_NONCE].s)) {
17789  if (!req->ignore) {
17790  build_nonce(p, 1);
17791  }
17792  transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
17793 
17794  /* Schedule auto destroy in 32 seconds */
17796  } else {
17797  __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
17798  }
17799 }
17800 
17801 /*!
17802  * Terminate the uri at the first ';' or space.
17803  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
17804  * but don't do it for the time being. Remember the uri format is:
17805  * (User-parameters was added after RFC 3261)
17806  *\verbatim
17807  *
17808  * sip:user:password;user-parameters@host:port;uri-parameters?headers
17809  * sips:user:password;user-parameters@host:port;uri-parameters?headers
17810  *
17811  *\endverbatim
17812  * \todo As this function does not support user-parameters, it's considered broken
17813  * and needs fixing.
17814  */
17815 static char *terminate_uri(char *uri)
17816 {
17817  char *t = uri;
17818  while (*t && *t > ' ' && *t != ';') {
17819  t++;
17820  }
17821  *t = '\0';
17822  return uri;
17823 }
17824 
17825 /*! \brief Terminate a host:port at the ':'
17826  * \param hostport The address of the hostport string
17827  *
17828  * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
17829  * will contain the non-bracketed host as a result of calling this function.
17830  */
17831 static void extract_host_from_hostport(char **hostport)
17832 {
17833  char *dont_care;
17834  ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
17835 }
17836 
17837 /*!
17838  * \internal
17839  * \brief Helper function to update a peer's lastmsgssent value
17840  */
17841 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
17842 {
17843  if (!locked) {
17844  ao2_lock(peer);
17845  }
17846  peer->lastmsgssent = value;
17847  if (!locked) {
17848  ao2_unlock(peer);
17849  }
17850 }
17851 
17852 
17853 /*!
17854  * \brief Verify registration of user
17855  *
17856  * \details
17857  * - Registration is done in several steps, first a REGISTER without auth
17858  * to get a challenge (nonce) then a second one with auth
17859  * - Registration requests are only matched with peers that are marked as "dynamic"
17860  */
17861 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
17862  struct sip_request *req, const char *uri)
17863 {
17864  enum check_auth_result res = AUTH_NOT_FOUND;
17865  struct sip_peer *peer;
17866  char tmp[256];
17867  char *c, *name, *unused_password, *domain;
17868  char *uri2 = ast_strdupa(uri);
17869  int send_mwi = 0;
17870 
17871  terminate_uri(uri2);
17872 
17873  ast_copy_string(tmp, sip_get_header(req, "To"), sizeof(tmp));
17874 
17875  c = get_in_brackets(tmp);
17876  c = remove_uri_parameters(c);
17877 
17878  if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
17879  ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
17880  return -1;
17881  }
17882 
17883  SIP_PEDANTIC_DECODE(name);
17884  SIP_PEDANTIC_DECODE(domain);
17885 
17886  extract_host_from_hostport(&domain);
17887 
17888  if (ast_strlen_zero(domain)) {
17889  /* <sip:name@[EMPTY]>, never good */
17890  transmit_response(p, "404 Not found", &p->initreq);
17891  return AUTH_UNKNOWN_DOMAIN;
17892  }
17893 
17894  if (ast_strlen_zero(name)) {
17895  /* <sip:[EMPTY][@]hostport>, unsure whether valid for
17896  * registration. RFC 3261, 10.2 states:
17897  * "The To header field and the Request-URI field typically
17898  * differ, as the former contains a user name."
17899  * But, Asterisk has always treated the domain-only uri as a
17900  * username: we allow admins to create accounts described by
17901  * domain name. */
17902  name = domain;
17903  }
17904 
17905  /* This here differs from 1.4 and 1.6: the domain matching ACLs were
17906  * skipped if it was a domain-only URI (used as username). Here we treat
17907  * <sip:hostport> as <sip:host@hostport> and won't forget to test the
17908  * domain ACLs against host. */
17909  if (!AST_LIST_EMPTY(&domain_list)) {
17910  if (!check_sip_domain(domain, NULL, 0)) {
17911  if (sip_cfg.alwaysauthreject) {
17913  } else {
17914  transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
17915  }
17916  return AUTH_UNKNOWN_DOMAIN;
17917  }
17918  }
17919 
17920  ast_string_field_set(p, exten, name);
17921  build_contact(p, req, 1);
17922  if (req->ignore) {
17923  /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
17924  const char *expires = sip_get_header(req, "Expires");
17925  int expire = atoi(expires);
17926 
17927  if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
17928  if ((expires = strcasestr(sip_get_header(req, "Contact"), ";expires="))) {
17929  expire = atoi(expires + 9);
17930  }
17931  }
17932  if (!ast_strlen_zero(expires) && expire == 0) {
17933  transmit_response_with_date(p, "200 OK", req);
17934  return 0;
17935  }
17936  }
17937  peer = sip_find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
17938 
17939  /* If we don't want username disclosure, use the bogus_peer when a user
17940  * is not found. */
17942  peer = ao2_t_global_obj_ref(g_bogus_peer, "register_verify: Get the bogus peer.");
17943  }
17944 
17945  if (!(peer && ast_apply_acl(peer->acl, addr, "SIP Peer ACL: "))) {
17946  /* Peer fails ACL check */
17947  if (peer) {
17948  sip_unref_peer(peer, "register_verify: sip_unref_peer: from sip_find_peer operation");
17949  peer = NULL;
17950  res = AUTH_ACL_FAILED;
17951  } else {
17952  res = AUTH_NOT_FOUND;
17953  }
17954  }
17955 
17956  if (peer) {
17957  ao2_lock(peer);
17958  if (!peer->host_dynamic) {
17959  ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
17960  res = AUTH_PEER_NOT_DYNAMIC;
17961  } else {
17962 
17963  set_peer_nat(p, peer);
17964 
17965  ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
17966 
17967  if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE))) {
17968  sip_cancel_destroy(p);
17969 
17970  if (check_request_transport(peer, req)) {
17972  transmit_response_with_date(p, "403 Forbidden", req);
17973  res = AUTH_BAD_TRANSPORT;
17974  } else {
17975 
17976  /* We have a successful registration attempt with proper authentication,
17977  now, update the peer */
17978  switch (parse_register_contact(p, peer, req)) {
17979  case PARSE_REGISTER_DENIED:
17980  ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
17981  transmit_response_with_date(p, "603 Denied", req);
17982  res = 0;
17983  break;
17984  case PARSE_REGISTER_FAILED:
17985  ast_log(LOG_WARNING, "Failed to parse contact info\n");
17986  transmit_response_with_date(p, "400 Bad Request", req);
17987  res = 0;
17988  break;
17989  case PARSE_REGISTER_QUERY:
17990  ast_string_field_set(p, fullcontact, peer->fullcontact);
17991  transmit_response_with_date(p, "200 OK", req);
17992  res = 0;
17993  send_mwi = 1;
17994  break;
17995  case PARSE_REGISTER_UPDATE:
17996  ast_string_field_set(p, fullcontact, peer->fullcontact);
17997  /* If expiry is 0, peer has been unregistered already */
17998  if (p->expiry != 0) {
17999  update_peer(peer, p->expiry);
18000  }
18001  /* Say OK and ask subsystem to retransmit msg counter */
18002  transmit_response_with_date(p, "200 OK", req);
18003  send_mwi = 1;
18004  res = 0;
18005  break;
18006  }
18007  }
18008 
18009  }
18010  }
18011  ao2_unlock(peer);
18012  }
18013  if (!peer && sip_cfg.autocreatepeer != AUTOPEERS_DISABLED) {
18014  /* Create peer if we have autocreate mode enabled */
18015  peer = temp_peer(name);
18016  if (peer && !(peer->endpoint = ast_endpoint_create("SIP", name))) {
18017  ao2_t_ref(peer, -1, "failed to allocate Stasis endpoint, drop peer");
18018  peer = NULL;
18019  }
18020  if (peer) {
18021  ao2_t_link(peers, peer, "link peer into peer table");
18022  if (!ast_sockaddr_isnull(&peer->addr)) {
18023  ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
18024  }
18025  ao2_lock(peer);
18026  sip_cancel_destroy(p);
18027  switch (parse_register_contact(p, peer, req)) {
18028  case PARSE_REGISTER_DENIED:
18029  ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
18030  transmit_response_with_date(p, "403 Forbidden", req);
18031  res = 0;
18032  break;
18033  case PARSE_REGISTER_FAILED:
18034  ast_log(LOG_WARNING, "Failed to parse contact info\n");
18035  transmit_response_with_date(p, "400 Bad Request", req);
18036  res = 0;
18037  break;
18038  case PARSE_REGISTER_QUERY:
18039  ast_string_field_set(p, fullcontact, peer->fullcontact);
18040  transmit_response_with_date(p, "200 OK", req);
18041  send_mwi = 1;
18042  res = 0;
18043  break;
18044  case PARSE_REGISTER_UPDATE:
18045  ast_string_field_set(p, fullcontact, peer->fullcontact);
18046  /* Say OK and ask subsystem to retransmit msg counter */
18047  transmit_response_with_date(p, "200 OK", req);
18048  if (peer->endpoint) {
18049  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
18051  blob = ast_json_pack("{s: s, s: s}",
18052  "peer_status", "Registered",
18053  "address", ast_sockaddr_stringify(addr));
18055  }
18056  send_mwi = 1;
18057  res = 0;
18058  break;
18059  }
18060  ao2_unlock(peer);
18061  }
18062  }
18063  if (!res) {
18064  if (send_mwi) {
18065  sip_pvt_unlock(p);
18066  sip_send_mwi_to_peer(peer, 0);
18067  sip_pvt_lock(p);
18068  } else {
18069  update_peer_lastmsgssent(peer, -1, 0);
18070  }
18072  }
18073  if (res < 0) {
18074  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
18075 
18076  switch (res) {
18077  case AUTH_SECRET_FAILED:
18078  /* Wrong password in authentication. Go away, don't try again until you fixed it */
18079  transmit_response(p, "403 Forbidden", &p->initreq);
18081  const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
18082  const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
18083 
18084  blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
18085  "peer_status", "Rejected",
18086  "cause", "AUTH_SECRET_FAILED",
18087  "address", peer_addr,
18088  "port", peer_port);
18089  }
18090  break;
18092  /* Username and digest username does not match.
18093  Asterisk uses the From: username for authentication. We need the
18094  devices to use the same authentication user name until we support
18095  proper authentication by digest auth name */
18096  case AUTH_NOT_FOUND:
18097  case AUTH_PEER_NOT_DYNAMIC:
18098  case AUTH_ACL_FAILED:
18099  if (sip_cfg.alwaysauthreject) {
18102  const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
18103  const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
18104 
18105  blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
18106  "peer_status", "Rejected",
18107  "cause", res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
18108  "address", peer_addr,
18109  "port", peer_port);
18110  }
18111  } else {
18112  /* URI not found */
18113  if (res == AUTH_PEER_NOT_DYNAMIC) {
18114  transmit_response(p, "403 Forbidden", &p->initreq);
18116  const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
18117  const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
18118 
18119  blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
18120  "peer_status", "Rejected",
18121  "cause", "AUTH_PEER_NOT_DYNAMIC",
18122  "address", peer_addr,
18123  "port", peer_port);
18124  }
18125  } else {
18126  transmit_response(p, "404 Not found", &p->initreq);
18128  const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
18129  const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
18130 
18131  blob = ast_json_pack("{s: s, s: s, s: s, s: s}",
18132  "peer_status", "Rejected",
18133  "cause", (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
18134  "address", peer_addr,
18135  "port", peer_port);
18136  }
18137  }
18138  }
18139  break;
18140  case AUTH_BAD_TRANSPORT:
18141  default:
18142  break;
18143  }
18144 
18145  if (peer && peer->endpoint) {
18147  }
18148  }
18149  if (peer) {
18150  sip_unref_peer(peer, "register_verify: sip_unref_peer: tossing stack peer pointer at end of func");
18151  }
18152 
18153  return res;
18154 }
18155 
18156 /*! \brief Translate referring cause */
18157 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
18158 
18159  if (!strcmp(reason, "unknown")) {
18160  ast_string_field_set(p, redircause, "UNKNOWN");
18161  } else if (!strcmp(reason, "user-busy")) {
18162  ast_string_field_set(p, redircause, "BUSY");
18163  } else if (!strcmp(reason, "no-answer")) {
18164  ast_string_field_set(p, redircause, "NOANSWER");
18165  } else if (!strcmp(reason, "unavailable")) {
18166  ast_string_field_set(p, redircause, "UNREACHABLE");
18167  } else if (!strcmp(reason, "unconditional")) {
18168  ast_string_field_set(p, redircause, "UNCONDITIONAL");
18169  } else if (!strcmp(reason, "time-of-day")) {
18170  ast_string_field_set(p, redircause, "UNKNOWN");
18171  } else if (!strcmp(reason, "do-not-disturb")) {
18172  ast_string_field_set(p, redircause, "UNKNOWN");
18173  } else if (!strcmp(reason, "deflection")) {
18174  ast_string_field_set(p, redircause, "UNKNOWN");
18175  } else if (!strcmp(reason, "follow-me")) {
18176  ast_string_field_set(p, redircause, "UNKNOWN");
18177  } else if (!strcmp(reason, "out-of-service")) {
18178  ast_string_field_set(p, redircause, "UNREACHABLE");
18179  } else if (!strcmp(reason, "away")) {
18180  ast_string_field_set(p, redircause, "UNREACHABLE");
18181  } else {
18182  ast_string_field_set(p, redircause, "UNKNOWN");
18183  }
18184 }
18185 
18186 /*! \brief Parse the parts of the P-Asserted-Identity header
18187  * on an incoming packet. Returns 1 if a valid header is found
18188  * and it is different from the current caller id.
18189  */
18190 static int get_pai(struct sip_pvt *p, struct sip_request *req)
18191 {
18192  char pai[256];
18193  char privacy[64];
18194  char *cid_num = NULL;
18195  char *cid_name = NULL;
18196  char emptyname[1] = "";
18198  char *uri = NULL;
18199  int is_anonymous = 0, do_update = 1, no_name = 0;
18200 
18201  ast_copy_string(pai, sip_get_header(req, "P-Asserted-Identity"), sizeof(pai));
18202 
18203  if (ast_strlen_zero(pai)) {
18204  return 0;
18205  }
18206 
18207  /* use the reqresp_parser function get_name_and_number*/
18208  if (get_name_and_number(pai, &cid_name, &cid_num)) {
18209  return 0;
18210  }
18211 
18213  ast_shrink_phone_number(cid_num);
18214  }
18215 
18216  uri = get_in_brackets(pai);
18217  if (!strncasecmp(uri, "sip:[email protected]", 31)) {
18219  /*XXX Assume no change in cid_num. Perhaps it should be
18220  * blanked?
18221  */
18222  ast_free(cid_num);
18223  is_anonymous = 1;
18224  cid_num = (char *)p->cid_num;
18225  }
18226 
18227  ast_copy_string(privacy, sip_get_header(req, "Privacy"), sizeof(privacy));
18228  if (!ast_strlen_zero(privacy) && strcasecmp(privacy, "none")) {
18230  }
18231  if (!cid_name) {
18232  no_name = 1;
18233  cid_name = (char *)emptyname;
18234  }
18235  /* Only return true if the supplied caller id is different */
18236  if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
18237  do_update = 0;
18238  } else {
18239 
18240  ast_string_field_set(p, cid_num, cid_num);
18241  ast_string_field_set(p, cid_name, cid_name);
18242  p->callingpres = callingpres;
18243 
18244  if (p->owner) {
18245  ast_set_callerid(p->owner, cid_num, cid_name, NULL);
18246  ast_channel_caller(p->owner)->id.name.presentation = callingpres;
18247  ast_channel_caller(p->owner)->id.number.presentation = callingpres;
18248  }
18249  }
18250 
18251  /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
18252  if (!is_anonymous) {
18253  ast_free(cid_num);
18254  }
18255  if (!no_name) {
18256  ast_free(cid_name);
18257  }
18258 
18259  return do_update;
18260 }
18261 
18262 /*! \brief Get name, number and presentation from remote party id header,
18263  * returns true if a valid header was found and it was different from the
18264  * current caller id.
18265  */
18266 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
18267 {
18268  char tmp[256];
18269  struct sip_request *req;
18270  char *cid_num = "";
18271  char *cid_name = "";
18273  char *privacy = "";
18274  char *screen = "";
18275  char *start, *end;
18276 
18277  if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
18278  return 0;
18279  req = oreq;
18280  if (!req)
18281  req = &p->initreq;
18282  ast_copy_string(tmp, sip_get_header(req, "Remote-Party-ID"), sizeof(tmp));
18283  if (ast_strlen_zero(tmp)) {
18284  return get_pai(p, req);
18285  }
18286 
18287  /*
18288  * RPID is not:
18289  * rpid = (name-addr / addr-spec) *(SEMI rpi-token)
18290  * But it is:
18291  * rpid = [display-name] LAQUOT addr-spec RAQUOT *(SEMI rpi-token)
18292  * Ergo, calling parse_name_andor_addr() on it wouldn't be
18293  * correct because that would allow addr-spec style too.
18294  */
18295  start = tmp;
18296  /* Quoted (note that we're not dealing with escapes properly) */
18297  if (*start == '"') {
18298  *start++ = '\0';
18299  end = strchr(start, '"');
18300  if (!end)
18301  return 0;
18302  *end++ = '\0';
18303  cid_name = start;
18304  start = ast_skip_blanks(end);
18305  /* Unquoted */
18306  } else {
18307  cid_name = start;
18308  start = end = strchr(start, '<');
18309  if (!start) {
18310  return 0;
18311  }
18312  /* trim blanks if there are any. the mandatory NUL is done below */
18313  while (--end >= cid_name && *end < 33) {
18314  *end = '\0';
18315  }
18316  }
18317 
18318  if (*start != '<')
18319  return 0;
18320  *start++ = '\0';
18321  end = strchr(start, '@');
18322  if (!end)
18323  return 0;
18324  *end++ = '\0';
18325  if (strncasecmp(start, "sip:", 4))
18326  return 0;
18327  cid_num = start + 4;
18329  ast_shrink_phone_number(cid_num);
18330  start = end;
18331 
18332  end = strchr(start, '>');
18333  if (!end)
18334  return 0;
18335  *end++ = '\0';
18336  if (*end) {
18337  start = end;
18338  if (*start != ';')
18339  return 0;
18340  *start++ = '\0';
18341  while (!ast_strlen_zero(start)) {
18342  end = strchr(start, ';');
18343  if (end)
18344  *end++ = '\0';
18345  if (!strncasecmp(start, "privacy=", 8))
18346  privacy = start + 8;
18347  else if (!strncasecmp(start, "screen=", 7))
18348  screen = start + 7;
18349  start = end;
18350  }
18351 
18352  if (!strcasecmp(privacy, "full")) {
18353  if (!strcasecmp(screen, "yes"))
18355  else if (!strcasecmp(screen, "no"))
18357  } else {
18358  if (!strcasecmp(screen, "yes"))
18360  else if (!strcasecmp(screen, "no"))
18362  }
18363  }
18364 
18365  /* Only return true if the supplied caller id is different */
18366  if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
18367  return 0;
18368 
18369  ast_string_field_set(p, cid_num, cid_num);
18370  ast_string_field_set(p, cid_name, cid_name);
18371  p->callingpres = callingpres;
18372 
18373  if (p->owner) {
18374  ast_set_callerid(p->owner, cid_num, cid_name, NULL);
18375  ast_channel_caller(p->owner)->id.name.presentation = callingpres;
18376  ast_channel_caller(p->owner)->id.number.presentation = callingpres;
18377  }
18378 
18379  return 1;
18380 }
18381 
18382 /*! \brief Get referring dnis
18383  *
18384  * \param p dialog information
18385  * \param oreq The request to retrieve RDNIS from
18386  * \param[out] name The name of the party redirecting the call.
18387  * \param[out] number The number of the party redirecting the call.
18388  * \param[out] reason_code The numerical code corresponding to the reason for the redirection.
18389  * \param[out] reason_str A string describing the reason for redirection. Will never be zero-length
18390  *
18391  * \retval -1 Could not retrieve RDNIS information
18392  * \retval 0 RDNIS successfully retrieved
18393  */
18394 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason_code, char **reason_str)
18395 {
18396  char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
18397  char *params, *reason_param = NULL;
18398  struct sip_request *req;
18399 
18400  ast_assert(reason_code != NULL);
18401  ast_assert(reason_str != NULL);
18402 
18403  req = oreq ? oreq : &p->initreq;
18404 
18405  ast_copy_string(tmp, sip_get_header(req, "Diversion"), sizeof(tmp));
18406  if (ast_strlen_zero(tmp))
18407  return -1;
18408 
18409  if ((params = strchr(tmp, '>'))) {
18410  params = strchr(params, ';');
18411  }
18412 
18413  exten = get_in_brackets(tmp);
18414  if (!strncasecmp(exten, "sip:", 4)) {
18415  exten += 4;
18416  } else if (!strncasecmp(exten, "sips:", 5)) {
18417  exten += 5;
18418  } else {
18419  ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
18420  return -1;
18421  }
18422 
18423  /* Get diversion-reason param if present */
18424  if (params) {
18425  *params = '\0'; /* Cut off parameters */
18426  params++;
18427  while (*params == ';' || *params == ' ')
18428  params++;
18429  /* Check if we have a reason parameter */
18430  if ((reason_param = strcasestr(params, "reason="))) {
18431  char *end;
18432  reason_param+=7;
18433  if ((end = strchr(reason_param, ';'))) {
18434  *end = '\0';
18435  }
18436  }
18437  }
18438 
18439  rdomain = exten;
18440  rexten = strsep(&rdomain, "@"); /* trim anything after @ */
18441  if (p->owner)
18442  pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
18443 
18444  if (sip_debug_test_pvt(p)) {
18445  ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
18446  }
18447  /*ast_string_field_set(p, rdnis, rexten);*/
18448 
18449  if (*tmp == '\"') {
18450  char *end_quote;
18451  rname = tmp + 1;
18452  end_quote = strchr(rname, '\"');
18453  if (end_quote) {
18454  *end_quote = '\0';
18455  }
18456  }
18457 
18458  if (number) {
18459  *number = ast_strdup(rexten);
18460  }
18461 
18462  if (name && rname) {
18463  *name = ast_strdup(rname);
18464  }
18465 
18466  if (!ast_strlen_zero(reason_param)) {
18467  *reason_str = ast_strdup(reason_param);
18468 
18469  /* Remove any enclosing double-quotes */
18470  if (*reason_param == '"') {
18471  reason_param = ast_strip_quoted(reason_param, "\"", "\"");
18472  }
18473 
18474  *reason_code = ast_redirecting_reason_parse(reason_param);
18475  if (*reason_code < 0) {
18476  *reason_code = AST_REDIRECTING_REASON_UNKNOWN;
18477  } else {
18478  ast_free(*reason_str);
18479  *reason_str = ast_strdup("");
18480  }
18481 
18482  if (!ast_strlen_zero(reason_param)) {
18483  sip_set_redirstr(p, reason_param);
18484  if (p->owner) {
18485  pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
18486  pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
18487  }
18488  }
18489  }
18490 
18491  return 0;
18492 }
18493 
18494 /*!
18495  * \brief Find out who the call is for.
18496  *
18497  * \details
18498  * We use the request uri as a destination.
18499  * This code assumes authentication has been done, so that the
18500  * device (peer/user) context is already set.
18501  *
18502  * \return 0 on success (found a matching extension), non-zero on failure
18503  *
18504  * \note If the incoming uri is a SIPS: uri, we are required to carry this across
18505  * the dialplan, so that the outbound call also is a sips: call or encrypted
18506  * IAX2 call. If that's not available, the call should FAIL.
18507  */
18508 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
18509 {
18510  char tmp[256] = "", *uri, *unused_password, *domain;
18511  RAII_VAR(char *, tmpf, NULL, ast_free);
18512  char *from = NULL;
18513  struct sip_request *req;
18514  char *decoded_uri;
18516  const char *pickupexten;
18517 
18518  if (!pickup_cfg) {
18519  ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
18520  pickupexten = "";
18521  } else {
18522  /* Don't need to duplicate since channel is locked for the duration of this function */
18523  pickupexten = pickup_cfg->pickupexten;
18524  }
18525 
18526  req = oreq;
18527  if (!req) {
18528  req = &p->initreq;
18529  }
18530 
18531  /* Find the request URI */
18532  if (req->rlpart2) {
18533  ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlpart2), sizeof(tmp));
18534  }
18535 
18536  uri = ast_strdupa(get_in_brackets(tmp));
18537 
18538  if (parse_uri_legacy_check(uri, "sip:,sips:,tel:", &uri, &unused_password, &domain, NULL)) {
18539  ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
18540  return SIP_GET_DEST_INVALID_URI;
18541  }
18542 
18543  SIP_PEDANTIC_DECODE(domain);
18544  SIP_PEDANTIC_DECODE(uri);
18545 
18546  extract_host_from_hostport(&domain);
18547 
18548  if (strncasecmp(get_in_brackets(tmp), "tel:", 4)) {
18549  ast_string_field_set(p, domain, domain);
18550  } else {
18551  ast_string_field_set(p, tel_phone_context, domain);
18552  }
18553 
18554  if (ast_strlen_zero(uri)) {
18555  /*
18556  * Either there really was no extension found or the request
18557  * URI had encoded nulls that made the string "empty". Use "s"
18558  * as the extension.
18559  */
18560  uri = "s";
18561  }
18562 
18563  /* Now find the From: caller ID and name */
18564  /* XXX Why is this done in get_destination? Isn't it already done?
18565  Needs to be checked
18566  */
18567  tmpf = ast_strdup(sip_get_header(req, "From"));
18568  if (!ast_strlen_zero(tmpf)) {
18569  from = get_in_brackets(tmpf);
18570  if (parse_uri_legacy_check(from, "sip:,sips:,tel:", &from, NULL, &domain, NULL)) {
18571  ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
18572  return SIP_GET_DEST_INVALID_URI;
18573  }
18574 
18575  SIP_PEDANTIC_DECODE(from);
18576  SIP_PEDANTIC_DECODE(domain);
18577 
18578  extract_host_from_hostport(&domain);
18579 
18580  ast_string_field_set(p, fromdomain, domain);
18581  }
18582 
18583  if (!AST_LIST_EMPTY(&domain_list)) {
18584  char domain_context[AST_MAX_EXTENSION];
18585 
18586  domain_context[0] = '\0';
18587  if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
18588  if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
18589  ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
18590  return SIP_GET_DEST_REFUSED;
18591  }
18592  }
18593  /* If we don't have a peer (i.e. we're a guest call),
18594  * overwrite the original context */
18595  if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
18596  ast_string_field_set(p, context, domain_context);
18597  }
18598  }
18599 
18600  /* If the request coming in is a subscription and subscribecontext has been specified use it */
18601  if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
18603  }
18604 
18605  if (sip_debug_test_pvt(p)) {
18606  ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
18607  }
18608 
18609  /* Since extensions.conf can have unescaped characters, try matching a
18610  * decoded uri in addition to the non-decoded uri. */
18611  decoded_uri = ast_strdupa(uri);
18612  ast_uri_decode(decoded_uri, ast_uri_sip_user);
18613 
18614  /* If this is a subscription we actually just need to see if a hint exists for the extension */
18615  if (req->method == SIP_SUBSCRIBE) {
18616  int which = 0;
18617 
18618  if (ast_get_hint(NULL, 0, NULL, 0, NULL, p->context, uri)
18619  || (ast_get_hint(NULL, 0, NULL, 0, NULL, p->context, decoded_uri)
18620  && (which = 1))) {
18621  if (!oreq) {
18622  ast_string_field_set(p, exten, which ? decoded_uri : uri);
18623  }
18624  return SIP_GET_DEST_EXTEN_FOUND;
18625  } else {
18627  }
18628  } else {
18629  struct ast_cc_agent *agent;
18630  /* Check the dialplan for the username part of the request URI,
18631  the domain will be stored in the SIPDOMAIN variable
18632  Return 0 if we have a matching extension */
18633  if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
18634  if (!oreq) {
18635  ast_string_field_set(p, exten, uri);
18636  }
18637  return SIP_GET_DEST_EXTEN_FOUND;
18638  }
18639  if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
18640  || !strcmp(decoded_uri, pickupexten)) {
18641  if (!oreq) {
18642  ast_string_field_set(p, exten, decoded_uri);
18643  }
18644  return SIP_GET_DEST_EXTEN_FOUND;
18645  }
18646  if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
18647  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
18648  /* This is a CC recall. We can set p's extension to the exten from
18649  * the original INVITE
18650  */
18651  ast_string_field_set(p, exten, agent_pvt->original_exten);
18652  /* And we need to let the CC core know that the caller is attempting
18653  * his recall
18654  */
18655  ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
18656  agent->device_name);
18657  if (cc_recall_core_id) {
18658  *cc_recall_core_id = agent->core_id;
18659  }
18660  ao2_ref(agent, -1);
18661  return SIP_GET_DEST_EXTEN_FOUND;
18662  }
18663  }
18664 
18665  if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
18666  && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
18667  || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
18668  || !strncmp(decoded_uri, pickupexten, strlen(decoded_uri)))) {
18669  /* Overlap dialing is enabled and we need more digits to match an extension. */
18671  }
18672 
18674 }
18675 
18676 /*! \brief Find a companion dialog based on Replaces information
18677  *
18678  * This information may come from a Refer-To header in a REFER or from
18679  * a Replaces header in an INVITE.
18680  *
18681  * This function will find the appropriate sip_pvt and increment the refcount
18682  * of both the sip_pvt and its owner channel. These two references are returned
18683  * in the out parameters
18684  *
18685  * \param callid Callid to search for
18686  * \param totag to-tag parameter from Replaces
18687  * \param fromtag from-tag parameter from Replaces
18688  * \param[out] out_pvt The found sip_pvt.
18689  * \param[out] out_chan The found sip_pvt's owner channel.
18690  * \retval 0 Success
18691  * \retval non-zero Failure
18692  */
18693 static int get_sip_pvt_from_replaces(const char *callid, const char *totag,
18694  const char *fromtag, struct sip_pvt **out_pvt, struct ast_channel **out_chan)
18695 {
18696  RAII_VAR(struct sip_pvt *, sip_pvt_ptr, NULL, ao2_cleanup);
18697  struct sip_pvt tmp_dialog = {
18698  .callid = callid,
18699  };
18700 
18701  if (totag) {
18702  ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
18703  }
18704 
18705  /* Search dialogs and find the match */
18706 
18707  sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
18708  if (sip_pvt_ptr) {
18709  /* Go ahead and lock it (and its owner) before returning */
18710  SCOPED_LOCK(lock, sip_pvt_ptr, sip_pvt_lock, sip_pvt_unlock);
18712  unsigned char frommismatch = 0, tomismatch = 0;
18713 
18714  if (ast_strlen_zero(fromtag)) {
18715  ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
18716  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
18717  return -1;
18718  }
18719 
18720  if (ast_strlen_zero(totag)) {
18721  ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
18722  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
18723  return -1;
18724  }
18725  /* RFC 3891
18726  * > 3. User Agent Server Behavior: Receiving a Replaces Header
18727  * > The Replaces header contains information used to match an existing
18728  * > SIP dialog (call-id, to-tag, and from-tag). Upon receiving an INVITE
18729  * > with a Replaces header, the User Agent (UA) attempts to match this
18730  * > information with a confirmed or early dialog. The User Agent Server
18731  * > (UAS) matches the to-tag and from-tag parameters as if they were tags
18732  * > present in an incoming request. In other words, the to-tag parameter
18733  * > is compared to the local tag, and the from-tag parameter is compared
18734  * > to the remote tag.
18735  *
18736  * Thus, the totag is always compared to the local tag, regardless if
18737  * this our call is an incoming or outgoing call.
18738  */
18739  frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
18740  tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
18741 
18742  /* Don't check from if the dialog is not established, due to multi forking the from
18743  * can change when the call is not answered yet.
18744  */
18745  if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
18746  if (frommismatch) {
18747  ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
18748  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
18749  fromtag, sip_pvt_ptr->theirtag);
18750  }
18751  if (tomismatch) {
18752  ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
18753  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
18754  totag, sip_pvt_ptr->tag);
18755  }
18756  return -1;
18757  }
18758  }
18759 
18760  if (totag)
18761  ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
18762  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
18763  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
18764 
18765  *out_pvt = sip_pvt_ptr;
18766  if (out_chan) {
18767  *out_chan = sip_pvt_ptr->owner ? ast_channel_ref(sip_pvt_ptr->owner) : NULL;
18768  }
18769  }
18770 
18771  if (!sip_pvt_ptr) {
18772  /* return error if sip_pvt was not found */
18773  return -1;
18774  }
18775 
18776  /* If we're here sip_pvt_ptr has been copied to *out_pvt, prevent RAII_VAR cleanup */
18777  sip_pvt_ptr = NULL;
18778 
18779  return 0;
18780 }
18781 
18782 static void extract_transferrer_headers(const char *prefix, struct ast_channel *peer, const struct sip_request *req)
18783 {
18784  struct ast_str *pbxvar = ast_str_alloca(120);
18785  int i;
18786 
18787  /* The '*' alone matches all headers. */
18788  if (strcmp(prefix, "*") == 0) {
18789  prefix = "";
18790  }
18791 
18792  for (i = 0; i < req->headers; i++) {
18793  const char *header = REQ_OFFSET_TO_STR(req, header[i]);
18794  if (ast_begins_with(header, prefix)) {
18795  int hdrlen = strcspn(header, " \t:");
18796  const char *val = ast_skip_blanks(header + hdrlen);
18797  if (hdrlen > 0 && *val == ':') {
18798  ast_str_set(&pbxvar, -1, "~HASH~TRANSFER_DATA~%.*s~", hdrlen, header);
18799  pbx_builtin_setvar_helper(peer, ast_str_buffer(pbxvar), ast_skip_blanks(val + 1));
18800  }
18801  }
18802  }
18803 }
18804 
18805 /*! \brief Call transfer support (the REFER method)
18806  * Extracts Refer headers into pvt dialog structure
18807  *
18808  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
18809  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
18810  * flag.
18811  */
18812 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
18813 {
18814  const char *p_referred_by = NULL;
18815  char *h_refer_to = NULL;
18816  char *h_referred_by = NULL;
18817  char *refer_to;
18818  const char *p_refer_to;
18819  char *referred_by_uri = NULL;
18820  char *ptr;
18821  struct sip_request *req = NULL;
18822  const char *transfer_context = NULL;
18823  struct sip_refer *refer;
18824 
18825  req = outgoing_req;
18826  refer = transferer->refer;
18827 
18828  if (!req) {
18829  req = &transferer->initreq;
18830  }
18831 
18832  p_refer_to = sip_get_header(req, "Refer-To");
18833  if (ast_strlen_zero(p_refer_to)) {
18834  ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
18835  return -2; /* Syntax error */
18836  }
18837  h_refer_to = ast_strdupa(p_refer_to);
18838  refer_to = get_in_brackets(h_refer_to);
18839  if (!strncasecmp(refer_to, "sip:", 4)) {
18840  refer_to += 4; /* Skip sip: */
18841  } else if (!strncasecmp(refer_to, "sips:", 5)) {
18842  refer_to += 5;
18843  } else {
18844  ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
18845  return -3;
18846  }
18847 
18848  /* Get referred by header if it exists */
18849  p_referred_by = sip_get_header(req, "Referred-By");
18850 
18851  /* Give useful transfer information to the dialplan */
18852  if (transferer->owner) {
18853  RAII_VAR(struct ast_channel *, peer, NULL, ast_channel_cleanup);
18854  RAII_VAR(struct ast_channel *, owner_relock, NULL, ast_channel_cleanup);
18855  RAII_VAR(struct ast_channel *, owner_ref, NULL, ast_channel_cleanup);
18856 
18857  /* Grab a reference to transferer->owner to prevent it from going away */
18858  owner_ref = ast_channel_ref(transferer->owner);
18859 
18860  /* Established locking order here is bridge, channel, pvt
18861  * and the bridge will be locked during ast_channel_bridge_peer */
18862  ast_channel_unlock(owner_ref);
18863  sip_pvt_unlock(transferer);
18864 
18865  peer = ast_channel_bridge_peer(owner_ref);
18866  if (peer) {
18867  const char *get_xfrdata;
18868 
18869  pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT",
18870  S_OR(transferer->context, NULL));
18871  pbx_builtin_setvar_helper(peer, "__SIPREFERREDBYHDR",
18872  S_OR(p_referred_by, NULL));
18873 
18874  ast_channel_lock(peer);
18875  get_xfrdata = pbx_builtin_getvar_helper(peer, "GET_TRANSFERRER_DATA");
18876  if (!ast_strlen_zero(get_xfrdata)) {
18877  extract_transferrer_headers(get_xfrdata, peer, req);
18878  }
18879  ast_channel_unlock(peer);
18880  }
18881 
18882  owner_relock = sip_pvt_lock_full(transferer);
18883  if (!owner_relock) {
18884  ast_debug(3, "Unable to reacquire owner channel lock, channel is gone\n");
18885  return -5;
18886  }
18887  }
18888 
18889  if (!ast_strlen_zero(p_referred_by)) {
18890  h_referred_by = ast_strdupa(p_referred_by);
18891 
18892  referred_by_uri = get_in_brackets(h_referred_by);
18893 
18894  if (!strncasecmp(referred_by_uri, "sip:", 4)) {
18895  referred_by_uri += 4; /* Skip sip: */
18896  } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
18897  referred_by_uri += 5; /* Skip sips: */
18898  } else {
18899  ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
18900  referred_by_uri = NULL;
18901  }
18902  }
18903 
18904  /* Check for arguments in the refer_to header */
18905  if ((ptr = strcasestr(refer_to, "replaces="))) {
18906  char *to = NULL, *from = NULL, *callid;
18907 
18908  /* This is an attended transfer */
18909  refer->attendedtransfer = 1;
18910 
18911  callid = ast_strdupa(ptr + 9);
18913  if ((ptr = strchr(callid, ';'))) { /* Find options */
18914  *ptr++ = '\0';
18915  }
18916  ast_string_field_set(refer, replaces_callid, callid);
18917 
18918  if (ptr) {
18919  /* Find the different tags before we destroy the string */
18920  to = strcasestr(ptr, "to-tag=");
18921  from = strcasestr(ptr, "from-tag=");
18922  }
18923 
18924  /* Grab the to header */
18925  if (to) {
18926  ptr = to + 7;
18927  if ((to = strchr(ptr, '&'))) {
18928  *to = '\0';
18929  }
18930  if ((to = strchr(ptr, ';'))) {
18931  *to = '\0';
18932  }
18933  ast_string_field_set(refer, replaces_callid_totag, ptr);
18934  }
18935 
18936  if (from) {
18937  ptr = from + 9;
18938  if ((from = strchr(ptr, '&'))) {
18939  *from = '\0';
18940  }
18941  if ((from = strchr(ptr, ';'))) {
18942  *from = '\0';
18943  }
18944  ast_string_field_set(refer, replaces_callid_fromtag, ptr);
18945  }
18946 
18947  if (!strcmp(refer->replaces_callid, transferer->callid) &&
18949  (!strcmp(refer->replaces_callid_fromtag, transferer->theirtag) &&
18950  !strcmp(refer->replaces_callid_totag, transferer->tag)))) {
18951  ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
18952  return -4;
18953  }
18954 
18956  ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", refer->replaces_callid);
18957  } else {
18958  ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", refer->replaces_callid, refer->replaces_callid_fromtag ? refer->replaces_callid_fromtag : "<none>", refer->replaces_callid_totag ? refer->replaces_callid_totag : "<none>");
18959  }
18960  }
18961 
18962  if ((ptr = strchr(refer_to, '@'))) { /* Separate domain */
18963  char *urioption = NULL, *domain;
18964  int bracket = 0;
18965  *ptr++ = '\0';
18966 
18967  if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
18968  *urioption++ = '\0';
18969  }
18970 
18971  domain = ptr;
18972 
18973  /* Remove :port */
18974  for (; *ptr != '\0'; ++ptr) {
18975  if (*ptr == ':' && bracket == 0) {
18976  *ptr = '\0';
18977  break;
18978  } else if (*ptr == '[') {
18979  ++bracket;
18980  } else if (*ptr == ']') {
18981  --bracket;
18982  }
18983  }
18984 
18985  SIP_PEDANTIC_DECODE(domain);
18986  SIP_PEDANTIC_DECODE(urioption);
18987 
18988  /* Save the domain for the dial plan */
18989  ast_string_field_set(refer, refer_to_domain, domain);
18990  if (urioption) {
18991  ast_string_field_set(refer, refer_to_urioption, urioption);
18992  }
18993  }
18994 
18995  if ((ptr = strchr(refer_to, ';'))) /* Remove options */
18996  *ptr = '\0';
18997 
18998  SIP_PEDANTIC_DECODE(refer_to);
18999  ast_string_field_set(refer, refer_to, refer_to);
19000 
19001  if (referred_by_uri) {
19002  if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
19003  *ptr = '\0';
19004  SIP_PEDANTIC_DECODE(referred_by_uri);
19005  ast_string_field_build(refer, referred_by, "<sip:%s>", referred_by_uri);
19006  } else {
19007  ast_string_field_set(refer, referred_by, "");
19008  }
19009 
19010  /* Determine transfer context */
19011  if (transferer->owner) {
19012  /* By default, use the context in the channel sending the REFER */
19013  transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
19014  if (ast_strlen_zero(transfer_context)) {
19015  transfer_context = ast_channel_macrocontext(transferer->owner);
19016  }
19017  }
19018  if (ast_strlen_zero(transfer_context)) {
19019  transfer_context = S_OR(transferer->context, sip_cfg.default_context);
19020  }
19021 
19022  ast_string_field_set(refer, refer_to_context, transfer_context);
19023 
19024  /* Either an existing extension or the parking extension */
19025  if (refer->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL)) {
19026  if (sip_debug_test_pvt(transferer)) {
19027  ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, S_OR(referred_by_uri, "Unknown"));
19028  }
19029  /* We are ready to transfer to the extension */
19030  return 0;
19031  }
19032  if (sip_debug_test_pvt(transferer))
19033  ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
19034 
19035  /* Failure, we can't find this extension */
19036  return -1;
19037 }
19038 
19039 
19040 /*! \brief Call transfer support (old way, deprecated by the IETF)
19041  * \note does not account for SIPS: uri requirements, nor check transport
19042  */
19043 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
19044 {
19045  char tmp[256] = "", *c, *a;
19046  struct sip_request *req = oreq ? oreq : &p->initreq;
19047  struct sip_refer *refer = NULL;
19048  const char *transfer_context = NULL;
19049 
19050  if (!sip_refer_alloc(p)) {
19051  return -1;
19052  }
19053 
19054  refer = p->refer;
19055 
19056  ast_copy_string(tmp, sip_get_header(req, "Also"), sizeof(tmp));
19057  c = get_in_brackets(tmp);
19058 
19059  if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
19060  ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
19061  return -1;
19062  }
19063 
19066 
19067  if (!ast_strlen_zero(a)) {
19068  ast_string_field_set(refer, refer_to_domain, a);
19069  }
19070 
19071  if (sip_debug_test_pvt(p))
19072  ast_verbose("Looking for %s in %s\n", c, p->context);
19073 
19074  /* Determine transfer context */
19075  if (p->owner) {
19076  /* By default, use the context in the channel sending the REFER */
19077  transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
19078  if (ast_strlen_zero(transfer_context)) {
19079  transfer_context = ast_channel_macrocontext(p->owner);
19080  }
19081  }
19082  if (ast_strlen_zero(transfer_context)) {
19083  transfer_context = S_OR(p->context, sip_cfg.default_context);
19084  }
19085 
19086  if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
19087  /* This is a blind transfer */
19088  ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
19089  ast_string_field_set(refer, refer_to, c);
19090  ast_string_field_set(refer, referred_by, "");
19091  ast_string_field_set(refer, refer_contact, "");
19092  /* Set new context */
19093  ast_string_field_set(p, context, transfer_context);
19094  return 0;
19095  } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
19096  return 1;
19097  }
19098 
19099  return -1;
19100 }
19101 
19102 /*! \brief Set the peers nat flags if they are using auto_* settings */
19103 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer)
19104 {
19105 
19106  if (!p || !peer) {
19107  return;
19108  }
19109 
19110  if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
19111  if (p->natdetected) {
19113  } else {
19115  }
19116  }
19117 
19119  if (p->natdetected) {
19121  } else {
19123  }
19124  }
19125 }
19126 
19127 /*! \brief Check and see if the requesting UA is likely to be behind a NAT.
19128  *
19129  * If the requesting NAT is behind NAT, set the * natdetected flag so that
19130  * later, peers with nat=auto_* can use the value. Also, set the flags so
19131  * that Asterisk responds identically whether or not a peer exists so as
19132  * not to leak peer name information.
19133  */
19134 static void check_for_nat(const struct ast_sockaddr *addr, struct sip_pvt *p)
19135 {
19136 
19137  if (!addr || !p) {
19138  return;
19139  }
19140 
19141  if (ast_sockaddr_cmp_addr(addr, &p->recv)) {
19142  char *tmp_str = ast_strdupa(ast_sockaddr_stringify_addr(addr));
19143  ast_debug(3, "NAT detected for %s / %s\n", tmp_str, ast_sockaddr_stringify_addr(&p->recv));
19144  p->natdetected = 1;
19147  }
19150  }
19151  } else {
19152  p->natdetected = 0;
19155  }
19158  }
19159  }
19160 
19161 }
19162 
19163 /*! \brief check Via: header for hostname, port and rport request/answer */
19164 static void check_via(struct sip_pvt *p, const struct sip_request *req)
19165 {
19166  char via[512];
19167  char *c, *maddr;
19168  struct ast_sockaddr tmp = { { 0, } };
19169  uint16_t port;
19170 
19171  ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
19172 
19173  /* If this is via WebSocket we don't use the Via header contents at all */
19174  if (!strncasecmp(via, "SIP/2.0/WS", 10)) {
19175  return;
19176  }
19177 
19178  /* Work on the leftmost value of the topmost Via header */
19179  c = strchr(via, ',');
19180  if (c)
19181  *c = '\0';
19182 
19183  /* Check for rport */
19184  c = strstr(via, ";rport");
19185  if (c && (c[6] != '=')) { /* rport query, not answer */
19188  }
19189 
19190  /* Check for maddr */
19191  maddr = strstr(via, "maddr=");
19192  if (maddr) {
19193  maddr += 6;
19194  c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
19195  "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
19196  *c = '\0';
19197  }
19198 
19199  c = strchr(via, ';');
19200  if (c)
19201  *c = '\0';
19202 
19203  c = strchr(via, ' ');
19204  if (c) {
19205  *c = '\0';
19206  c = ast_strip(c+1);
19207  if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
19208  ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
19209  return;
19210  }
19211 
19212  if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
19213  p->sa = p->recv;
19214  }
19215 
19216  if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
19217  ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
19218  port = STANDARD_SIP_PORT;
19219  } else if (!(port = ast_sockaddr_port(&tmp))) {
19220  port = STANDARD_SIP_PORT;
19221  ast_sockaddr_set_port(&tmp, port);
19222  }
19223 
19224  ast_sockaddr_set_port(&p->sa, port);
19225 
19226  check_for_nat(&tmp, p);
19227 
19228  if (sip_debug_test_pvt(p)) {
19229  ast_verbose("Sending to %s (%s)\n",
19231  sip_nat_mode(p));
19232  }
19233  }
19234 }
19235 
19236 /*! \brief Validate device authentication */
19237 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
19238  struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
19239  struct sip_peer **authpeer,
19240  enum xmittype reliable, char *calleridname, char *uri2)
19241 {
19242  enum check_auth_result res;
19243  int debug = sip_debug_test_addr(addr);
19244  struct sip_peer *peer;
19245  struct sip_peer *bogus_peer;
19246 
19247  if (sipmethod == SIP_SUBSCRIBE) {
19248  /* For subscribes, match on device name only; for other methods,
19249  * match on IP address-port of the incoming request.
19250  */
19251  peer = sip_find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
19252  } else {
19253  /* First find devices based on username (avoid all type=peer's) */
19254  peer = sip_find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
19255 
19256  /* Then find devices based on IP */
19257  if (!peer) {
19258  char *uri_tmp, *callback = NULL, *dummy;
19259  uri_tmp = ast_strdupa(uri2);
19260  parse_uri(uri_tmp, "sip:,sips:,tel:", &callback, &dummy, &dummy, &dummy);
19261  if (!ast_strlen_zero(callback) && (peer = sip_find_peer_by_ip_and_exten(&p->recv, callback, p->socket.type))) {
19262  ; /* found, fall through */
19263  } else {
19264  peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
19265  }
19266  }
19267  }
19268 
19269  if (!peer) {
19270  if (debug) {
19271  ast_verbose("No matching peer for '%s' from '%s'\n",
19272  of, ast_sockaddr_stringify(&p->recv));
19273  }
19274 
19275  /* If you don't mind, we can return 404s for devices that do
19276  * not exist: username disclosure. If we allow guests, there
19277  * is no way around that. */
19279  return AUTH_DONT_KNOW;
19280  }
19281 
19282  /* If you do mind, we use a peer that will never authenticate.
19283  * This ensures that we follow the same code path as regular
19284  * auth: less chance for username disclosure. */
19285  peer = ao2_t_global_obj_ref(g_bogus_peer, "check_peer_ok: Get the bogus peer.");
19286  if (!peer) {
19287  return AUTH_DONT_KNOW;
19288  }
19289  bogus_peer = peer;
19290  } else {
19291  bogus_peer = NULL;
19292  }
19293 
19294  if (!ast_apply_acl(peer->acl, addr, "SIP Peer ACL: ")) {
19295  ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
19296  sip_unref_peer(peer, "sip_unref_peer: check_peer_ok: from sip_find_peer call, early return of AUTH_ACL_FAILED");
19297  return AUTH_ACL_FAILED;
19298  }
19299  if (debug && peer != bogus_peer) {
19300  ast_verbose("Found peer '%s' for '%s' from %s\n",
19301  peer->name, of, ast_sockaddr_stringify(&p->recv));
19302  }
19303 
19304  /* Set Frame packetization */
19305  if (p->rtp) {
19307  p->autoframing = peer->autoframing;
19308  }
19309 
19310  /* Take the peer */
19311  ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
19312  ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
19313  ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
19314 
19315  if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
19316  p->t38_maxdatagram = peer->t38_maxdatagram;
19318  }
19319 
19321 
19322  /* Copy SIP extensions profile to peer */
19323  /* XXX is this correct before a successful auth ? */
19324  if (p->sipoptions)
19325  peer->sipoptions = p->sipoptions;
19326 
19327  do_setnat(p);
19328 
19329  ast_string_field_set(p, peersecret, peer->secret);
19330  ast_string_field_set(p, peermd5secret, peer->md5secret);
19331  ast_string_field_set(p, subscribecontext, peer->subscribecontext);
19334  if (!ast_strlen_zero(peer->parkinglot)) {
19336  }
19337  ast_string_field_set(p, engine, peer->engine);
19339  set_pvt_allowed_methods(p, req);
19341  if (peer->callingpres) /* Peer calling pres setting will override RPID */
19342  p->callingpres = peer->callingpres;
19343  if (peer->maxms && peer->lastms)
19344  p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
19345  else
19346  p->timer_t1 = peer->timer_t1;
19347 
19348  /* Set timer B to control transaction timeouts */
19349  if (peer->timer_b)
19350  p->timer_b = peer->timer_b;
19351  else
19352  p->timer_b = 64 * p->timer_t1;
19353 
19354  p->allowtransfer = peer->allowtransfer;
19355 
19356  if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
19357  /* Pretend there is no required authentication */
19358  ast_string_field_set(p, peersecret, NULL);
19359  ast_string_field_set(p, peermd5secret, NULL);
19360  }
19361  if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable))) {
19362 
19363  /* build_peer, called through sip_find_peer, is not able to check the
19364  * sip_pvt->natdetected flag in order to determine if the peer is behind
19365  * NAT or not when SIP_PAGE3_NAT_AUTO_RPORT or SIP_PAGE3_NAT_AUTO_COMEDIA
19366  * are set on the peer. So we check for that here and set the peer's
19367  * address accordingly. The address should ONLY be set once we are sure
19368  * authentication was a success. If, for example, an INVITE was sent that
19369  * matched the peer name but failed the authentication check, the address
19370  * would be updated, which is bad.
19371  */
19372  set_peer_nat(p, peer);
19373  if (p->natdetected && ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
19374  ast_sockaddr_copy(&peer->addr, &p->recv);
19375  }
19376 
19377  /* If we have a call limit, set flag */
19378  if (peer->call_limit)
19380  ast_string_field_set(p, peername, peer->name);
19381  ast_string_field_set(p, authname, peer->name);
19382 
19384 
19385  if (sipmethod == SIP_INVITE) {
19386  /* destroy old channel vars and copy in new ones. */
19388  p->chanvars = copy_vars(peer->chanvars);
19389  }
19390 
19391  if (authpeer) {
19392  ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
19393  (*authpeer) = peer; /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
19394  }
19395 
19396  if (!ast_strlen_zero(peer->username)) {
19397  ast_string_field_set(p, username, peer->username);
19398  /* Use the default username for authentication on outbound calls */
19399  /* XXX this takes the name from the caller... can we override ? */
19400  ast_string_field_set(p, authname, peer->username);
19401  }
19402  if (!get_rpid(p, req)) {
19403  if (!ast_strlen_zero(peer->cid_num)) {
19404  char *tmp = ast_strdupa(peer->cid_num);
19407  ast_string_field_set(p, cid_num, tmp);
19408  }
19409  if (!ast_strlen_zero(peer->cid_name))
19411  if (peer->callingpres)
19412  p->callingpres = peer->callingpres;
19413  }
19414  if (!ast_strlen_zero(peer->cid_tag)) {
19415  ast_string_field_set(p, cid_tag, peer->cid_tag);
19416  }
19417  ast_string_field_set(p, fullcontact, peer->fullcontact);
19418  if (!ast_strlen_zero(peer->context)) {
19420  }
19421  if (!ast_strlen_zero(peer->messagecontext)) {
19422  ast_string_field_set(p, messagecontext, peer->messagecontext);
19423  }
19424  if (!ast_strlen_zero(peer->mwi_from)) {
19425  ast_string_field_set(p, mwi_from, peer->mwi_from);
19426  }
19427  ast_string_field_set(p, peersecret, peer->secret);
19428  ast_string_field_set(p, peermd5secret, peer->md5secret);
19431  p->amaflags = peer->amaflags;
19432  p->callgroup = peer->callgroup;
19433  p->pickupgroup = peer->pickupgroup;
19442  ast_copy_string(p->zone, peer->zone, sizeof(p->zone));
19443  if (peer->maxforwards > 0) {
19444  p->maxforwards = peer->maxforwards;
19445  }
19446  if (ast_format_cap_count(p->peercaps)) {
19447  struct ast_format_cap *joint;
19448 
19450  if (joint) {
19452  ao2_ref(p->jointcaps, -1);
19453  p->jointcaps = joint;
19454  }
19455  }
19456  p->maxcallbitrate = peer->maxcallbitrate;
19457  if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
19458  (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
19460  else
19463  p->rtptimeout = peer->rtptimeout;
19464  p->rtpholdtimeout = peer->rtpholdtimeout;
19465  p->rtpkeepalive = peer->rtpkeepalive;
19466  if (!dialog_initialize_rtp(p)) {
19467  if (p->rtp) {
19469  p->autoframing = peer->autoframing;
19470  }
19471  } else {
19472  res = AUTH_RTP_FAILED;
19473  }
19474  }
19475  sip_unref_peer(peer, "check_peer_ok: sip_unref_peer: tossing temp ptr to peer from sip_find_peer");
19476 
19477  return res;
19478 }
19479 
19480 
19481 /*! \brief Check if matching user or peer is defined
19482  Match user on From: user name and peer on IP/port
19483  This is used on first invite (not re-invites) and subscribe requests
19484  \return 0 on success, non-zero on failure
19485 */
19486 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
19487  int sipmethod, const char *uri, enum xmittype reliable,
19488  struct ast_sockaddr *addr, struct sip_peer **authpeer)
19489 {
19490  char *of, *name, *unused_password, *domain;
19491  RAII_VAR(char *, ofbuf, NULL, ast_free); /* beware, everyone starts pointing to this */
19492  RAII_VAR(char *, namebuf, NULL, ast_free);
19493  enum check_auth_result res = AUTH_DONT_KNOW;
19494  char calleridname[256];
19495  char *uri2 = ast_strdupa(uri);
19496 
19497  terminate_uri(uri2); /* trim extra stuff */
19498 
19499  ofbuf = ast_strdup(sip_get_header(req, "From"));
19500  /* XXX here tries to map the username for invite things */
19501 
19502  /* strip the display-name portion off the beginning of the FROM header. */
19503  if (!(of = (char *) get_calleridname(ofbuf, calleridname, sizeof(calleridname)))) {
19504  ast_log(LOG_ERROR, "FROM header can not be parsed\n");
19505  return res;
19506  }
19507 
19508  if (calleridname[0]) {
19509  ast_string_field_set(p, cid_name, calleridname);
19510  }
19511 
19512  if (ast_strlen_zero(p->exten)) {
19513  char *t = uri2;
19514  if (!strncasecmp(t, "sip:", 4)) {
19515  t += 4;
19516  } else if (!strncasecmp(t, "sips:", 5)) {
19517  t += 5;
19518  } else if (!strncasecmp(t, "tel:", 4)) { /* TEL URI INVITE */
19519  t += 4;
19520  }
19521  ast_string_field_set(p, exten, t);
19522  t = strchr(p->exten, '@');
19523  if (t)
19524  *t = '\0';
19525 
19526  if (ast_strlen_zero(p->our_contact)) {
19527  build_contact(p, req, 1);
19528  }
19529  }
19530 
19531  of = get_in_brackets(of);
19532 
19533  /* save the URI part of the From header */
19534  ast_string_field_set(p, from, of);
19535 
19536  if (parse_uri_legacy_check(of, "sip:,sips:,tel:", &name, &unused_password, &domain, NULL)) {
19537  ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
19538  }
19539 
19540  SIP_PEDANTIC_DECODE(name);
19541  SIP_PEDANTIC_DECODE(domain);
19542 
19543  extract_host_from_hostport(&domain);
19544 
19545  if (ast_strlen_zero(domain)) {
19546  /* <sip:name@[EMPTY]>, never good */
19547  ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
19548  return res;
19549  }
19550 
19551  if (ast_strlen_zero(name)) {
19552  /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
19553  * treated that as a username, so we continue the tradition:
19554  * uri is now <sip:host@hostport>. */
19555  name = domain;
19556  } else {
19557  /* Non-empty name, try to get caller id from it */
19558  char *tmp = ast_strdupa(name);
19559  /* We need to be able to handle from-headers looking like
19560  <sip:8164444422;[email protected]:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
19561  */
19562  tmp = strsep(&tmp, ";");
19565  }
19566  ast_string_field_set(p, cid_num, tmp);
19567  }
19568 
19570  /*
19571  * XXX This is experimental code to grab the search key from the
19572  * Auth header's username instead of the 'From' name, if available.
19573  * Do not enable this block unless you understand the side effects (if any!)
19574  * Note, the search for "username" should be done in a more robust way.
19575  * Note2, at the moment we check both fields, though maybe we should
19576  * pick one or another depending on the request ? XXX
19577  */
19578  const char *hdr = sip_get_header(req, "Authorization");
19579  if (ast_strlen_zero(hdr)) {
19580  hdr = sip_get_header(req, "Proxy-Authorization");
19581  }
19582 
19583  if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
19584  namebuf = name = ast_strdup(hdr + strlen("username=\""));
19585  name = strsep(&name, "\"");
19586  }
19587  }
19588 
19589  res = check_peer_ok(p, name, req, sipmethod, addr,
19590  authpeer, reliable, calleridname, uri2);
19591  if (res != AUTH_DONT_KNOW) {
19592  return res;
19593  }
19594 
19595  /* Finally, apply the guest policy */
19596  if (sip_cfg.allowguest) {
19597  /* Ignore check_return warning from Coverity for get_rpid below. */
19598  get_rpid(p, req);
19602  if (!dialog_initialize_rtp(p)) {
19603  res = AUTH_SUCCESSFUL;
19604  } else {
19605  res = AUTH_RTP_FAILED;
19606  }
19607  } else {
19608  res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
19609  }
19610 
19613  }
19614 
19615  return res;
19616 }
19617 
19618 /*! \brief Find user
19619  If we get a match, this will add a reference pointer to the user object, that needs to be unreferenced
19620 */
19621 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
19622 {
19623  return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
19624 }
19625 
19626 static void send_check_user_failure_response(struct sip_pvt *p, struct sip_request *req, int res, enum xmittype reliable)
19627 {
19628  const char *response;
19629 
19630  switch (res) {
19631  case AUTH_SECRET_FAILED:
19633  case AUTH_NOT_FOUND:
19634  case AUTH_UNKNOWN_DOMAIN:
19635  case AUTH_PEER_NOT_DYNAMIC:
19636  case AUTH_BAD_TRANSPORT:
19637  case AUTH_ACL_FAILED:
19638  ast_log(LOG_NOTICE, "Failed to authenticate device %s for %s, code = %d\n",
19639  sip_get_header(req, "From"), sip_methods[p->method].text, res);
19640  response = "403 Forbidden";
19641  break;
19642  case AUTH_SESSION_LIMIT:
19643  /* Unexpected here, actually. As it's handled elsewhere. */
19644  ast_log(LOG_NOTICE, "Call limit reached for device %s for %s, code = %d\n",
19645  sip_get_header(req, "From"), sip_methods[p->method].text, res);
19646  response = "480 Temporarily Unavailable";
19647  break;
19648  case AUTH_RTP_FAILED:
19649  /* We don't want to send a 403 in the RTP_FAILED case.
19650  * The cause could be any one of:
19651  * - out of memory or rtp ports
19652  * - dtls/srtp requested but not loaded/invalid
19653  * Neither of them warrant a 403. A 503 makes more
19654  * sense, as this node is broken/overloaded. */
19655  ast_log(LOG_NOTICE, "RTP init failure for device %s for %s, code = %d\n",
19656  sip_get_header(req, "From"), sip_methods[p->method].text, res);
19657  response = "503 Service Unavailable";
19658  break;
19659  case AUTH_SUCCESSFUL:
19660  case AUTH_CHALLENGE_SENT:
19661  /* These should have been handled elsewhere. */
19662  default:
19663  ast_log(LOG_NOTICE, "Unexpected error for device %s for %s, code = %d\n",
19664  sip_get_header(req, "From"), sip_methods[p->method].text, res);
19665  response = "503 Service Unavailable";
19666  }
19667 
19668  if (reliable == XMIT_RELIABLE) {
19669  transmit_response_reliable(p, response, req);
19670  } else if (reliable == XMIT_UNRELIABLE) {
19671  transmit_response(p, response, req);
19672  }
19673 }
19674 
19675 static int set_message_vars_from_req(struct ast_msg *msg, struct sip_request *req)
19676 {
19677  size_t x;
19678  char name_buf[1024];
19679  char val_buf[1024];
19680  const char *name;
19681  char *c;
19682  int res = 0;
19683 
19684  for (x = 0; x < req->headers; x++) {
19685  const char *header = REQ_OFFSET_TO_STR(req, header[x]);
19686 
19687  if ((c = strchr(header, ':'))) {
19688  ast_copy_string(name_buf, header, MIN((c - header + 1), sizeof(name_buf)));
19689  ast_copy_string(val_buf, ast_skip_blanks(c + 1), sizeof(val_buf));
19690  ast_trim_blanks(name_buf);
19691 
19692  /* Convert header name to full name alias. */
19693  name = find_full_alias(name_buf, name_buf);
19694 
19695  res = ast_msg_set_var(msg, name, val_buf);
19696  if (res) {
19697  break;
19698  }
19699  }
19700  }
19701  return res;
19702 }
19703 
19704 /*! \brief Receive SIP MESSAGE method messages
19705 \note We only handle messages within current calls currently
19706  Reference: RFC 3428 */
19707 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
19708 {
19709  char *buf;
19710  size_t len;
19711  struct ast_frame f;
19712  const char *content_type = sip_get_header(req, "Content-Type");
19713  struct ast_msg *msg;
19714  int res;
19715  char *from;
19716  char *to;
19717  char from_name[50];
19718  char stripped[SIPBUFSIZE];
19719  enum sip_get_dest_result dest_result;
19720 
19721  if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
19722  transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
19723  if (!p->owner) {
19725  }
19726  return;
19727  }
19728 
19729  if (!(buf = get_content(req))) {
19730  ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
19731  transmit_response(p, "500 Internal Server Error", req);
19732  if (!p->owner) {
19734  }
19735  return;
19736  }
19737 
19738  /* Strip trailing line feeds from message body. (get_content may add
19739  * a trailing linefeed and we don't need any at the end) */
19740  len = strlen(buf);
19741  while (len > 0) {
19742  if (buf[--len] != '\n') {
19743  ++len;
19744  break;
19745  }
19746  }
19747  buf[len] = '\0';
19748 
19749  if (p->owner) {
19750  if (sip_debug_test_pvt(p)) {
19751  ast_verbose("SIP Text message received: '%s'\n", buf);
19752  }
19753  memset(&f, 0, sizeof(f));
19755  f.subclass.integer = 0;
19756  f.offset = 0;
19757  f.data.ptr = buf;
19758  f.datalen = strlen(buf) + 1;
19759  ast_queue_frame(p->owner, &f);
19760  transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
19761  return;
19762  }
19763 
19764  /*
19765  * At this point MESSAGE is outside of a call.
19766  *
19767  * NOTE: p->owner is NULL so no additional check is needed after
19768  * this point.
19769  */
19770 
19772  /* Message outside of a call, we do not support that */
19773  ast_debug(1, "MESSAGE outside of a call administratively disabled.\n");
19774  transmit_response(p, "405 Method Not Allowed", req);
19776  return;
19777  }
19778 
19779  copy_request(&p->initreq, req);
19780 
19782  int res;
19783 
19784  set_pvt_allowed_methods(p, req);
19785  res = check_user(p, req, SIP_MESSAGE, e, XMIT_UNRELIABLE, addr);
19786  if (res == AUTH_CHALLENGE_SENT) {
19788  return;
19789  }
19790  if (res < 0) { /* Something failed in authentication */
19793  return;
19794  }
19795  /* Auth was successful. Proceed. */
19796  } else {
19797  struct sip_peer *peer;
19798 
19799  /*
19800  * MESSAGE outside of a call, not authenticating it.
19801  * Check to see if we match a peer anyway so that we can direct
19802  * it to the right context.
19803  */
19804 
19805  peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, 0, p->socket.type);
19806  if (peer) {
19807  /* Only if no auth is required. */
19808  if (ast_strlen_zero(peer->secret) && ast_strlen_zero(peer->md5secret)) {
19810  }
19811  if (!ast_strlen_zero(peer->messagecontext)) {
19812  ast_string_field_set(p, messagecontext, peer->messagecontext);
19813  }
19814  ast_string_field_set(p, peername, peer->name);
19815  peer = sip_unref_peer(peer, "from sip_find_peer() in receive_message");
19816  }
19817  }
19818 
19819  /* Override the context with the message context _BEFORE_
19820  * getting the destination. This way we can guarantee the correct
19821  * extension is used in the message context when it is present. */
19822  if (!ast_strlen_zero(p->messagecontext)) {
19824  } else if (!ast_strlen_zero(sip_cfg.messagecontext)) {
19826  }
19827 
19828  dest_result = get_destination(p, NULL, NULL);
19829  switch (dest_result) {
19830  case SIP_GET_DEST_REFUSED:
19831  /* Okay to send 403 since this is after auth processing */
19832  transmit_response(p, "403 Forbidden", req);
19834  return;
19836  transmit_response(p, "416 Unsupported URI Scheme", req);
19838  return;
19839  default:
19840  /* We may have something other than dialplan who wants
19841  * the message, so defer further error handling for now */
19842  break;
19843  }
19844 
19845  if (!(msg = ast_msg_alloc())) {
19846  transmit_response(p, "500 Internal Server Error", req);
19848  return;
19849  }
19850 
19851  to = ast_strdupa(REQ_OFFSET_TO_STR(req, rlpart2));
19852  from = ast_strdupa(sip_get_header(req, "From"));
19853 
19854  res = ast_msg_set_to(msg, "%s", to);
19855 
19856  /* Build "display" <uri> for from string. */
19857  from = (char *) get_calleridname(from, from_name, sizeof(from_name));
19858  from = get_in_brackets(from);
19859  if (from_name[0]) {
19860  char from_buf[128];
19861 
19862  ast_escape_quoted(from_name, from_buf, sizeof(from_buf));
19863  res |= ast_msg_set_from(msg, "\"%s\" <%s>", from_buf, from);
19864  } else {
19865  res |= ast_msg_set_from(msg, "<%s>", from);
19866  }
19867 
19868  res |= ast_msg_set_body(msg, "%s", buf);
19869  res |= ast_msg_set_context(msg, "%s", p->context);
19870 
19871  res |= ast_msg_set_var(msg, "SIP_RECVADDR", ast_sockaddr_stringify(&p->recv));
19872  res |= ast_msg_set_tech(msg, "%s", "SIP");
19873  if (!ast_strlen_zero(p->peername)) {
19874  res |= ast_msg_set_endpoint(msg, "%s", p->peername);
19875  res |= ast_msg_set_var(msg, "SIP_PEERNAME", p->peername);
19876  }
19877 
19878  ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
19879  res |= ast_msg_set_var(msg, "SIP_FULLCONTACT", get_in_brackets(stripped));
19880 
19881  res |= ast_msg_set_exten(msg, "%s", p->exten);
19882  res |= set_message_vars_from_req(msg, req);
19883 
19884  if (res) {
19885  ast_msg_destroy(msg);
19886  transmit_response(p, "500 Internal Server Error", req);
19888  return;
19889  }
19890 
19891  if (ast_msg_has_destination(msg)) {
19892  ast_msg_queue(msg);
19893  transmit_response(p, "202 Accepted", req);
19895  return;
19896  }
19897 
19898  /* Find a specific error cause to send */
19899  switch (dest_result) {
19902  transmit_response(p, "404 Not Found", req);
19903  break;
19905  default:
19906  /* We should have sent the message already! */
19907  ast_assert(0);
19908  transmit_response(p, "500 Internal Server Error", req);
19909  break;
19910  }
19912  ast_msg_destroy(msg);
19913 }
19914 
19915 /*! \brief CLI Command to show calls within limits set by call_limit */
19916 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19917 {
19918 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
19919 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
19920  char ilimits[40];
19921  char iused[40];
19922  int showall = FALSE;
19923  struct ao2_iterator i;
19924  struct sip_peer *peer;
19925 
19926  switch (cmd) {
19927  case CLI_INIT:
19928  e->command = "sip show inuse [all]";
19929  e->usage =
19930  "Usage: sip show inuse [all]\n"
19931  " List all SIP devices usage counters and limits.\n"
19932  " Add option \"all\" to show all devices, not only those with a limit.\n";
19933  return NULL;
19934  case CLI_GENERATE:
19935  return NULL;
19936  }
19937 
19938  if (a->argc < 3)
19939  return CLI_SHOWUSAGE;
19940 
19941  if (a->argc == 4 && !strcmp(a->argv[3], "all"))
19942  showall = TRUE;
19943 
19944  ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
19945 
19946  i = ao2_iterator_init(peers, 0);
19947  while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
19948  ao2_lock(peer);
19949  if (peer->call_limit)
19950  snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
19951  else
19952  ast_copy_string(ilimits, "N/A", sizeof(ilimits));
19953  snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inuse, peer->ringing, peer->onhold);
19954  if (showall || peer->call_limit)
19955  ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
19956  ao2_unlock(peer);
19957  sip_unref_peer(peer, "toss iterator pointer");
19958  }
19960 
19961  return CLI_SUCCESS;
19962 #undef FORMAT
19963 #undef FORMAT2
19964 }
19965 
19966 
19967 /*! \brief Convert transfer mode to text string */
19968 static char *transfermode2str(enum transfermodes mode)
19969 {
19970  if (mode == TRANSFER_OPENFORALL)
19971  return "open";
19972  else if (mode == TRANSFER_CLOSED)
19973  return "closed";
19974  return "strict";
19975 }
19976 
19977 /*! \brief Report Peer status in character string
19978  * \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
19979  */
19980 
19981 
19982 /* Session-Timer Modes */
19983 static const struct _map_x_s stmodes[] = {
19984  { SESSION_TIMER_MODE_ACCEPT, "Accept"},
19985  { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
19986  { SESSION_TIMER_MODE_REFUSE, "Refuse"},
19987  { -1, NULL},
19988 };
19989 
19990 static const char *stmode2str(enum st_mode m)
19991 {
19992  return map_x_s(stmodes, m, "Unknown");
19993 }
19994 
19995 static enum st_mode str2stmode(const char *s)
19996 {
19997  return map_s_x(stmodes, s, -1);
19998 }
19999 
20000 /* Session-Timer Refreshers */
20001 static const struct _map_x_s strefresher_params[] = {
20005  { -1, NULL },
20006 };
20007 
20008 static const struct _map_x_s strefreshers[] = {
20009  { SESSION_TIMER_REFRESHER_AUTO, "auto" },
20010  { SESSION_TIMER_REFRESHER_US, "us" },
20011  { SESSION_TIMER_REFRESHER_THEM, "them" },
20012  { -1, NULL },
20013 };
20014 
20015 static const char *strefresherparam2str(enum st_refresher_param r)
20016 {
20017  return map_x_s(strefresher_params, r, "Unknown");
20018 }
20019 
20020 static enum st_refresher_param str2strefresherparam(const char *s)
20021 {
20022  return map_s_x(strefresher_params, s, -1);
20023 }
20024 
20025 /* Autocreatepeer modes */
20026 static struct _map_x_s autopeermodes[] = {
20027  { AUTOPEERS_DISABLED, "Off"},
20028  { AUTOPEERS_VOLATILE, "Volatile"},
20029  { AUTOPEERS_PERSIST, "Persisted"},
20030  { -1, NULL},
20031 };
20032 
20033 static const char *strefresher2str(enum st_refresher r)
20034 {
20035  return map_x_s(strefreshers, r, "Unknown");
20036 }
20037 
20038 static const char *autocreatepeer2str(enum autocreatepeer_mode r)
20039 {
20040  return map_x_s(autopeermodes, r, "Unknown");
20041 }
20042 
20043 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
20044 {
20045  int res = 0;
20046  if (peer->maxms) {
20047  if (peer->lastms < 0) {
20048  ast_copy_string(status, "UNREACHABLE", statuslen);
20049  } else if (peer->lastms > peer->maxms) {
20050  snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
20051  res = 1;
20052  } else if (peer->lastms) {
20053  snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
20054  res = 1;
20055  } else {
20056  ast_copy_string(status, "UNKNOWN", statuslen);
20057  }
20058  } else {
20059  ast_copy_string(status, "Unmonitored", statuslen);
20060  /* Checking if port is 0 */
20061  res = -1;
20062  }
20063  return res;
20064 }
20065 
20066 /*! \brief Show active TCP connections */
20067 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20068 {
20069  struct sip_threadinfo *th;
20070  struct ao2_iterator i;
20071 
20072 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
20073 #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
20074 
20075  switch (cmd) {
20076  case CLI_INIT:
20077  e->command = "sip show tcp";
20078  e->usage =
20079  "Usage: sip show tcp\n"
20080  " Lists all active TCP/TLS sessions.\n";
20081  return NULL;
20082  case CLI_GENERATE:
20083  return NULL;
20084  }
20085 
20086  if (a->argc != 3)
20087  return CLI_SHOWUSAGE;
20088 
20089  ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
20090 
20091  i = ao2_iterator_init(threadt, 0);
20092  while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
20093  ast_cli(a->fd, FORMAT,
20095  sip_get_transport(th->type),
20096  (th->tcptls_session->client ? "Client" : "Server"));
20097  ao2_t_ref(th, -1, "decrement ref from iterator");
20098  }
20100 
20101  return CLI_SUCCESS;
20102 #undef FORMAT
20103 #undef FORMAT2
20104 }
20105 
20106 /*! \brief CLI Command 'SIP Show Users' */
20107 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20108 {
20109  regex_t regexbuf;
20110  int havepattern = FALSE;
20111  struct ao2_iterator user_iter;
20112  struct sip_peer *user;
20113 
20114 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
20115 
20116  switch (cmd) {
20117  case CLI_INIT:
20118  e->command = "sip show users [like]";
20119  e->usage =
20120  "Usage: sip show users [like <pattern>]\n"
20121  " Lists all known SIP users.\n"
20122  " Optional regular expression pattern is used to filter the user list.\n";
20123  return NULL;
20124  case CLI_GENERATE:
20125  return NULL;
20126  }
20127 
20128  switch (a->argc) {
20129  case 5:
20130  if (!strcasecmp(a->argv[3], "like")) {
20131  if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
20132  return CLI_SHOWUSAGE;
20133  havepattern = TRUE;
20134  } else
20135  return CLI_SHOWUSAGE;
20136  case 3:
20137  break;
20138  default:
20139  return CLI_SHOWUSAGE;
20140  }
20141 
20142  ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
20143 
20144  user_iter = ao2_iterator_init(peers, 0);
20145  while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
20146  ao2_lock(user);
20147  if (!(user->type & SIP_TYPE_USER)) {
20148  ao2_unlock(user);
20149  sip_unref_peer(user, "sip show users");
20150  continue;
20151  }
20152 
20153  if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
20154  ao2_unlock(user);
20155  sip_unref_peer(user, "sip show users");
20156  continue;
20157  }
20158 
20159  ast_cli(a->fd, FORMAT, user->name,
20160  user->secret,
20161  user->accountcode,
20162  user->context,
20165  ao2_unlock(user);
20166  sip_unref_peer(user, "sip show users");
20167  }
20168  ao2_iterator_destroy(&user_iter);
20169 
20170  if (havepattern)
20171  regfree(&regexbuf);
20172 
20173  return CLI_SUCCESS;
20174 #undef FORMAT
20175 }
20176 
20177 /*! \brief Show SIP registrations in the manager API */
20178 static int manager_show_registry(struct mansession *s, const struct message *m)
20179 {
20180  const char *id = astman_get_header(m, "ActionID");
20181  char idtext[256] = "";
20182  int total = 0;
20183  struct ao2_iterator iter;
20184  struct sip_registry *iterator;
20185 
20186  if (!ast_strlen_zero(id))
20187  snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
20188 
20189  astman_send_listack(s, m, "Registrations will follow", "start");
20190 
20191  iter = ao2_iterator_init(registry_list, 0);
20192  while ((iterator = ao2_t_iterator_next(&iter, "manager_show_registry iter"))) {
20193  ao2_lock(iterator);
20194 
20195  astman_append(s,
20196  "Event: RegistryEntry\r\n"
20197  "%s"
20198  "Host: %s\r\n"
20199  "Port: %d\r\n"
20200  "Username: %s\r\n"
20201  "Domain: %s\r\n"
20202  "DomainPort: %d\r\n"
20203  "Refresh: %d\r\n"
20204  "State: %s\r\n"
20205  "RegistrationTime: %ld\r\n"
20206  "\r\n",
20207  idtext,
20208  iterator->hostname,
20209  iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
20210  iterator->username,
20211  S_OR(iterator->regdomain,iterator->hostname),
20212  iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
20213  iterator->refresh,
20214  regstate2str(iterator->regstate),
20215  (long) iterator->regtime.tv_sec);
20216 
20217  ao2_unlock(iterator);
20218  ao2_t_ref(iterator, -1, "manager_show_registry iter");
20219  total++;
20220  }
20221  ao2_iterator_destroy(&iter);
20222 
20223  astman_send_list_complete_start(s, m, "RegistrationsComplete", total);
20225 
20226  return 0;
20227 }
20228 
20229 /*! \brief Show SIP peers in the manager API */
20230 /* Inspired from chan_iax2 */
20231 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
20232 {
20233  const char *id = astman_get_header(m, "ActionID");
20234  const char *a[] = {"sip", "show", "peers"};
20235  char idtext[256] = "";
20236  int total = 0;
20237 
20238  if (!ast_strlen_zero(id))
20239  snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
20240 
20241  astman_send_listack(s, m, "Peer status list will follow", "start");
20242 
20243  /* List the peers in separate manager events */
20244  _sip_show_peers(-1, &total, s, m, 3, a);
20245 
20246  /* Send final confirmation */
20247  astman_send_list_complete_start(s, m, "PeerlistComplete", total);
20249  return 0;
20250 }
20251 
20252 /*! \brief CLI Show Peers command */
20253 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20254 {
20255  switch (cmd) {
20256  case CLI_INIT:
20257  e->command = "sip show peers [like]";
20258  e->usage =
20259  "Usage: sip show peers [like <pattern>]\n"
20260  " Lists all known SIP peers.\n"
20261  " Optional regular expression pattern is used to filter the peer list.\n";
20262  return NULL;
20263  case CLI_GENERATE:
20264  return NULL;
20265  }
20266 
20267  return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
20268 }
20269 
20270 int peercomparefunc(const void *a, const void *b);
20271 
20272 int peercomparefunc(const void *a, const void *b)
20273 {
20274  struct sip_peer **ap = (struct sip_peer **)a;
20275  struct sip_peer **bp = (struct sip_peer **)b;
20276  return strcmp((*ap)->name, (*bp)->name);
20277 }
20278 
20279 /* the last argument is left-aligned, so we don't need a size anyways */
20280 #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-10.10s %-3.3s %-8s %-11s %-32.32s %s\n"
20281 
20282 /*! \brief Used in the sip_show_peers functions to pass parameters */
20283 struct show_peers_context {
20284  regex_t regexbuf;
20285  int havepattern;
20286  char idtext[256];
20292 };
20293 
20294 /*! \brief Execute sip show peers command */
20295 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
20296 {
20297  struct show_peers_context cont = {
20298  .havepattern = FALSE,
20299  .idtext = "",
20300 
20301  .peers_mon_online = 0,
20302  .peers_mon_offline = 0,
20303  .peers_unmon_online = 0,
20304  .peers_unmon_offline = 0,
20305  };
20306 
20307  struct sip_peer *peer;
20308  struct ao2_iterator* it_peers;
20309 
20310  int total_peers = 0;
20311  const char *id;
20312  struct sip_peer **peerarray;
20313  int k;
20314 
20315  cont.realtimepeers = ast_check_realtime("sippeers");
20316 
20317  if (s) { /* Manager - get ActionID */
20318  id = astman_get_header(m, "ActionID");
20319  if (!ast_strlen_zero(id)) {
20320  snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
20321  }
20322  }
20323 
20324  switch (argc) {
20325  case 5:
20326  if (!strcasecmp(argv[3], "like")) {
20327  if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB)) {
20328  return CLI_SHOWUSAGE;
20329  }
20330  cont.havepattern = TRUE;
20331  } else {
20332  return CLI_SHOWUSAGE;
20333  }
20334  case 3:
20335  break;
20336  default:
20337  return CLI_SHOWUSAGE;
20338  }
20339 
20340  if (!s) {
20341  /* Normal list */
20342  ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "Comedia", "ACL", "Port", "Status", "Description", (cont.realtimepeers ? "Realtime" : ""));
20343  }
20344 
20345  ao2_lock(peers);
20346  if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
20347  ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
20348  ao2_unlock(peers);
20349  return CLI_FAILURE;
20350  }
20351  if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
20352  ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
20353  ao2_iterator_destroy(it_peers);
20354  ao2_unlock(peers);
20355  return CLI_FAILURE;
20356  }
20357  ao2_unlock(peers);
20358 
20359  while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
20360  ao2_lock(peer);
20361 
20362  if (!(peer->type & SIP_TYPE_PEER)) {
20363  ao2_unlock(peer);
20364  sip_unref_peer(peer, "unref peer because it's actually a user");
20365  continue;
20366  }
20367 
20368  if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
20369  ao2_unlock(peer);
20370  sip_unref_peer(peer, "toss iterator peer ptr before continue");
20371  continue;
20372  }
20373 
20374  peerarray[total_peers++] = peer;
20375  ao2_unlock(peer);
20376  }
20377  ao2_iterator_destroy(it_peers);
20378 
20379  qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
20380 
20381  for(k = 0; k < total_peers; k++) {
20382  peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
20383  }
20384 
20385  if (!s) {
20386  ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
20387  total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
20388  }
20389 
20390  if (cont.havepattern) {
20391  regfree(&cont.regexbuf);
20392  }
20393 
20394  if (total) {
20395  *total = total_peers;
20396  }
20397 
20398  ast_free(peerarray);
20399 
20400  return CLI_SUCCESS;
20401 }
20402 
20403 /*! \brief Emit informations for one peer during sip show peers command */
20404 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
20405 {
20406  /* _sip_show_peers_one() is separated from _sip_show_peers() to properly free the ast_strdupa
20407  * (this is executed in a loop in _sip_show_peers() )
20408  */
20409 
20410  char name[256];
20411  char status[20] = "";
20412  char pstatus;
20413 
20414  /*
20415  * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
20416  * string pointers for that function aren't valid between subsequent calls to
20417  * ast_sockaddr_stringify functions
20418  */
20419  char *tmp_port;
20420  char *tmp_host;
20421 
20422  tmp_port = ast_sockaddr_isnull(&peer->addr) ?
20424 
20425  tmp_host = ast_sockaddr_isnull(&peer->addr) ?
20426  "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
20427 
20428  ao2_lock(peer);
20429  if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
20430  ao2_unlock(peer);
20431  return sip_unref_peer(peer, "toss iterator peer ptr no match");
20432  }
20433 
20434  if (!ast_strlen_zero(peer->username) && !s) {
20435  snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
20436  } else {
20437  ast_copy_string(name, peer->name, sizeof(name));
20438  }
20439 
20440  pstatus = peer_status(peer, status, sizeof(status));
20441  if (pstatus == 1) {
20442  cont->peers_mon_online++;
20443  } else if (pstatus == 0) {
20444  cont->peers_mon_offline++;
20445  } else {
20446  if (ast_sockaddr_isnull(&peer->addr) ||
20447  !ast_sockaddr_port(&peer->addr)) {
20448  cont->peers_unmon_offline++;
20449  } else {
20450  cont->peers_unmon_online++;
20451  }
20452  }
20453 
20454  if (!s) { /* Normal CLI list */
20455  ast_cli(fd, PEERS_FORMAT2, name,
20456  tmp_host,
20457  peer->host_dynamic ? " D " : " ", /* Dynamic or not? */
20458  force_rport_string(peer->flags),
20459  comedia_string(peer->flags),
20460  (!ast_acl_list_is_empty(peer->acl)) ? " A " : " ", /* permit/deny */
20461  tmp_port, status,
20462  peer->description ? peer->description : "",
20463  cont->realtimepeers ? (peer->is_realtime ? "Cached RT" : "") : "");
20464  } else { /* Manager format */
20465  /* The names here need to be the same as other channels */
20466  astman_append(s,
20467  "Event: PeerEntry\r\n%s"
20468  "Channeltype: SIP\r\n"
20469  "ObjectName: %s\r\n"
20470  "ChanObjectType: peer\r\n" /* "peer" or "user" */
20471  "IPaddress: %s\r\n"
20472  "IPport: %s\r\n"
20473  "Dynamic: %s\r\n"
20474  "AutoForcerport: %s\r\n"
20475  "Forcerport: %s\r\n"
20476  "AutoComedia: %s\r\n"
20477  "Comedia: %s\r\n"
20478  "VideoSupport: %s\r\n"
20479  "TextSupport: %s\r\n"
20480  "ACL: %s\r\n"
20481  "Status: %s\r\n"
20482  "RealtimeDevice: %s\r\n"
20483  "Description: %s\r\n"
20484  "Accountcode: %s\r\n"
20485  "\r\n",
20486  cont->idtext,
20487  peer->name,
20488  ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
20489  ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
20490  peer->host_dynamic ? "yes" : "no", /* Dynamic or not? */
20491  ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ? "yes" : "no",
20492  ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
20493  ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ? "yes" : "no",
20494  ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "yes" : "no",
20495  ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no", /* VIDEOSUPPORT=yes? */
20496  ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no", /* TEXTSUPPORT=yes? */
20497  ast_acl_list_is_empty(peer->acl) ? "no" : "yes", /* permit/deny/acl */
20498  status,
20499  cont->realtimepeers ? (peer->is_realtime ? "yes" : "no") : "no",
20500  peer->description,
20501  peer->accountcode);
20502  }
20503  ao2_unlock(peer);
20504 
20505  return sip_unref_peer(peer, "toss iterator peer ptr");
20506 }
20507 #undef PEERS_FORMAT2
20508 
20509 static int peer_dump_func(void *userobj, void *arg, int flags)
20510 {
20511  struct sip_peer *peer = userobj;
20512  int refc = ao2_t_ref(userobj, 0, "");
20513  struct ast_cli_args *a = (struct ast_cli_args *) arg;
20514 
20515  ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
20516  peer->name, 0, refc);
20517  return 0;
20518 }
20519 
20520 static int dialog_dump_func(void *userobj, void *arg, int flags)
20521 {
20522  struct sip_pvt *pvt = userobj;
20523  int refc = ao2_t_ref(userobj, 0, "");
20524  struct ast_cli_args *a = (struct ast_cli_args *) arg;
20525 
20526  ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
20527  pvt->callid, 0, refc);
20528  return 0;
20529 }
20530 
20531 
20532 /*! \brief List all allocated SIP Objects (realtime or static) */
20533 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20534 {
20535  struct sip_registry *reg;
20536  struct ao2_iterator iter;
20537 
20538  switch (cmd) {
20539  case CLI_INIT:
20540  e->command = "sip show objects";
20541  e->usage =
20542  "Usage: sip show objects\n"
20543  " Lists status of known SIP objects\n";
20544  return NULL;
20545  case CLI_GENERATE:
20546  return NULL;
20547  }
20548 
20549  if (a->argc != 3)
20550  return CLI_SHOWUSAGE;
20551  ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
20552  ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
20553  ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
20554  ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
20555 
20556  iter = ao2_iterator_init(registry_list, 0);
20557  ast_cli(a->fd, "-= Registry objects: %d =-\n\n", ao2_container_count(registry_list));
20558  while ((reg = ao2_t_iterator_next(&iter, "sip_show_objects iter"))) {
20559  ao2_lock(reg);
20560  ast_cli(a->fd, "name: %s\n", reg->configvalue);
20561  ao2_unlock(reg);
20562  ao2_t_ref(reg, -1, "sip_show_objects iter");
20563  }
20564  ao2_iterator_destroy(&iter);
20565 
20566  ast_cli(a->fd, "-= Dialog objects:\n\n");
20567  ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
20568  return CLI_SUCCESS;
20569 }
20570 /*! \brief Print call group and pickup group */
20571 static void print_group(int fd, ast_group_t group, int crlf)
20572 {
20573  char buf[256];
20574  ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
20575 }
20576 
20577 /*! \brief Print named call groups and pickup groups */
20578 static void print_named_groups(int fd, struct ast_namedgroups *group, int crlf)
20579 {
20580  struct ast_str *buf = ast_str_create(1024);
20581  if (buf) {
20582  ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_namedgroups(&buf, group) );
20583  ast_free(buf);
20584  }
20585 }
20586 
20587 /*! \brief mapping between dtmf flags and strings */
20588 static const struct _map_x_s dtmfstr[] = {
20589  { SIP_DTMF_RFC2833, "rfc2833" },
20590  { SIP_DTMF_INFO, "info" },
20591  { SIP_DTMF_SHORTINFO, "shortinfo" },
20592  { SIP_DTMF_INBAND, "inband" },
20593  { SIP_DTMF_AUTO, "auto" },
20594  { -1, NULL }, /* terminator */
20595 };
20596 
20597 /*! \brief Convert DTMF mode to printable string */
20598 static const char *dtmfmode2str(int mode)
20599 {
20600  return map_x_s(dtmfstr, mode, "<error>");
20601 }
20602 
20603 /*! \brief maps a string to dtmfmode, returns -1 on error */
20604 static int str2dtmfmode(const char *str)
20605 {
20606  return map_s_x(dtmfstr, str, -1);
20607 }
20608 
20609 static const struct _map_x_s insecurestr[] = {
20610  { SIP_INSECURE_PORT, "port" },
20611  { SIP_INSECURE_INVITE, "invite" },
20612  { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
20613  { 0, "no" },
20614  { -1, NULL }, /* terminator */
20615 };
20616 
20617 /*! \brief Convert Insecure setting to printable string */
20618 static const char *insecure2str(int mode)
20619 {
20620  return map_x_s(insecurestr, mode, "<error>");
20621 }
20622 
20623 static const struct _map_x_s allowoverlapstr[] = {
20624  { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
20625  { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
20626  { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
20627  { -1, NULL }, /* terminator */
20628 };
20629 
20630 /*! \brief Convert AllowOverlap setting to printable string */
20631 static const char *allowoverlap2str(int mode)
20632 {
20633  return map_x_s(allowoverlapstr, mode, "<error>");
20634 }
20635 
20636 static const struct _map_x_s trust_id_outboundstr[] = {
20637  { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY, "Legacy" },
20640  { -1, NULL }, /* terminator */
20641 };
20642 
20643 static const char *trust_id_outbound2str(int mode)
20644 {
20645  return map_x_s(trust_id_outboundstr, mode, "<error>");
20646 }
20647 
20648 /*! \brief Destroy disused contexts between reloads
20649  Only used in reload_config so the code for regcontext doesn't get ugly
20650 */
20651 static void cleanup_stale_contexts(char *new, char *old)
20652 {
20653  char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
20654 
20655  while ((oldcontext = strsep(&old, "&"))) {
20656  stalecontext = NULL;
20657  ast_copy_string(newlist, new, sizeof(newlist));
20658  stringp = newlist;
20659  while ((newcontext = strsep(&stringp, "&"))) {
20660  if (!strcmp(newcontext, oldcontext)) {
20661  /* This is not the context you're looking for */
20662  stalecontext = NULL;
20663  break;
20664  } else if (strcmp(newcontext, oldcontext)) {
20665  stalecontext = oldcontext;
20666  }
20667 
20668  }
20669  ast_context_destroy_by_name(stalecontext, "SIP");
20670  }
20671 }
20672 
20673 /*!
20674  * \brief Check RTP Timeout on dialogs
20675  *
20676  * \details This is used with ao2_callback to check rtptimeout
20677  * rtponholdtimeout and send rtpkeepalive packets.
20678  *
20679  * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
20680  */
20681 static int dialog_checkrtp_cb(void *dialogobj, void *arg, int flags)
20682 {
20683  struct sip_pvt *dialog = dialogobj;
20684  time_t *t = arg;
20685  int match_status;
20686 
20687  if (sip_pvt_trylock(dialog)) {
20688  return 0;
20689  }
20690 
20691  if (dialog->rtp || dialog->vrtp) {
20692  match_status = check_rtp_timeout(dialog, *t);
20693  } else {
20694  /* Dialog has no active RTP or VRTP. unlink it from dialogs_rtpcheck. */
20695  match_status = CMP_MATCH;
20696  }
20697  sip_pvt_unlock(dialog);
20698 
20699  return match_status;
20700 }
20701 
20702 /*!
20703  * \brief Match dialogs that need to be destroyed
20704  *
20705  * \details This is used with ao2_callback to unlink/delete all dialogs that
20706  * are marked needdestroy.
20707  *
20708  * \todo Re-work this to improve efficiency. Currently, this function is called
20709  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
20710  * potentially even more often when the scheduler has entries to run.
20711  */
20712 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
20713 {
20714  struct sip_pvt *dialog = dialogobj;
20715 
20716  if (sip_pvt_trylock(dialog)) {
20717  /* Don't block the monitor thread. This function is called often enough
20718  * that we can wait for the next time around. */
20719  return 0;
20720  }
20721 
20722  /* If we have sessions that needs to be destroyed, do it now */
20723  /* Check if we have outstanding requests not responsed to or an active call
20724  - if that's the case, wait with destruction */
20725  if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
20726  /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
20727  if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
20728  ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
20729  sip_pvt_unlock(dialog);
20730  return 0;
20731  }
20732 
20733  if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
20734  ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
20735  sip_pvt_unlock(dialog);
20736  return 0;
20737  }
20738 
20739  sip_pvt_unlock(dialog);
20740  /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
20741  /* the CMP_MATCH will unlink this dialog from the dialog hash table */
20742  dialog_unlink_all(dialog);
20743  return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
20744  }
20745 
20746  sip_pvt_unlock(dialog);
20747 
20748  return 0;
20749 }
20750 
20751 /*! \brief Remove temporary realtime objects from memory (CLI) */
20752 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
20753 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20754 {
20755  struct sip_peer *peer, *pi;
20756  int prunepeer = FALSE;
20757  int multi = FALSE;
20758  const char *name = NULL;
20759  regex_t regexbuf;
20760  int havepattern = 0;
20761  struct ao2_iterator i;
20762  static const char * const choices[] = { "all", "like", NULL };
20763  char *cmplt;
20764 
20765  if (cmd == CLI_INIT) {
20766  e->command = "sip prune realtime [peer|all]";
20767  e->usage =
20768  "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
20769  " Prunes object(s) from the cache.\n"
20770  " Optional regular expression pattern is used to filter the objects.\n";
20771  return NULL;
20772  } else if (cmd == CLI_GENERATE) {
20773  if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
20774  cmplt = ast_cli_complete(a->word, choices, a->n);
20775  if (!cmplt)
20776  cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
20777  return cmplt;
20778  }
20779  if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
20781  return NULL;
20782  }
20783  switch (a->argc) {
20784  case 4:
20785  name = a->argv[3];
20786  /* we accept a name in position 3, but keywords are not good. */
20787  if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
20788  return CLI_SHOWUSAGE;
20789  prunepeer = TRUE;
20790  if (!strcasecmp(name, "all")) {
20791  multi = TRUE;
20792  name = NULL;
20793  }
20794  /* else a single name, already set */
20795  break;
20796  case 5:
20797  /* sip prune realtime {peer|like} name */
20798  name = a->argv[4];
20799  if (!strcasecmp(a->argv[3], "peer"))
20800  prunepeer = TRUE;
20801  else if (!strcasecmp(a->argv[3], "like")) {
20802  prunepeer = TRUE;
20803  multi = TRUE;
20804  } else
20805  return CLI_SHOWUSAGE;
20806  if (!strcasecmp(name, "like"))
20807  return CLI_SHOWUSAGE;
20808  if (!multi && !strcasecmp(name, "all")) {
20809  multi = TRUE;
20810  name = NULL;
20811  }
20812  break;
20813  case 6:
20814  name = a->argv[5];
20815  multi = TRUE;
20816  /* sip prune realtime {peer} like name */
20817  if (strcasecmp(a->argv[4], "like"))
20818  return CLI_SHOWUSAGE;
20819  if (!strcasecmp(a->argv[3], "peer")) {
20820  prunepeer = TRUE;
20821  } else
20822  return CLI_SHOWUSAGE;
20823  break;
20824  default:
20825  return CLI_SHOWUSAGE;
20826  }
20827 
20828  if (multi && name) {
20829  if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
20830  return CLI_SHOWUSAGE;
20831  }
20832  havepattern = 1;
20833  }
20834 
20835  if (multi) {
20836  if (prunepeer) {
20837  int pruned = 0;
20838 
20839  i = ao2_iterator_init(peers, 0);
20840  while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
20841  ao2_lock(pi);
20842  if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
20843  ao2_unlock(pi);
20844  sip_unref_peer(pi, "toss iterator peer ptr before continue");
20845  continue;
20846  };
20848  pi->the_mark = 1;
20849  pruned++;
20850  }
20851  ao2_unlock(pi);
20852  sip_unref_peer(pi, "toss iterator peer ptr");
20853  }
20855  if (pruned) {
20857  ast_cli(a->fd, "%d peers pruned.\n", pruned);
20858  } else
20859  ast_cli(a->fd, "No peers found to prune.\n");
20860  }
20861  } else {
20862  if (prunepeer) {
20863  struct sip_peer tmp;
20864  ast_copy_string(tmp.name, name, sizeof(tmp.name));
20865  if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
20866  if (!ast_sockaddr_isnull(&peer->addr)) {
20867  ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
20868  }
20869  if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
20870  ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
20871  /* put it back! */
20872  ao2_t_link(peers, peer, "link peer into peer table");
20873  if (!ast_sockaddr_isnull(&peer->addr)) {
20874  ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
20875  }
20876  } else
20877  ast_cli(a->fd, "Peer '%s' pruned.\n", name);
20878  sip_unref_peer(peer, "sip_prune_realtime: sip_unref_peer: tossing temp peer ptr");
20879  } else
20880  ast_cli(a->fd, "Peer '%s' not found.\n", name);
20881  }
20882  }
20883 
20884  if (havepattern) {
20885  regfree(&regexbuf);
20886  }
20887 
20888  return CLI_SUCCESS;
20889 }
20890 
20891 /*! \brief Print domain mode to cli */
20892 static const char *domain_mode_to_text(const enum domain_mode mode)
20893 {
20894  switch (mode) {
20895  case SIP_DOMAIN_AUTO:
20896  return "[Automatic]";
20897  case SIP_DOMAIN_CONFIG:
20898  return "[Configured]";
20899  }
20900 
20901  return "";
20902 }
20903 
20904 /*! \brief CLI command to list local domains */
20905 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20906 {
20907  struct domain *d;
20908 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
20909 
20910  switch (cmd) {
20911  case CLI_INIT:
20912  e->command = "sip show domains";
20913  e->usage =
20914  "Usage: sip show domains\n"
20915  " Lists all configured SIP local domains.\n"
20916  " Asterisk only responds to SIP messages to local domains.\n";
20917  return NULL;
20918  case CLI_GENERATE:
20919  return NULL;
20920  }
20921 
20922  if (AST_LIST_EMPTY(&domain_list)) {
20923  ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
20924  return CLI_SUCCESS;
20925  } else {
20926  ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
20928  AST_LIST_TRAVERSE(&domain_list, d, list)
20929  ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
20932  ast_cli(a->fd, "\n");
20933  return CLI_SUCCESS;
20934  }
20935 }
20936 #undef FORMAT
20937 
20938 /*! \brief Show SIP peers in the manager API */
20939 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
20940 {
20941  const char *a[4];
20942  const char *peer;
20943 
20944  peer = astman_get_header(m, "Peer");
20945  if (ast_strlen_zero(peer)) {
20946  astman_send_error(s, m, "Peer: <name> missing.");
20947  return 0;
20948  }
20949  a[0] = "sip";
20950  a[1] = "show";
20951  a[2] = "peer";
20952  a[3] = peer;
20953 
20954  _sip_show_peer(1, -1, s, m, 4, a);
20955  astman_append(s, "\r\n" );
20956  return 0;
20957 }
20958 
20959 /*! \brief Show one peer in detail */
20960 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20961 {
20962  switch (cmd) {
20963  case CLI_INIT:
20964  e->command = "sip show peer";
20965  e->usage =
20966  "Usage: sip show peer <name> [load]\n"
20967  " Shows all details on one SIP peer and the current status.\n"
20968  " Option \"load\" forces lookup of peer in realtime storage.\n";
20969  return NULL;
20970  case CLI_GENERATE:
20971  if (a->pos == 4) {
20972  static const char * const completions[] = { "load", NULL };
20973  return ast_cli_complete(a->word, completions, a->n);
20974  } else {
20975  return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
20976  }
20977  }
20978  return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
20979 }
20980 
20981 static void send_manager_peer_status(struct mansession *s, struct sip_peer *peer, const char *idText)
20982 {
20983  char time[128] = "";
20984  char status[128] = "";
20985  if (peer->maxms) {
20986  if (peer->lastms < 0) {
20987  snprintf(status, sizeof(status), "PeerStatus: Unreachable\r\n");
20988  } else if (peer->lastms > peer->maxms) {
20989  snprintf(status, sizeof(status), "PeerStatus: Lagged\r\n");
20990  snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
20991  } else if (peer->lastms) {
20992  snprintf(status, sizeof(status), "PeerStatus: Reachable\r\n");
20993  snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
20994  } else {
20995  snprintf(status, sizeof(status), "PeerStatus: Unknown\r\n");
20996  }
20997  } else {
20998  snprintf(status, sizeof(status), "PeerStatus: Unmonitored\r\n");
20999  }
21000 
21001  astman_append(s,
21002  "Event: PeerStatus\r\n"
21003  "Privilege: System\r\n"
21004  "ChannelType: SIP\r\n"
21005  "Peer: SIP/%s\r\n"
21006  "%s"
21007  "%s"
21008  "%s"
21009  "\r\n",
21010  peer->name, status, time, idText);
21011 }
21012 
21013 /*! \brief Show SIP peers in the manager API */
21014 static int manager_sip_peer_status(struct mansession *s, const struct message *m)
21015 {
21016  const char *id = astman_get_header(m,"ActionID");
21017  const char *peer_name = astman_get_header(m,"Peer");
21018  char idText[256];
21019  struct sip_peer *peer = NULL;
21020  int num_peers = 0;
21021 
21022  idText[0] = '\0';
21023  if (!ast_strlen_zero(id)) {
21024  snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
21025  }
21026 
21027  if (!ast_strlen_zero(peer_name)) {
21028  /* strip SIP/ from the begining of the peer name */
21029  if (strlen(peer_name) >= 4 && !strncasecmp("SIP/", peer_name, 4)) {
21030  peer_name += 4;
21031  }
21032 
21033  peer = sip_find_peer(peer_name, NULL, TRUE, FINDPEERS, FALSE, 0);
21034  if (!peer) {
21035  astman_send_error(s, m, "No such peer");
21036  return 0;
21037  }
21038  }
21039 
21040  astman_send_listack(s, m, "Peer status will follow", "start");
21041 
21042  if (!peer) {
21043  struct ao2_iterator i = ao2_iterator_init(peers, 0);
21044 
21045  while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table for SIPpeerstatus"))) {
21046  ao2_lock(peer);
21047  send_manager_peer_status(s, peer, idText);
21048  ao2_unlock(peer);
21049  sip_unref_peer(peer, "unref peer for SIPpeerstatus");
21050  ++num_peers;
21051  }
21053  } else {
21054  ao2_lock(peer);
21055  send_manager_peer_status(s, peer, idText);
21056  ao2_unlock(peer);
21057  sip_unref_peer(peer, "unref peer for SIPpeerstatus");
21058  ++num_peers;
21059  }
21060 
21061  astman_send_list_complete_start(s, m, "SIPpeerstatusComplete", num_peers);
21063 
21064  return 0;
21065 }
21066 
21067 static void publish_qualify_peer_done(const char *id, const char *peer)
21068 {
21069  RAII_VAR(struct ast_json *, body, NULL, ast_json_unref);
21070 
21071  if (ast_strlen_zero(id)) {
21072  body = ast_json_pack("{s: s}", "Peer", peer);
21073  } else {
21074  body = ast_json_pack("{s: s, s: s}", "Peer", peer, "ActionID", id);
21075  }
21076  if (!body) {
21077  return;
21078  }
21079 
21080  ast_manager_publish_event("SIPQualifyPeerDone", EVENT_FLAG_CALL, body);
21081 }
21082 
21083 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
21084 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
21085 {
21086  struct sip_peer *peer;
21087  int load_realtime;
21088 
21089  if (argc < 4)
21090  return CLI_SHOWUSAGE;
21091 
21092  load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
21093  if ((peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
21094  const char *id = astman_get_header(m,"ActionID");
21095 
21096  if (type != 0) {
21097  astman_send_ack(s, m, "SIP peer found - will qualify");
21098  }
21099 
21100  sip_poke_peer(peer, 1);
21101 
21102  publish_qualify_peer_done(id, argv[3]);
21103 
21104  sip_unref_peer(peer, "qualify: done with peer");
21105  } else if (type == 0) {
21106  ast_cli(fd, "Peer '%s' not found\n", argv[3]);
21107  } else {
21108  astman_send_error(s, m, "Peer not found");
21109  }
21110 
21111  return CLI_SUCCESS;
21112 }
21113 
21114 /*! \brief Qualify SIP peers in the manager API */
21115 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
21116 {
21117  const char *a[4];
21118  const char *peer;
21119 
21120  peer = astman_get_header(m, "Peer");
21121  if (ast_strlen_zero(peer)) {
21122  astman_send_error(s, m, "Peer: <name> missing.");
21123  return 0;
21124  }
21125  a[0] = "sip";
21126  a[1] = "qualify";
21127  a[2] = "peer";
21128  a[3] = peer;
21129 
21130  _sip_qualify_peer(1, -1, s, m, 4, a);
21131  return 0;
21132 }
21133 
21134 /*! \brief Send an OPTIONS packet to a SIP peer */
21135 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21136 {
21137  switch (cmd) {
21138  case CLI_INIT:
21139  e->command = "sip qualify peer";
21140  e->usage =
21141  "Usage: sip qualify peer <name> [load]\n"
21142  " Requests a response from one SIP peer and the current status.\n"
21143  " Option \"load\" forces lookup of peer in realtime storage.\n";
21144  return NULL;
21145  case CLI_GENERATE:
21146  if (a->pos == 4) {
21147  static const char * const completions[] = { "load", NULL };
21148  return ast_cli_complete(a->word, completions, a->n);
21149  } else {
21150  return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
21151  }
21152  }
21153  return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
21154 }
21155 
21156 /*! \brief list peer mailboxes to CLI */
21157 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
21158 {
21159  struct sip_mailbox *mailbox;
21160 
21161  AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21162  ast_str_append(mailbox_str, 0, "%s%s",
21163  mailbox->id,
21164  AST_LIST_NEXT(mailbox, entry) ? "," : "");
21165  }
21166 }
21167 
21168 static struct _map_x_s faxecmodes[] = {
21169  { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
21171  { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
21172  { -1, NULL},
21173 };
21174 
21175 static const char *faxec2str(int faxec)
21176 {
21177  return map_x_s(faxecmodes, faxec, "Unknown");
21178 }
21179 
21180 /*! \brief Show one peer in detail (main function) */
21181 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
21182 {
21183  char status[30] = "";
21184  char cbuf[256];
21185  struct sip_peer *peer;
21186  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
21187  struct ast_variable *v;
21188  int x = 0, load_realtime;
21189  int realtimepeers;
21190 
21191  realtimepeers = ast_check_realtime("sippeers");
21192 
21193  if (argc < 4)
21194  return CLI_SHOWUSAGE;
21195 
21196  load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
21197  peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
21198 
21199  if (s) { /* Manager */
21200  if (peer) {
21201  const char *id = astman_get_header(m, "ActionID");
21202 
21203  astman_append(s, "Response: Success\r\n");
21204  if (!ast_strlen_zero(id))
21205  astman_append(s, "ActionID: %s\r\n", id);
21206  } else {
21207  snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
21208  astman_send_error(s, m, cbuf);
21209  return CLI_SUCCESS;
21210  }
21211  }
21212  if (peer && type==0 ) { /* Normal listing */
21213  struct ast_str *mailbox_str = ast_str_alloca(512);
21214  struct ast_str *path;
21215  struct sip_auth_container *credentials;
21216 
21217  ao2_lock(peer);
21218  credentials = peer->auth;
21219  if (credentials) {
21220  ao2_t_ref(credentials, +1, "Ref peer auth for show");
21221  }
21222  ao2_unlock(peer);
21223 
21224  ast_cli(fd, "\n\n");
21225  ast_cli(fd, " * Name : %s\n", peer->name);
21226  ast_cli(fd, " Description : %s\n", peer->description);
21227  if (realtimepeers) { /* Realtime is enabled */
21228  ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
21229  }
21230  ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
21231  ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
21232  ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
21233  if (credentials) {
21234  struct sip_auth *auth;
21235 
21236  AST_LIST_TRAVERSE(&credentials->list, auth, node) {
21237  ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
21238  auth->realm,
21239  auth->username,
21240  !ast_strlen_zero(auth->secret)
21241  ? "<Secret set>"
21242  : (!ast_strlen_zero(auth->md5secret)
21243  ? "<MD5secret set>" : "<Not set>"));
21244  }
21245  ao2_t_ref(credentials, -1, "Unref peer auth for show");
21246  }
21247  ast_cli(fd, " Context : %s\n", peer->context);
21248  ast_cli(fd, " Record On feature : %s\n", peer->record_on_feature);
21249  ast_cli(fd, " Record Off feature : %s\n", peer->record_off_feature);
21250  ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
21251  ast_cli(fd, " Language : %s\n", peer->language);
21252  ast_cli(fd, " Tonezone : %s\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
21253  if (!ast_strlen_zero(peer->accountcode))
21254  ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
21255  ast_cli(fd, " AMA flags : %s\n", ast_channel_amaflags2string(peer->amaflags));
21256  ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
21257  ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
21258  if (!ast_strlen_zero(peer->fromuser))
21259  ast_cli(fd, " FromUser : %s\n", peer->fromuser);
21260  if (!ast_strlen_zero(peer->fromdomain))
21261  ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
21262  ast_cli(fd, " Callgroup : ");
21263  print_group(fd, peer->callgroup, 0);
21264  ast_cli(fd, " Pickupgroup : ");
21265  print_group(fd, peer->pickupgroup, 0);
21266  ast_cli(fd, " Named Callgr : ");
21267  print_named_groups(fd, peer->named_callgroups, 0);
21268  ast_cli(fd, " Nam. Pickupgr: ");
21269  print_named_groups(fd, peer->named_pickupgroups, 0);
21270  peer_mailboxes_to_str(&mailbox_str, peer);
21271  ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
21272  ast_cli(fd, " Mailbox : %s\n", ast_str_buffer(mailbox_str));
21273  ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
21274  ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
21275  ast_cli(fd, " Call limit : %d\n", peer->call_limit);
21276  ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
21277  if (peer->busy_level)
21278  ast_cli(fd, " Busy level : %d\n", peer->busy_level);
21279  ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
21280  ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
21281  ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
21282  ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
21283  ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
21284  ast_cli(fd, " Force rport : %s\n", force_rport_string(peer->flags));
21285  ast_cli(fd, " Symmetric RTP: %s\n", comedia_string(peer->flags));
21286  ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->acl) == 0));
21287  ast_cli(fd, " ContactACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->contactacl) == 0));
21288  ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->directmediaacl) == 0));
21289  ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
21290  ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
21291  ast_cli(fd, " T.38 MaxDtgrm: %u\n", peer->t38_maxdatagram);
21292  ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
21293  ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
21294  ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
21295  ast_cli(fd, " Video Support: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
21296  ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
21297  ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
21298  ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
21299  ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
21300  ast_cli(fd, " Path support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEPATH)));
21301  if ((path = sip_route_list(&peer->path, 1, 0))) {
21302  ast_cli(fd, " Path : %s\n", ast_str_buffer(path));
21303  ast_free(path);
21304  }
21305  ast_cli(fd, " TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
21306  ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
21307  ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
21308  if (peer->outboundproxy)
21309  ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
21310  peer->outboundproxy->force ? "(forced)" : "");
21311 
21312  /* - is enumerated */
21313  ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
21314  ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
21315  ast_cli(fd, " Timer B : %d\n", peer->timer_b);
21316  ast_cli(fd, " ToHost : %s\n", peer->tohost);
21317  ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
21318  ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
21319  ast_cli(fd, " Prim.Transp. : %s\n", sip_get_transport(peer->socket.type));
21320  ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
21322  ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
21323  ast_cli(fd, " Def. Username: %s\n", peer->username);
21324  ast_cli(fd, " SIP Options : ");
21325  if (peer->sipoptions) {
21326  int lastoption = -1;
21327  for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
21328  if (sip_options[x].id != lastoption) {
21329  if (peer->sipoptions & sip_options[x].id)
21330  ast_cli(fd, "%s ", sip_options[x].text);
21331  lastoption = x;
21332  }
21333  }
21334  } else
21335  ast_cli(fd, "(none)");
21336 
21337  ast_cli(fd, "\n");
21338  ast_cli(fd, " Codecs : %s\n", ast_format_cap_get_names(peer->caps, &codec_buf));
21339 
21340  ast_cli(fd, " Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
21341  ast_cli(fd, " Status : ");
21342  peer_status(peer, status, sizeof(status));
21343  ast_cli(fd, "%s\n", status);
21344  ast_cli(fd, " Useragent : %s\n", peer->useragent);
21345  ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
21346  ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
21347  ast_cli(fd, " Keepalive : %d ms\n", peer->keepalive * 1000);
21348  if (peer->chanvars) {
21349  ast_cli(fd, " Variables :\n");
21350  for (v = peer->chanvars ; v ; v = v->next)
21351  ast_cli(fd, " %s = %s\n", v->name, v->value);
21352  }
21353 
21354  ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
21355  ast_cli(fd, " Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
21356  ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
21357  ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
21358  ast_cli(fd, " RTP Engine : %s\n", peer->engine);
21359  ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
21360  ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
21361  ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
21362  ast_cli(fd, " RTCP Mux : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[2], SIP_PAGE3_RTCP_MUX)));
21363  ast_cli(fd, "\n");
21364  peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer ptr");
21365  } else if (peer && type == 1) { /* manager listing */
21366  char buffer[256];
21367  struct ast_str *tmp_str = ast_str_alloca(512);
21368  astman_append(s, "Channeltype: SIP\r\n");
21369  astman_append(s, "ObjectName: %s\r\n", peer->name);
21370  astman_append(s, "ChanObjectType: peer\r\n");
21371  astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
21372  astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
21373  astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
21374  astman_append(s, "Context: %s\r\n", peer->context);
21375  if (!ast_strlen_zero(peer->subscribecontext)) {
21376  astman_append(s, "SubscribeContext: %s\r\n", peer->subscribecontext);
21377  }
21378  astman_append(s, "Language: %s\r\n", peer->language);
21379  astman_append(s, "ToneZone: %s\r\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
21380  if (!ast_strlen_zero(peer->accountcode))
21381  astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
21382  astman_append(s, "AMAflags: %s\r\n", ast_channel_amaflags2string(peer->amaflags));
21383  astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
21384  if (!ast_strlen_zero(peer->fromuser))
21385  astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
21386  if (!ast_strlen_zero(peer->fromdomain))
21387  astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
21388  astman_append(s, "Callgroup: ");
21389  astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
21390  astman_append(s, "Pickupgroup: ");
21391  astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
21392  astman_append(s, "Named Callgroup: ");
21393  astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_callgroups));
21394  ast_str_reset(tmp_str);
21395  astman_append(s, "Named Pickupgroup: ");
21396  astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_pickupgroups));
21397  ast_str_reset(tmp_str);
21398  astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
21399  peer_mailboxes_to_str(&tmp_str, peer);
21400  astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(tmp_str));
21401  astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
21402  astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
21403  astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
21404  astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
21405  astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
21406  astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
21407  astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
21408  astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
21409  astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
21410  astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
21411  astman_append(s, "SIP-Forcerport: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
21412  (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "A" : "a") :
21413  (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "Y" : "N"));
21414  astman_append(s, "SIP-Comedia: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ?
21415  (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "A" : "a") :
21416  (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "Y" : "N"));
21417  astman_append(s, "ACL: %s\r\n", (ast_acl_list_is_empty(peer->acl) ? "N" : "Y"));
21418  astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
21419  astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
21420  astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
21421  astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
21422  astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
21423  astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
21424  astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
21425  astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
21426  astman_append(s, "SIP-T.38MaxDtgrm: %u\r\n", peer->t38_maxdatagram);
21427  astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
21428  astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
21429  astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
21430  astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
21431  astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
21432  astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
21433  astman_append(s, "SIP-RTCP-Mux: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_RTCP_MUX) ? "Y" : "N");
21434 
21435  /* - is enumerated */
21436  astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
21437  astman_append(s, "ToHost: %s\r\n", peer->tohost);
21438  astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
21439  astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_sockaddr_stringify_addr(&peer->defaddr), ast_sockaddr_port(&peer->defaddr));
21440  astman_append(s, "Default-Username: %s\r\n", peer->username);
21442  astman_append(s, "RegExtension: %s\r\n", peer->regexten);
21443  astman_append(s, "Codecs: %s\r\n", ast_format_cap_get_names(peer->caps, &codec_buf));
21444  astman_append(s, "Status: ");
21445  peer_status(peer, status, sizeof(status));
21446  astman_append(s, "%s\r\n", status);
21447  astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
21448  astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
21449  astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
21450  astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
21451  if (peer->chanvars) {
21452  for (v = peer->chanvars ; v ; v = v->next) {
21453  astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
21454  }
21455  }
21456  astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
21457  astman_append(s, "Description: %s\r\n", peer->description);
21458 
21459  peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer");
21460 
21461  } else {
21462  ast_cli(fd, "Peer %s not found.\n", argv[3]);
21463  ast_cli(fd, "\n");
21464  }
21465 
21466  return CLI_SUCCESS;
21467 }
21468 
21469 /*! \brief Do completion on user name */
21470 static char *complete_sip_user(const char *word, int state)
21471 {
21472  char *result = NULL;
21473  int wordlen = strlen(word);
21474  int which = 0;
21475  struct ao2_iterator user_iter;
21476  struct sip_peer *user;
21477 
21478  user_iter = ao2_iterator_init(peers, 0);
21479  while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
21480  ao2_lock(user);
21481  if (!(user->type & SIP_TYPE_USER)) {
21482  ao2_unlock(user);
21483  sip_unref_peer(user, "complete sip user");
21484  continue;
21485  }
21486  /* locking of the object is not required because only the name and flags are being compared */
21487  if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
21488  result = ast_strdup(user->name);
21489  }
21490  ao2_unlock(user);
21491  sip_unref_peer(user, "complete sip user");
21492  if (result) {
21493  break;
21494  }
21495  }
21496  ao2_iterator_destroy(&user_iter);
21497  return result;
21498 }
21499 /*! \brief Support routine for 'sip show user' CLI */
21500 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
21501 {
21502  if (pos == 3)
21503  return complete_sip_user(word, state);
21504 
21505  return NULL;
21506 }
21507 
21508 /*! \brief Show one user in detail */
21509 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21510 {
21511  char cbuf[256];
21512  struct sip_peer *user;
21513  struct ast_variable *v;
21514  int load_realtime;
21515 
21516  switch (cmd) {
21517  case CLI_INIT:
21518  e->command = "sip show user";
21519  e->usage =
21520  "Usage: sip show user <name> [load]\n"
21521  " Shows all details on one SIP user and the current status.\n"
21522  " Option \"load\" forces lookup of peer in realtime storage.\n";
21523  return NULL;
21524  case CLI_GENERATE:
21525  if (a->pos == 4) {
21526  static const char * const completions[] = { "load", NULL };
21527  return ast_cli_complete(a->word, completions, a->n);
21528  } else {
21529  return complete_sip_show_user(a->line, a->word, a->pos, a->n);
21530  }
21531  }
21532 
21533  if (a->argc < 4)
21534  return CLI_SHOWUSAGE;
21535 
21536  /* Load from realtime storage? */
21537  load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
21538 
21539  if ((user = sip_find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
21540  ao2_lock(user);
21541  ast_cli(a->fd, "\n\n");
21542  ast_cli(a->fd, " * Name : %s\n", user->name);
21543  ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
21544  ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
21545  ast_cli(a->fd, " Context : %s\n", user->context);
21546  ast_cli(a->fd, " Language : %s\n", user->language);
21547  if (!ast_strlen_zero(user->accountcode))
21548  ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
21549  ast_cli(a->fd, " AMA flags : %s\n", ast_channel_amaflags2string(user->amaflags));
21550  ast_cli(a->fd, " Tonezone : %s\n", user->zone[0] != '\0' ? user->zone : "<Not set>");
21551  ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
21552  ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
21553  ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
21554  ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
21555  ast_cli(a->fd, " Callgroup : ");
21556  print_group(a->fd, user->callgroup, 0);
21557  ast_cli(a->fd, " Pickupgroup : ");
21558  print_group(a->fd, user->pickupgroup, 0);
21559  ast_cli(a->fd, " Named Callgr : ");
21560  print_named_groups(a->fd, user->named_callgroups, 0);
21561  ast_cli(a->fd, " Nam. Pickupgr: ");
21563  ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
21564  ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0));
21565  ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
21566  ast_cli(a->fd, " Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
21567  ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
21568  ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
21569  ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
21570 
21571  ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
21572  if (user->chanvars) {
21573  ast_cli(a->fd, " Variables :\n");
21574  for (v = user->chanvars ; v ; v = v->next)
21575  ast_cli(a->fd, " %s = %s\n", v->name, v->value);
21576  }
21577 
21578  ast_cli(a->fd, "\n");
21579 
21580  ao2_unlock(user);
21581  sip_unref_peer(user, "sip show user");
21582  } else {
21583  ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
21584  ast_cli(a->fd, "\n");
21585  }
21586 
21587  return CLI_SUCCESS;
21588 }
21589 
21590 
21591 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21592 {
21593  struct ast_str *cbuf;
21594  struct ast_cb_names cbnames = {
21595  10,
21596  {
21597  "retrans_pkt",
21598  "__sip_autodestruct",
21599  "expire_register",
21600  "auto_congest",
21601  "sip_reg_timeout",
21602  "sip_poke_peer_s",
21603  "sip_poke_peer_now",
21604  "sip_poke_noanswer",
21605  "sip_reregister",
21606  "sip_reinvite_retry"
21607  },
21608  {
21609  retrans_pkt,
21612  auto_congest,
21619  }
21620  };
21621 
21622  switch (cmd) {
21623  case CLI_INIT:
21624  e->command = "sip show sched";
21625  e->usage =
21626  "Usage: sip show sched\n"
21627  " Shows stats on what's in the sched queue at the moment\n";
21628  return NULL;
21629  case CLI_GENERATE:
21630  return NULL;
21631  }
21632 
21633  cbuf = ast_str_alloca(2048);
21634 
21635  ast_cli(a->fd, "\n");
21636  ast_sched_report(sched, &cbuf, &cbnames);
21637  ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
21638 
21639  return CLI_SUCCESS;
21640 }
21641 
21642 /*! \brief Show SIP Registry (registrations with other SIP proxies */
21643 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21644 {
21645 #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
21646 #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
21647  char host[80];
21648  char user[80];
21649  char tmpdat[256];
21650  struct ast_tm tm;
21651  int counter = 0;
21652  struct ao2_iterator iter;
21653  struct sip_registry *iterator;
21654 
21655  switch (cmd) {
21656  case CLI_INIT:
21657  e->command = "sip show registry";
21658  e->usage =
21659  "Usage: sip show registry\n"
21660  " Lists all registration requests and status.\n";
21661  return NULL;
21662  case CLI_GENERATE:
21663  return NULL;
21664  }
21665 
21666  if (a->argc != 3)
21667  return CLI_SHOWUSAGE;
21668  ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
21669 
21670  iter = ao2_iterator_init(registry_list, 0);
21671  while ((iterator = ao2_t_iterator_next(&iter, "sip_show_registry iter"))) {
21672  ao2_lock(iterator);
21673 
21674  snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
21675  snprintf(user, sizeof(user), "%s", iterator->username);
21676  if (!ast_strlen_zero(iterator->regdomain)) {
21677  snprintf(tmpdat, sizeof(tmpdat), "%s", user);
21678  snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
21679  if (iterator->regdomainport) {
21680  snprintf(tmpdat, sizeof(tmpdat), "%s", user);
21681  snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
21682  if (iterator->regtime.tv_sec) {
21683  ast_localtime(&iterator->regtime, &tm, NULL);
21684  ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
21685  } else
21686  tmpdat[0] = '\0';
21687  ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
21688 
21689  ao2_unlock(iterator);
21690  ao2_t_ref(iterator, -1, "sip_show_registry iter");
21691  counter++;
21692  }
21693  ao2_iterator_destroy(&iter);
21694 
21695  ast_cli(a->fd, "%d SIP registrations.\n", counter);
21696  return CLI_SUCCESS;
21697 #undef FORMAT
21698 #undef FORMAT2
21699 }
21700 
21701 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
21702  \note This function does not tell the SIP device what's going on,
21703  so use it with great care.
21704 */
21705 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21706 {
21707  struct sip_peer *peer;
21708  int load_realtime = 0;
21709 
21710  switch (cmd) {
21711  case CLI_INIT:
21712  e->command = "sip unregister";
21713  e->usage =
21714  "Usage: sip unregister <peer>\n"
21715  " Unregister (force expiration) a SIP peer from the registry\n";
21716  return NULL;
21717  case CLI_GENERATE:
21718  return complete_sip_unregister(a->line, a->word, a->pos, a->n);
21719  }
21720 
21721  if (a->argc != 3)
21722  return CLI_SHOWUSAGE;
21723 
21724  if ((peer = sip_find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
21725  if (peer->expire > -1) {
21726  AST_SCHED_DEL_UNREF(sched, peer->expire,
21727  sip_unref_peer(peer, "remove register expire ref"));
21728  expire_register(sip_ref_peer(peer, "ref for expire_register"));
21729  ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
21730  } else {
21731  ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
21732  }
21733  sip_unref_peer(peer, "sip_unregister: sip_unref_peer via sip_unregister: done with peer from sip_find_peer call");
21734  } else {
21735  ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
21736  }
21737 
21738  return CLI_SUCCESS;
21739 }
21740 
21741 /*! \brief Callback for show_chanstats */
21742 static int show_chanstats_cb(struct sip_pvt *cur, struct __show_chan_arg *arg)
21743 {
21744 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
21745 #define FORMAT "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.4lf %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.4lf\n"
21746  struct ast_rtp_instance_stats stats;
21747  char durbuf[10];
21748  struct ast_channel *c;
21749  int fd = arg->fd;
21750 
21751  sip_pvt_lock(cur);
21752  c = cur->owner;
21753 
21754  if (cur->subscribed != NONE) {
21755  /* Subscriptions */
21756  sip_pvt_unlock(cur);
21757  return 0; /* don't care, we scan all channels */
21758  }
21759 
21760  if (!cur->rtp) {
21761  if (sipdebug) {
21762  ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
21763  ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
21765  "-- No RTP active");
21766  }
21767  sip_pvt_unlock(cur);
21768  return 0; /* don't care, we scan all channels */
21769  }
21770 
21772  sip_pvt_unlock(cur);
21773  ast_log(LOG_WARNING, "Could not get RTP stats.\n");
21774  return 0;
21775  }
21776 
21777  if (c) {
21778  ast_format_duration_hh_mm_ss(ast_channel_get_duration(c), durbuf, sizeof(durbuf));
21779  } else {
21780  durbuf[0] = '\0';
21781  }
21782 
21783  ast_cli(fd, FORMAT,
21785  cur->callid,
21786  durbuf,
21787  stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
21788  stats.rxcount > (unsigned int) 100000 ? "K":" ",
21789  stats.rxploss,
21790  (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
21791  stats.rxjitter,
21792  stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
21793  stats.txcount > (unsigned int) 100000 ? "K":" ",
21794  stats.txploss,
21795  stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
21796  stats.txjitter
21797  );
21798  arg->numchans++;
21799  sip_pvt_unlock(cur);
21800 
21801  return 0; /* don't care, we scan all channels */
21802 }
21803 
21804 /*! \brief SIP show channelstats CLI (main function) */
21805 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21806 {
21807  struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
21808  struct sip_pvt *cur;
21809  struct ao2_iterator i;
21810 
21811  switch (cmd) {
21812  case CLI_INIT:
21813  e->command = "sip show channelstats";
21814  e->usage =
21815  "Usage: sip show channelstats\n"
21816  " Lists all currently active SIP channel's RTCP statistics.\n"
21817  " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
21818  return NULL;
21819  case CLI_GENERATE:
21820  return NULL;
21821  }
21822 
21823  if (a->argc != 3)
21824  return CLI_SHOWUSAGE;
21825 
21826  ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
21827 
21828  /* iterate on the container and invoke the callback on each item */
21829  i = ao2_iterator_init(dialogs, 0);
21830  for (; (cur = ao2_iterator_next(&i)); ao2_ref(cur, -1)) {
21831  show_chanstats_cb(cur, &arg);
21832  }
21834 
21835  ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
21836  return CLI_SUCCESS;
21837 }
21838 #undef FORMAT
21839 #undef FORMAT2
21840 
21841 /*! \brief List global settings for the SIP channel */
21842 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21843 {
21844  int realtimepeers;
21845  int realtimeregs;
21846  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
21847  const char *msg; /* temporary msg pointer */
21848  struct sip_auth_container *credentials;
21849 
21850  switch (cmd) {
21851  case CLI_INIT:
21852  e->command = "sip show settings";
21853  e->usage =
21854  "Usage: sip show settings\n"
21855  " Provides detailed list of the configuration of the SIP channel.\n";
21856  return NULL;
21857  case CLI_GENERATE:
21858  return NULL;
21859  }
21860 
21861  if (a->argc != 3)
21862  return CLI_SHOWUSAGE;
21863 
21864  realtimepeers = ast_check_realtime("sippeers");
21865  realtimeregs = ast_check_realtime("sipregs");
21866 
21868  credentials = authl;
21869  if (credentials) {
21870  ao2_t_ref(credentials, +1, "Ref global auth for show");
21871  }
21873 
21874  ast_cli(a->fd, "\n\nGlobal Settings:\n");
21875  ast_cli(a->fd, "----------------\n");
21876  ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
21878  ast_cli(a->fd, " ** Additional Info:\n");
21879  ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
21880  }
21881  ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
21883  ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
21884  "Disabled");
21885  ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
21886  default_tls_cfg.enabled != FALSE ?
21887  ast_sockaddr_stringify(&sip_tls_desc.local_address) :
21888  "Disabled");
21889  ast_cli(a->fd, " RTP Bindaddress: %s\n",
21892  "Disabled");
21893  ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
21894  ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
21895  ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
21896  ast_cli(a->fd, " AutoCreate Peer: %s\n", autocreatepeer2str(sip_cfg.autocreatepeer));
21897  ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
21898  ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
21899  ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
21900  ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
21901  ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
21902  ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
21903  ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
21904  ast_cli(a->fd, " Path support : %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEPATH)));
21905  ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
21906  if (credentials) {
21907  struct sip_auth *auth;
21908 
21909  AST_LIST_TRAVERSE(&credentials->list, auth, node) {
21910  ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
21911  auth->realm,
21912  auth->username,
21913  !ast_strlen_zero(auth->secret)
21914  ? "<Secret set>"
21915  : (!ast_strlen_zero(auth->md5secret)
21916  ? "<MD5secret set>" : "<Not set>"));
21917  }
21918  ao2_t_ref(credentials, -1, "Unref global auth for show");
21919  }
21920  ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
21921  ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
21922  ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
21923  ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
21924  ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
21925  ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
21926  ast_cli(a->fd, " User Agent: %s\n", global_useragent);
21927  ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
21928  ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
21929  ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
21930  ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
21931  ast_cli(a->fd, " Trust RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_TRUSTRPID)));
21932  ast_cli(a->fd, " Send RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_SENDRPID)));
21933  ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
21934  ast_cli(a->fd, " Send Diversion: %s\n", AST_CLI_YESNO(sip_cfg.send_diversion));
21935  ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
21937  ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
21938  } else {
21939  ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
21940  }
21941  ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
21942  ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
21943 
21944  ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
21945  ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
21946  ast_cli(a->fd, " T.38 MaxDtgrm: %u\n", global_t38_maxdatagram);
21947  if (!realtimepeers && !realtimeregs)
21948  ast_cli(a->fd, " SIP realtime: Disabled\n" );
21949  else
21950  ast_cli(a->fd, " SIP realtime: Enabled\n" );
21951  ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
21952  ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
21953  ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
21954  ast_cli(a->fd, "\nNetwork QoS Settings:\n");
21955  ast_cli(a->fd, "---------------------------\n");
21956  ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
21957  ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
21958  ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
21959  ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
21960  ast_cli(a->fd, " 802.1p CoS SIP: %u\n", global_cos_sip);
21961  ast_cli(a->fd, " 802.1p CoS RTP audio: %u\n", global_cos_audio);
21962  ast_cli(a->fd, " 802.1p CoS RTP video: %u\n", global_cos_video);
21963  ast_cli(a->fd, " 802.1p CoS RTP text: %u\n", global_cos_text);
21964  ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
21966  ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
21967  ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
21968  ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
21969  ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
21970  if (!strcasecmp(global_jbconf.impl, "adaptive")) {
21971  ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
21972  }
21973  ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
21974  }
21975 
21976  ast_cli(a->fd, "\nNetwork Settings:\n");
21977  ast_cli(a->fd, "---------------------------\n");
21978  /* determine if/how SIP address can be remapped */
21979  if (localaddr == NULL)
21980  msg = "Disabled, no localnet list";
21981  else if (ast_sockaddr_isnull(&externaddr))
21982  msg = "Disabled";
21983  else if (!ast_strlen_zero(externhost))
21984  msg = "Enabled using externhost";
21985  else
21986  msg = "Enabled using externaddr";
21987  ast_cli(a->fd, " SIP address remapping: %s\n", msg);
21988  ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
21989  ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
21990  ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
21991  {
21992  struct ast_ha *d;
21993  const char *prefix = "Localnet:";
21994 
21995  for (d = localaddr; d ; prefix = "", d = d->next) {
21996  const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
21997  const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
21998  ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
21999  }
22000  }
22001  ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
22002  ast_cli(a->fd, "---------------------------\n");
22003  ast_cli(a->fd, " Codecs: %s\n", ast_format_cap_get_names(sip_cfg.caps, &codec_buf));
22004  ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
22005  ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
22006  ast_cli(a->fd, " Symmetric RTP: %s\n", comedia_string(global_flags));
22007  ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
22008  ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
22009  ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
22010  ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
22011  ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
22012  ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
22013  ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
22014  ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
22015  ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
22016  ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
22017  ast_cli(a->fd, " Sub. min duration %d secs\n", min_subexpiry);
22018  ast_cli(a->fd, " Sub. max duration: %d secs\n", max_subexpiry);
22019  ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
22020  ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
22021  ast_cli(a->fd, " Outbound reg. retry 403:%s\n", AST_CLI_YESNO(global_reg_retry_403));
22022  ast_cli(a->fd, " Notify ringing state: %s%s\n", AST_CLI_YESNO(sip_cfg.notifyringing), sip_cfg.notifyringing == NOTIFYRINGING_NOTINUSE ? " (when not in use)" : "");
22023  if (sip_cfg.notifyringing) {
22024  ast_cli(a->fd, " Include CID: %s%s\n",
22026  sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
22027  }
22028  ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
22029  ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
22030  ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
22031  ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
22032  ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
22033  sip_cfg.outboundproxy.force ? "(forced)" : "");
22034  ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
22035  ast_cli(a->fd, " Session Refresher: %s\n", strefresherparam2str(global_st_refresher));
22036  ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
22037  ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
22038  ast_cli(a->fd, " Timer T1: %d\n", global_t1);
22039  ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
22040  ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
22041  ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
22042  ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
22043 
22044  ast_cli(a->fd, "\nDefault Settings:\n");
22045  ast_cli(a->fd, "-----------------\n");
22046  ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
22047  ast_cli(a->fd, " Outbound transport: %s\n", sip_get_transport(default_primary_transport));
22048  ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
22049  ast_cli(a->fd, " Record on feature: %s\n", sip_cfg.default_record_on_feature);
22050  ast_cli(a->fd, " Record off feature: %s\n", sip_cfg.default_record_off_feature);
22051  ast_cli(a->fd, " Force rport: %s\n", force_rport_string(global_flags));
22052  ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
22053  ast_cli(a->fd, " Qualify: %d\n", default_qualify);
22054  ast_cli(a->fd, " Keepalive: %d\n", default_keepalive);
22055  ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
22056  ast_cli(a->fd, " Progress inband: %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_NO)));
22057  ast_cli(a->fd, " Language: %s\n", default_language);
22058  ast_cli(a->fd, " Tone zone: %s\n", default_zone[0] != '\0' ? default_zone : "<Not set>");
22059  ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
22060  ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
22061  ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
22062  ast_cli(a->fd, " RTCP Multiplexing: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[2], SIP_PAGE3_RTCP_MUX)));
22063 
22064 
22065  if (realtimepeers || realtimeregs) {
22066  ast_cli(a->fd, "\nRealtime SIP Settings:\n");
22067  ast_cli(a->fd, "----------------------\n");
22068  ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
22069  ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
22070  ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
22071  ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
22072  ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
22073  ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
22074  ast_cli(a->fd, " Save path header: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_path));
22075  ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
22076  }
22077  ast_cli(a->fd, "\n----\n");
22078  return CLI_SUCCESS;
22079 }
22080 
22081 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
22082 {
22083 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
22084  char host[80];
22085  struct ao2_iterator iter;
22086  struct sip_subscription_mwi *iterator;
22087 
22088  switch (cmd) {
22089  case CLI_INIT:
22090  e->command = "sip show mwi";
22091  e->usage =
22092  "Usage: sip show mwi\n"
22093  " Provides a list of MWI subscriptions and status.\n";
22094  return NULL;
22095  case CLI_GENERATE:
22096  return NULL;
22097  }
22098 
22099  ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
22100 
22101  iter = ao2_iterator_init(subscription_mwi_list, 0);
22102  while ((iterator = ao2_t_iterator_next(&iter, "sip_show_mwi iter"))) {
22103  ao2_lock(iterator);
22104  snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
22105  ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
22106  ao2_unlock(iterator);
22107  ao2_t_ref(iterator, -1, "sip_show_mwi iter");
22108  }
22109  ao2_iterator_destroy(&iter);
22110 
22111  return CLI_SUCCESS;
22112 #undef FORMAT
22113 }
22114 
22115 
22116 /*! \brief Show subscription type in string format */
22117 static const char *subscription_type2str(enum subscriptiontype subtype)
22118 {
22119  int i;
22120 
22121  for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
22122  if (subscription_types[i].type == subtype) {
22123  return subscription_types[i].text;
22124  }
22125  }
22126  return subscription_types[0].text;
22127 }
22128 
22129 /*! \brief Find subscription type in array */
22131 {
22132  int i;
22133 
22134  for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
22135  if (subscription_types[i].type == subtype) {
22136  return &subscription_types[i];
22137  }
22138  }
22139  return &subscription_types[0];
22140 }
22141 
22142 /*
22143  * We try to structure all functions that loop on data structures as
22144  * a handler for individual entries, and a mainloop that iterates
22145  * on the main data structure. This way, moving the code to containers
22146  * that support iteration through callbacks will be a lot easier.
22147  */
22148 
22149 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
22150 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
22151 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
22152 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
22153 
22154 /*! \brief callback for show channel|subscription */
22155 static int show_channels_cb(struct sip_pvt *cur, struct __show_chan_arg *arg)
22156 {
22157  const struct ast_sockaddr *dst;
22158 
22159  sip_pvt_lock(cur);
22160  dst = sip_real_dst(cur);
22161 
22162  /* XXX indentation preserved to reduce diff. Will be fixed later */
22163  if (cur->subscribed == NONE && !arg->subscriptions) {
22164  /* set if SIP transfer in progress */
22165  const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
22166  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
22167 
22169  S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
22170  cur->callid,
22171  cur->owner ? ast_format_cap_get_names(ast_channel_nativeformats(cur->owner), &codec_buf) : "(nothing)",
22173  cur->needdestroy ? "(d)" : "",
22174  cur->lastmsg ,
22175  referstatus,
22176  cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
22177  );
22178  arg->numchans++;
22179  }
22180  if (cur->subscribed != NONE && arg->subscriptions) {
22181  struct ast_str *mailbox_str = ast_str_alloca(512);
22182  if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
22183  peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
22185  S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
22186  cur->callid,
22187  /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
22188  cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
22189  cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
22191  cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
22192  cur->expiry
22193  );
22194  arg->numchans++;
22195  }
22196  sip_pvt_unlock(cur);
22197  return 0; /* don't care, we scan all channels */
22198 }
22199 
22200 /*! \brief CLI for show channels or subscriptions.
22201  * This is a new-style CLI handler so a single function contains
22202  * the prototype for the function, the 'generator' to produce multiple
22203  * entries in case it is required, and the actual handler for the command.
22204  */
22205 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
22206 {
22207  struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
22208  struct sip_pvt *cur;
22209  struct ao2_iterator i;
22210 
22211  if (cmd == CLI_INIT) {
22212  e->command = "sip show {channels|subscriptions}";
22213  e->usage =
22214  "Usage: sip show channels\n"
22215  " Lists all currently active SIP calls (dialogs).\n"
22216  "Usage: sip show subscriptions\n"
22217  " Lists active SIP subscriptions.\n";
22218  return NULL;
22219  } else if (cmd == CLI_GENERATE)
22220  return NULL;
22221 
22222  if (a->argc != e->args)
22223  return CLI_SHOWUSAGE;
22224  arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
22225  if (!arg.subscriptions)
22226  ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
22227  else
22228  ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
22229 
22230  /* iterate on the container and invoke the callback on each item */
22231  i = ao2_iterator_init(dialogs, 0);
22232  for (; (cur = ao2_iterator_next(&i)); ao2_ref(cur, -1)) {
22233  show_channels_cb(cur, &arg);
22234  }
22236 
22237  /* print summary information */
22238  ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
22239  (arg.subscriptions ? "subscription" : "dialog"),
22240  ESS(arg.numchans)); /* ESS(n) returns an "s" if n>1 */
22241  return CLI_SUCCESS;
22242 #undef FORMAT
22243 #undef FORMAT2
22244 #undef FORMAT3
22245 }
22246 
22247 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
22248  * This is in charge of generating all strings that match a prefix in the
22249  * given position. As many functions of this kind, each invokation has
22250  * O(state) time complexity so be careful in using it.
22251  */
22252 static char *complete_sipch(const char *line, const char *word, int pos, int state)
22253 {
22254  int which=0;
22255  struct sip_pvt *cur;
22256  char *c = NULL;
22257  int wordlen = strlen(word);
22258  struct ao2_iterator i;
22259 
22260  if (pos != 3) {
22261  return NULL;
22262  }
22263 
22264  i = ao2_iterator_init(dialogs, 0);
22265  while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
22266  sip_pvt_lock(cur);
22267  if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
22268  c = ast_strdup(cur->callid);
22269  sip_pvt_unlock(cur);
22270  dialog_unref(cur, "drop ref in iterator loop break");
22271  break;
22272  }
22273  sip_pvt_unlock(cur);
22274  dialog_unref(cur, "drop ref in iterator loop");
22275  }
22277  return c;
22278 }
22279 
22280 
22281 /*! \brief Do completion on peer name */
22282 static char *complete_sip_peer(const char *word, int state, int flags2)
22283 {
22284  char *result = NULL;
22285  int wordlen = strlen(word);
22286  int which = 0;
22287  struct ao2_iterator i = ao2_iterator_init(peers, 0);
22288  struct sip_peer *peer;
22289 
22290  while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
22291  /* locking of the object is not required because only the name and flags are being compared */
22292  if (!strncasecmp(word, peer->name, wordlen) &&
22293  (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
22294  ++which > state)
22295  result = ast_strdup(peer->name);
22296  sip_unref_peer(peer, "toss iterator peer ptr before break");
22297  if (result) {
22298  break;
22299  }
22300  }
22302  return result;
22303 }
22304 
22305 /*! \brief Do completion on registered peer name */
22306 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
22307 {
22308  char *result = NULL;
22309  int wordlen = strlen(word);
22310  int which = 0;
22311  struct ao2_iterator i;
22312  struct sip_peer *peer;
22313 
22314  i = ao2_iterator_init(peers, 0);
22315  while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
22316  if (!strncasecmp(word, peer->name, wordlen) &&
22317  (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
22318  ++which > state && peer->expire > -1)
22319  result = ast_strdup(peer->name);
22320  if (result) {
22321  sip_unref_peer(peer, "toss iterator peer ptr before break");
22322  break;
22323  }
22324  sip_unref_peer(peer, "toss iterator peer ptr");
22325  }
22327  return result;
22328 }
22329 
22330 /*! \brief Support routine for 'sip show history' CLI */
22331 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
22332 {
22333  if (pos == 3)
22334  return complete_sipch(line, word, pos, state);
22335 
22336  return NULL;
22337 }
22338 
22339 /*! \brief Support routine for 'sip show peer' CLI */
22340 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
22341 {
22342  if (pos == 3) {
22343  return complete_sip_peer(word, state, 0);
22344  }
22345 
22346  return NULL;
22347 }
22348 
22349 /*! \brief Support routine for 'sip unregister' CLI */
22350 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
22351 {
22352  if (pos == 2)
22353  return complete_sip_registered_peer(word, state, 0);
22354 
22355  return NULL;
22356 }
22357 
22358 /*! \brief Support routine for 'sip notify' CLI */
22359 static char *complete_sip_notify(const char *line, const char *word, int pos, int state)
22360 {
22361  char *c = NULL;
22362 
22363  if (pos == 2) {
22364  int which = 0;
22365  char *cat = NULL;
22366  int wordlen = strlen(word);
22367 
22368  /* do completion for notify type */
22369 
22370  if (!notify_types)
22371  return NULL;
22372 
22373  while ( (cat = ast_category_browse(notify_types, cat)) ) {
22374  if (!strncasecmp(word, cat, wordlen) && ++which > state) {
22375  c = ast_strdup(cat);
22376  break;
22377  }
22378  }
22379  return c;
22380  }
22381 
22382  if (pos > 2)
22383  return complete_sip_peer(word, state, 0);
22384 
22385  return NULL;
22386 }
22387 
22388 /*! \brief Show details of one active dialog */
22389 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
22390 {
22391  struct sip_pvt *cur;
22392  size_t len;
22393  int found = 0;
22394  struct ao2_iterator i;
22395 
22396  switch (cmd) {
22397  case CLI_INIT:
22398  e->command = "sip show channel";
22399  e->usage =
22400  "Usage: sip show channel <call-id>\n"
22401  " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
22402  return NULL;
22403  case CLI_GENERATE:
22404  return complete_sipch(a->line, a->word, a->pos, a->n);
22405  }
22406 
22407  if (a->argc != 4)
22408  return CLI_SHOWUSAGE;
22409  len = strlen(a->argv[3]);
22410 
22411  i = ao2_iterator_init(dialogs, 0);
22412  while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
22413  sip_pvt_lock(cur);
22414 
22415  if (!strncasecmp(cur->callid, a->argv[3], len)) {
22416  struct ast_str *strbuf;
22417  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
22418 
22419  ast_cli(a->fd, "\n");
22420  if (cur->subscribed != NONE) {
22421  ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
22422  } else {
22423  ast_cli(a->fd, " * SIP Call\n");
22424  }
22425  ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
22426  ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
22427  ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? ast_channel_name(cur->owner) : "<none>");
22428  ast_cli(a->fd, " Our Codec Capability: %s\n", ast_format_cap_get_names(cur->caps, &codec_buf));
22429  ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
22430  ast_cli(a->fd, " Their Codec Capability: %s\n", ast_format_cap_get_names(cur->peercaps, &codec_buf));
22431  ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_format_cap_get_names(cur->jointcaps, &codec_buf));
22432  ast_cli(a->fd, " Format: %s\n", cur->owner ? ast_format_cap_get_names(ast_channel_nativeformats(cur->owner), &codec_buf) : "(nothing)" );
22433  ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
22434  ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
22435  ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
22436  ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
22437  ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
22438  ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
22439  ast_cli(a->fd, " Force rport: %s\n", force_rport_string(cur->flags));
22440  if (ast_sockaddr_isnull(&cur->redirip)) {
22441  ast_cli(a->fd,
22442  " Audio IP: %s (local)\n",
22444  } else {
22445  ast_cli(a->fd,
22446  " Audio IP: %s (Outside bridge)\n",
22448  }
22449  ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
22450  ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
22451  ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
22452  if (!ast_strlen_zero(cur->username)) {
22453  ast_cli(a->fd, " Username: %s\n", cur->username);
22454  }
22455  if (!ast_strlen_zero(cur->peername)) {
22456  ast_cli(a->fd, " Peername: %s\n", cur->peername);
22457  }
22458  if (!ast_strlen_zero(cur->uri)) {
22459  ast_cli(a->fd, " Original uri: %s\n", cur->uri);
22460  }
22461  if (!ast_strlen_zero(cur->cid_num)) {
22462  ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
22463  }
22464  ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
22465  ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
22466  ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
22467  if ((strbuf = sip_route_list(&cur->route, 1, 0))) {
22468  ast_cli(a->fd, " Route: %s\n", ast_str_buffer(strbuf));
22469  ast_free(strbuf);
22470  }
22471  ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
22472  ast_cli(a->fd, " SIP Options: ");
22473  if (cur->sipoptions) {
22474  int x;
22475  for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
22476  if (cur->sipoptions & sip_options[x].id)
22477  ast_cli(a->fd, "%s ", sip_options[x].text);
22478  }
22479  ast_cli(a->fd, "\n");
22480  } else {
22481  ast_cli(a->fd, "(none)\n");
22482  }
22483 
22484  if (!cur->stimer) {
22485  ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
22486  } else {
22487  ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
22488  if (cur->stimer->st_active == TRUE) {
22489  ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
22490  ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
22491  ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
22492  ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
22493  ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
22494  ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
22495  ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
22496  ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
22497  }
22498  }
22499 
22500  /* add transport and media types */
22501  ast_cli(a->fd, " Transport: %s\n", ast_transport2str(cur->socket.type));
22502  ast_cli(a->fd, " Media: %s\n", cur->srtp ? "SRTP" : cur->rtp ? "RTP" : "None");
22503 
22504  ast_cli(a->fd, "\n\n");
22505 
22506  found++;
22507  }
22508 
22509  sip_pvt_unlock(cur);
22510 
22511  ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
22512  }
22514 
22515  if (!found) {
22516  ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
22517  }
22518 
22519  return CLI_SUCCESS;
22520 }
22521 
22522 /*! \brief Show history details of one dialog */
22523 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
22524 {
22525  struct sip_pvt *cur;
22526  size_t len;
22527  int found = 0;
22528  struct ao2_iterator i;
22529 
22530  switch (cmd) {
22531  case CLI_INIT:
22532  e->command = "sip show history";
22533  e->usage =
22534  "Usage: sip show history <call-id>\n"
22535  " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
22536  return NULL;
22537  case CLI_GENERATE:
22538  return complete_sip_show_history(a->line, a->word, a->pos, a->n);
22539  }
22540 
22541  if (a->argc != 4) {
22542  return CLI_SHOWUSAGE;
22543  }
22544 
22545  if (!recordhistory) {
22546  ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
22547  }
22548 
22549  len = strlen(a->argv[3]);
22550 
22551  i = ao2_iterator_init(dialogs, 0);
22552  while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
22553  sip_pvt_lock(cur);
22554  if (!strncasecmp(cur->callid, a->argv[3], len)) {
22555  struct sip_history *hist;
22556  int x = 0;
22557 
22558  ast_cli(a->fd, "\n");
22559  if (cur->subscribed != NONE) {
22560  ast_cli(a->fd, " * Subscription\n");
22561  } else {
22562  ast_cli(a->fd, " * SIP Call\n");
22563  }
22564  if (cur->history) {
22565  AST_LIST_TRAVERSE(cur->history, hist, list)
22566  ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
22567  }
22568  if (x == 0) {
22569  ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
22570  }
22571  found++;
22572  }
22573  sip_pvt_unlock(cur);
22574  ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
22575  }
22577 
22578  if (!found) {
22579  ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
22580  }
22581 
22582  return CLI_SUCCESS;
22583 }
22584 
22585 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
22586 static void sip_dump_history(struct sip_pvt *dialog)
22587 {
22588  int x = 0;
22589  struct sip_history *hist;
22590  static int errmsg = 0;
22591 
22592  if (!dialog) {
22593  return;
22594  }
22595 
22596  if (!sipdebug && !DEBUG_ATLEAST(1)) {
22597  if (!errmsg) {
22598  ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
22599  errmsg = 1;
22600  }
22601  return;
22602  }
22603 
22604  ast_log(LOG_DEBUG, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
22605  if (dialog->subscribed) {
22606  ast_log(LOG_DEBUG, " * Subscription\n");
22607  } else {
22608  ast_log(LOG_DEBUG, " * SIP Call\n");
22609  }
22610  if (dialog->history) {
22611  AST_LIST_TRAVERSE(dialog->history, hist, list)
22612  ast_log(LOG_DEBUG, " %-3.3d. %s\n", ++x, hist->event);
22613  }
22614  if (!x) {
22615  ast_log(LOG_DEBUG, "Call '%s' has no history\n", dialog->callid);
22616  }
22617  ast_log(LOG_DEBUG, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
22618 }
22619 
22620 
22621 /*! \brief Receive SIP INFO Message */
22622 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
22623 {
22624  const char *buf = "";
22625  unsigned int event;
22626  const char *c = sip_get_header(req, "Content-Type");
22627 
22628  /* Need to check the media/type */
22629 
22630  if (!strcasecmp(c, "application/hook-flash")) {
22631  /* send a FLASH event, for ATAs that send flash as hook-flash not dtmf */
22632  struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
22633  ast_queue_frame(p->owner, &f);
22634  if (sipdebug) {
22635  ast_verbose("* DTMF-relay event received: FLASH\n");
22636  }
22637  transmit_response(p, "200 OK", req);
22638  return;
22639  }
22640 
22641  if (!strcasecmp(c, "application/dtmf-relay") ||
22642  !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
22643  !strcasecmp(c, "application/dtmf")) {
22644  unsigned int duration = 0;
22645 
22646  if (!p->owner) { /* not a PBX call */
22647  transmit_response(p, "481 Call leg/transaction does not exist", req);
22649  return;
22650  }
22651 
22652  /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
22653  * otherwise use the body as the signal */
22654  if (strcasecmp(c, "application/dtmf")) {
22655  const char *tmp;
22656 
22657  if (ast_strlen_zero(buf = get_content_line(req, "Signal", '='))
22658  && ast_strlen_zero(buf = get_content_line(req, "d", '='))) {
22659  ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
22660  "call %s\n", p->callid);
22661  transmit_response(p, "200 OK", req);
22662  return;
22663  }
22664  if (!ast_strlen_zero((tmp = get_content_line(req, "Duration", '=')))) {
22665  sscanf(tmp, "%30u", &duration);
22666  }
22667  } else {
22668  /* Type is application/dtmf, simply use what's in the message body */
22669  buf = get_content(req);
22670  }
22671 
22672  /* An empty message body requires us to send a 200 OK */
22673  if (ast_strlen_zero(buf)) {
22674  transmit_response(p, "200 OK", req);
22675  return;
22676  }
22677 
22678  if (!duration) {
22679  duration = 100; /* 100 ms */
22680  }
22681 
22682  if (buf[0] == '*') {
22683  event = 10;
22684  } else if (buf[0] == '#') {
22685  event = 11;
22686  } else if (buf[0] == '!') {
22687  event = 16;
22688  } else if ('A' <= buf[0] && buf[0] <= 'D') {
22689  event = 12 + buf[0] - 'A';
22690  } else if ('a' <= buf[0] && buf[0] <= 'd') {
22691  event = 12 + buf[0] - 'a';
22692  } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
22693  ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
22694  "value for INFO message on call %s\n", p->callid);
22695  transmit_response(p, "200 OK", req);
22696  return;
22697  }
22698 
22699  if (event == 16) {
22700  /* send a FLASH event */
22701  struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
22702  ast_queue_frame(p->owner, &f);
22703  if (sipdebug) {
22704  ast_verbose("* DTMF-relay event received: FLASH\n");
22705  }
22706  } else {
22707  /* send a DTMF event */
22708  struct ast_frame f = { AST_FRAME_DTMF, };
22709  if (event < 10) {
22710  f.subclass.integer = '0' + event;
22711  } else if (event == 10) {
22712  f.subclass.integer = '*';
22713  } else if (event == 11) {
22714  f.subclass.integer = '#';
22715  } else {
22716  f.subclass.integer = 'A' + (event - 12);
22717  }
22718  f.len = duration;
22719  ast_queue_frame(p->owner, &f);
22720  if (sipdebug) {
22721  ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
22722  }
22723  }
22724  transmit_response(p, "200 OK", req);
22725  return;
22726  } else if (!strcasecmp(c, "application/media_control+xml")) {
22727  /* Eh, we'll just assume it's a fast picture update for now */
22728  if (p->owner) {
22730  }
22731  transmit_response(p, "200 OK", req);
22732  return;
22733  } else if (!ast_strlen_zero(c = sip_get_header(req, "X-ClientCode"))) {
22734  /* Client code (from SNOM phone) */
22735  if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
22736  if (p->owner) {
22738  }
22739  transmit_response(p, "200 OK", req);
22740  } else {
22741  transmit_response(p, "403 Forbidden", req);
22742  }
22743  return;
22744  } else if (!ast_strlen_zero(c = sip_get_header(req, "Record"))) {
22745  /* INFO messages generated by some phones to start/stop recording
22746  * on phone calls.
22747  */
22748 
22749  char feat[AST_FEATURE_MAX_LEN];
22750  int feat_res = -1;
22751  int j;
22752  struct ast_frame f = { AST_FRAME_DTMF, };
22753  int suppress_warning = 0; /* Supress warning if the feature is blank */
22754 
22755  if (!p->owner) { /* not a PBX call */
22756  transmit_response(p, "481 Call leg/transaction does not exist", req);
22758  return;
22759  }
22760 
22761  /* first, get the feature string, if it exists */
22762  if (p->relatedpeer) {
22763  if (!strcasecmp(c, "on")) {
22765  suppress_warning = 1;
22766  } else {
22767  feat_res = ast_get_feature(p->owner, p->relatedpeer->record_on_feature, feat, sizeof(feat));
22768  }
22769  } else if (!strcasecmp(c, "off")) {
22771  suppress_warning = 1;
22772  } else {
22773  feat_res = ast_get_feature(p->owner, p->relatedpeer->record_off_feature, feat, sizeof(feat));
22774  }
22775  } else {
22776  ast_log(LOG_ERROR, "Received INFO requesting to record with invalid value: %s\n", c);
22777  }
22778  }
22779  if (feat_res || ast_strlen_zero(feat)) {
22780  if (!suppress_warning) {
22781  ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
22782  }
22783  /* 403 means that we don't support this feature, so don't request it again */
22784  transmit_response(p, "403 Forbidden", req);
22785  return;