Re-add LastMsgsSent value for SIP peers
[asterisk/asterisk.git] / channels / sip / include / sip.h
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2010, Digium, Inc.
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*!
18  * \file
19  * \brief chan_sip header file
20  */
21
22 #ifndef _SIP_H
23 #define _SIP_H
24
25 #include "asterisk.h"
26
27 #include "asterisk/stringfields.h"
28 #include "asterisk/linkedlists.h"
29 #include "asterisk/strings.h"
30 #include "asterisk/tcptls.h"
31 #include "asterisk/test.h"
32 #include "asterisk/channel.h"
33 #include "asterisk/app.h"
34 #include "asterisk/astobj.h"
35 #include "asterisk/indications.h"
36 #include "asterisk/security_events.h"
37 #include "asterisk/features.h"
38
39 #ifndef FALSE
40 #define FALSE    0
41 #endif
42
43 #ifndef TRUE
44 #define TRUE     1
45 #endif
46
47 /* Arguments for sip_find_peer */
48 #define FINDUSERS (1 << 0)
49 #define FINDPEERS (1 << 1)
50 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
51
52 #define SIPBUFSIZE      512             /*!< Buffer size for many operations */
53
54 #define XMIT_ERROR      -2
55
56 #define SIP_RESERVED    ";/?:@&=+$,# "  /*!< Reserved characters in the username part of the URI */
57
58 #define DEFAULT_DEFAULT_EXPIRY       120
59 #define DEFAULT_MIN_EXPIRY           60
60 #define DEFAULT_MAX_EXPIRY           3600
61 #define DEFAULT_MWI_EXPIRY           3600
62 #define DEFAULT_REGISTRATION_TIMEOUT 20
63 #define DEFAULT_MAX_FORWARDS         70
64
65 #define DEFAULT_AUTHLIMIT            100
66 #define DEFAULT_AUTHTIMEOUT          30
67
68 /* guard limit must be larger than guard secs */
69 /* guard min must be < 1000, and should be >= 250 */
70 #define EXPIRY_GUARD_SECS    15   /*!< How long before expiry do we reregister */
71 #define EXPIRY_GUARD_LIMIT   30   /*!< Below here, we use EXPIRY_GUARD_PCT instead of EXPIRY_GUARD_SECS */
72 #define EXPIRY_GUARD_MIN     500  /*!< This is the minimum guard time applied. If
73                                    *   GUARD_PCT turns out to be lower than this, it
74                                    *   will use this time instead.
75                                    *   This is in milliseconds.
76                                                                    */
77 #define EXPIRY_GUARD_PCT     0.20 /*!< Percentage of expires timeout to use when
78                                    *   below EXPIRY_GUARD_LIMIT */
79 #define DEFAULT_EXPIRY       900  /*!< Expire slowly */
80
81 #define DEFAULT_QUALIFY_GAP   100
82 #define DEFAULT_QUALIFY_PEERS 1
83
84 #define CALLERID_UNKNOWN          "Anonymous"
85 #define FROMDOMAIN_INVALID        "anonymous.invalid"
86
87 #define DEFAULT_MAXMS             2000        /*!< Qualification: Must be faster than 2 seconds by default */
88 #define DEFAULT_QUALIFYFREQ       60 * 1000   /*!< Qualification: How often to check for the host to be up */
89 #define DEFAULT_FREQ_NOTOK        10 * 1000   /*!< Qualification: How often to check, if the host is down... */
90
91 #define DEFAULT_RETRANS           1000        /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
92 #define DEFAULT_TIMER_T1          500         /*!< SIP timer T1 (according to RFC 3261) */
93 #define SIP_TRANS_TIMEOUT         64 * DEFAULT_TIMER_T1 /*!< SIP request timeout (rfc 3261) 64*T1
94                                                          *  \todo Use known T1 for timeout (peerpoke)
95                                                          */
96 #define DEFAULT_TRANS_TIMEOUT     -1     /*!< Use default SIP transaction timeout */
97 #define PROVIS_KEEPALIVE_TIMEOUT  60000  /*!< How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1) */
98 #define MAX_AUTHTRIES             3      /*!< Try authentication three times, then fail */
99
100 #define SIP_MAX_HEADERS           64     /*!< Max amount of SIP headers to read */
101 #define SIP_MAX_LINES             256    /*!< Max amount of lines in SIP attachment (like SDP) */
102 #define SIP_MIN_PACKET            4096   /*!< Initialize size of memory to allocate for packets */
103 #define MAX_HISTORY_ENTRIES               50     /*!< Max entires in the history list for a sip_pvt */
104
105 #define INITIAL_CSEQ              101    /*!< Our initial sip sequence number */
106
107 #define DEFAULT_MAX_SE            1800   /*!< Session-Timer Default Session-Expires period (RFC 4028) */
108 #define DEFAULT_MIN_SE            90     /*!< Session-Timer Default Min-SE period (RFC 4028) */
109
110 #define SDP_MAX_RTPMAP_CODECS     32     /*!< Maximum number of codecs allowed in received SDP */
111
112 #define RTP     1
113 #define NO_RTP  0
114
115 #define DEC_CALL_LIMIT   0
116 #define INC_CALL_LIMIT   1
117 #define DEC_CALL_RINGING 2
118 #define INC_CALL_RINGING 3
119
120 /*! Define SIP option tags, used in Require: and Supported: headers
121  *  We need to be aware of these properties in the phones to use
122  *  the replace: header. We should not do that without knowing
123  *  that the other end supports it...
124  *  This is nothing we can configure, we learn by the dialog
125  *  Supported: header on the REGISTER (peer) or the INVITE
126  *  (other devices)
127  *  We are not using many of these today, but will in the future.
128  *  This is documented in RFC 3261
129  */
130 #define SUPPORTED       1
131 #define NOT_SUPPORTED   0
132
133 /* SIP options */
134 #define SIP_OPT_REPLACES      (1 << 0)
135 #define SIP_OPT_100REL        (1 << 1)
136 #define SIP_OPT_TIMER         (1 << 2)
137 #define SIP_OPT_EARLY_SESSION (1 << 3)
138 #define SIP_OPT_JOIN          (1 << 4)
139 #define SIP_OPT_PATH          (1 << 5)
140 #define SIP_OPT_PREF          (1 << 6)
141 #define SIP_OPT_PRECONDITION  (1 << 7)
142 #define SIP_OPT_PRIVACY       (1 << 8)
143 #define SIP_OPT_SDP_ANAT      (1 << 9)
144 #define SIP_OPT_SEC_AGREE     (1 << 10)
145 #define SIP_OPT_EVENTLIST     (1 << 11)
146 #define SIP_OPT_GRUU          (1 << 12)
147 #define SIP_OPT_TARGET_DIALOG (1 << 13)
148 #define SIP_OPT_NOREFERSUB    (1 << 14)
149 #define SIP_OPT_HISTINFO      (1 << 15)
150 #define SIP_OPT_RESPRIORITY   (1 << 16)
151 #define SIP_OPT_FROMCHANGE    (1 << 17)
152 #define SIP_OPT_RECLISTINV    (1 << 18)
153 #define SIP_OPT_RECLISTSUB    (1 << 19)
154 #define SIP_OPT_OUTBOUND      (1 << 20)
155 #define SIP_OPT_UNKNOWN       (1 << 21)
156
157 /*! \brief SIP Methods we support
158  *  \todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
159  *  allowsubscribe and allowrefer on in sip.conf.
160  */
161 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH"
162
163 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
164 #define STANDARD_SIP_PORT       5060
165 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
166 #define STANDARD_TLS_PORT       5061
167
168 /*! \note in many SIP headers, absence of a port number implies port 5060,
169  * and this is why we cannot change the above constant.
170  * There is a limited number of places in asterisk where we could,
171  * in principle, use a different "default" port number, but
172  * we do not support this feature at the moment.
173  * You can run Asterisk with SIP on a different port with a configuration
174  * option. If you change this value in the source code, the signalling will be incorrect.
175  *
176  */
177
178 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration
179
180    These are default values in the source. There are other recommended values in the
181    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
182    yet encouraging new behaviour on new installations
183  */
184 /*@{*/
185 #define DEFAULT_CONTEXT        "default"  /*!< The default context for [general] section as well as devices */
186 #define DEFAULT_RECORD_FEATURE   "automon"  /*!< The default feature specified for use with INFO */
187 #define DEFAULT_MOHINTERPRET   "default"  /*!< The default music class */
188 #define DEFAULT_MOHSUGGEST     ""
189 #define DEFAULT_VMEXTEN        "asterisk" /*!< Default voicemail extension */
190 #define DEFAULT_CALLERID       "asterisk" /*!< Default caller ID */
191 #define DEFAULT_MWI_FROM       ""
192 #define DEFAULT_NOTIFYMIME     "application/simple-message-summary"
193 #define DEFAULT_ALLOWGUEST     TRUE
194 #define DEFAULT_RTPKEEPALIVE   0      /*!< Default RTPkeepalive setting */
195 #define DEFAULT_CALLCOUNTER    FALSE   /*!< Do not enable call counters by default */
196 #define DEFAULT_SRVLOOKUP      TRUE    /*!< Recommended setting is ON */
197 #define DEFAULT_COMPACTHEADERS FALSE  /*!< Send compact (one-character) SIP headers. Default off */
198 #define DEFAULT_TOS_SIP        0      /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
199 #define DEFAULT_TOS_AUDIO      0      /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
200 #define DEFAULT_TOS_VIDEO      0      /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
201 #define DEFAULT_TOS_TEXT       0      /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
202 #define DEFAULT_COS_SIP        4      /*!< Level 2 class of service for SIP signalling */
203 #define DEFAULT_COS_AUDIO      5      /*!< Level 2 class of service for audio media  */
204 #define DEFAULT_COS_VIDEO      6      /*!< Level 2 class of service for video media */
205 #define DEFAULT_COS_TEXT       5      /*!< Level 2 class of service for text media (T.140) */
206 #define DEFAULT_ALLOW_EXT_DOM  TRUE    /*!< Allow external domains */
207 #define DEFAULT_REALM          "asterisk" /*!< Realm for HTTP digest authentication */
208 #define DEFAULT_DOMAINSASREALM FALSE    /*!< Use the domain option to guess the realm for registration and invite requests */
209 #define DEFAULT_NOTIFYRINGING  TRUE     /*!< Notify devicestate system on ringing state */
210 #define DEFAULT_NOTIFYCID      DISABLED /*!< Include CID with ringing notifications */
211 #define DEFAULT_PEDANTIC       TRUE     /*!< Follow SIP standards for dialog matching */
212 #define DEFAULT_AUTOCREATEPEER AUTOPEERS_DISABLED    /*!< Don't create peers automagically */
213 #define DEFAULT_MATCHEXTERNADDRLOCALLY FALSE /*!< Match extern IP locally default setting */
214 #define DEFAULT_QUALIFY        FALSE    /*!< Don't monitor devices */
215 #define DEFAULT_KEEPALIVE      0        /*!< Don't send keep alive packets */
216 #define DEFAULT_KEEPALIVE_INTERVAL 60   /*!< Send keep alive packets at 60 second intervals */
217 #define DEFAULT_CALLEVENTS     FALSE    /*!< Extra manager SIP call events */
218 #define DEFAULT_ALWAYSAUTHREJECT  TRUE  /*!< Don't reject authentication requests always */
219 #define DEFAULT_AUTH_OPTIONS  FALSE
220 #define DEFAULT_AUTH_MESSAGE  TRUE
221 #define DEFAULT_ACCEPT_OUTOFCALL_MESSAGE TRUE
222 #define DEFAULT_REGEXTENONQUALIFY FALSE
223 #define DEFAULT_LEGACY_USEROPTION_PARSING FALSE
224 #define DEFAULT_SEND_DIVERSION TRUE
225 #define DEFAULT_T1MIN             100   /*!< 100 MS for minimal roundtrip time */
226 #define DEFAULT_MAX_CALL_BITRATE (384)  /*!< Max bitrate for video */
227 #ifndef DEFAULT_USERAGENT
228 #define DEFAULT_USERAGENT  "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
229 #define DEFAULT_SDPSESSION "Asterisk PBX"  /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
230 #define DEFAULT_SDPOWNER   "root"          /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
231 #define DEFAULT_ENGINE     "asterisk"      /*!< Default RTP engine to use for sessions */
232 #define DEFAULT_STORE_SIP_CAUSE FALSE      /*!< Don't store HASH(SIP_CAUSE,<channel name>) for channels by default */
233 #endif
234 /*@}*/
235
236 /*! \name SIPflags
237         Various flags for the flags field in the pvt structure
238         Trying to sort these up (one or more of the following):
239         D: Dialog
240         P: Peer/user
241         G: Global flag
242         When flags are used by multiple structures, it is important that
243         they have a common layout so it is easy to copy them.
244 */
245 /*@{*/
246 #define SIP_OUTGOING        (1 << 0) /*!< D: Direction of the last transaction in this dialog */
247 #define SIP_OFFER_CC        (1 << 1) /*!< D: Offer CC on subsequent responses */
248 #define SIP_RINGING         (1 << 2) /*!< D: Have sent 180 ringing */
249 #define SIP_PROGRESS_SENT   (1 << 3) /*!< D: Have sent 183 message progress */
250 #define SIP_NEEDREINVITE    (1 << 4) /*!< D: Do we need to send another reinvite? */
251 #define SIP_PENDINGBYE      (1 << 5) /*!< D: Need to send bye after we ack? */
252 #define SIP_GOTREFER        (1 << 6) /*!< D: Got a refer? */
253 #define SIP_CALL_LIMIT      (1 << 7) /*!< D: Call limit enforced for this call */
254 #define SIP_INC_COUNT       (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
255 #define SIP_INC_RINGING     (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
256 #define SIP_DEFER_BYE_ON_TRANSFER       (1 << 10) /*!< D: Do not hangup at first ast_hangup */
257
258 #define SIP_PROMISCREDIR    (1 << 11) /*!< DP: Promiscuous redirection */
259 #define SIP_TRUSTRPID       (1 << 12) /*!< DP: Trust RPID headers? */
260 #define SIP_USEREQPHONE     (1 << 13) /*!< DP: Add user=phone to numeric URI. Default off */
261 #define SIP_USECLIENTCODE   (1 << 14) /*!< DP: Trust X-ClientCode info message */
262
263 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
264 #define SIP_DTMF            (7 << 15) /*!< DP: DTMF Support: five settings, uses three bits */
265 #define SIP_DTMF_RFC2833    (0 << 15) /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
266 #define SIP_DTMF_INBAND     (1 << 15) /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
267 #define SIP_DTMF_INFO       (2 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" */
268 #define SIP_DTMF_AUTO       (3 << 15) /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
269 #define SIP_DTMF_SHORTINFO  (4 << 15) /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
270
271 /* NAT settings */
272 #define SIP_NAT_FORCE_RPORT     (1 << 18) /*!< DP: Force rport even if not present in the request */
273 #define SIP_NAT_RPORT_PRESENT   (1 << 19) /*!< DP: rport was present in the request */
274
275 /* re-INVITE related settings */
276 #define SIP_REINVITE         (7 << 20) /*!< DP: four settings, uses three bits */
277 #define SIP_REINVITE_NONE    (0 << 20) /*!< DP: no reinvite allowed */
278 #define SIP_DIRECT_MEDIA     (1 << 20) /*!< DP: allow peers to be reinvited to send media directly p2p */
279 #define SIP_DIRECT_MEDIA_NAT (2 << 20) /*!< DP: allow media reinvite when new peer is behind NAT */
280 #define SIP_REINVITE_UPDATE  (4 << 20) /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
281
282 /* "insecure" settings - see insecure2str() */
283 #define SIP_INSECURE         (3 << 23)    /*!< DP: three settings, uses two bits */
284 #define SIP_INSECURE_NONE    (0 << 23)    /*!< DP: secure mode */
285 #define SIP_INSECURE_PORT    (1 << 23)    /*!< DP: don't require matching port for incoming requests */
286 #define SIP_INSECURE_INVITE  (1 << 24)    /*!< DP: don't require authentication for incoming INVITEs */
287
288 /* Sending PROGRESS in-band settings */
289 #define SIP_PROG_INBAND        (3 << 25) /*!< DP: three settings, uses two bits */
290 #define SIP_PROG_INBAND_NEVER  (0 << 25)
291 #define SIP_PROG_INBAND_NO     (1 << 25)
292 #define SIP_PROG_INBAND_YES    (2 << 25)
293
294 #define SIP_SENDRPID         (3 << 29) /*!< DP: Remote Party-ID Support */
295 #define SIP_SENDRPID_NO      (0 << 29)
296 #define SIP_SENDRPID_PAI     (1 << 29) /*!< Use "P-Asserted-Identity" for rpid */
297 #define SIP_SENDRPID_RPID    (2 << 29) /*!< Use "Remote-Party-ID" for rpid */
298 #define SIP_G726_NONSTANDARD (1 << 31) /*!< DP: Use non-standard packing for G726-32 data */
299
300 /*! \brief Flags to copy from peer/user to dialog */
301 #define SIP_FLAGS_TO_COPY \
302         (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
303          SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT_FORCE_RPORT | SIP_G726_NONSTANDARD | \
304          SIP_USEREQPHONE | SIP_INSECURE)
305 /*@}*/
306
307 /*! \name SIPflags2
308         a second page of flags (for flags[1] */
309 /*@{*/
310 /* realtime flags */
311 #define SIP_PAGE2_RTCACHEFRIENDS            (1 <<  0)   /*!< GP: Should we keep RT objects in memory for extended time? */
312 #define SIP_PAGE2_RTAUTOCLEAR               (1 <<  1)   /*!< GP: Should we clean memory from peers after expiry? */
313 #define SIP_PAGE2_RPID_UPDATE               (1 <<  2)
314 #define SIP_PAGE2_Q850_REASON               (1 <<  3)   /*!< DP: Get/send cause code via Reason header */
315 #define SIP_PAGE2_SYMMETRICRTP              (1 <<  4)   /*!< GDP: Whether symmetric RTP is enabled or not */
316 #define SIP_PAGE2_STATECHANGEQUEUE          (1 <<  5)   /*!< D: Unsent state pending change exists */
317 #define SIP_PAGE2_CONNECTLINEUPDATE_PEND    (1 <<  6)
318 #define SIP_PAGE2_RPID_IMMEDIATE            (1 <<  7)
319 #define SIP_PAGE2_RPORT_PRESENT             (1 <<  8)   /*!< Was rport received in the Via header? */
320 #define SIP_PAGE2_PREFERRED_CODEC           (1 <<  9)   /*!< GDP: Only respond with single most preferred joint codec */
321 #define SIP_PAGE2_VIDEOSUPPORT              (1 << 10)   /*!< DP: Video supported if offered? */
322 #define SIP_PAGE2_TEXTSUPPORT               (1 << 11)   /*!< GDP: Global text enable */
323 #define SIP_PAGE2_ALLOWSUBSCRIBE            (1 << 12)   /*!< GP: Allow subscriptions from this peer? */
324
325 #define SIP_PAGE2_ALLOWOVERLAP              (3 << 13)   /*!< DP: Allow overlap dialing ? */
326 #define SIP_PAGE2_ALLOWOVERLAP_NO           (0 << 13)   /*!< No, terminate with 404 Not found */
327 #define SIP_PAGE2_ALLOWOVERLAP_YES          (1 << 13)   /*!< Yes, using the 484 Address Incomplete response */
328 #define SIP_PAGE2_ALLOWOVERLAP_DTMF         (2 << 13)   /*!< Yes, using the DTMF transmission through Early Media */
329 #define SIP_PAGE2_ALLOWOVERLAP_SPARE        (3 << 13)   /*!< Spare (reserved for another dialling transmission mechanisms like KPML) */
330
331 #define SIP_PAGE2_SUBSCRIBEMWIONLY          (1 << 15)   /*!< GP: Only issue MWI notification if subscribed to */
332 #define SIP_PAGE2_IGNORESDPVERSION          (1 << 16)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
333
334 #define SIP_PAGE2_T38SUPPORT                (3 << 17)   /*!< GDP: T.38 Fax Support */
335 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 17)   /*!< GDP: T.38 Fax Support (no error correction) */
336 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC      (2 << 17)   /*!< GDP: T.38 Fax Support (FEC error correction) */
337 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 17)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
338
339 #define SIP_PAGE2_CALL_ONHOLD               (3 << 19)   /*!< D: Call hold states: */
340 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE        (1 << 19)   /*!< D: Active hold */
341 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR        (2 << 19)   /*!< D: One directional hold */
342 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE      (3 << 19)   /*!< D: Inactive hold */
343
344 #define SIP_PAGE2_RFC2833_COMPENSATE        (1 << 21)   /*!< DP: Compensate for buggy RFC2833 implementations */
345 #define SIP_PAGE2_BUGGY_MWI                 (1 << 22)   /*!< DP: Buggy CISCO MWI fix */
346 #define SIP_PAGE2_DIALOG_ESTABLISHED        (1 << 23)   /*!< 29: Has a dialog been established? */
347
348 #define SIP_PAGE2_FAX_DETECT                (3 << 24)   /*!< DP: Fax Detection support */
349 #define SIP_PAGE2_FAX_DETECT_CNG            (1 << 24)   /*!< DP: Fax Detection support - detect CNG in audio */
350 #define SIP_PAGE2_FAX_DETECT_T38            (2 << 24)   /*!< DP: Fax Detection support - detect T.38 reinvite from peer */
351 #define SIP_PAGE2_FAX_DETECT_BOTH           (3 << 24)   /*!< DP: Fax Detection support - detect both */
352
353 #define SIP_PAGE2_UDPTL_DESTINATION         (1 << 26)   /*!< DP: Use source IP of RTP as destination if NAT is enabled */
354 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS       (1 << 27)   /*!< DP: Always set up video, even if endpoints don't support it */
355 #define SIP_PAGE2_HAVEPEERCONTEXT           (1 << 28)   /*< Are we associated with a configured peer context? */
356 #define SIP_PAGE2_USE_SRTP                  (1 << 29)   /*!< DP: Whether we should offer (only)  SRTP */
357
358 #define SIP_PAGE2_FLAGS_TO_COPY \
359         (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
360         SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
361         SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
362         SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | SIP_PAGE2_PREFERRED_CODEC | \
363         SIP_PAGE2_RPID_IMMEDIATE | SIP_PAGE2_RPID_UPDATE | SIP_PAGE2_SYMMETRICRTP |\
364         SIP_PAGE2_Q850_REASON | SIP_PAGE2_HAVEPEERCONTEXT | SIP_PAGE2_USE_SRTP)
365
366
367 #define SIP_PAGE3_SNOM_AOC               (1 << 0)  /*!< DPG: Allow snom aoc messages */
368 #define SIP_PAGE3_SRTP_TAG_32            (1 << 1)  /*!< DP: Use a 32bit auth tag in INVITE not 80bit */
369 #define SIP_PAGE3_NAT_AUTO_RPORT         (1 << 2)  /*!< DGP: Set SIP_NAT_FORCE_RPORT when NAT is detected */
370 #define SIP_PAGE3_NAT_AUTO_COMEDIA       (1 << 3)  /*!< DGP: Set SIP_PAGE2_SYMMETRICRTP when NAT is detected */
371
372 #define SIP_PAGE3_FLAGS_TO_COPY \
373         (SIP_PAGE3_SNOM_AOC | SIP_PAGE3_SRTP_TAG_32 | SIP_PAGE3_NAT_AUTO_RPORT | SIP_PAGE3_NAT_AUTO_COMEDIA)
374
375 #define CHECK_AUTH_BUF_INITLEN   256
376
377 /*@}*/
378
379 /*----------------------------------------------------------*/
380 /*----                    ENUMS                         ----*/
381 /*----------------------------------------------------------*/
382
383 /*! \brief Authorization scheme for call transfers
384  *
385  * \note Not a bitfield flag, since there are plans for other modes,
386  * like "only allow transfers for authenticated devices"
387  */
388 enum transfermodes {
389         TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
390         TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
391 };
392
393 /*! \brief The result of a lot of functions */
394 enum sip_result {
395         AST_SUCCESS = 0,                /*!< FALSE means success, funny enough */
396         AST_FAILURE = -1,               /*!< Failure code */
397 };
398
399 /*! \brief The results from handling an invite request
400  *
401  * \note Start at these values so we do not conflict with
402  * check_auth_results values when returning from
403  * handle_request_invite.  check_auth_results only returned during
404  * authentication routines
405  * */
406 enum inv_req_result {
407         INV_REQ_SUCCESS = 11,    /*!< Success code */
408         INV_REQ_FAILED  = 10,    /*!< Failure code */
409         INV_REQ_ERROR   = 9,     /*!< Error code */
410 };
411
412 /*! \brief States for the INVITE transaction, not the dialog
413  *  \note this is for the INVITE that sets up the dialog
414  */
415 enum invitestates {
416         INV_NONE = 0,         /*!< No state at all, maybe not an INVITE dialog */
417         INV_CALLING = 1,      /*!< Invite sent, no answer */
418         INV_PROCEEDING = 2,   /*!< We got/sent 1xx message */
419         INV_EARLY_MEDIA = 3,  /*!< We got 18x message with to-tag back */
420         INV_COMPLETED = 4,    /*!< Got final response with error. Wait for ACK, then CONFIRMED */
421         INV_CONFIRMED = 5,    /*!< Confirmed response - we've got an ack (Incoming calls only) */
422         INV_TERMINATED = 6,   /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done
423                                      The only way out of this is a BYE from one side */
424         INV_CANCELLED = 7,    /*!< Transaction cancelled by client or server in non-terminated state */
425 };
426
427 /*! \brief When sending a SIP message, we can send with a few options, depending on
428  * type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
429  * where the original response would be sent RELIABLE in an INVITE transaction
430  */
431 enum xmittype {
432         XMIT_CRITICAL = 2,    /*!< Transmit critical SIP message reliably, with re-transmits.
433                                *   If it fails, it's critical and will cause a teardown of the session */
434         XMIT_RELIABLE = 1,    /*!< Transmit SIP message reliably, with re-transmits */
435         XMIT_UNRELIABLE = 0,  /*!< Transmit SIP message without bothering with re-transmits */
436 };
437
438 /*! \brief Results from the parse_register() function */
439 enum parse_register_result {
440         PARSE_REGISTER_DENIED,
441         PARSE_REGISTER_FAILED,
442         PARSE_REGISTER_UPDATE,
443         PARSE_REGISTER_QUERY,
444 };
445
446 /*! \brief Type of subscription, based on the packages we do support, see \ref subscription_types */
447 enum subscriptiontype {
448         NONE = 0,
449         XPIDF_XML,
450         DIALOG_INFO_XML,
451         CPIM_PIDF_XML,
452         PIDF_XML,
453         MWI_NOTIFICATION,
454         CALL_COMPLETION,
455 };
456
457 /*! \brief The number of media types in enum \ref media_type below. */
458 #define OFFERED_MEDIA_COUNT     4
459
460 /*! \brief Media types generate different "dummy answers" for not accepting the offer of 
461         a media stream. We need to add definitions for each RTP profile. Secure RTP is not
462         the same as normal RTP and will require a new definition */
463 enum media_type {
464         SDP_AUDIO,   /*!< RTP/AVP Audio */
465         SDP_VIDEO,   /*!< RTP/AVP Video */
466         SDP_IMAGE,   /*!< Image udptl, not TCP or RTP */
467         SDP_TEXT,    /*!< RTP/AVP Realtime Text */
468 };
469
470 /*! \brief Authentication types - proxy or www authentication
471  *  \note Endpoints, like Asterisk, should always use WWW authentication to
472  *  allow multiple authentications in the same call - to the proxy and
473  *  to the end point.
474  */
475 enum sip_auth_type {
476         PROXY_AUTH = 407,
477         WWW_AUTH = 401,
478 };
479
480 /*! \brief Result from get_destination function */
481 enum sip_get_dest_result {
482         SIP_GET_DEST_EXTEN_MATCHMORE = 1,
483         SIP_GET_DEST_EXTEN_FOUND = 0,
484         SIP_GET_DEST_EXTEN_NOT_FOUND = -1,
485         SIP_GET_DEST_REFUSED = -2,
486         SIP_GET_DEST_INVALID_URI = -3,
487 };
488
489 /*! \brief Authentication result from check_auth* functions */
490 enum check_auth_result {
491         AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
492                 /* XXX maybe this is the same as AUTH_NOT_FOUND */
493         AUTH_SUCCESSFUL = 0,
494         AUTH_CHALLENGE_SENT = 1,
495         AUTH_SECRET_FAILED = -1,
496         AUTH_USERNAME_MISMATCH = -2,
497         AUTH_NOT_FOUND = -3,    /*!< returned by register_verify */
498         AUTH_FAKE_AUTH = -4,
499         AUTH_UNKNOWN_DOMAIN = -5,
500         AUTH_PEER_NOT_DYNAMIC = -6,
501         AUTH_ACL_FAILED = -7,
502         AUTH_BAD_TRANSPORT = -8,
503         AUTH_RTP_FAILED = -9,
504         AUTH_SESSION_LIMIT = -10,
505 };
506
507 /*! \brief States for outbound registrations (with register= lines in sip.conf */
508 enum sipregistrystate {
509         REG_STATE_UNREGISTERED = 0,     /*!< We are not registered
510                  *  \note Initial state. We should have a timeout scheduled for the initial
511                  * (or next) registration transmission, calling sip_reregister
512                  */
513
514         REG_STATE_REGSENT,      /*!< Registration request sent
515                  * \note sent initial request, waiting for an ack or a timeout to
516                  * retransmit the initial request.
517                 */
518
519         REG_STATE_AUTHSENT,     /*!< We have tried to authenticate
520                  * \note entered after transmit_register with auth info,
521                  * waiting for an ack.
522                  */
523
524         REG_STATE_REGISTERED,   /*!< Registered and done */
525
526         REG_STATE_REJECTED,     /*!< Registration rejected
527                  * \note only used when the remote party has an expire larger than
528                  * our max-expire. This is a final state from which we do not
529                  * recover (not sure how correctly).
530                  */
531
532         REG_STATE_TIMEOUT,      /*!< Registration timed out
533                 * \note XXX unused */
534
535         REG_STATE_NOAUTH,       /*!< We have no accepted credentials
536                  * \note fatal - no chance to proceed */
537
538         REG_STATE_FAILED,       /*!< Registration failed after several tries
539                  * \note fatal - no chance to proceed */
540 };
541
542 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
543 enum st_mode {
544         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */
545         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
546         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
547         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
548 };
549
550 /*! \brief The entity playing the refresher role for Session-Timers */
551 enum st_refresher {
552         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
553         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
554         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
555 };
556
557 /*! \brief Define some implemented SIP transports
558         \note Asterisk does not support SCTP or UDP/DTLS
559 */
560 enum sip_transport {
561         SIP_TRANSPORT_UDP = 1,         /*!< Unreliable transport for SIP, needs retransmissions */
562         SIP_TRANSPORT_TCP = 1 << 1,    /*!< Reliable, but unsecure */
563         SIP_TRANSPORT_TLS = 1 << 2,    /*!< TCP/TLS - reliable and secure transport for signalling */
564 };
565
566 /*! \brief Automatic peer registration behavior
567 */
568 enum autocreatepeer_mode {
569         AUTOPEERS_DISABLED = 0,         /*!< Automatic peer creation disabled */
570         AUTOPEERS_VOLATILE,                     /*!< Automatic peers dropped on sip reload (pre-1.8 behavior) */
571         AUTOPEERS_PERSIST                       /*!< Automatic peers survive sip configuration reload */
572 };
573
574 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
575 enum can_create_dialog {
576         CAN_NOT_CREATE_DIALOG,
577         CAN_CREATE_DIALOG,
578         CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
579 };
580
581 /*! \brief SIP Request methods known by Asterisk
582  *
583  * \note Do _NOT_ make any changes to this enum, or the array following it;
584  * if you think you are doing the right thing, you are probably
585  * not doing the right thing. If you think there are changes
586  * needed, get someone else to review them first _before_
587  * submitting a patch. If these two lists do not match properly
588  * bad things will happen.
589  */
590 enum sipmethod {
591         SIP_UNKNOWN,    /*!< Unknown response */
592         SIP_RESPONSE,   /*!< Not request, response to outbound request */
593         SIP_REGISTER,   /*!< Registration to the mothership, tell us where you are located */
594         SIP_OPTIONS,    /*!< Check capabilities of a device, used for "ping" too */
595         SIP_NOTIFY,     /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
596         SIP_INVITE,     /*!< Set up a session */
597         SIP_ACK,        /*!< End of a three-way handshake started with INVITE. */
598         SIP_PRACK,      /*!< Reliable pre-call signalling. Not supported in Asterisk. */
599         SIP_BYE,        /*!< End of a session */
600         SIP_REFER,      /*!< Refer to another URI (transfer) */
601         SIP_SUBSCRIBE,  /*!< Subscribe for updates (voicemail, session status, device status, presence) */
602         SIP_MESSAGE,    /*!< Text messaging */
603         SIP_UPDATE,     /*!< Update a dialog. We can send UPDATE; but not accept it */
604         SIP_INFO,       /*!< Information updates during a session */
605         SIP_CANCEL,     /*!< Cancel an INVITE */
606         SIP_PUBLISH,    /*!< Not supported in Asterisk */
607         SIP_PING,       /*!< Not supported at all, no standard but still implemented out there */
608 };
609
610 /*! \brief Settings for the 'notifycid' option, see sip.conf.sample for details. */
611 enum notifycid_setting {
612         DISABLED       = 0,
613         ENABLED        = 1,
614         IGNORE_CONTEXT = 2,
615 };
616
617 /*! \brief Modes for SIP domain handling in the PBX */
618 enum domain_mode {
619         SIP_DOMAIN_AUTO,      /*!< This domain is auto-configured */
620         SIP_DOMAIN_CONFIG,    /*!< This domain is from configuration */
621 };
622
623 /*! \brief debugging state
624  * We store separately the debugging requests from the config file
625  * and requests from the CLI. Debugging is enabled if either is set
626  * (which means that if sipdebug is set in the config file, we can
627  * only turn it off by reloading the config).
628  */
629 enum sip_debug_e {
630         sip_debug_none = 0,
631         sip_debug_config = 1,
632         sip_debug_console = 2,
633 };
634
635 /*! \brief T38 States for a call */
636 enum t38state {
637         T38_DISABLED = 0,     /*!< Not enabled */
638         T38_LOCAL_REINVITE,   /*!< Offered from local - REINVITE */
639         T38_PEER_REINVITE,    /*!< Offered from peer - REINVITE */
640         T38_ENABLED,          /*!< Negotiated (enabled) */
641         T38_REJECTED          /*!< Refused */
642 };
643
644 /*! \brief Parameters to know status of transfer */
645 enum referstatus {
646         REFER_IDLE,           /*!< No REFER is in progress */
647         REFER_SENT,           /*!< Sent REFER to transferee */
648         REFER_RECEIVED,       /*!< Received REFER from transferrer */
649         REFER_CONFIRMED,      /*!< Refer confirmed with a 100 TRYING (unused) */
650         REFER_ACCEPTED,       /*!< Accepted by transferee */
651         REFER_RINGING,        /*!< Target Ringing */
652         REFER_200OK,          /*!< Answered by transfer target */
653         REFER_FAILED,         /*!< REFER declined - go on */
654         REFER_NOAUTH          /*!< We had no auth for REFER */
655 };
656
657 enum sip_peer_type {
658         SIP_TYPE_PEER = (1 << 0),
659         SIP_TYPE_USER = (1 << 1),
660 };
661
662 enum t38_action_flag {
663         SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
664         SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
665         SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
666 };
667
668 enum sip_tcptls_alert {
669         TCPTLS_ALERT_DATA,  /*!< \brief There is new data to be sent out */
670         TCPTLS_ALERT_STOP,  /*!< \brief A request to stop the tcp_handler thread */
671 };
672
673 enum digest_keys {
674         K_RESP,
675         K_URI,
676         K_USER,
677         K_NONCE,
678         K_LAST
679 };
680
681 /*----------------------------------------------------------*/
682 /*----                    STRUCTS                       ----*/
683 /*----------------------------------------------------------*/
684
685 /*! \brief definition of a sip proxy server
686  *
687  * For outbound proxies, a sip_peer will contain a reference to a
688  * dynamically allocated instance of a sip_proxy. A sip_pvt may also
689  * contain a reference to a peer's outboundproxy, or it may contain
690  * a reference to the sip_cfg.outboundproxy.
691  */
692 struct sip_proxy {
693         char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
694         struct ast_sockaddr ip;          /*!< Currently used IP address and port */
695         int port;
696         time_t last_dnsupdate;          /*!< When this was resolved */
697         enum sip_transport transport;
698         int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
699         /* Room for a SRV record chain based on the name */
700 };
701
702 /*! \brief argument for the 'show channels|subscriptions' callback. */
703 struct __show_chan_arg {
704         int fd;
705         int subscriptions;
706         int numchans;   /* return value */
707 };
708
709 /*! \name GlobalSettings
710         Global settings apply to the channel (often settings you can change in the general section
711         of sip.conf
712 */
713 /*@{*/
714 /*! \brief a place to store all global settings for the sip channel driver
715
716         These are settings that will be possibly to apply on a group level later on.
717         \note Do not add settings that only apply to the channel itself and can't
718               be applied to devices (trunks, services, phones)
719 */
720 struct sip_settings {
721         int peer_rtupdate;          /*!< G: Update database with registration data for peer? */
722         int rtsave_sysname;         /*!< G: Save system name at registration? */
723         int ignore_regexpire;       /*!< G: Ignore expiration of peer  */
724         int rtautoclear;            /*!< Realtime ?? */
725         int directrtpsetup;         /*!< Enable support for Direct RTP setup (no re-invites) */
726         int pedanticsipchecking;    /*!< Extra checking ?  Default off */
727         enum autocreatepeer_mode autocreatepeer;  /*!< Auto creation of peers at registration? Default off. */
728         int srvlookup;              /*!< SRV Lookup on or off. Default is on */
729         int allowguest;             /*!< allow unauthenticated peers to connect? */
730         int alwaysauthreject;       /*!< Send 401 Unauthorized for all failing requests */
731         int auth_options_requests;  /*!< Authenticate OPTIONS requests */
732         int auth_message_requests;  /*!< Authenticate MESSAGE requests */
733         int accept_outofcall_message; /*!< Accept MESSAGE outside of a call */
734         int compactheaders;         /*!< send compact sip headers */
735         int allow_external_domains; /*!< Accept calls to external SIP domains? */
736         int callevents;             /*!< Whether we send manager events or not */
737         int regextenonqualify;      /*!< Whether to add/remove regexten when qualifying peers */
738         int legacy_useroption_parsing; /*!< Whether to strip useroptions in URI via semicolons */
739         int send_diversion;             /*!< Whether to Send SIP Diversion headers */
740         int matchexternaddrlocally;   /*!< Match externaddr/externhost setting against localnet setting */
741         char regcontext[AST_MAX_CONTEXT];  /*!< Context for auto-extensions */
742         char messagecontext[AST_MAX_CONTEXT];  /*!< Default context for out of dialog msgs. */
743         unsigned int disallowed_methods;   /*!< methods that we should never try to use */
744         int notifyringing;          /*!< Send notifications on ringing */
745         int notifyhold;             /*!< Send notifications on hold */
746         enum notifycid_setting notifycid;  /*!< Send CID with ringing notifications */
747         enum transfermodes allowtransfer;  /*!< SIP Refer restriction scheme */
748         int allowsubscribe;         /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE
749                                          the global setting is in globals_flags[1] */
750         char realm[MAXHOSTNAMELEN]; /*!< Default realm */
751         int domainsasrealm;         /*!< Use domains lists as realms */
752         struct sip_proxy outboundproxy; /*!< Outbound proxy */
753         char default_context[AST_MAX_CONTEXT];
754         char default_subscribecontext[AST_MAX_CONTEXT];
755         char default_record_on_feature[FEATURE_MAX_LEN];
756         char default_record_off_feature[FEATURE_MAX_LEN];
757         struct ast_ha *contact_ha;  /*! \brief Global list of addresses dynamic peers are not allowed to use */
758         struct ast_format_cap *caps; /*!< Supported codecs */
759         int tcp_enabled;
760         int default_max_forwards;    /*!< Default max forwards (SIP Anti-loop) */
761 };
762
763 /*! \brief The SIP socket definition */
764 struct sip_socket {
765         enum sip_transport type;  /*!< UDP, TCP or TLS */
766         int fd;                   /*!< Filed descriptor, the actual socket */
767         uint16_t port;
768         struct ast_tcptls_session_instance *tcptls_session;  /* If tcp or tls, a socket manager */
769 };
770
771 /*! \brief sip_request: The data grabbed from the UDP socket
772  *
773  * \verbatim
774  * Incoming messages: we first store the data from the socket in data[],
775  * adding a trailing \0 to make string parsing routines happy.
776  * Then call parse_request() and req.method = find_sip_method();
777  * to initialize the other fields. The \r\n at the end of each line is
778  * replaced by \0, so that data[] is not a conforming SIP message anymore.
779  * After this processing, rlPart1 is set to non-NULL to remember
780  * that we can run get_header() on this kind of packet.
781  *
782  * parse_request() splits the first line as follows:
783  * Requests have in the first line      method uri SIP/2.0
784  *      rlPart1 = method; rlPart2 = uri;
785  * Responses have in the first line     SIP/2.0 NNN description
786  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
787  *
788  * For outgoing packets, we initialize the fields with init_req() or init_resp()
789  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
790  * and then fill the rest with add_header() and add_line().
791  * The \r\n at the end of the line are still there, so the get_header()
792  * and similar functions don't work on these packets.
793  * \endverbatim
794  */
795 struct sip_request {
796         ptrdiff_t rlPart1;      /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
797         ptrdiff_t rlPart2;      /*!< Offset of the Request URI or Response Status */
798         int headers;            /*!< # of SIP Headers */
799         int method;             /*!< Method of this request */
800         int lines;              /*!< Body Content */
801         unsigned int sdp_start; /*!< the line number where the SDP begins */
802         unsigned int sdp_count; /*!< the number of lines of SDP */
803         char debug;             /*!< print extra debugging if non zero */
804         char has_to_tag;        /*!< non-zero if packet has To: tag */
805         char ignore;            /*!< if non-zero This is a re-transmit, ignore it */
806         char authenticated;     /*!< non-zero if this request was authenticated */
807         ptrdiff_t header[SIP_MAX_HEADERS]; /*!< Array of offsets into the request string of each SIP header*/
808         ptrdiff_t line[SIP_MAX_LINES];     /*!< Array of offsets into the request string of each SDP line*/
809         struct ast_str *data;   
810         struct ast_str *content;
811         /* XXX Do we need to unref socket.ser when the request goes away? */
812         struct sip_socket socket;          /*!< The socket used for this request */
813         AST_LIST_ENTRY(sip_request) next;
814 };
815
816 /* \brief given a sip_request and an offset, return the char * that resides there
817  *
818  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
819  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
820  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
821  * provided to retrieve the string at a particular offset within the request's buffer
822  */
823 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
824
825 /*! \brief structure used in transfers */
826 struct sip_dual {
827         struct ast_channel *chan1;   /*!< First channel involved */
828         struct ast_channel *chan2;   /*!< Second channel involved */
829         struct sip_request req;      /*!< Request that caused the transfer (REFER) */
830         uint32_t seqno;              /*!< Sequence number */
831         char *park_exten;
832         char *park_context;
833 };
834
835 /*! \brief Parameters to the transmit_invite function */
836 struct sip_invite_param {
837         int addsipheaders;          /*!< Add extra SIP headers */
838         const char *uri_options;    /*!< URI options to add to the URI */
839         const char *vxml_url;       /*!< VXML url for Cisco phones */
840         char *auth;                 /*!< Authentication */
841         char *authheader;           /*!< Auth header */
842         enum sip_auth_type auth_type;  /*!< Authentication type */
843         const char *replaces;       /*!< Replaces header for call transfers */
844         int transfer;               /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
845 };
846
847 /*! \brief Structure to save routing information for a SIP session */
848 struct sip_route {
849         struct sip_route *next;
850         char hop[0];
851 };
852
853 /*! \brief Structure to store Via information */
854 struct sip_via {
855         char *via;
856         const char *protocol;
857         const char *sent_by;
858         const char *branch;
859         const char *maddr;
860         unsigned int port;
861         unsigned char ttl;
862 };
863
864 /*! \brief Domain data structure.
865         \note In the future, we will connect this to a configuration tree specific
866         for this domain
867 */
868 struct domain {
869         char domain[MAXHOSTNAMELEN];       /*!< SIP domain we are responsible for */
870         char context[AST_MAX_EXTENSION];   /*!< Incoming context for this domain */
871         enum domain_mode mode;             /*!< How did we find this domain? */
872         AST_LIST_ENTRY(domain) list;       /*!< List mechanics */
873 };
874
875 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
876 struct sip_history {
877         AST_LIST_ENTRY(sip_history) list;
878         char event[0];  /* actually more, depending on needs */
879 };
880
881 /*! \brief sip_auth: Credentials for authentication to other SIP services */
882 struct sip_auth {
883         AST_LIST_ENTRY(sip_auth) node;
884         char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
885         char username[256];             /*!< Username */
886         char secret[256];               /*!< Secret */
887         char md5secret[256];            /*!< MD5Secret */
888 };
889
890 /*! \brief Container of SIP authentication credentials. */
891 struct sip_auth_container {
892         AST_LIST_HEAD_NOLOCK(, sip_auth) list;
893 };
894
895 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
896 struct t38properties {
897         enum t38state state;            /*!< T.38 state */
898         struct ast_control_t38_parameters our_parms;
899         struct ast_control_t38_parameters their_parms;
900 };
901
902 /*! \brief generic struct to map between strings and integers.
903  * Fill it with x-s pairs, terminate with an entry with s = NULL;
904  * Then you can call map_x_s(...) to map an integer to a string,
905  * and map_s_x() for the string -> integer mapping.
906  */
907 struct _map_x_s {
908         int x;
909         const char *s;
910 };
911
912 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
913         \note OEJ: Should be moved to string fields */
914 struct sip_refer {
915         char refer_to[AST_MAX_EXTENSION];             /*!< Place to store REFER-TO extension */
916         char refer_to_domain[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO domain */
917         char refer_to_urioption[AST_MAX_EXTENSION];   /*!< Place to store REFER-TO uri options */
918         char refer_to_context[AST_MAX_EXTENSION];     /*!< Place to store REFER-TO context */
919         char referred_by[AST_MAX_EXTENSION];          /*!< Place to store REFERRED-BY extension */
920         char referred_by_name[AST_MAX_EXTENSION];     /*!< Place to store REFERRED-BY extension */
921         char refer_contact[AST_MAX_EXTENSION];        /*!< Place to store Contact info from a REFER extension */
922         char replaces_callid[SIPBUFSIZE];             /*!< Replace info: callid */
923         char replaces_callid_totag[SIPBUFSIZE/2];     /*!< Replace info: to-tag */
924         char replaces_callid_fromtag[SIPBUFSIZE/2];   /*!< Replace info: from-tag */
925         struct sip_pvt *refer_call;                   /*!< Call we are referring. This is just a reference to a
926                                                        * dialog owned by someone else, so we should not destroy
927                                                        * it when the sip_refer object goes.
928                                                        */
929         int attendedtransfer;                         /*!< Attended or blind transfer? */
930         int localtransfer;                            /*!< Transfer to local domain? */
931         enum referstatus status;                      /*!< REFER status */
932 };
933
934 /*! \brief Struct to handle custom SIP notify requests. Dynamically allocated when needed */
935 struct sip_notify {
936         struct ast_variable *headers;
937         struct ast_str *content;
938 };
939
940 /*! \brief Structure that encapsulates all attributes related to running
941  *   SIP Session-Timers feature on a per dialog basis.
942  */
943 struct sip_st_dlg {
944         int st_active;                     /*!< Session-Timers on/off */
945         int st_interval;                   /*!< Session-Timers negotiated session refresh interval */
946         int st_schedid;                    /*!< Session-Timers ast_sched scheduler id */
947         enum st_refresher st_ref;          /*!< Session-Timers session refresher */
948         int st_expirys;                    /*!< Session-Timers number of expirys */
949         int st_active_peer_ua;             /*!< Session-Timers on/off in peer UA */
950         int st_cached_min_se;              /*!< Session-Timers cached Min-SE */
951         int st_cached_max_se;              /*!< Session-Timers cached Session-Expires */
952         enum st_mode st_cached_mode;       /*!< Session-Timers cached M.O. */
953         enum st_refresher st_cached_ref;   /*!< Session-Timers cached refresher */
954         unsigned char quit_flag:1;         /*!< Stop trying to lock; just quit */
955 };
956
957
958 /*! \brief Structure that encapsulates all attributes related to configuration
959  *   of SIP Session-Timers feature on a per user/peer basis.
960  */
961 struct sip_st_cfg {
962         enum st_mode st_mode_oper;    /*!< Mode of operation for Session-Timers           */
963         enum st_refresher st_ref;     /*!< Session-Timer refresher                        */
964         int st_min_se;                /*!< Lowest threshold for session refresh interval  */
965         int st_max_se;                /*!< Highest threshold for session refresh interval */
966 };
967
968 /*! \brief Structure for remembering offered media in an INVITE, to make sure we reply
969         to all media streams. In theory. In practise, we try our best. */
970 struct offered_media {
971         int order_offered;              /*!< Order the media was offered in. Not offered is 0 */
972         char codecs[128];
973 };
974
975 /*! Additional headers to send with MESSAGE method packet. */
976 struct sip_msg_hdr {
977         AST_LIST_ENTRY(sip_msg_hdr) next;
978         /*! Name of header to stick in MESSAGE */
979         const char *name;
980         /*! Value of header to stick in MESSAGE */
981         const char *value;
982         /*! The name and value strings are stuffed here in that order. */
983         char stuff[0];
984 };
985
986 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
987  * Created and initialized by sip_alloc(), the descriptor goes into the list of
988  * descriptors (dialoglist).
989  */
990 struct sip_pvt {
991         struct sip_pvt *next;                   /*!< Next dialog in chain */
992         enum invitestates invitestate;          /*!< Track state of SIP_INVITEs */
993         struct ast_callid *logger_callid;               /*!< Identifier for call used in log messages */
994         int method;                             /*!< SIP method that opened this dialog */
995         AST_DECLARE_STRING_FIELDS(
996                 AST_STRING_FIELD(callid);       /*!< Global CallID */
997                 AST_STRING_FIELD(initviabranch); /*!< The branch ID from the topmost Via header in the initial request */
998                 AST_STRING_FIELD(initviasentby); /*!< The sent-by from the topmost Via header in the initial request */
999                 AST_STRING_FIELD(randdata);     /*!< Random data */
1000                 AST_STRING_FIELD(accountcode);  /*!< Account code */
1001                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
1002                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
1003                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
1004                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1005                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
1006                 AST_STRING_FIELD(from);         /*!< The From: header */
1007                 AST_STRING_FIELD(useragent);    /*!< User agent in SIP request */
1008                 AST_STRING_FIELD(exten);        /*!< Extension where to start */
1009                 AST_STRING_FIELD(context);      /*!< Context for this call */
1010                 AST_STRING_FIELD(messagecontext); /*!< Default context for outofcall messages. */
1011                 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1012                 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1013                 AST_STRING_FIELD(fromdomain);   /*!< Domain to show in the from field */
1014                 AST_STRING_FIELD(fromuser);     /*!< User to show in the user field */
1015                 AST_STRING_FIELD(fromname);     /*!< Name to show in the user field */
1016                 AST_STRING_FIELD(tohost);       /*!< Host we should put in the "to" field */
1017                 AST_STRING_FIELD(todnid);       /*!< DNID of this call (overrides host) */
1018                 AST_STRING_FIELD(language);     /*!< Default language for this call */
1019                 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1020                 AST_STRING_FIELD(mohsuggest);   /*!< MOH class to suggest when putting a peer on hold */
1021                 AST_STRING_FIELD(rdnis);        /*!< Referring DNIS */
1022                 AST_STRING_FIELD(redircause);   /*!< Referring cause */
1023                 AST_STRING_FIELD(theirtag);     /*!< Their tag */
1024                 AST_STRING_FIELD(username);     /*!< [user] name */
1025                 AST_STRING_FIELD(peername);     /*!< [peer] name, not set if [user] */
1026                 AST_STRING_FIELD(authname);     /*!< Who we use for authentication */
1027                 AST_STRING_FIELD(uri);          /*!< Original requested URI */
1028                 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1029                 AST_STRING_FIELD(peersecret);   /*!< Password */
1030                 AST_STRING_FIELD(peermd5secret);
1031                 AST_STRING_FIELD(cid_num);      /*!< Caller*ID number */
1032                 AST_STRING_FIELD(cid_name);     /*!< Caller*ID name */
1033                 AST_STRING_FIELD(cid_tag);      /*!< Caller*ID tag */
1034                 AST_STRING_FIELD(mwi_from);     /*!< Name to place in the From header in outgoing NOTIFY requests */
1035                 AST_STRING_FIELD(fullcontact);  /*!< The Contact: that the UA registers with us */
1036                                                 /* we only store the part in <brackets> in this field. */
1037                 AST_STRING_FIELD(our_contact);  /*!< Our contact header */
1038                 AST_STRING_FIELD(url);          /*!< URL to be sent with next message to peer */
1039                 AST_STRING_FIELD(parkinglot);   /*!< Parkinglot */
1040                 AST_STRING_FIELD(engine);       /*!< RTP engine to use */
1041                 AST_STRING_FIELD(dialstring);   /*!< The dialstring used to call this SIP endpoint */
1042                 AST_STRING_FIELD(msg_body);     /*!< Text for a MESSAGE body */
1043         );
1044         char via[128];                          /*!< Via: header */
1045         int maxforwards;                        /*!< SIP Loop prevention */
1046         struct sip_socket socket;               /*!< The socket used for this dialog */
1047         uint32_t ocseq;                         /*!< Current outgoing seqno */
1048         uint32_t icseq;                         /*!< Current incoming seqno */
1049         uint32_t init_icseq;                    /*!< Initial incoming seqno from first request */
1050         ast_group_t callgroup;                  /*!< Call group */
1051         ast_group_t pickupgroup;                /*!< Pickup group */
1052         uint32_t lastinvite;                    /*!< Last seqno of invite */
1053         struct ast_flags flags[3];              /*!< SIP_ flags */
1054
1055         /* boolean flags that don't belong in flags */
1056         unsigned short do_history:1;          /*!< Set if we want to record history */
1057         unsigned short alreadygone:1;         /*!< the peer has sent a message indicating termination of the dialog */
1058         unsigned short needdestroy:1;         /*!< this dialog needs to be destroyed by the monitor thread */
1059         unsigned short final_destruction_scheduled:1; /*!< final dialog destruction is scheduled. Keep dialog
1060                                                        *   around until then to handle retransmits. */
1061         unsigned short outgoing_call:1;       /*!< this is an outgoing call */
1062         unsigned short answered_elsewhere:1;  /*!< This call is cancelled due to answer on another channel */
1063         unsigned short novideo:1;             /*!< Didn't get video in invite, don't offer */
1064         unsigned short notext:1;              /*!< Text not supported  (?) */
1065         unsigned short session_modify:1;      /*!< Session modification request true/false  */
1066         unsigned short route_persistent:1;    /*!< Is this the "real" route? */
1067         unsigned short autoframing:1;         /*!< Whether to use our local configuration for frame sizes (off)
1068                                                *   or respect the other endpoint's request for frame sizes (on)
1069                                                *   for incoming calls
1070                                                */
1071         unsigned short req_secure_signaling:1;/*!< Whether we are required to have secure signaling or not */
1072         unsigned short natdetected:1;         /*!< Whether we detected a NAT when processing the Via */
1073         char tag[11];                     /*!< Our tag for this session */
1074         int timer_t1;                     /*!< SIP timer T1, ms rtt */
1075         int timer_b;                      /*!< SIP timer B, ms */
1076         unsigned int sipoptions;          /*!< Supported SIP options on the other end */
1077         unsigned int reqsipoptions;       /*!< Required SIP options on the other end */
1078         struct ast_codec_pref prefs;      /*!< codec prefs */
1079         struct ast_format_cap *caps;             /*!< Special capability (codec) */
1080         struct ast_format_cap *jointcaps;        /*!< Supported capability at both ends (codecs) */
1081         struct ast_format_cap *peercaps;         /*!< Supported peer capability */
1082         struct ast_format_cap *redircaps;        /*!< Redirect codecs */
1083         struct ast_format_cap *prefcaps;         /*!< Preferred codec (outbound only) */
1084         int noncodeccapability;           /*!< DTMF RFC2833 telephony-event */
1085         int jointnoncodeccapability;      /*!< Joint Non codec capability */
1086         int maxcallbitrate;               /*!< Maximum Call Bitrate for Video Calls */  
1087         int t38_maxdatagram;              /*!< T.38 FaxMaxDatagram override */
1088         int request_queue_sched_id;       /*!< Scheduler ID of any scheduled action to process queued requests */
1089         int provisional_keepalive_sched_id;   /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
1090         const char *last_provisional;         /*!< The last successfully transmitted provisonal response message */
1091         int authtries;                        /*!< Times we've tried to authenticate */
1092         struct sip_proxy *outboundproxy;      /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
1093         struct t38properties t38;             /*!< T38 settings */
1094         struct ast_sockaddr udptlredirip;     /*!< Where our T.38 UDPTL should be going if not to us */
1095         struct ast_udptl *udptl;              /*!< T.38 UDPTL session */
1096         char zone[MAX_TONEZONE_COUNTRY];      /*!< Default tone zone for channels created by this dialog */
1097         int callingpres;                      /*!< Calling presentation */
1098         int expiry;                         /*!< How long we take to expire */
1099         int sessionversion;                 /*!< SDP Session Version */
1100         int sessionid;                      /*!< SDP Session ID */
1101         long branch;                        /*!< The branch identifier of this session */
1102         long invite_branch;                 /*!< The branch used when we sent the initial INVITE */
1103         int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
1104         unsigned int portinuri:1;           /*!< Non zero if a port has been specified, will also disable srv lookups */
1105         struct ast_sockaddr sa;              /*!< Our peer */
1106         struct ast_sockaddr redirip;         /*!< Where our RTP should be going if not to us */
1107         struct ast_sockaddr vredirip;        /*!< Where our Video RTP should be going if not to us */
1108         struct ast_sockaddr tredirip;        /*!< Where our Text RTP should be going if not to us */
1109         time_t lastrtprx;                   /*!< Last RTP received */
1110         time_t lastrtptx;                   /*!< Last RTP sent */
1111         int rtptimeout;                     /*!< RTP timeout time */
1112         int rtpholdtimeout;                 /*!< RTP timeout time on hold*/
1113         int rtpkeepalive;                   /*!< RTP send packets for keepalive */
1114         struct ast_ha *directmediaha;           /*!< Which IPs are allowed to interchange direct media with this peer - copied from sip_peer */
1115         struct ast_sockaddr recv;            /*!< Received as */
1116         struct ast_sockaddr ourip;           /*!< Our IP (as seen from the outside) */
1117         enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
1118         struct ast_channel *owner;          /*!< Who owns us (if we have an owner) */
1119         struct sip_route *route;            /*!< Head of linked list of routing steps (fm Record-Route) */
1120         struct sip_notify *notify;          /*!< Custom notify type */
1121         struct sip_auth_container *peerauth;/*!< Realm authentication credentials */
1122         int noncecount;                     /*!< Nonce-count */
1123         unsigned int stalenonce:1;          /*!< Marks the current nonce as responded too */
1124         char lastmsg[256];                  /*!< Last Message sent/received */
1125         int amaflags;                       /*!< AMA Flags */
1126         uint32_t pendinginvite; /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
1127         uint32_t glareinvite;      /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
1128                                    value. Since this glare invite's seqno is not the same as the pending invite's, it must be
1129                                    held in order to properly process acknowledgements for our 491 response. */
1130         struct sip_request initreq;         /*!< Latest request that opened a new transaction
1131                                                  within this dialog.
1132                                                  NOT the request that opened the dialog */
1133
1134         int initid;                         /*!< Auto-congest ID if appropriate (scheduler) */
1135         int waitid;                         /*!< Wait ID for scheduler after 491 or other delays */
1136         int autokillid;                     /*!< Auto-kill ID (scheduler) */
1137         int t38id;                          /*!< T.38 Response ID */
1138         struct sip_refer *refer;            /*!< REFER: SIP transfer data structure */
1139         enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
1140         int stateid;                        /*!< SUBSCRIBE: ID for devicestate subscriptions */
1141         int laststate;                      /*!< SUBSCRIBE: Last known extension state */
1142         uint32_t dialogver;                 /*!< SUBSCRIBE: Version for subscription dialog-info */
1143
1144         struct ast_dsp *dsp;                /*!< Inband DTMF or Fax CNG tone Detection dsp */
1145
1146         struct sip_peer *relatedpeer;       /*!< If this dialog is related to a peer, which one
1147                                                  Used in peerpoke, mwi subscriptions */
1148         struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
1149         struct ast_rtp_instance *rtp;       /*!< RTP Session */
1150         struct ast_rtp_instance *vrtp;      /*!< Video RTP session */
1151         struct ast_rtp_instance *trtp;      /*!< Text RTP session */
1152         struct sip_pkt *packets;            /*!< Packets scheduled for re-transmission */
1153         struct sip_history_head *history;   /*!< History of this SIP dialog */
1154         size_t history_entries;             /*!< Number of entires in the history */
1155         struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
1156         AST_LIST_HEAD_NOLOCK(, sip_msg_hdr) msg_headers; /*!< Additional MESSAGE headers to send. */
1157         AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
1158         struct sip_invite_param *options;   /*!< Options for INVITE */
1159         struct sip_st_dlg *stimer;          /*!< SIP Session-Timers */
1160         struct sip_srtp *srtp;              /*!< Structure to hold Secure RTP session data for audio */
1161         struct sip_srtp *vsrtp;             /*!< Structure to hold Secure RTP session data for video */
1162         struct sip_srtp *tsrtp;             /*!< Structure to hold Secure RTP session data for text */
1163
1164         int red;                            /*!< T.140 RTP Redundancy */
1165         int hangupcause;                    /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
1166
1167         struct sip_subscription_mwi *mwi;   /*!< If this is a subscription MWI dialog, to which subscription */
1168         /*! The SIP methods supported by this peer. We get this information from the Allow header of the first
1169          * message we receive from an endpoint during a dialog.
1170          */
1171         unsigned int allowed_methods;
1172         /*! Some peers are not trustworthy with their Allow headers, and so we need to override their wicked
1173          * ways through configuration. This is a copy of the peer's disallowed_methods, so that we can apply them
1174          * to the sip_pvt at various stages of dialog establishment
1175          */
1176         unsigned int disallowed_methods;
1177         /*! When receiving an SDP offer, it is important to take note of what media types were offered.
1178          * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
1179          * still put an m= line in our answer with the port set to 0.
1180          *
1181          * The reason for the length being 4 (OFFERED_MEDIA_COUNT) is that in this branch of Asterisk, the only media types supported are
1182          * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
1183          * Note that secure RTP defines new types of SDP media.
1184          *
1185          * If we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
1186          * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
1187          * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
1188          * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
1189          *
1190          * The large-scale changes would be a good idea for implementing during an SDP rewrite.
1191          */
1192         struct offered_media offered_media[OFFERED_MEDIA_COUNT];
1193         struct ast_cc_config_params *cc_params;
1194         struct sip_epa_entry *epa_entry;
1195         int fromdomainport;                 /*!< Domain port to show in from field */
1196 };
1197
1198 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1199  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1200  * Each packet holds a reference to the parent struct sip_pvt.
1201  * This structure is allocated in __sip_reliable_xmit() and only for packets that
1202  * require retransmissions.
1203  */
1204 struct sip_pkt {
1205         struct sip_pkt *next;     /*!< Next packet in linked list */
1206         int retrans;              /*!< Retransmission number */
1207         int method;               /*!< SIP method for this packet */
1208         uint32_t seqno;           /*!< Sequence number */
1209         char is_resp;             /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1210         char is_fatal;            /*!< non-zero if there is a fatal error */
1211         int response_code;        /*!< If this is a response, the response code */
1212         struct sip_pvt *owner;    /*!< Owner AST call */
1213         int retransid;            /*!< Retransmission ID */
1214         int timer_a;              /*!< SIP timer A, retransmission timer */
1215         int timer_t1;             /*!< SIP Timer T1, estimated RTT or 500 ms */
1216         struct timeval time_sent;  /*!< When pkt was sent */
1217         int64_t retrans_stop_time; /*!< Time in ms after 'now' that retransmission must stop */
1218         int retrans_stop;         /*!< Timeout is reached, stop retransmission  */
1219         struct ast_str *data;
1220 };
1221
1222 /*!
1223  * \brief A peer's mailbox
1224  *
1225  * We could use STRINGFIELDS here, but for only two strings, it seems like
1226  * too much effort ...
1227  */
1228 struct sip_mailbox {
1229         /*! Associated MWI subscription */
1230         struct ast_event_sub *event_sub;
1231         AST_LIST_ENTRY(sip_mailbox) entry;
1232         unsigned int delme:1;
1233         char *context;
1234         char mailbox[2];
1235 };
1236
1237 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host)
1238 */
1239 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
1240 struct sip_peer {
1241         char name[80];                          /*!< the unique name of this object */
1242         AST_DECLARE_STRING_FIELDS(
1243                 AST_STRING_FIELD(secret);       /*!< Password for inbound auth */
1244                 AST_STRING_FIELD(md5secret);    /*!< Password in MD5 */
1245                 AST_STRING_FIELD(description);  /*!< Description of this peer */
1246                 AST_STRING_FIELD(remotesecret); /*!< Remote secret (trunks, remote devices) */
1247                 AST_STRING_FIELD(context);      /*!< Default context for incoming calls */
1248                 AST_STRING_FIELD(messagecontext); /*!< Default context for outofcall messages. */
1249                 AST_STRING_FIELD(subscribecontext); /*!< Default context for subscriptions */
1250                 AST_STRING_FIELD(username);     /*!< Temporary username until registration */
1251                 AST_STRING_FIELD(accountcode);  /*!< Account code */
1252                 AST_STRING_FIELD(tohost);       /*!< If not dynamic, IP address */
1253                 AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
1254                 AST_STRING_FIELD(fromuser);     /*!< From: user when calling this peer */
1255                 AST_STRING_FIELD(fromdomain);   /*!< From: domain when calling this peer */
1256                 AST_STRING_FIELD(fullcontact);  /*!< Contact registered with us (not in sip.conf) */
1257                 AST_STRING_FIELD(cid_num);      /*!< Caller ID num */
1258                 AST_STRING_FIELD(cid_name);     /*!< Caller ID name */
1259                 AST_STRING_FIELD(cid_tag);      /*!< Caller ID tag */
1260                 AST_STRING_FIELD(vmexten);      /*!< Dialplan extension for MWI notify message*/
1261                 AST_STRING_FIELD(language);     /*!<  Default language for prompts */
1262                 AST_STRING_FIELD(mohinterpret); /*!<  Music on Hold class */
1263                 AST_STRING_FIELD(mohsuggest);   /*!<  Music on Hold class */
1264                 AST_STRING_FIELD(parkinglot);   /*!<  Parkinglot */
1265                 AST_STRING_FIELD(useragent);    /*!<  User agent in SIP request (saved from registration) */
1266                 AST_STRING_FIELD(mwi_from);     /*!< Name to place in From header for outgoing NOTIFY requests */
1267                 AST_STRING_FIELD(engine);       /*!<  RTP Engine to use */
1268                 AST_STRING_FIELD(unsolicited_mailbox);  /*!< Mailbox to store received unsolicited MWI NOTIFY messages information in */
1269                 AST_STRING_FIELD(zone);         /*!< Tonezone for this device */
1270                 AST_STRING_FIELD(record_on_feature); /*!< Feature to use when receiving INFO with record: on during a call */
1271                 AST_STRING_FIELD(record_off_feature); /*!< Feature to use when receiving INFO with record: off during a call */
1272                 AST_STRING_FIELD(callback); /*!< Callback extension */
1273                 );
1274         struct sip_socket socket;       /*!< Socket used for this peer */
1275         enum sip_transport default_outbound_transport;   /*!< Peer Registration may change the default outbound transport.
1276                                                              If register expires, default should be reset. to this value */
1277         /* things that don't belong in flags */
1278         unsigned short transports:3;    /*!< Transports (enum sip_transport) that are acceptable for this peer */
1279         unsigned short is_realtime:1;   /*!< this is a 'realtime' peer */
1280         unsigned short rt_fromcontact:1;/*!< copy fromcontact from realtime */
1281         unsigned short host_dynamic:1;  /*!< Dynamic Peers register with Asterisk */
1282         unsigned short selfdestruct:1;  /*!< Automatic peers need to destruct themselves */
1283         unsigned short the_mark:1;      /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
1284         unsigned short autoframing:1;   /*!< Whether to use our local configuration for frame sizes (off)
1285                                          *   or respect the other endpoint's request for frame sizes (on)
1286                                          *   for incoming calls
1287                                          */
1288         unsigned short deprecated_username:1; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
1289         struct sip_auth_container *auth;/*!< Realm authentication credentials */
1290         int amaflags;                   /*!< AMA Flags (for billing) */
1291         int callingpres;                /*!< Calling id presentation */
1292         int inUse;                      /*!< Number of calls in use */
1293         int inRinging;                  /*!< Number of calls ringing */
1294         int onHold;                     /*!< Peer has someone on hold */
1295         int call_limit;                 /*!< Limit of concurrent calls */
1296         int t38_maxdatagram;            /*!< T.38 FaxMaxDatagram override */
1297         int busy_level;                 /*!< Level of active channels where we signal busy */
1298         int maxforwards;                /*!< SIP Loop prevention */
1299         enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
1300         struct ast_codec_pref prefs;    /*!<  codec prefs */
1301         int lastmsgssent;                               /*!< The last known VM message counts (new/old) */
1302         unsigned int sipoptions;        /*!<  Supported SIP options */
1303         struct ast_flags flags[3];      /*!<  SIP_ flags */
1304
1305         /*! Mailboxes that this peer cares about */
1306         AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1307
1308         int maxcallbitrate;             /*!<  Maximum Bitrate for a video call */
1309         int expire;                     /*!<  When to expire this peer registration */
1310         struct ast_format_cap *caps;            /*!<  Codec capability */
1311         int rtptimeout;                 /*!<  RTP timeout */
1312         int rtpholdtimeout;             /*!<  RTP Hold Timeout */
1313         int rtpkeepalive;               /*!<  Send RTP packets for keepalive */
1314         ast_group_t callgroup;          /*!<  Call group */
1315         ast_group_t pickupgroup;        /*!<  Pickup group */
1316         struct sip_proxy *outboundproxy;/*!< Outbound proxy for this peer */
1317         struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
1318         struct ast_sockaddr addr;        /*!<  IP address of peer */
1319         unsigned int portinuri:1;       /*!< Whether the port should be included in the URI */
1320         struct sip_pvt *call;           /*!<  Call pointer */
1321         int pokeexpire;                 /*!<  Qualification: When to expire poke (qualify= checking) */
1322         int lastms;                     /*!<  Qualification: How long last response took (in ms), or -1 for no response */
1323         int maxms;                      /*!<  Qualification: Max ms we will accept for the host to be up, 0 to not monitor */
1324         int qualifyfreq;                /*!<  Qualification: Qualification: How often to check for the host to be up */
1325         struct timeval ps;              /*!<  Qualification: Time for sending SIP OPTION in sip_pke_peer() */
1326         int keepalive;                  /*!<  Keepalive: How often to send keep alive packet */
1327         int keepalivesend;              /*!<  Keepalive: Scheduled item for sending keep alive packet */
1328         struct ast_sockaddr defaddr;     /*!<  Default IP address, used until registration */
1329         struct ast_ha *ha;              /*!<  Access control list */
1330         struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
1331         struct ast_ha *directmediaha;   /*!<  Restrict what IPs are allowed to interchange direct media with */
1332         struct ast_variable *chanvars;  /*!<  Variables to set for channel created by user */
1333         struct sip_pvt *mwipvt;         /*!<  Subscription for MWI */
1334         struct sip_st_cfg stimer;       /*!<  SIP Session-Timers */
1335         int timer_t1;                   /*!<  The maximum T1 value for the peer */
1336         int timer_b;                    /*!<  The maximum timer B (transaction timeouts) */
1337         int fromdomainport;             /*!<  The From: domain port */
1338
1339         /*XXX Seems like we suddenly have two flags with the same content. Why? To be continued... */
1340         enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
1341         unsigned int disallowed_methods;
1342         struct ast_cc_config_params *cc_params;
1343 };
1344
1345 /*!
1346  * \brief Registrations with other SIP proxies
1347  *
1348  * Created by sip_register(), the entry is linked in the 'regl' list,
1349  * and never deleted (other than at 'sip reload' or module unload times).
1350  * The entry always has a pending timeout, either waiting for an ACK to
1351  * the REGISTER message (in which case we have to retransmit the request),
1352  * or waiting for the next REGISTER message to be sent (either the initial one,
1353  * or once the previously completed registration one expires).
1354  * The registration can be in one of many states, though at the moment
1355  * the handling is a bit mixed.
1356  *
1357  * \todo Convert this to astobj2
1358  */
1359 struct sip_registry {
1360         ASTOBJ_COMPONENTS_FULL(struct sip_registry, 80, 1);
1361         AST_DECLARE_STRING_FIELDS(
1362                 AST_STRING_FIELD(callid);     /*!< Global Call-ID */
1363                 AST_STRING_FIELD(realm);      /*!< Authorization realm */
1364                 AST_STRING_FIELD(nonce);      /*!< Authorization nonce */
1365                 AST_STRING_FIELD(opaque);     /*!< Opaque nonsense */
1366                 AST_STRING_FIELD(qop);        /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1367                 AST_STRING_FIELD(authdomain); /*!< Authorization domain */
1368                 AST_STRING_FIELD(regdomain);  /*!< Registration doamin */
1369                 AST_STRING_FIELD(username);   /*!< Who we are registering as */
1370                 AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
1371                 AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
1372                 AST_STRING_FIELD(secret);     /*!< Password in clear text */
1373                 AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
1374                 AST_STRING_FIELD(callback);   /*!< Contact extension */
1375                 AST_STRING_FIELD(peername);   /*!< Peer registering to */
1376         );
1377         enum sip_transport transport;   /*!< Transport for this registration UDP, TCP or TLS */
1378         int portno;                     /*!< Optional port override */
1379         int regdomainport;              /*!< Port override for domainport */
1380         int expire;                     /*!< Sched ID of expiration */
1381         int configured_expiry;          /*!< Configured value to use for the Expires header */
1382         int expiry;             /*!< Negotiated value used for the Expires header */
1383         int regattempts;        /*!< Number of attempts (since the last success) */
1384         int timeout;            /*!< sched id of sip_reg_timeout */
1385         int refresh;            /*!< How often to refresh */
1386         struct sip_pvt *call;   /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1387         enum sipregistrystate regstate; /*!< Registration state (see above) */
1388         struct timeval regtime;         /*!< Last successful registration time */
1389         int callid_valid;       /*!< 0 means we haven't chosen callid for this registry yet. */
1390         uint32_t ocseq;         /*!< Sequence number we got to for REGISTERs for this registry */
1391         struct ast_dnsmgr_entry *dnsmgr;  /*!<  DNS refresh manager for register */
1392         struct ast_sockaddr us;  /*!< Who the server thinks we are */
1393         int noncecount;         /*!< Nonce-count */
1394         char lastmsg[256];      /*!< Last Message sent/received */
1395 };
1396
1397 struct tcptls_packet {
1398         AST_LIST_ENTRY(tcptls_packet) entry;
1399         struct ast_str *data;
1400         size_t len;
1401 };
1402 /*! \brief Definition of a thread that handles a socket */
1403 struct sip_threadinfo {
1404         /*! TRUE if the thread needs to kill itself.  (The module is being unloaded.) */
1405         int stop;
1406         int alert_pipe[2];          /*! Used to alert tcptls thread when packet is ready to be written */
1407         pthread_t threadid;
1408         struct ast_tcptls_session_instance *tcptls_session;
1409         enum sip_transport type;    /*!< We keep a copy of the type here so we can display it in the connection list */
1410         AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
1411 };
1412
1413 /*!
1414  * \brief Definition of an MWI subscription to another server
1415  * 
1416  * \todo Convert this to astobj2.
1417  */
1418 struct sip_subscription_mwi {
1419         ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
1420         AST_DECLARE_STRING_FIELDS(
1421                 AST_STRING_FIELD(username);     /*!< Who we are sending the subscription as */
1422                 AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
1423                 AST_STRING_FIELD(hostname);     /*!< Domain or host we subscribe to */
1424                 AST_STRING_FIELD(secret);       /*!< Password in clear text */
1425                 AST_STRING_FIELD(mailbox);      /*!< Mailbox store to put MWI into */
1426                 );
1427         enum sip_transport transport;    /*!< Transport to use */
1428         int portno;                      /*!< Optional port override */
1429         int resub;                       /*!< Sched ID of resubscription */
1430         unsigned int subscribed:1;       /*!< Whether we are currently subscribed or not */
1431         struct sip_pvt *call;            /*!< Outbound subscription dialog */
1432         struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
1433         struct ast_sockaddr us;           /*!< Who the server thinks we are */
1434 };
1435
1436 /*!
1437  * SIP PUBLISH support!
1438  * PUBLISH support was added to chan_sip due to its use in the call-completion
1439  * event package. In order to suspend and unsuspend monitoring of a called party,
1440  * a PUBLISH message must be sent. Rather than try to hack in PUBLISH transmission
1441  * and reception solely for the purposes of handling call-completion-related messages,
1442  * an effort has been made to create a generic framework for handling PUBLISH messages.
1443  *
1444  * There are two main components to the effort, the event publication agent (EPA) and
1445  * the event state compositor (ESC). Both of these terms appear in RFC 3903, and the
1446  * implementation in Asterisk conforms to the defintions there. An EPA is a UAC that
1447  * transmits PUBLISH requests. An ESC is a UAS that receives PUBLISH requests and
1448  * acts appropriately based on the content of those requests.
1449  *
1450  * ESC:
1451  * The main structure in chan_sip is the event_state_compositor. There is an
1452  * event_state_compositor structure for each event package supported (as of Nov 2009
1453  * this is only the call-completion package). The structure contains data which is
1454  * intrinsic to the event package itself, such as the name of the package and a set
1455  * of callbacks for handling incoming PUBLISH requests. In addition, the
1456  * event_state_compositor struct contains an ao2_container of sip_esc_entries.
1457  *
1458  * A sip_esc_entry corresponds to an entity which has sent a PUBLISH to Asterisk. We are
1459  * able to match the incoming PUBLISH to a sip_esc_entry using the Sip-If-Match header
1460  * of the message. Of course, if none is present, then a new sip_esc_entry will be created.
1461  *
1462  * Once it is determined what type of PUBLISH request has come in (from RFC 3903, it may
1463  * be an initial, modify, refresh, or remove), then the event package-specific callbacks
1464  * may be called. If your event package doesn't need to take any specific action for a
1465  * specific PUBLISH type, it is perfectly safe to not define the callback at all. The callback
1466  * only needs to take care of application-specific information. If there is a problem, it is
1467  * up to the callback to take care of sending an appropriate 4xx or 5xx response code. In such
1468  * a case, the callback should return -1. This will tell the function that called the handler
1469  * that an appropriate error response has been sent. If the callback returns 0, however, then
1470  * the caller of the callback will generate a new entity tag and send a 200 OK response.
1471  *
1472  * ESC entries are reference-counted, however as an implementor of a specific event package,
1473  * this should be transparent, since the reference counts are handled by the general ESC
1474  * framework.
1475  *
1476  * EPA:
1477  * The event publication agent in chan_sip is structured quite a bit differently than the
1478  * ESC. With an ESC, an appropriate entry has to be found based on the contents of an incoming
1479  * PUBLISH message. With an EPA, the application interested in sending the PUBLISH can maintain
1480  * a reference to the appropriate EPA entry instead. Similarly, when matching a PUBLISH response
1481  * to an appropriate EPA entry, the sip_pvt can maintain a reference to the corresponding
1482  * EPA entry. The result of this train of thought is that there is no compelling reason to
1483  * maintain a container of these entries.
1484  *
1485  * Instead, there is only the sip_epa_entry structure. Every sip_epa_entry has an entity tag
1486  * that it maintains so that subsequent PUBLISH requests will be identifiable by the ESC on
1487  * the far end. In addition, there is a static_data field which contains information that is
1488  * common to all sip_epa_entries for a specific event package. This static data includes the
1489  * name of the event package and callbacks for handling specific responses for outgoing PUBLISHes.
1490  * Also, there is a field for pointing to instance-specific data. This can include the current
1491  * published state or other identifying information that is specific to an instance of an EPA
1492  * entry of a particular event package.
1493  *
1494  * When an application wishes to send a PUBLISH request, it simply will call create_epa_entry,
1495  * followed by transmit_publish in order to send the PUBLISH. That's all that is necessary.
1496  * Like with ESC entries, sip_epa_entries are reference counted. Unlike ESC entries, though,
1497  * sip_epa_entries reference counts have to be maintained to some degree by the application making
1498  * use of the sip_epa_entry. The application will acquire a reference to the EPA entry when it
1499  * calls create_epa_entry. When the application has finished using the EPA entry (which may not
1500  * be until after several PUBLISH transactions have taken place) it must use ao2_ref to decrease
1501  * the reference count by 1.
1502  */
1503
1504 /*!
1505  * \brief The states that can be represented in a SIP call-completion PUBLISH
1506  */
1507 enum sip_cc_publish_state {
1508         /*! Closed, i.e. unavailable */
1509         CC_CLOSED,
1510         /*! Open, i.e. available */
1511         CC_OPEN,
1512 };
1513
1514 /*!
1515  * \brief The states that can be represented in a SIP call-completion NOTIFY
1516  */
1517 enum sip_cc_notify_state {
1518         /*! Queued, i.e. unavailable */
1519         CC_QUEUED,
1520         /*! Ready, i.e. available */
1521         CC_READY,
1522 };
1523
1524 /*!
1525  * \brief The types of PUBLISH messages defined in RFC 3903
1526  */
1527 enum sip_publish_type {
1528         /*!
1529          * \brief Unknown
1530          *
1531          * \details
1532          * This actually is not defined in RFC 3903. We use this as a constant
1533          * to indicate that an incoming PUBLISH does not fit into any of the
1534          * other categories and is thus invalid.
1535          */
1536         SIP_PUBLISH_UNKNOWN,
1537         /*!
1538          * \brief Initial
1539          *
1540          * \details
1541          * The first PUBLISH sent. This will contain a non-zero Expires header
1542          * as well as a body that indicates the current state of the endpoint
1543          * that has sent the message. The initial PUBLISH is the only type
1544          * of PUBLISH to not contain a Sip-If-Match header in it.
1545          */
1546         SIP_PUBLISH_INITIAL,
1547         /*!
1548          * \brief Refresh
1549          *
1550          * \details
1551          * Used to keep a published state from expiring. This will contain a
1552          * non-zero Expires header but no body since its purpose is not to
1553          * update state.
1554          */
1555         SIP_PUBLISH_REFRESH,
1556         /*!
1557          * \brief Modify
1558          *
1559          * \details
1560          * Used to change state from its previous value. This will contain
1561          * a body updating the published state. May or may not contain an
1562          * Expires header.
1563          */
1564         SIP_PUBLISH_MODIFY,
1565         /*!
1566          * \brief Remove
1567          * 
1568          * \details
1569          * Used to remove published state from an ESC. This will contain
1570          * an Expires header set to 0 and likely no body.
1571          */
1572         SIP_PUBLISH_REMOVE,
1573 };
1574
1575 /*!
1576  * Data which is the same for all instances of an EPA for a
1577  * particular event package
1578  */
1579 struct epa_static_data {
1580         /*! The event type */
1581         enum subscriptiontype event;
1582         /*!
1583          * The name of the event as it would
1584          * appear in a SIP message
1585          */
1586         const char *name;
1587         /*!
1588          * The callback called when a 200 OK is received on an outbound PUBLISH
1589          */
1590         void (*handle_ok)(struct sip_pvt *, struct sip_request *, struct sip_epa_entry *);
1591         /*!
1592          * The callback called when an error response is received on an outbound PUBLISH
1593          */
1594         void (*handle_error)(struct sip_pvt *, const int resp, struct sip_request *, struct sip_epa_entry *);
1595         /*!
1596          * Destructor to call to clean up instance data
1597          */
1598         void (*destructor)(void *instance_data);
1599 };
1600
1601 /*!
1602  * \brief backend for an event publication agent
1603  */
1604 struct epa_backend {
1605         const struct epa_static_data *static_data;
1606         AST_LIST_ENTRY(epa_backend) next;
1607 };
1608
1609 struct sip_epa_entry {
1610         /*!
1611          * When we are going to send a publish, we need to
1612          * know the type of PUBLISH to send.
1613          */
1614         enum sip_publish_type publish_type;
1615         /*!
1616          * When we send a PUBLISH, we have to be
1617          * sure to include the entity tag that we
1618          * received in the previous response.
1619          */
1620         char entity_tag[SIPBUFSIZE];
1621         /*!
1622          * The destination to which this EPA should send
1623          * PUBLISHes. This may be the name of a SIP peer
1624          * or a hostname.
1625          */
1626         char destination[SIPBUFSIZE];
1627         /*!
1628          * The body of the most recently-sent PUBLISH message.
1629          * This is useful for situations such as authentication,
1630          * in which we must send a message identical to the
1631          * one previously sent
1632          */
1633         char body[SIPBUFSIZE];
1634         /*!
1635          * Every event package has some constant data and
1636          * callbacks that all instances will share. This
1637          * data resides in this field.
1638          */
1639         const struct epa_static_data *static_data;
1640         /*!
1641          * In addition to the static data that all instances
1642          * of sip_epa_entry will have, each instance will
1643          * require its own instance-specific data.
1644          */
1645         void *instance_data;
1646 };
1647
1648 /*!
1649  * \brief Instance data for a Call completion EPA entry
1650  */
1651 struct cc_epa_entry {
1652         /*!
1653          * The core ID of the CC transaction
1654          * for which this EPA entry belongs. This
1655          * essentially acts as a unique identifier
1656          * for the entry and is used in the hash
1657          * and comparison functions
1658          */
1659         int core_id;
1660         /*!
1661          * We keep the last known state of the
1662          * device in question handy in case
1663          * it needs to be known by a third party.
1664          * Also, in the case where for some reason
1665          * we get asked to transmit state that we
1666          * already sent, we can just ignore the
1667          * request.
1668          */
1669         enum sip_cc_publish_state current_state;
1670 };
1671
1672 struct event_state_compositor;
1673
1674 /*!
1675  * \brief common ESC items for all event types
1676  *
1677  * The entity_id field serves as a means by which
1678  * A specific entry may be found.
1679  */
1680 struct sip_esc_entry {
1681         /*!
1682          * The name of the party who
1683          * sent us the PUBLISH. This will more
1684          * than likely correspond to a peer name.
1685          *
1686          * This field's utility isn't really that
1687          * great. It's mainly just a user-recognizable
1688          * handle that can be printed in debug messages.
1689          */
1690         const char *device_name;
1691         /*!
1692          * The event package for which this esc_entry
1693          * exists. Most of the time this isn't really
1694          * necessary since you'll have easy access to the
1695          * ESC which contains this entry. However, in
1696          * some circumstances, we won't have the ESC
1697          * available.
1698          */
1699         const char *event;
1700         /*!
1701          * The entity ID used when corresponding
1702          * with the EPA on the other side. As the
1703          * ESC, we generate an entity ID for each
1704          * received PUBLISH and store it in this
1705          * structure.
1706          */
1707         char entity_tag[30];
1708         /*!
1709          * The ID for the scheduler. We schedule
1710          * destruction of a sip_esc_entry when we
1711          * receive a PUBLISH. The destruction is
1712          * scheduled for the duration received in
1713          * the Expires header.
1714          */
1715         int sched_id;
1716         /*!
1717          * Each ESC entry will be for a specific
1718          * event type. Those entries will need to
1719          * carry data which is intrinsic to the
1720          * ESC entry but which is specific to
1721          * the event package
1722          */
1723         void *event_specific_data;
1724 };
1725
1726 typedef int (* const esc_publish_callback)(struct sip_pvt *, struct sip_request *, struct event_state_compositor *, struct sip_esc_entry *);
1727
1728 /*!
1729  * \brief Callbacks for SIP ESCs
1730  *
1731  * \details
1732  * The names of the callbacks are self-explanatory. The
1733  * corresponding handler is called whenever the specific
1734  * type of PUBLISH is received.
1735  */
1736 struct sip_esc_publish_callbacks {
1737         const esc_publish_callback initial_handler;
1738         const esc_publish_callback refresh_handler;
1739         const esc_publish_callback modify_handler;
1740         const esc_publish_callback remove_handler;
1741 };
1742
1743 struct sip_cc_agent_pvt {
1744         int offer_timer_id;
1745         /* A copy of the original call's Call-ID.
1746          * We use this as a search key when attempting
1747          * to find a particular sip_pvt.
1748          */
1749         char original_callid[SIPBUFSIZE];
1750         /* A copy of the exten called originally.
1751          * We use this to set the proper extension
1752          * to dial during the recall since the incoming
1753          * request URI is one that was generated just
1754          * for the recall
1755          */
1756         char original_exten[SIPBUFSIZE];
1757         /* A reference to the dialog which we will
1758          * be sending a NOTIFY on when it comes time
1759          * to send one
1760          */
1761         struct sip_pvt *subscribe_pvt;
1762         /* When we send a NOTIFY, we include a URI
1763          * that should be used by the caller when he
1764          * wishes to send a PUBLISH or INVITE to us.
1765          * We store that URI here.
1766          */
1767         char notify_uri[SIPBUFSIZE];
1768         /* When we advertise call completion to a caller,
1769          * we provide a URI for the caller to use when
1770          * he sends us a SUBSCRIBE. We store it for matching
1771          * purposes when we receive the SUBSCRIBE from the
1772          * caller.
1773          */
1774         char subscribe_uri[SIPBUFSIZE];
1775         char is_available;
1776 };
1777
1778 struct sip_monitor_instance {
1779         AST_DECLARE_STRING_FIELDS(
1780                 AST_STRING_FIELD(subscribe_uri);
1781                 AST_STRING_FIELD(notify_uri);
1782                 AST_STRING_FIELD(peername);
1783                 AST_STRING_FIELD(device_name);
1784         );
1785         int core_id;
1786         struct sip_pvt *subscription_pvt;
1787         struct sip_epa_entry *suspension_entry;
1788 };
1789
1790 /*!
1791  * \brief uri parameters
1792  *
1793  */
1794
1795 struct uriparams {
1796         char *transport;
1797         char *user;
1798         char *method;
1799         char *ttl;
1800         char *maddr;
1801         int lr;
1802 };
1803
1804 struct contact {
1805         AST_LIST_ENTRY(contact) list;
1806         char *name;
1807         char *user;
1808         char *pass;
1809         char *hostport;
1810         struct uriparams params;
1811         char *headers;
1812         char *expires;
1813         char *q;
1814 };
1815
1816 AST_LIST_HEAD_NOLOCK(contactliststruct, contact);
1817
1818 /*! \brief List of well-known SIP options. If we get this in a require,
1819    we should check the list and answer accordingly. */
1820 static const struct cfsip_options {
1821         int id;             /*!< Bitmap ID */
1822         int supported;      /*!< Supported by Asterisk ? */
1823         char * const text;  /*!< Text id, as in standard */
1824 } sip_options[] = {     /* XXX used in 3 places */
1825         /* RFC3262: PRACK 100% reliability */
1826         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },
1827         /* RFC3959: SIP Early session support */
1828         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
1829         /* SIMPLE events:  RFC4662 */
1830         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
1831         /* RFC 4916- Connected line ID updates */
1832         { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED,  "from-change" },
1833         /* GRUU: Globally Routable User Agent URI's */
1834         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
1835         /* RFC4244 History info */
1836         { SIP_OPT_HISTINFO,     NOT_SUPPORTED,  "histinfo" },
1837         /* RFC3911: SIP Join header support */
1838         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
1839         /* Disable the REFER subscription, RFC 4488 */
1840         { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED,  "norefersub" },
1841         /* SIP outbound - the final NAT battle - draft-sip-outbound */
1842         { SIP_OPT_OUTBOUND,     NOT_SUPPORTED,  "outbound" },
1843         /* RFC3327: Path support */
1844         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
1845         /* RFC3840: Callee preferences */
1846         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
1847         /* RFC3312: Precondition support */
1848         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
1849         /* RFC3323: Privacy with proxies*/
1850         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
1851         /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
1852         { SIP_OPT_RECLISTINV,   NOT_SUPPORTED,  "recipient-list-invite" },
1853         /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
1854         { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED,  "recipient-list-subscribe" },
1855         /* RFC3891: Replaces: header for transfer */
1856         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },
1857         /* One version of Polycom firmware has the wrong label */
1858         { SIP_OPT_REPLACES,     SUPPORTED,      "replace" },
1859         /* RFC4412 Resource priorities */
1860         { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED,  "resource-priority" },
1861         /* RFC3329: Security agreement mechanism */
1862         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
1863         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
1864         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
1865         /* RFC4028: SIP Session-Timers */
1866         { SIP_OPT_TIMER,        SUPPORTED,      "timer" },
1867         /* RFC4538: Target-dialog */
1868         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "tdialog" },
1869 };
1870
1871 struct digestkeys {
1872         const char *key;
1873         const char *s;
1874 };
1875
1876 AST_THREADSTORAGE(check_auth_buf);
1877
1878 /*----------------------------------------------------------*/
1879 /*----                    FUNCTIONS                     ----*/
1880 /*----------------------------------------------------------*/
1881
1882 struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport);
1883 void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader);
1884 const char *sip_get_header(const struct sip_request *req, const char *name);
1885 const char *sip_get_transport(enum sip_transport t);
1886 void *sip_unref_peer(struct sip_peer *peer, char *tag);
1887 struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag);
1888
1889 #endif