Merged revisions 49636 via svnmerge from
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief Implementation of Session Initiation Protocol
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  *
28  * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
29  * Configuration file \link Config_sip sip.conf \endlink
30  *
31  *
32  * \todo SIP over TCP
33  * \todo SIP over TLS
34  * \todo Better support of forking
35  * \todo VIA branch tag transaction checking
36  * \todo Transaction support
37  *
38  * \ingroup channel_drivers
39  *
40  * \par Overview of the handling of SIP sessions
41  * The SIP channel handles several types of SIP sessions, or dialogs,
42  * not all of them being "telephone calls".
43  * - Incoming calls that will be sent to the PBX core
44  * - Outgoing calls, generated by the PBX
45  * - SIP subscriptions and notifications of states and voicemail messages
46  * - SIP registrations, both inbound and outbound
47  * - SIP peer management (peerpoke, OPTIONS)
48  * - SIP text messages
49  *
50  * In the SIP channel, there's a list of active SIP dialogs, which includes
51  * all of these when they are active. "sip show channels" in the CLI will
52  * show most of these, excluding subscriptions which are shown by
53  * "sip show subscriptions"
54  *
55  * \par incoming packets
56  * Incoming packets are received in the monitoring thread, then handled by
57  * sipsock_read(). This function parses the packet and matches an existing
58  * dialog or starts a new SIP dialog.
59  * 
60  * sipsock_read sends the packet to handle_request(), that parses a bit more.
61  * if it's a response to an outbound request, it's sent to handle_response().
62  * If it is a request, handle_request sends it to one of a list of functions
63  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64  * sipsock_read locks the ast_channel if it exists (an active call) and
65  * unlocks it after we have processed the SIP message.
66  *
67  * A new INVITE is sent to handle_request_invite(), that will end up
68  * starting a new channel in the PBX, the new channel after that executing
69  * in a separate channel thread. This is an incoming "call".
70  * When the call is answered, either by a bridged channel or the PBX itself
71  * the sip_answer() function is called.
72  *
73  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
74  * in rtp.c 
75  * 
76  * \par Outbound calls
77  * Outbound calls are set up by the PBX through the sip_request_call()
78  * function. After that, they are activated by sip_call().
79  * 
80  * \par Hanging up
81  * The PBX issues a hangup on both incoming and outgoing calls through
82  * the sip_hangup() function
83  */
84
85
86 #include "asterisk.h"
87
88 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
89
90 #include <stdio.h>
91 #include <ctype.h>
92 #include <string.h>
93 #include <unistd.h>
94 #include <sys/socket.h>
95 #include <sys/ioctl.h>
96 #include <net/if.h>
97 #include <errno.h>
98 #include <stdlib.h>
99 #include <fcntl.h>
100 #include <netdb.h>
101 #include <signal.h>
102 #include <sys/signal.h>
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <arpa/inet.h>
106 #include <netinet/ip.h>
107 #include <regex.h>
108
109 #include "asterisk/lock.h"
110 #include "asterisk/channel.h"
111 #include "asterisk/config.h"
112 #include "asterisk/logger.h"
113 #include "asterisk/module.h"
114 #include "asterisk/pbx.h"
115 #include "asterisk/options.h"
116 #include "asterisk/sched.h"
117 #include "asterisk/io.h"
118 #include "asterisk/rtp.h"
119 #include "asterisk/udptl.h"
120 #include "asterisk/acl.h"
121 #include "asterisk/manager.h"
122 #include "asterisk/callerid.h"
123 #include "asterisk/cli.h"
124 #include "asterisk/app.h"
125 #include "asterisk/musiconhold.h"
126 #include "asterisk/dsp.h"
127 #include "asterisk/features.h"
128 #include "asterisk/srv.h"
129 #include "asterisk/astdb.h"
130 #include "asterisk/causes.h"
131 #include "asterisk/utils.h"
132 #include "asterisk/file.h"
133 #include "asterisk/astobj.h"
134 #include "asterisk/dnsmgr.h"
135 #include "asterisk/devicestate.h"
136 #include "asterisk/linkedlists.h"
137 #include "asterisk/stringfields.h"
138 #include "asterisk/monitor.h"
139 #include "asterisk/localtime.h"
140 #include "asterisk/abstract_jb.h"
141 #include "asterisk/compiler.h"
142 #include "asterisk/threadstorage.h"
143 #include "asterisk/translate.h"
144 #include "asterisk/version.h"
145
146 #ifndef FALSE
147 #define FALSE    0
148 #endif
149
150 #ifndef TRUE
151 #define TRUE     1
152 #endif
153
154 #define VIDEO_CODEC_MASK        0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
155 #ifndef IPTOS_MINCOST
156 #define IPTOS_MINCOST           0x02
157 #endif
158
159 /* #define VOCAL_DATA_HACK */
160
161 #define DEFAULT_DEFAULT_EXPIRY  120
162 #define DEFAULT_MIN_EXPIRY      60
163 #define DEFAULT_MAX_EXPIRY      3600
164 #define DEFAULT_REGISTRATION_TIMEOUT 20
165 #define DEFAULT_MAX_FORWARDS    "70"
166
167 /* guard limit must be larger than guard secs */
168 /* guard min must be < 1000, and should be >= 250 */
169 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
170 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
171                                                    EXPIRY_GUARD_SECS */
172 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
173                                                    GUARD_PCT turns out to be lower than this, it 
174                                                    will use this time instead.
175                                                    This is in milliseconds. */
176 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
177                                                     below EXPIRY_GUARD_LIMIT */
178 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
179
180 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
181 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
182 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
183 static int expiry = DEFAULT_EXPIRY;
184
185 #ifndef MAX
186 #define MAX(a,b) ((a) > (b) ? (a) : (b))
187 #endif
188
189 #define CALLERID_UNKNOWN        "Unknown"
190
191 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
192 #define DEFAULT_FREQ_OK              60 * 1000        /*!< Qualification: How often to check for the host to be up */
193 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
194
195 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
196 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
197 #define SIP_TIMER_T1                 500              /* SIP timer T1 (according to RFC 3261) */
198 #define SIP_TRANS_TIMEOUT            32000            /*!< SIP request timeout (rfc 3261) 64*T1 
199                                                       \todo Use known T1 for timeout (peerpoke)
200                                                       */
201 #define DEFAULT_TRANS_TIMEOUT        -1               /* Use default SIP transaction timeout */
202 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
203
204 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
205 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
206 #define SIP_MAX_PACKET               4096             /*!< Also from RFC 3261 (2543), should sub headers tho */
207
208 #define INITIAL_CSEQ                 101              /*!< our initial sip sequence number */
209
210 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
211 static struct ast_jb_conf default_jbconf =
212 {
213         .flags = 0,
214         .max_size = -1,
215         .resync_threshold = -1,
216         .impl = ""
217 };
218 static struct ast_jb_conf global_jbconf;
219
220 static const char config[] = "sip.conf";
221 static const char notify_config[] = "sip_notify.conf";
222
223 #define RTP     1
224 #define NO_RTP  0
225
226 /*! \brief Authorization scheme for call transfers 
227 \note Not a bitfield flag, since there are plans for other modes,
228         like "only allow transfers for authenticated devices" */
229 enum transfermodes {
230         TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
231         TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
232 };
233
234
235 enum sip_result {
236         AST_SUCCESS = 0,
237         AST_FAILURE = -1,
238 };
239
240 /*! \brief States for the INVITE transaction, not the dialog 
241         \note this is for the INVITE that sets up the dialog
242 */
243 enum invitestates {
244         INV_NONE = 0,           /*!< No state at all, maybe not an INVITE dialog */
245         INV_CALLING = 1,        /*!< Invite sent, no answer */
246         INV_PROCEEDING = 2,     /*!< We got/sent 1xx message */
247         INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
248         INV_COMPLETED = 4,      /*!< Got final response with error. Wait for ACK, then CONFIRMED */
249         INV_CONFIRMED = 5,      /*!< Confirmed response - we've got an ack (Incoming calls only) */
250         INV_TERMINATED = 6,     /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
251                                      The only way out of this is a BYE from one side */
252         INV_CANCELLED = 7,      /*!< Transaction cancelled by client or server in non-terminated state */
253 };
254
255 /* Do _NOT_ make any changes to this enum, or the array following it;
256    if you think you are doing the right thing, you are probably
257    not doing the right thing. If you think there are changes
258    needed, get someone else to review them first _before_
259    submitting a patch. If these two lists do not match properly
260    bad things will happen.
261 */
262
263 enum xmittype {
264         XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
265                                               If it fails, it's critical and will cause a teardown of the session */
266         XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
267         XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
268 };
269
270 enum parse_register_result {
271         PARSE_REGISTER_FAILED,
272         PARSE_REGISTER_UPDATE,
273         PARSE_REGISTER_QUERY,
274 };
275
276 enum subscriptiontype { 
277         NONE = 0,
278         XPIDF_XML,
279         DIALOG_INFO_XML,
280         CPIM_PIDF_XML,
281         PIDF_XML,
282         MWI_NOTIFICATION
283 };
284
285 static const struct cfsubscription_types {
286         enum subscriptiontype type;
287         const char * const event;
288         const char * const mediatype;
289         const char * const text;
290 } subscription_types[] = {
291         { NONE,            "-",        "unknown",                    "unknown" },
292         /* RFC 4235: SIP Dialog event package */
293         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
294         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
295         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
296         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
297         { MWI_NOTIFICATION,     "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
298 };
299
300 /*! \brief SIP Request methods known by Asterisk */
301 enum sipmethod {
302         SIP_UNKNOWN,            /* Unknown response */
303         SIP_RESPONSE,           /* Not request, response to outbound request */
304         SIP_REGISTER,
305         SIP_OPTIONS,
306         SIP_NOTIFY,
307         SIP_INVITE,
308         SIP_ACK,
309         SIP_PRACK,              /* Not supported at all */
310         SIP_BYE,
311         SIP_REFER,
312         SIP_SUBSCRIBE,
313         SIP_MESSAGE,
314         SIP_UPDATE,             /* We can send UPDATE; but not accept it */
315         SIP_INFO,
316         SIP_CANCEL,
317         SIP_PUBLISH,            /* Not supported at all */
318         SIP_PING,               /* Not supported at all, no standard but still implemented out there */
319 };
320
321 /*! \brief Authentication types - proxy or www authentication 
322         \note Endpoints, like Asterisk, should always use WWW authentication to
323         allow multiple authentications in the same call - to the proxy and
324         to the end point.
325 */
326 enum sip_auth_type {
327         PROXY_AUTH = 407,
328         WWW_AUTH = 401,
329 };
330
331 /*! \brief Authentication result from check_auth* functions */
332 enum check_auth_result {
333         AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
334                 /* XXX maybe this is the same as AUTH_NOT_FOUND */
335
336         AUTH_SUCCESSFUL = 0,
337         AUTH_CHALLENGE_SENT = 1,
338         AUTH_SECRET_FAILED = -1,
339         AUTH_USERNAME_MISMATCH = -2,
340         AUTH_NOT_FOUND = -3,    /* returned by register_verify */
341         AUTH_FAKE_AUTH = -4,
342         AUTH_UNKNOWN_DOMAIN = -5,
343 };
344
345 /*! \brief States for outbound registrations (with register= lines in sip.conf */
346 enum sipregistrystate {
347         REG_STATE_UNREGISTERED = 0,     /*!< We are not registred */
348         REG_STATE_REGSENT,      /*!< Registration request sent */
349         REG_STATE_AUTHSENT,     /*!< We have tried to authenticate */
350         REG_STATE_REGISTERED,   /*!< Registred and done */
351         REG_STATE_REJECTED,     /*!< Registration rejected */
352         REG_STATE_TIMEOUT,      /*!< Registration timed out */
353         REG_STATE_NOAUTH,       /*!< We have no accepted credentials */
354         REG_STATE_FAILED,       /*!< Registration failed after several tries */
355 };
356
357 enum can_create_dialog {
358         CAN_NOT_CREATE_DIALOG,
359         CAN_CREATE_DIALOG,
360         CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
361 };
362
363 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
364 static const struct  cfsip_methods { 
365         enum sipmethod id;
366         int need_rtp;           /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
367         char * const text;
368         enum can_create_dialog can_create;
369 } sip_methods[] = {
370         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
371         { SIP_RESPONSE,  NO_RTP, "SIP/2.0",     CAN_NOT_CREATE_DIALOG },
372         { SIP_REGISTER,  NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
373         { SIP_OPTIONS,   NO_RTP, "OPTIONS",     CAN_CREATE_DIALOG },
374         { SIP_NOTIFY,    NO_RTP, "NOTIFY",      CAN_CREATE_DIALOG },
375         { SIP_INVITE,    RTP,    "INVITE",      CAN_CREATE_DIALOG },
376         { SIP_ACK,       NO_RTP, "ACK",         CAN_NOT_CREATE_DIALOG },
377         { SIP_PRACK,     NO_RTP, "PRACK",       CAN_NOT_CREATE_DIALOG },
378         { SIP_BYE,       NO_RTP, "BYE",         CAN_NOT_CREATE_DIALOG },
379         { SIP_REFER,     NO_RTP, "REFER",       CAN_CREATE_DIALOG },
380         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",   CAN_CREATE_DIALOG },
381         { SIP_MESSAGE,   NO_RTP, "MESSAGE",     CAN_CREATE_DIALOG },
382         { SIP_UPDATE,    NO_RTP, "UPDATE",      CAN_NOT_CREATE_DIALOG },
383         { SIP_INFO,      NO_RTP, "INFO",        CAN_NOT_CREATE_DIALOG },
384         { SIP_CANCEL,    NO_RTP, "CANCEL",      CAN_NOT_CREATE_DIALOG },
385         { SIP_PUBLISH,   NO_RTP, "PUBLISH",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
386         { SIP_PING,      NO_RTP, "PING",        CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
387 };
388
389 /*!  Define SIP option tags, used in Require: and Supported: headers 
390         We need to be aware of these properties in the phones to use 
391         the replace: header. We should not do that without knowing
392         that the other end supports it... 
393         This is nothing we can configure, we learn by the dialog
394         Supported: header on the REGISTER (peer) or the INVITE
395         (other devices)
396         We are not using many of these today, but will in the future.
397         This is documented in RFC 3261
398 */
399 #define SUPPORTED               1
400 #define NOT_SUPPORTED           0
401
402 #define SIP_OPT_REPLACES        (1 << 0)
403 #define SIP_OPT_100REL          (1 << 1)
404 #define SIP_OPT_TIMER           (1 << 2)
405 #define SIP_OPT_EARLY_SESSION   (1 << 3)
406 #define SIP_OPT_JOIN            (1 << 4)
407 #define SIP_OPT_PATH            (1 << 5)
408 #define SIP_OPT_PREF            (1 << 6)
409 #define SIP_OPT_PRECONDITION    (1 << 7)
410 #define SIP_OPT_PRIVACY         (1 << 8)
411 #define SIP_OPT_SDP_ANAT        (1 << 9)
412 #define SIP_OPT_SEC_AGREE       (1 << 10)
413 #define SIP_OPT_EVENTLIST       (1 << 11)
414 #define SIP_OPT_GRUU            (1 << 12)
415 #define SIP_OPT_TARGET_DIALOG   (1 << 13)
416 #define SIP_OPT_NOREFERSUB      (1 << 14)
417 #define SIP_OPT_HISTINFO        (1 << 15)
418 #define SIP_OPT_RESPRIORITY     (1 << 16)
419
420 /*! \brief List of well-known SIP options. If we get this in a require,
421    we should check the list and answer accordingly. */
422 static const struct cfsip_options {
423         int id;                 /*!< Bitmap ID */
424         int supported;          /*!< Supported by Asterisk ? */
425         char * const text;      /*!< Text id, as in standard */
426 } sip_options[] = {     /* XXX used in 3 places */
427         /* RFC3891: Replaces: header for transfer */
428         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },   
429         /* One version of Polycom firmware has the wrong label */
430         { SIP_OPT_REPLACES,     SUPPORTED,      "replace" },    
431         /* RFC3262: PRACK 100% reliability */
432         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },     
433         /* RFC4028: SIP Session Timers */
434         { SIP_OPT_TIMER,        NOT_SUPPORTED,  "timer" },
435         /* RFC3959: SIP Early session support */
436         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
437         /* RFC3911: SIP Join header support */
438         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
439         /* RFC3327: Path support */
440         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
441         /* RFC3840: Callee preferences */
442         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
443         /* RFC3312: Precondition support */
444         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
445         /* RFC3323: Privacy with proxies*/
446         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
447         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
448         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
449         /* RFC3329: Security agreement mechanism */
450         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
451         /* SIMPLE events:  RFC4662 */
452         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
453         /* GRUU: Globally Routable User Agent URI's */
454         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
455         /* RFC4538: Target-dialog */
456         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "tdialog" },
457         /* Disable the REFER subscription, RFC 4488 */
458         { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED,  "norefersub" },
459         /* ietf-sip-history-info-06.txt */
460         { SIP_OPT_HISTINFO,     NOT_SUPPORTED,  "histinfo" },
461         /* ietf-sip-resource-priority-10.txt */
462         { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED,  "resource-priority" },
463 };
464
465
466 /*! \brief SIP Methods we support */
467 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
468
469 /*! \brief SIP Extensions we support */
470 #define SUPPORTED_EXTENSIONS "replaces" 
471
472 /*! \brief Standard SIP port from RFC 3261. DO NOT CHANGE THIS */
473 #define STANDARD_SIP_PORT       5060
474 /* Note: in many SIP headers, absence of a port number implies port 5060,
475  * and this is why we cannot change the above constant.
476  * There is a limited number of places in asterisk where we could,
477  * in principle, use a different "default" port number, but
478  * we do not support this feature at the moment.
479  */
480
481 /* Default values, set and reset in reload_config before reading configuration */
482 /* These are default values in the source. There are other recommended values in the
483    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
484    yet encouraging new behaviour on new installations 
485  */
486 #define DEFAULT_CONTEXT         "default"
487 #define DEFAULT_MOHINTERPRET    "default"
488 #define DEFAULT_MOHSUGGEST      ""
489 #define DEFAULT_VMEXTEN         "asterisk"
490 #define DEFAULT_CALLERID        "asterisk"
491 #define DEFAULT_NOTIFYMIME      "application/simple-message-summary"
492 #define DEFAULT_MWITIME         10
493 #define DEFAULT_ALLOWGUEST      TRUE
494 #define DEFAULT_SRVLOOKUP       FALSE           /*!< Recommended setting is ON */
495 #define DEFAULT_COMPACTHEADERS  FALSE
496 #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. */
497 #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. */
498 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
499 #define DEFAULT_ALLOW_EXT_DOM   TRUE
500 #define DEFAULT_REALM           "asterisk"
501 #define DEFAULT_NOTIFYRINGING   TRUE
502 #define DEFAULT_PEDANTIC        FALSE
503 #define DEFAULT_AUTOCREATEPEER  FALSE
504 #define DEFAULT_QUALIFY         FALSE
505 #define DEFAULT_T1MIN           100             /*!< 100 MS for minimal roundtrip time */
506 #define DEFAULT_MAX_CALL_BITRATE (384)          /*!< Max bitrate for video */
507 #ifndef DEFAULT_USERAGENT
508 #define DEFAULT_USERAGENT "Asterisk PBX"        /*!< Default Useragent: header unless re-defined in sip.conf */
509 #endif
510
511
512 /* Default setttings are used as a channel setting and as a default when
513    configuring devices */
514 static char default_context[AST_MAX_CONTEXT];
515 static char default_subscribecontext[AST_MAX_CONTEXT];
516 static char default_language[MAX_LANGUAGE];
517 static char default_callerid[AST_MAX_EXTENSION];
518 static char default_fromdomain[AST_MAX_EXTENSION];
519 static char default_notifymime[AST_MAX_EXTENSION];
520 static int default_qualify;             /*!< Default Qualify= setting */
521 static char default_vmexten[AST_MAX_EXTENSION];
522 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
523 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
524                                                     *   a bridged channel on hold */
525 static int default_maxcallbitrate;      /*!< Maximum bitrate for call */
526 static struct ast_codec_pref default_prefs;             /*!< Default codec prefs */
527
528 /* Global settings only apply to the channel */
529 static int global_limitonpeers;         /*!< Match call limit on peers only */
530 static int global_rtautoclear;
531 static int global_notifyringing;        /*!< Send notifications on ringing */
532 static int global_notifyhold;           /*!< Send notifications on hold */
533 static int global_alwaysauthreject;     /*!< Send 401 Unauthorized for all failing requests */
534 static int global_srvlookup;                    /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
535 static int pedanticsipchecking;         /*!< Extra checking ?  Default off */
536 static int autocreatepeer;              /*!< Auto creation of peers at registration? Default off. */
537 static int global_match_auth_username;          /*!< Match auth username if available instead of From: Default off. */
538 static int global_relaxdtmf;                    /*!< Relax DTMF */
539 static int global_rtptimeout;           /*!< Time out call if no RTP */
540 static int global_rtpholdtimeout;
541 static int global_rtpkeepalive;         /*!< Send RTP keepalives */
542 static int global_reg_timeout;  
543 static int global_regattempts_max;      /*!< Registration attempts before giving up */
544 static int global_allowguest;           /*!< allow unauthenticated users/peers to connect? */
545 static int global_allowsubscribe;       /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
546                                             the global setting is in globals_flags[1] */
547 static int global_mwitime;              /*!< Time between MWI checks for peers */
548 static unsigned int global_tos_sip;             /*!< IP type of service for SIP packets */
549 static unsigned int global_tos_audio;           /*!< IP type of service for audio RTP packets */
550 static unsigned int global_tos_video;           /*!< IP type of service for video RTP packets */
551 static int compactheaders;              /*!< send compact sip headers */
552 static int recordhistory;               /*!< Record SIP history. Off by default */
553 static int dumphistory;                 /*!< Dump history to verbose before destroying SIP dialog */
554 static char global_realm[MAXHOSTNAMELEN];               /*!< Default realm */
555 static char global_regcontext[AST_MAX_CONTEXT];         /*!< Context for auto-extensions */
556 static char global_useragent[AST_MAX_EXTENSION];        /*!< Useragent for the SIP channel */
557 static int allow_external_domains;      /*!< Accept calls to external SIP domains? */
558 static int global_callevents;           /*!< Whether we send manager events or not */
559 static int global_t1min;                /*!< T1 roundtrip time minimum */
560 static int global_autoframing;          /*!< Turn autoframing on or off. */
561 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
562
563 /*! \brief Codecs that we support by default: */
564 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
565 static int noncodeccapability = AST_RTP_DTMF;
566
567 /* Object counters */
568 static int suserobjs = 0;                /*!< Static users */
569 static int ruserobjs = 0;                /*!< Realtime users */
570 static int speerobjs = 0;                /*!< Statis peers */
571 static int rpeerobjs = 0;                /*!< Realtime peers */
572 static int apeerobjs = 0;                /*!< Autocreated peer objects */
573 static int regobjs = 0;                  /*!< Registry objects */
574
575 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
576
577 AST_MUTEX_DEFINE_STATIC(netlock);
578
579 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
580    when it's doing something critical. */
581
582 AST_MUTEX_DEFINE_STATIC(monlock);
583
584 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
585
586 /*! \brief This is the thread for the monitor which checks for input on the channels
587    which are not currently in use.  */
588 static pthread_t monitor_thread = AST_PTHREADT_NULL;
589
590 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
591 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
592
593 static struct sched_context *sched;     /*!< The scheduling context */
594 static struct io_context *io;           /*!< The IO context */
595 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
596
597 #define DEC_CALL_LIMIT  0
598 #define INC_CALL_LIMIT  1
599 #define DEC_CALL_RINGING 2
600 #define INC_CALL_RINGING 3
601
602 /*! \brief sip_request: The data grabbed from the UDP socket */
603 struct sip_request {
604         char *rlPart1;          /*!< SIP Method Name or "SIP/2.0" protocol version */
605         char *rlPart2;          /*!< The Request URI or Response Status */
606         int len;                /*!< Length */
607         int headers;            /*!< # of SIP Headers */
608         int method;             /*!< Method of this request */
609         int lines;              /*!< Body Content */
610         unsigned int flags;     /*!< SIP_PKT Flags for this packet */
611         char *header[SIP_MAX_HEADERS];
612         char *line[SIP_MAX_LINES];
613         char data[SIP_MAX_PACKET];
614         unsigned int sdp_start; /*!< the line number where the SDP begins */
615         unsigned int sdp_end;   /*!< the line number where the SDP ends */
616 };
617
618 /*
619  * A sip packet is stored into the data[] buffer, with the header followed
620  * by an empty line and the body of the message.
621  * On outgoing packets, data is accumulated in data[] with len reflecting
622  * the next available byte, headers and lines count the number of lines
623  * in both parts. There are no '\0' in data[0..len-1].
624  *
625  * On received packet, the input read from the socket is copied into data[],
626  * len is set and the string is NUL-terminated. Then a parser fills up
627  * the other fields -header[] and line[] to point to the lines of the
628  * message, rlPart1 and rlPart2 parse the first lnie as below:
629  *
630  * Requests have in the first line      METHOD URI SIP/2.0
631  *      rlPart1 = method; rlPart2 = uri;
632  * Responses have in the first line     SIP/2.0 code description
633  *      rlPart1 = SIP/2.0; rlPart2 = code + description;
634  *
635  */
636
637 /*! \brief structure used in transfers */
638 struct sip_dual {
639         struct ast_channel *chan1;      /*!< First channel involved */
640         struct ast_channel *chan2;      /*!< Second channel involved */
641         struct sip_request req;         /*!< Request that caused the transfer (REFER) */
642         int seqno;                      /*!< Sequence number */
643 };
644
645 struct sip_pkt;
646
647 /*! \brief Parameters to the transmit_invite function */
648 struct sip_invite_param {
649         int addsipheaders;              /*!< Add extra SIP headers */
650         const char *uri_options;        /*!< URI options to add to the URI */
651         const char *vxml_url;           /*!< VXML url for Cisco phones */
652         char *auth;                     /*!< Authentication */
653         char *authheader;               /*!< Auth header */
654         enum sip_auth_type auth_type;   /*!< Authentication type */
655         const char *replaces;           /*!< Replaces header for call transfers */
656         int transfer;                   /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
657 };
658
659 /*! \brief Structure to save routing information for a SIP session */
660 struct sip_route {
661         struct sip_route *next;
662         char hop[0];
663 };
664
665 /*! \brief Modes for SIP domain handling in the PBX */
666 enum domain_mode {
667         SIP_DOMAIN_AUTO,                /*!< This domain is auto-configured */
668         SIP_DOMAIN_CONFIG,              /*!< This domain is from configuration */
669 };
670
671 /*! \brief Domain data structure. 
672         \note In the future, we will connect this to a configuration tree specific
673         for this domain
674 */
675 struct domain {
676         char domain[MAXHOSTNAMELEN];            /*!< SIP domain we are responsible for */
677         char context[AST_MAX_EXTENSION];        /*!< Incoming context for this domain */
678         enum domain_mode mode;                  /*!< How did we find this domain? */
679         AST_LIST_ENTRY(domain) list;            /*!< List mechanics */
680 };
681
682 static AST_LIST_HEAD_STATIC(domain_list, domain);       /*!< The SIP domain list */
683
684
685 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
686 struct sip_history {
687         AST_LIST_ENTRY(sip_history) list;
688         char event[0];  /* actually more, depending on needs */
689 };
690
691 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
692
693 /*! \brief sip_auth: Credentials for authentication to other SIP services */
694 struct sip_auth {
695         char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
696         char username[256];             /*!< Username */
697         char secret[256];               /*!< Secret */
698         char md5secret[256];            /*!< MD5Secret */
699         struct sip_auth *next;          /*!< Next auth structure in list */
700 };
701
702 /*--- Various flags for the flags field in the pvt structure */
703 #define SIP_ALREADYGONE         (1 << 0)        /*!< Whether or not we've already been destroyed by our peer */
704 #define SIP_NEEDDESTROY         (1 << 1)        /*!< if we need to be destroyed by the monitor thread */
705 #define SIP_NOVIDEO             (1 << 2)        /*!< Didn't get video in invite, don't offer */
706 #define SIP_RINGING             (1 << 3)        /*!< Have sent 180 ringing */
707 #define SIP_PROGRESS_SENT       (1 << 4)        /*!< Have sent 183 message progress */
708 #define SIP_NEEDREINVITE        (1 << 5)        /*!< Do we need to send another reinvite? */
709 #define SIP_PENDINGBYE          (1 << 6)        /*!< Need to send bye after we ack? */
710 #define SIP_GOTREFER            (1 << 7)        /*!< Got a refer? */
711 #define SIP_PROMISCREDIR        (1 << 8)        /*!< Promiscuous redirection */
712 #define SIP_TRUSTRPID           (1 << 9)        /*!< Trust RPID headers? */
713 #define SIP_USEREQPHONE         (1 << 10)       /*!< Add user=phone to numeric URI. Default off */
714 #define SIP_REALTIME            (1 << 11)       /*!< Flag for realtime users */
715 #define SIP_USECLIENTCODE       (1 << 12)       /*!< Trust X-ClientCode info message */
716 #define SIP_OUTGOING            (1 << 13)       /*!< Direction of the last transaction in this dialog */
717 #define SIP_FREE_BIT            (1 << 14)       /*!< ---- */
718 #define SIP_DEFER_BYE_ON_TRANSFER       (1 << 15)       /*!< Do not hangup at first ast_hangup */
719 #define SIP_DTMF                (3 << 16)       /*!< DTMF Support: four settings, uses two bits */
720 #define SIP_DTMF_RFC2833        (0 << 16)       /*!< DTMF Support: RTP DTMF - "rfc2833" */
721 #define SIP_DTMF_INBAND         (1 << 16)       /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
722 #define SIP_DTMF_INFO           (2 << 16)       /*!< DTMF Support: SIP Info messages - "info" */
723 #define SIP_DTMF_AUTO           (3 << 16)       /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
724 /* NAT settings */
725 #define SIP_NAT                 (3 << 18)       /*!< four settings, uses two bits */
726 #define SIP_NAT_NEVER           (0 << 18)       /*!< No nat support */
727 #define SIP_NAT_RFC3581         (1 << 18)       /*!< NAT RFC3581 */
728 #define SIP_NAT_ROUTE           (2 << 18)       /*!< NAT Only ROUTE */
729 #define SIP_NAT_ALWAYS          (3 << 18)       /*!< NAT Both ROUTE and RFC3581 */
730 /* re-INVITE related settings */
731 #define SIP_REINVITE            (7 << 20)       /*!< three bits used */
732 #define SIP_CAN_REINVITE        (1 << 20)       /*!< allow peers to be reinvited to send media directly p2p */
733 #define SIP_CAN_REINVITE_NAT    (2 << 20)       /*!< allow media reinvite when new peer is behind NAT */
734 #define SIP_REINVITE_UPDATE     (4 << 20)       /*!< use UPDATE (RFC3311) when reinviting this peer */
735 /* "insecure" settings */
736 #define SIP_INSECURE_PORT       (1 << 23)       /*!< don't require matching port for incoming requests */
737 #define SIP_INSECURE_INVITE     (1 << 24)       /*!< don't require authentication for incoming INVITEs */
738 /* Sending PROGRESS in-band settings */
739 #define SIP_PROG_INBAND         (3 << 25)       /*!< three settings, uses two bits */
740 #define SIP_PROG_INBAND_NEVER   (0 << 25)
741 #define SIP_PROG_INBAND_NO      (1 << 25)
742 #define SIP_PROG_INBAND_YES     (2 << 25)
743 #define SIP_NO_HISTORY          (1 << 27)       /*!< Suppress recording request/response history */
744 #define SIP_CALL_LIMIT          (1 << 28)       /*!< Call limit enforced for this call */
745 #define SIP_SENDRPID            (1 << 29)       /*!< Remote Party-ID Support */
746 #define SIP_INC_COUNT           (1 << 30)       /*!< Did this connection increment the counter of in-use calls? */
747 #define SIP_G726_NONSTANDARD    (1 << 31)       /*!< Use non-standard packing for G726-32 data */
748
749 #define SIP_FLAGS_TO_COPY \
750         (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
751          SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
752          SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
753
754 /*--- a new page of flags (for flags[1] */
755 /* realtime flags */
756 #define SIP_PAGE2_RTCACHEFRIENDS        (1 << 0)
757 #define SIP_PAGE2_RTUPDATE              (1 << 1)
758 #define SIP_PAGE2_RTAUTOCLEAR           (1 << 2)
759 #define SIP_PAGE2_RT_FROMCONTACT        (1 << 4)
760 #define SIP_PAGE2_RTSAVE_SYSNAME        (1 << 5)
761 /* Space for addition of other realtime flags in the future */
762 #define SIP_PAGE2_IGNOREREGEXPIRE       (1 << 10)
763 #define SIP_PAGE2_DEBUG                 (3 << 11)
764 #define SIP_PAGE2_DEBUG_CONFIG          (1 << 11)
765 #define SIP_PAGE2_DEBUG_CONSOLE         (1 << 12)
766 #define SIP_PAGE2_DYNAMIC               (1 << 13)       /*!< Dynamic Peers register with Asterisk */
767 #define SIP_PAGE2_SELFDESTRUCT          (1 << 14)       /*!< Automatic peers need to destruct themselves */
768 #define SIP_PAGE2_VIDEOSUPPORT          (1 << 15)
769 #define SIP_PAGE2_ALLOWSUBSCRIBE        (1 << 16)       /*!< Allow subscriptions from this peer? */
770 #define SIP_PAGE2_ALLOWOVERLAP          (1 << 17)       /*!< Allow overlap dialing ? */
771 #define SIP_PAGE2_SUBSCRIBEMWIONLY      (1 << 18)       /*!< Only issue MWI notification if subscribed to */
772 #define SIP_PAGE2_INC_RINGING           (1 << 19)       /*!< Did this connection increment the counter of in-use calls? */
773 #define SIP_PAGE2_T38SUPPORT            (7 << 20)       /*!< T38 Fax Passthrough Support */
774 #define SIP_PAGE2_T38SUPPORT_UDPTL      (1 << 20)       /*!< 20: T38 Fax Passthrough Support */
775 #define SIP_PAGE2_T38SUPPORT_RTP        (2 << 20)       /*!< 21: T38 Fax Passthrough Support (not implemented) */
776 #define SIP_PAGE2_T38SUPPORT_TCP        (4 << 20)       /*!< 22: T38 Fax Passthrough Support (not implemented) */
777 #define SIP_PAGE2_CALL_ONHOLD           (3 << 23)       /*!< Call states */
778 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR    (1 << 23)       /*!< 23: One directional hold */
779 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE  (1 << 24)       /*!< 24: Inactive  */
780 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)       /*!< 25: ???? */
781 #define SIP_PAGE2_BUGGY_MWI             (1 << 26)       /*!< 26: Buggy CISCO MWI fix */
782
783 #define SIP_PAGE2_FLAGS_TO_COPY \
784         (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
785         SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI)
786
787 /* SIP packet flags */
788 #define SIP_PKT_DEBUG           (1 << 0)        /*!< Debug this packet */
789 #define SIP_PKT_WITH_TOTAG      (1 << 1)        /*!< This packet has a to-tag */
790 #define SIP_PKT_IGNORE          (1 << 2)        /*!< This is a re-transmit, ignore it */
791
792 /* T.38 set of flags */
793 #define T38FAX_FILL_BIT_REMOVAL         (1 << 0)        /*!< Default: 0 (unset)*/
794 #define T38FAX_TRANSCODING_MMR                  (1 << 1)        /*!< Default: 0 (unset)*/
795 #define T38FAX_TRANSCODING_JBIG         (1 << 2)        /*!< Default: 0 (unset)*/
796 /* Rate management */
797 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF   (0 << 3)
798 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF        (1 << 3)        /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
799 /* UDP Error correction */
800 #define T38FAX_UDP_EC_NONE                      (0 << 4)        /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
801 #define T38FAX_UDP_EC_FEC                       (1 << 4)        /*!< Set for t38UDPFEC */
802 #define T38FAX_UDP_EC_REDUNDANCY                (2 << 4)        /*!< Set for t38UDPRedundancy */
803 /* T38 Spec version */
804 #define T38FAX_VERSION                          (3 << 6)        /*!< two bits, 2 values so far, up to 4 values max */
805 #define T38FAX_VERSION_0                        (0 << 6)        /*!< Version 0 */
806 #define T38FAX_VERSION_1                        (1 << 6)        /*!< Version 1 */
807 /* Maximum Fax Rate */
808 #define T38FAX_RATE_2400                        (1 << 8)        /*!< 2400 bps t38FaxRate */
809 #define T38FAX_RATE_4800                        (1 << 9)        /*!< 4800 bps t38FaxRate */
810 #define T38FAX_RATE_7200                        (1 << 10)       /*!< 7200 bps t38FaxRate */
811 #define T38FAX_RATE_9600                        (1 << 11)       /*!< 9600 bps t38FaxRate */
812 #define T38FAX_RATE_12000                       (1 << 12)       /*!< 12000 bps t38FaxRate */
813 #define T38FAX_RATE_14400                       (1 << 13)       /*!< 14400 bps t38FaxRate */
814
815 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
816 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
817
818 #define sipdebug                ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
819 #define sipdebug_config         ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
820 #define sipdebug_console        ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
821
822 /*! \brief T38 States for a call */
823 enum t38state {
824         T38_DISABLED = 0,                /*!< Not enabled */
825         T38_LOCAL_DIRECT,                /*!< Offered from local */
826         T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
827         T38_PEER_DIRECT,                 /*!< Offered from peer */
828         T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
829         T38_ENABLED                      /*!< Negotiated (enabled) */
830 };
831
832 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
833 struct t38properties {
834         struct ast_flags t38support;    /*!< Flag for udptl, rtp or tcp support for this session */
835         int capability;                 /*!< Our T38 capability */
836         int peercapability;             /*!< Peers T38 capability */
837         int jointcapability;            /*!< Supported T38 capability at both ends */
838         enum t38state state;            /*!< T.38 state */
839 };
840
841 /*! \brief Parameters to know status of transfer */
842 enum referstatus {
843         REFER_IDLE,                    /*!< No REFER is in progress */
844         REFER_SENT,                    /*!< Sent REFER to transferee */
845         REFER_RECEIVED,                /*!< Received REFER from transferrer */
846         REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING */
847         REFER_ACCEPTED,                /*!< Accepted by transferee */
848         REFER_RINGING,                 /*!< Target Ringing */
849         REFER_200OK,                   /*!< Answered by transfer target */
850         REFER_FAILED,                  /*!< REFER declined - go on */
851         REFER_NOAUTH                   /*!< We had no auth for REFER */
852 };
853
854 static const struct c_referstatusstring {
855         enum referstatus status;
856         char *text;
857 } referstatusstrings[] = {
858         { REFER_IDLE,           "<none>" },
859         { REFER_SENT,           "Request sent" },
860         { REFER_RECEIVED,       "Request received" },
861         { REFER_ACCEPTED,       "Accepted" },
862         { REFER_RINGING,        "Target ringing" },
863         { REFER_200OK,          "Done" },
864         { REFER_FAILED,         "Failed" },
865         { REFER_NOAUTH,         "Failed - auth failure" }
866 } ;
867
868 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed  */
869 /* OEJ: Should be moved to string fields */
870 struct sip_refer {
871         char refer_to[AST_MAX_EXTENSION];               /*!< Place to store REFER-TO extension */
872         char refer_to_domain[AST_MAX_EXTENSION];        /*!< Place to store REFER-TO domain */
873         char refer_to_urioption[AST_MAX_EXTENSION];     /*!< Place to store REFER-TO uri options */
874         char refer_to_context[AST_MAX_EXTENSION];       /*!< Place to store REFER-TO context */
875         char referred_by[AST_MAX_EXTENSION];            /*!< Place to store REFERRED-BY extension */
876         char referred_by_name[AST_MAX_EXTENSION];       /*!< Place to store REFERRED-BY extension */
877         char refer_contact[AST_MAX_EXTENSION];          /*!< Place to store Contact info from a REFER extension */
878         char replaces_callid[BUFSIZ];                   /*!< Replace info: callid */
879         char replaces_callid_totag[BUFSIZ/2];           /*!< Replace info: to-tag */
880         char replaces_callid_fromtag[BUFSIZ/2];         /*!< Replace info: from-tag */
881         struct sip_pvt *refer_call;                     /*!< Call we are referring */
882         int attendedtransfer;                           /*!< Attended or blind transfer? */
883         int localtransfer;                              /*!< Transfer to local domain? */
884         enum referstatus status;                        /*!< REFER status */
885 };
886
887 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe  */
888 struct sip_pvt {
889         ast_mutex_t pvt_lock;                   /*!< Dialog private lock */
890         enum invitestates invitestate;          /*!< Track state of SIP_INVITEs */
891         int method;                             /*!< SIP method that opened this dialog */
892         AST_DECLARE_STRING_FIELDS(
893                 AST_STRING_FIELD(callid);       /*!< Global CallID */
894                 AST_STRING_FIELD(randdata);     /*!< Random data */
895                 AST_STRING_FIELD(accountcode);  /*!< Account code */
896                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
897                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
898                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
899                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
900                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
901                 AST_STRING_FIELD(from);         /*!< The From: header */
902                 AST_STRING_FIELD(useragent);    /*!< User agent in SIP request */
903                 AST_STRING_FIELD(exten);        /*!< Extension where to start */
904                 AST_STRING_FIELD(context);      /*!< Context for this call */
905                 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
906                 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
907                 AST_STRING_FIELD(fromdomain);   /*!< Domain to show in the from field */
908                 AST_STRING_FIELD(fromuser);     /*!< User to show in the user field */
909                 AST_STRING_FIELD(fromname);     /*!< Name to show in the user field */
910                 AST_STRING_FIELD(tohost);       /*!< Host we should put in the "to" field */
911                 AST_STRING_FIELD(language);     /*!< Default language for this call */
912                 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
913                 AST_STRING_FIELD(mohsuggest);   /*!< MOH class to suggest when putting a peer on hold */
914                 AST_STRING_FIELD(rdnis);        /*!< Referring DNIS */
915                 AST_STRING_FIELD(redircause);   /*!< Referring cause */
916                 AST_STRING_FIELD(theirtag);     /*!< Their tag */
917                 AST_STRING_FIELD(username);     /*!< [user] name */
918                 AST_STRING_FIELD(peername);     /*!< [peer] name, not set if [user] */
919                 AST_STRING_FIELD(authname);     /*!< Who we use for authentication */
920                 AST_STRING_FIELD(uri);          /*!< Original requested URI */
921                 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
922                 AST_STRING_FIELD(peersecret);   /*!< Password */
923                 AST_STRING_FIELD(peermd5secret);
924                 AST_STRING_FIELD(cid_num);      /*!< Caller*ID number */
925                 AST_STRING_FIELD(cid_name);     /*!< Caller*ID name */
926                 AST_STRING_FIELD(via);          /*!< Via: header */
927                 AST_STRING_FIELD(fullcontact);  /*!< The Contact: that the UA registers with us */
928                         /* we only store the part in <brackets> in this field. */
929                 AST_STRING_FIELD(our_contact);  /*!< Our contact header */
930                 AST_STRING_FIELD(rpid);         /*!< Our RPID header */
931                 AST_STRING_FIELD(rpid_from);    /*!< Our RPID From header */
932         );
933         unsigned int ocseq;                     /*!< Current outgoing seqno */
934         unsigned int icseq;                     /*!< Current incoming seqno */
935         ast_group_t callgroup;                  /*!< Call group */
936         ast_group_t pickupgroup;                /*!< Pickup group */
937         int lastinvite;                         /*!< Last Cseq of invite */
938         struct ast_flags flags[2];              /*!< SIP_ flags */
939         int timer_t1;                           /*!< SIP timer T1, ms rtt */
940         unsigned int sipoptions;                /*!< Supported SIP options on the other end */
941         struct ast_codec_pref prefs;            /*!< codec prefs */
942         int capability;                         /*!< Special capability (codec) */
943         int jointcapability;                    /*!< Supported capability at both ends (codecs) */
944         int peercapability;                     /*!< Supported peer capability */
945         int prefcodec;                          /*!< Preferred codec (outbound only) */
946         int noncodeccapability;                 /*!< DTMF RFC2833 telephony-event */
947         int redircodecs;                        /*!< Redirect codecs */
948         int maxcallbitrate;                     /*!< Maximum Call Bitrate for Video Calls */    
949         struct t38properties t38;               /*!< T38 settings */
950         struct sockaddr_in udptlredirip;        /*!< Where our T.38 UDPTL should be going if not to us */
951         struct ast_udptl *udptl;                /*!< T.38 UDPTL session */
952         int callingpres;                        /*!< Calling presentation */
953         int authtries;                          /*!< Times we've tried to authenticate */
954         int expiry;                             /*!< How long we take to expire */
955         long branch;                            /*!< The branch identifier of this session */
956         char tag[11];                           /*!< Our tag for this session */
957         int sessionid;                          /*!< SDP Session ID */
958         int sessionversion;                     /*!< SDP Session Version */
959         struct sockaddr_in sa;                  /*!< Our peer */
960         struct sockaddr_in redirip;             /*!< Where our RTP should be going if not to us */
961         struct sockaddr_in vredirip;            /*!< Where our Video RTP should be going if not to us */
962         time_t lastrtprx;                       /*!< Last RTP received */
963         time_t lastrtptx;                       /*!< Last RTP sent */
964         int rtptimeout;                         /*!< RTP timeout time */
965         struct sockaddr_in recv;                /*!< Received as */
966         struct in_addr ourip;                   /*!< Our IP */
967         struct ast_channel *owner;              /*!< Who owns us (if we have an owner) */
968         struct sip_route *route;                /*!< Head of linked list of routing steps (fm Record-Route) */
969         int route_persistant;                   /*!< Is this the "real" route? */
970         struct sip_auth *peerauth;              /*!< Realm authentication */
971         int noncecount;                         /*!< Nonce-count */
972         char lastmsg[256];                      /*!< Last Message sent/received */
973         int amaflags;                           /*!< AMA Flags */
974         int pendinginvite;                      /*!< Any pending invite ? (seqno of this) */
975         struct sip_request initreq;             /*!< Latest request that opened a new transaction
976                                                         within this dialog.
977                                                         NOT the request that opened the dialog
978                                                 */
979         
980         int initid;                             /*!< Auto-congest ID if appropriate (scheduler) */
981         int autokillid;                         /*!< Auto-kill ID (scheduler) */
982         enum transfermodes allowtransfer;       /*!< REFER: restriction scheme */
983         struct sip_refer *refer;                /*!< REFER: SIP transfer data structure */
984         enum subscriptiontype subscribed;       /*!< SUBSCRIBE: Is this dialog a subscription?  */
985         int stateid;                            /*!< SUBSCRIBE: ID for devicestate subscriptions */
986         int laststate;                          /*!< SUBSCRIBE: Last known extension state */
987         int dialogver;                          /*!< SUBSCRIBE: Version for subscription dialog-info */
988         
989         struct ast_dsp *vad;                    /*!< Inband DTMF Detection dsp */
990         
991         struct sip_peer *relatedpeer;           /*!< If this dialog is related to a peer, which one 
992                                                         Used in peerpoke, mwi subscriptions */
993         struct sip_registry *registry;          /*!< If this is a REGISTER dialog, to which registry */
994         struct ast_rtp *rtp;                    /*!< RTP Session */
995         struct ast_rtp *vrtp;                   /*!< Video RTP session */
996         struct sip_pkt *packets;                /*!< Packets scheduled for re-transmission */
997         struct sip_history_head *history;       /*!< History of this SIP dialog */
998         struct ast_variable *chanvars;          /*!< Channel variables to set for inbound call */
999         struct sip_pvt *next;                   /*!< Next dialog in chain */
1000         struct sip_invite_param *options;       /*!< Options for INVITE */
1001         int autoframing;                        /*!< The number of Asters we group in a Pyroflax
1002                                                         before strolling to the GrokyzpÃ¥
1003                                                         (A bit unsure of this, please correct if
1004                                                         you know more) */
1005 };
1006
1007 static struct sip_pvt *dialoglist = NULL;
1008
1009 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
1010 AST_MUTEX_DEFINE_STATIC(dialoglock);
1011
1012 /*! \brief hide the way the list is locked/unlocked */
1013 static void dialoglist_lock(void)
1014 {
1015         ast_mutex_lock(&dialoglock);
1016 }
1017
1018 static void dialoglist_unlock(void)
1019 {
1020         ast_mutex_unlock(&dialoglock);
1021 }
1022
1023 #define FLAG_RESPONSE (1 << 0)
1024 #define FLAG_FATAL (1 << 1)
1025
1026 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission */
1027 struct sip_pkt {
1028         struct sip_pkt *next;                   /*!< Next packet in linked list */
1029         int retrans;                            /*!< Retransmission number */
1030         int method;                             /*!< SIP method for this packet */
1031         int seqno;                              /*!< Sequence number */
1032         unsigned int flags;                     /*!< non-zero if this is a response packet (e.g. 200 OK) */
1033         struct sip_pvt *owner;                  /*!< Owner AST call */
1034         int retransid;                          /*!< Retransmission ID */
1035         int timer_a;                            /*!< SIP timer A, retransmission timer */
1036         int timer_t1;                           /*!< SIP Timer T1, estimated RTT or 500 ms */
1037         int packetlen;                          /*!< Length of packet */
1038         char data[0];
1039 };      
1040
1041 /*! \brief Structure for SIP user data. User's place calls to us */
1042 struct sip_user {
1043         /* Users who can access various contexts */
1044         ASTOBJ_COMPONENTS(struct sip_user);
1045         char secret[80];                /*!< Password */
1046         char md5secret[80];             /*!< Password in md5 */
1047         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
1048         char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1049         char cid_num[80];               /*!< Caller ID num */
1050         char cid_name[80];              /*!< Caller ID name */
1051         char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1052         char language[MAX_LANGUAGE];    /*!< Default language for this user */
1053         char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1054         char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1055         char useragent[256];            /*!< User agent in SIP request */
1056         struct ast_codec_pref prefs;    /*!< codec prefs */
1057         ast_group_t callgroup;          /*!< Call group */
1058         ast_group_t pickupgroup;        /*!< Pickup Group */
1059         unsigned int sipoptions;        /*!< Supported SIP options */
1060         struct ast_flags flags[2];      /*!< SIP_ flags */
1061         int amaflags;                   /*!< AMA flags for billing */
1062         int callingpres;                /*!< Calling id presentation */
1063         int capability;                 /*!< Codec capability */
1064         int inUse;                      /*!< Number of calls in use */
1065         int call_limit;                 /*!< Limit of concurrent calls */
1066         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
1067         struct ast_ha *ha;              /*!< ACL setting */
1068         struct ast_variable *chanvars;  /*!< Variables to set for channel created by user */
1069         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
1070         int autoframing;
1071 };
1072
1073 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
1074 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1075 struct sip_peer {
1076         ASTOBJ_COMPONENTS(struct sip_peer);     /*!< name, refcount, objflags,  object pointers */
1077                                         /*!< peer->name is the unique name of this object */
1078         char secret[80];                /*!< Password */
1079         char md5secret[80];             /*!< Password in MD5 */
1080         struct sip_auth *auth;          /*!< Realm authentication list */
1081         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
1082         char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1083         char username[80];              /*!< Temporary username until registration */ 
1084         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1085         int amaflags;                   /*!< AMA Flags (for billing) */
1086         char tohost[MAXHOSTNAMELEN];    /*!< If not dynamic, IP address */
1087         char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1088         char fromuser[80];              /*!< From: user when calling this peer */
1089         char fromdomain[MAXHOSTNAMELEN];        /*!< From: domain when calling this peer */
1090         char fullcontact[256];          /*!< Contact registered with us (not in sip.conf) */
1091         char cid_num[80];               /*!< Caller ID num */
1092         char cid_name[80];              /*!< Caller ID name */
1093         int callingpres;                /*!< Calling id presentation */
1094         int inUse;                      /*!< Number of calls in use */
1095         int inRinging;                  /*!< Number of calls ringing */
1096         int onHold;                     /*!< Peer has someone on hold */
1097         int call_limit;                 /*!< Limit of concurrent calls */
1098         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
1099         char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1100         char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
1101         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
1102         char mohinterpret[MAX_MUSICCLASS];/*!<  Music on Hold class */
1103         char mohsuggest[MAX_MUSICCLASS];/*!<  Music on Hold class */
1104         char useragent[256];            /*!<  User agent in SIP request (saved from registration) */
1105         struct ast_codec_pref prefs;    /*!<  codec prefs */
1106         int lastmsgssent;
1107         time_t  lastmsgcheck;           /*!<  Last time we checked for MWI */
1108         unsigned int sipoptions;        /*!<  Supported SIP options */
1109         struct ast_flags flags[2];      /*!<  SIP_ flags */
1110         int expire;                     /*!<  When to expire this peer registration */
1111         int capability;                 /*!<  Codec capability */
1112         int rtptimeout;                 /*!<  RTP timeout */
1113         int rtpholdtimeout;             /*!<  RTP Hold Timeout */
1114         int rtpkeepalive;               /*!<  Send RTP packets for keepalive */
1115         ast_group_t callgroup;          /*!<  Call group */
1116         ast_group_t pickupgroup;        /*!<  Pickup group */
1117         struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
1118         struct sockaddr_in addr;        /*!<  IP address of peer */
1119         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
1120         
1121         /* Qualification */
1122         struct sip_pvt *call;           /*!<  Call pointer */
1123         int pokeexpire;                 /*!<  When to expire poke (qualify= checking) */
1124         int lastms;                     /*!<  How long last response took (in ms), or -1 for no response */
1125         int maxms;                      /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
1126         struct timeval ps;              /*!<  Time for sending SIP OPTION in sip_pke_peer() */
1127         struct sockaddr_in defaddr;     /*!<  Default IP address, used until registration */
1128         struct ast_ha *ha;              /*!<  Access control list */
1129         struct ast_variable *chanvars;  /*!<  Variables to set for channel created by user */
1130         struct sip_pvt *mwipvt;         /*!<  Subscription for MWI */
1131         int lastmsg;
1132         int autoframing;
1133 };
1134
1135
1136
1137 /*! \brief Registrations with other SIP proxies */
1138 struct sip_registry {
1139         ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1140         AST_DECLARE_STRING_FIELDS(
1141                 AST_STRING_FIELD(callid);       /*!< Global Call-ID */
1142                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
1143                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
1144                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
1145                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1146                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
1147                 AST_STRING_FIELD(username);     /*!< Who we are registering as */
1148                 AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
1149                 AST_STRING_FIELD(hostname);     /*!< Domain or host we register to */
1150                 AST_STRING_FIELD(secret);       /*!< Password in clear text */  
1151                 AST_STRING_FIELD(md5secret);    /*!< Password in md5 */
1152                 AST_STRING_FIELD(callback);     /*!< Contact extension */
1153                 AST_STRING_FIELD(random);
1154         );
1155         int portno;                     /*!<  Optional port override */
1156         int expire;                     /*!< Sched ID of expiration */
1157         int expiry;                     /*!< Value to use for the Expires header */
1158         int regattempts;                /*!< Number of attempts (since the last success) */
1159         int timeout;                    /*!< sched id of sip_reg_timeout */
1160         int refresh;                    /*!< How often to refresh */
1161         struct sip_pvt *call;           /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1162         enum sipregistrystate regstate; /*!< Registration state (see above) */
1163         time_t regtime;         /*!< Last successful registration time */
1164         int callid_valid;               /*!< 0 means we haven't chosen callid for this registry yet. */
1165         unsigned int ocseq;             /*!< Sequence number we got to for REGISTERs for this registry */
1166         struct sockaddr_in us;          /*!< Who the server thinks we are */
1167         int noncecount;                 /*!< Nonce-count */
1168         char lastmsg[256];              /*!< Last Message sent/received */
1169 };
1170
1171 /* --- Linked lists of various objects --------*/
1172
1173 /*! \brief  The user list: Users and friends */
1174 static struct ast_user_list {
1175         ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1176 } userl;
1177
1178 /*! \brief  The peer list: Peers and Friends */
1179 static struct ast_peer_list {
1180         ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1181 } peerl;
1182
1183 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
1184 static struct ast_register_list {
1185         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1186         int recheck;
1187 } regl;
1188
1189 static int temp_pvt_init(void *);
1190 static void temp_pvt_cleanup(void *);
1191
1192 /*! \brief A per-thread temporary pvt structure */
1193 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1194
1195 /*! \todo Move the sip_auth list to AST_LIST */
1196 static struct sip_auth *authl = NULL;           /*!< Authentication list for realm authentication */
1197
1198
1199 /* --- Sockets and networking --------------*/
1200 static int sipsock  = -1;                       /*!< Main socket for SIP network communication */
1201 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
1202 static struct sockaddr_in externip;             /*!< External IP address if we are behind NAT */
1203 static char externhost[MAXHOSTNAMELEN];         /*!< External host name (possibly with dynamic DNS and DHCP */
1204 static time_t externexpire = 0;                 /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1205 static int externrefresh = 10;
1206 static struct ast_ha *localaddr;                /*!< List of local networks, on the same side of NAT as this Asterisk */
1207 static struct in_addr __ourip;
1208 static struct sockaddr_in outboundproxyip;
1209 static int ourport;
1210 static struct sockaddr_in debugaddr;
1211
1212 static struct ast_config *notify_types;         /*!< The list of manual NOTIFY types we know how to send */
1213
1214 /*---------------------------- Forward declarations of functions in chan_sip.c */
1215 /*! \note This is added to help splitting up chan_sip.c into several files
1216         in coming releases */
1217
1218 /*--- PBX interface functions */
1219 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1220 static int sip_devicestate(void *data);
1221 static int sip_sendtext(struct ast_channel *ast, const char *text);
1222 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1223 static int sip_hangup(struct ast_channel *ast);
1224 static int sip_answer(struct ast_channel *ast);
1225 static struct ast_frame *sip_read(struct ast_channel *ast);
1226 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1227 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1228 static int sip_transfer(struct ast_channel *ast, const char *dest);
1229 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1230 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1231 static int sip_senddigit_end(struct ast_channel *ast, char digit);
1232
1233 /*--- Transmitting responses and requests */
1234 static int sipsock_read(int *id, int fd, short events, void *ignore);
1235 static int __sip_xmit(struct sip_pvt *p, char *data, int len);
1236 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
1237 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1238 static int retrans_pkt(void *data);
1239 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1240 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1241 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1242 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1243 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1244 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1245 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1246 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
1247 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1248 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1249 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1250 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1251 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1252 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version);
1253 static int transmit_info_with_digit(struct sip_pvt *p, const char digit);
1254 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1255 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1256 static int transmit_refer(struct sip_pvt *p, const char *dest);
1257 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1258 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1259 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1260 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1261 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1262 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1263 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1264 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1265 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1266 static int does_peer_need_mwi(struct sip_peer *peer);
1267
1268 /*--- Dialog management */
1269 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1270                                  int useglobal_nat, const int intended_method);
1271 static int __sip_autodestruct(void *data);
1272 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1273 static void sip_cancel_destroy(struct sip_pvt *p);
1274 static void sip_destroy(struct sip_pvt *p);
1275 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1276 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1277 static void __sip_pretend_ack(struct sip_pvt *p);
1278 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1279 static int auto_congest(void *nothing);
1280 static int update_call_counter(struct sip_pvt *fup, int event);
1281 static int hangup_sip2cause(int cause);
1282 static const char *hangup_cause2sip(int cause);
1283 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1284 static void free_old_route(struct sip_route *route);
1285 static void list_route(struct sip_route *route);
1286 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1287 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1288                                               struct sip_request *req, char *uri);
1289 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1290 static void check_pendings(struct sip_pvt *p);
1291 static void *sip_park_thread(void *stuff);
1292 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1293 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1294
1295 /*--- Codec handling / SDP */
1296 static void try_suggested_sip_codec(struct sip_pvt *p);
1297 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1298 static const char *get_sdp(struct sip_request *req, const char *name);
1299 static int find_sdp(struct sip_request *req);
1300 static int process_sdp(struct sip_pvt *p, struct sip_request *req);
1301 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1302                              char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1303                              int debug, int *min_packet_size);
1304 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1305                                 char **m_buf, size_t *m_size, char **a_buf, size_t *a_size,
1306                                 int debug);
1307 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p);
1308 static void do_setnat(struct sip_pvt *p, int natflags);
1309
1310 /*--- Authentication stuff */
1311 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1312 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1313 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1314                                          const char *secret, const char *md5secret, int sipmethod,
1315                                          char *uri, enum xmittype reliable, int ignore);
1316 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1317                                               int sipmethod, char *uri, enum xmittype reliable,
1318                                               struct sockaddr_in *sin, struct sip_peer **authpeer);
1319 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1320
1321 /*--- Domain handling */
1322 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1323 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1324 static void clear_sip_domains(void);
1325
1326 /*--- SIP realm authentication */
1327 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);
1328 static int clear_realm_authentication(struct sip_auth *authlist);       /* Clear realm authentication list (at reload) */
1329 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1330
1331 /*--- Misc functions */
1332 static int sip_do_reload(enum channelreloadreason reason);
1333 static int reload_config(enum channelreloadreason reason);
1334 static int expire_register(void *data);
1335 static void *do_monitor(void *data);
1336 static int restart_monitor(void);
1337 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1338 static void sip_destroy(struct sip_pvt *p);
1339 static int sip_addrcmp(char *name, struct sockaddr_in *sin);    /* Support for peer matching */
1340 static int sip_refer_allocate(struct sip_pvt *p);
1341 static void ast_quiet_chan(struct ast_channel *chan);
1342 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1343
1344 /*--- Device monitoring and Device/extension state handling */
1345 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1346 static int sip_devicestate(void *data);
1347 static int sip_poke_noanswer(void *data);
1348 static int sip_poke_peer(struct sip_peer *peer);
1349 static void sip_poke_all_peers(void);
1350 static void sip_peer_hold(struct sip_pvt *p, int hold);
1351
1352 /*--- Applications, functions, CLI and manager command helpers */
1353 static const char *sip_nat_mode(const struct sip_pvt *p);
1354 static int sip_show_inuse(int fd, int argc, char *argv[]);
1355 static char *transfermode2str(enum transfermodes mode) attribute_const;
1356 static char *nat2str(int nat) attribute_const;
1357 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1358 static int sip_show_users(int fd, int argc, char *argv[]);
1359 static int _sip_show_peers(int fd, int *total, struct mansession *s, struct message *m, int argc, char *argv[]);
1360 static int manager_sip_show_peers( struct mansession *s, struct message *m );
1361 static int sip_show_peers(int fd, int argc, char *argv[]);
1362 static int sip_show_objects(int fd, int argc, char *argv[]);
1363 static void  print_group(int fd, ast_group_t group, int crlf);
1364 static const char *dtmfmode2str(int mode) attribute_const;
1365 static const char *insecure2str(int port, int invite) attribute_const;
1366 static void cleanup_stale_contexts(char *new, char *old);
1367 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1368 static const char *domain_mode_to_text(const enum domain_mode mode);
1369 static int sip_show_domains(int fd, int argc, char *argv[]);
1370 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1371 static int manager_sip_show_peer( struct mansession *s, struct message *m);
1372 static int sip_show_peer(int fd, int argc, char *argv[]);
1373 static int _sip_show_peer(int type, int fd, struct mansession *s, struct message *m, int argc, char *argv[]);
1374 static int sip_show_user(int fd, int argc, char *argv[]);
1375 static int sip_show_registry(int fd, int argc, char *argv[]);
1376 static int sip_show_settings(int fd, int argc, char *argv[]);
1377 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1378 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1379 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1380 static int sip_show_channels(int fd, int argc, char *argv[]);
1381 static int sip_show_subscriptions(int fd, int argc, char *argv[]);
1382 static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
1383 static char *complete_sipch(const char *line, const char *word, int pos, int state);
1384 static char *complete_sip_peer(const char *word, int state, int flags2);
1385 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1386 static char *complete_sip_debug_peer(const char *line, const char *word, int pos, int state);
1387 static char *complete_sip_user(const char *word, int state, int flags2);
1388 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1389 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1390 static char *complete_sip_prune_realtime_peer(const char *line, const char *word, int pos, int state);
1391 static char *complete_sip_prune_realtime_user(const char *line, const char *word, int pos, int state);
1392 static int sip_show_channel(int fd, int argc, char *argv[]);
1393 static int sip_show_history(int fd, int argc, char *argv[]);
1394 static int sip_do_debug_ip(int fd, int argc, char *argv[]);
1395 static int sip_do_debug_peer(int fd, int argc, char *argv[]);
1396 static int sip_do_debug(int fd, int argc, char *argv[]);
1397 static int sip_no_debug(int fd, int argc, char *argv[]);
1398 static int sip_notify(int fd, int argc, char *argv[]);
1399 static int sip_do_history(int fd, int argc, char *argv[]);
1400 static int sip_no_history(int fd, int argc, char *argv[]);
1401 static int func_header_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len);
1402 static int func_check_sipdomain(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1403 static int function_sippeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1404 static int function_sipchaninfo_read(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len);
1405 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1406 static int sip_addheader(struct ast_channel *chan, void *data);
1407 static int sip_do_reload(enum channelreloadreason reason);
1408 static int sip_reload(int fd, int argc, char *argv[]);
1409
1410 /*--- Debugging 
1411         Functions for enabling debug per IP or fully, or enabling history logging for
1412         a SIP dialog
1413 */
1414 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
1415 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1416 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1417 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1418 static void sip_dump_history(struct sip_pvt *dialog);
1419
1420 /*--- Device object handling */
1421 static struct sip_peer *temp_peer(const char *name);
1422 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1423 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
1424 static int update_call_counter(struct sip_pvt *fup, int event);
1425 static void sip_destroy_peer(struct sip_peer *peer);
1426 static void sip_destroy_user(struct sip_user *user);
1427 static int sip_poke_peer(struct sip_peer *peer);
1428 static void set_peer_defaults(struct sip_peer *peer);
1429 static struct sip_peer *temp_peer(const char *name);
1430 static void register_peer_exten(struct sip_peer *peer, int onoff);
1431 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1432 static struct sip_user *find_user(const char *name, int realtime);
1433 static int sip_poke_peer_s(void *data);
1434 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1435 static void reg_source_db(struct sip_peer *peer);
1436 static void destroy_association(struct sip_peer *peer);
1437 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1438
1439 /* Realtime device support */
1440 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey);
1441 static struct sip_user *realtime_user(const char *username);
1442 static void update_peer(struct sip_peer *p, int expiry);
1443 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1444 static int sip_prune_realtime(int fd, int argc, char *argv[]);
1445
1446 /*--- Internal UA client handling (outbound registrations) */
1447 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us);
1448 static void sip_registry_destroy(struct sip_registry *reg);
1449 static int sip_register(char *value, int lineno);
1450 static char *regstate2str(enum sipregistrystate regstate) attribute_const;
1451 static int sip_reregister(void *data);
1452 static int __sip_do_register(struct sip_registry *r);
1453 static int sip_reg_timeout(void *data);
1454 static void sip_send_all_registers(void);
1455
1456 /*--- Parsing SIP requests and responses */
1457 static void append_date(struct sip_request *req);       /* Append date to SIP packet */
1458 static int determine_firstline_parts(struct sip_request *req);
1459 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1460 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1461 static int find_sip_method(const char *msg);
1462 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1463 static void parse_request(struct sip_request *req);
1464 static const char *get_header(const struct sip_request *req, const char *name);
1465 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1466 static int method_match(enum sipmethod id, const char *name);
1467 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1468 static char *get_in_brackets(char *tmp);
1469 static const char *find_alias(const char *name, const char *_default);
1470 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1471 static int lws2sws(char *msgbuf, int len);
1472 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1473 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1474 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1475 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1476 static int set_address_from_contact(struct sip_pvt *pvt);
1477 static void check_via(struct sip_pvt *p, struct sip_request *req);
1478 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1479 static int get_rpid_num(const char *input, char *output, int maxlen);
1480 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1481 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1482 static int get_msg_text(char *buf, int len, struct sip_request *req);
1483 static void free_old_route(struct sip_route *route);
1484 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1485
1486 /*--- Constructing requests and responses */
1487 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1488 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1489 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1490 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1491 static int init_resp(struct sip_request *resp, const char *msg);
1492 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1493 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1494 static void build_via(struct sip_pvt *p);
1495 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1496 static int create_addr(struct sip_pvt *dialog, const char *opeer);
1497 static char *generate_random_string(char *buf, size_t size);
1498 static void build_callid_pvt(struct sip_pvt *pvt);
1499 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1500 static void make_our_tag(char *tagbuf, size_t len);
1501 static int add_header(struct sip_request *req, const char *var, const char *value);
1502 static int add_header_contentLength(struct sip_request *req, int len);
1503 static int add_line(struct sip_request *req, const char *line);
1504 static int add_text(struct sip_request *req, const char *text);
1505 static int add_digit(struct sip_request *req, char digit);
1506 static int add_vidupdate(struct sip_request *req);
1507 static void add_route(struct sip_request *req, struct sip_route *route);
1508 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1509 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1510 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1511 static void set_destination(struct sip_pvt *p, char *uri);
1512 static void append_date(struct sip_request *req);
1513 static void build_contact(struct sip_pvt *p);
1514 static void build_rpid(struct sip_pvt *p);
1515
1516 /*------Request handling functions */
1517 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1518 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e);
1519 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1520 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1521 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1522 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1523 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1524 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1525 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1526 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1527 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1528 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1529 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int ignore, int seqno, struct sockaddr_in *sin);
1530 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1531
1532 /*------Response handling functions */
1533 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1534 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1535 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1536 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
1537
1538 /*----- RTP interface functions */
1539 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1540 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1541 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
1542 static int sip_get_codec(struct ast_channel *chan);
1543 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
1544
1545 /*------ T38 Support --------- */
1546 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); /*!< T38 negotiation helper function */
1547 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1548 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1549 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1550
1551 /*! \brief Definition of this channel for PBX channel registration */
1552 static const struct ast_channel_tech sip_tech = {
1553         .type = "SIP",
1554         .description = "Session Initiation Protocol (SIP)",
1555         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1556         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1557         .requester = sip_request_call,
1558         .devicestate = sip_devicestate,
1559         .call = sip_call,
1560         .hangup = sip_hangup,
1561         .answer = sip_answer,
1562         .read = sip_read,
1563         .write = sip_write,
1564         .write_video = sip_write,
1565         .indicate = sip_indicate,
1566         .transfer = sip_transfer,
1567         .fixup = sip_fixup,
1568         .send_digit_begin = sip_senddigit_begin,
1569         .send_digit_end = sip_senddigit_end,
1570         .bridge = ast_rtp_bridge,
1571         .early_bridge = ast_rtp_early_bridge,
1572         .send_text = sip_sendtext,
1573 };
1574
1575 /**--- some list management macros. **/
1576  
1577 #define UNLINK(element, head, prev) do {        \
1578         if (prev)                               \
1579                 (prev)->next = (element)->next; \
1580         else                                    \
1581                 (head) = (element)->next;       \
1582         } while (0)
1583
1584 /*! \brief Interface structure with callbacks used to connect to RTP module */
1585 static struct ast_rtp_protocol sip_rtp = {
1586         type: "SIP",
1587         get_rtp_info: sip_get_rtp_peer,
1588         get_vrtp_info: sip_get_vrtp_peer,
1589         set_rtp_peer: sip_set_rtp_peer,
1590         get_codec: sip_get_codec,
1591 };
1592
1593 /*! \brief Helper function to lock, hiding the underlying locking mechanism.  */
1594 static void sip_pvt_lock(struct sip_pvt *pvt)
1595 {
1596         ast_mutex_lock(&pvt->pvt_lock);
1597 }
1598
1599 /*! \brief Helper function to unlock pvt, hiding the underlying locking mechanism. */
1600 static void sip_pvt_unlock(struct sip_pvt *pvt)
1601 {
1602         ast_mutex_unlock(&pvt->pvt_lock);
1603 }
1604
1605 /*!
1606  * helper functions to unreference various types of objects.
1607  * By handling them this way, we don't have to declare the
1608  * destructor on each call, which removes the chance of errors.
1609  */
1610 static void unref_peer(struct sip_peer *peer)
1611 {
1612         ASTOBJ_UNREF(peer, sip_destroy_peer);
1613 }
1614
1615 static void unref_user(struct sip_user *user)
1616 {
1617         ASTOBJ_UNREF(user, sip_destroy_user);
1618 }
1619
1620 static void unref_registry(struct sip_registry *reg)
1621 {
1622         ASTOBJ_UNREF(reg, sip_registry_destroy);
1623 }
1624
1625 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
1626 static struct ast_udptl_protocol sip_udptl = {
1627         type: "SIP",
1628         get_udptl_info: sip_get_udptl_peer,
1629         set_udptl_peer: sip_set_udptl_peer,
1630 };
1631
1632 /*! \brief Convert transfer status to string */
1633 static const char *referstatus2str(enum referstatus rstatus)
1634 {
1635         int i = (sizeof(referstatusstrings) / sizeof(referstatusstrings[0]));
1636         int x;
1637
1638         for (x = 0; x < i; x++) {
1639                 if (referstatusstrings[x].status ==  rstatus)
1640                         return referstatusstrings[x].text;
1641         }
1642         return "";
1643 }
1644
1645 /*! \brief Initialize the initital request packet in the pvt structure.
1646         This packet is used for creating replies and future requests in
1647         a dialog */
1648 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
1649 {
1650         if (option_debug) {
1651                 if (p->initreq.headers)
1652                         ast_log(LOG_DEBUG, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
1653                 else
1654                         ast_log(LOG_DEBUG, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
1655         }
1656         /* Use this as the basis */
1657         copy_request(&p->initreq, req);
1658         parse_request(&p->initreq);
1659         if (ast_test_flag(req, SIP_PKT_DEBUG))
1660                 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
1661 }
1662
1663 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
1664 static void sip_alreadygone(struct sip_pvt *dialog)
1665 {
1666         if (option_debug > 2)
1667                 ast_log(LOG_DEBUG, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
1668         ast_set_flag(&dialog->flags[0], SIP_ALREADYGONE);
1669 }
1670
1671
1672 /*! \brief returns true if 'name' (with optional trailing whitespace)
1673  * matches the sip method 'id'.
1674  * Strictly speaking, SIP methods are case SENSITIVE, but we do
1675  * a case-insensitive comparison to be more tolerant.
1676  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
1677  */
1678 static int method_match(enum sipmethod id, const char *name)
1679 {
1680         int len = strlen(sip_methods[id].text);
1681         int l_name = name ? strlen(name) : 0;
1682         /* true if the string is long enough, and ends with whitespace, and matches */
1683         return (l_name >= len && name[len] < 33 &&
1684                 !strncasecmp(sip_methods[id].text, name, len));
1685 }
1686
1687 /*! \brief  find_sip_method: Find SIP method from header */
1688 static int find_sip_method(const char *msg)
1689 {
1690         int i, res = 0;
1691         
1692         if (ast_strlen_zero(msg))
1693                 return 0;
1694         for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
1695                 if (method_match(i, msg))
1696                         res = sip_methods[i].id;
1697         }
1698         return res;
1699 }
1700
1701 /*! \brief Parse supported header in incoming packet */
1702 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
1703 {
1704         char *next, *sep;
1705         char *temp;
1706         unsigned int profile = 0;
1707         int i, found;
1708
1709         if (ast_strlen_zero(supported) )
1710                 return 0;
1711         temp = ast_strdupa(supported);
1712
1713         if (option_debug > 2 && sipdebug)
1714                 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1715
1716         for (next = temp; next; next = sep) {
1717                 found = FALSE;
1718                 if ( (sep = strchr(next, ',')) != NULL)
1719                         *sep++ = '\0';
1720                 next = ast_skip_blanks(next);
1721                 if (option_debug > 2 && sipdebug)
1722                         ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1723                 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
1724                         if (!strcasecmp(next, sip_options[i].text)) {
1725                                 profile |= sip_options[i].id;
1726                                 found = TRUE;
1727                                 if (option_debug > 2 && sipdebug)
1728                                         ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1729                                 break;
1730                         }
1731                 }
1732                 if (!found && option_debug > 2 && sipdebug) {
1733                         if (!strncasecmp(next, "x-", 2))
1734                                 ast_log(LOG_DEBUG, "Found private SIP option, not supported: %s\n", next);
1735                         else
1736                                 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1737                 }
1738         }
1739
1740         if (pvt)
1741                 pvt->sipoptions = profile;
1742         return profile;
1743 }
1744
1745 /*! \brief See if we pass debug IP filter */
1746 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
1747 {
1748         if (!sipdebug)
1749                 return 0;
1750         if (debugaddr.sin_addr.s_addr) {
1751                 if (((ntohs(debugaddr.sin_port) != 0)
1752                         && (debugaddr.sin_port != addr->sin_port))
1753                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1754                         return 0;
1755         }
1756         return 1;
1757 }
1758
1759 /*! \brief The real destination address for a write */
1760 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
1761 {
1762         return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
1763 }
1764
1765 /*! \brief Display SIP nat mode */
1766 static const char *sip_nat_mode(const struct sip_pvt *p)
1767 {
1768         return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
1769 }
1770
1771 /*! \brief Test PVT for debugging output */
1772 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
1773 {
1774         if (!sipdebug)
1775                 return 0;
1776         return sip_debug_test_addr(sip_real_dst(p));
1777 }
1778
1779 /*! \brief Transmit SIP message */
1780 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1781 {
1782         int res;
1783         const struct sockaddr_in *dst = sip_real_dst(p);
1784         res = sendto(sipsock, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
1785
1786         if (res != len)
1787                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
1788         return res;
1789 }
1790
1791
1792 /*! \brief Build a Via header for a request */
1793 static void build_via(struct sip_pvt *p)
1794 {
1795         /* Work around buggy UNIDEN UIP200 firmware */
1796         const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1797
1798         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1799         ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1800                          ast_inet_ntoa(p->ourip), ourport, p->branch, rport);
1801 }
1802
1803 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1804  *
1805  * Using the localaddr structure built up with localnet statements in sip.conf
1806  * apply it to their address to see if we need to substitute our
1807  * externip or can get away with our internal bindaddr
1808  */
1809 static enum sip_result ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1810 {
1811         struct sockaddr_in theirs, ours;
1812
1813         /* Get our local information */
1814         ast_ouraddrfor(them, us);
1815         theirs.sin_addr = *them;
1816         ours.sin_addr = *us;
1817
1818         if (localaddr && externip.sin_addr.s_addr &&
1819             ast_apply_ha(localaddr, &theirs) &&
1820             !ast_apply_ha(localaddr, &ours)) {
1821                 if (externexpire && time(NULL) >= externexpire) {
1822                         struct ast_hostent ahp;
1823                         struct hostent *hp;
1824
1825                         externexpire = time(NULL) + externrefresh;
1826                         if ((hp = ast_gethostbyname(externhost, &ahp))) {
1827                                 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1828                         } else
1829                                 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1830                 }
1831                 *us = externip.sin_addr;
1832                 if (option_debug) {
1833                         ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", 
1834                                 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
1835                 }
1836         } else if (bindaddr.sin_addr.s_addr)
1837                 *us = bindaddr.sin_addr;
1838         return AST_SUCCESS;
1839 }
1840
1841 /*! \brief Append to SIP dialog history 
1842         \return Always returns 0 */
1843 #define append_history(p, event, fmt , args... )        append_history_full(p, "%-15s " fmt, event, ## args)
1844
1845 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1846         __attribute__ ((format (printf, 2, 3)));
1847
1848 /*! \brief Append to SIP dialog history with arg list  */
1849 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1850 {
1851         char buf[80], *c = buf; /* max history length */
1852         struct sip_history *hist;
1853         int l;
1854
1855         vsnprintf(buf, sizeof(buf), fmt, ap);
1856         strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1857         l = strlen(buf) + 1;
1858         if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1859                 return;
1860         if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1861                 free(hist);
1862                 return;
1863         }
1864         memcpy(hist->event, buf, l);
1865         AST_LIST_INSERT_TAIL(p->history, hist, list);
1866 }
1867
1868 /*! \brief Append to SIP dialog history with arg list  */
1869 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
1870 {
1871         va_list ap;
1872
1873         if (!p)
1874                 return;
1875         va_start(ap, fmt);
1876         append_history_va(p, fmt, ap);
1877         va_end(ap);
1878
1879         return;
1880 }
1881
1882 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
1883 static int retrans_pkt(void *data)
1884 {
1885         struct sip_pkt *pkt = data, *prev, *cur = NULL;
1886         int reschedule = DEFAULT_RETRANS;
1887
1888         /* Lock channel PVT */
1889         sip_pvt_lock(pkt->owner);
1890
1891         if (pkt->retrans < MAX_RETRANS) {
1892                 pkt->retrans++;
1893                 if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
1894                         if (sipdebug && option_debug > 3)
1895                                 ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
1896                 } else {
1897                         int siptimer_a;
1898
1899                         if (sipdebug && option_debug > 3)
1900                                 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1901                         if (!pkt->timer_a)
1902                                 pkt->timer_a = 2 ;
1903                         else
1904                                 pkt->timer_a = 2 * pkt->timer_a;
1905  
1906                         /* For non-invites, a maximum of 4 secs */
1907                         siptimer_a = pkt->timer_t1 * pkt->timer_a;      /* Double each time */
1908                         if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1909                                 siptimer_a = 4000;
1910                 
1911                         /* Reschedule re-transmit */
1912                         reschedule = siptimer_a;
1913                         if (option_debug > 3)
1914                                 ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
1915                 } 
1916
1917                 if (sip_debug_test_pvt(pkt->owner)) {
1918                         const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
1919                         ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
1920                                 pkt->retrans, sip_nat_mode(pkt->owner),
1921                                 ast_inet_ntoa(dst->sin_addr),
1922                                 ntohs(dst->sin_port), pkt->data);
1923                 }
1924
1925                 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1926                 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1927                 sip_pvt_unlock(pkt->owner);
1928                 return  reschedule;
1929         } 
1930         /* Too many retries */
1931         if (pkt->owner && pkt->method != SIP_OPTIONS) {
1932                 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1933                         ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
1934         } else {
1935                 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1936                         ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1937         }
1938         append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1939                 
1940         pkt->retransid = -1;
1941
1942         if (ast_test_flag(pkt, FLAG_FATAL)) {
1943                 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
1944                         sip_pvt_unlock(pkt->owner);     /* SIP_PVT, not channel */
1945                         usleep(1);
1946                         sip_pvt_lock(pkt->owner);
1947                 }
1948                 if (pkt->owner->owner) {
1949                         sip_alreadygone(pkt->owner);
1950                         ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1951                         ast_queue_hangup(pkt->owner->owner);
1952                         ast_channel_unlock(pkt->owner->owner);
1953                 } else {
1954                         /* If no channel owner, destroy now */
1955
1956                         /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
1957                         if (pkt->method != SIP_OPTIONS)
1958                                 ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);   
1959                 }
1960         }
1961         /* Remove the packet */
1962         for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
1963                 if (cur == pkt) {
1964                         UNLINK(cur, pkt->owner->packets, prev);
1965                         sip_pvt_unlock(pkt->owner);
1966                         free(pkt);
1967                         return 0;
1968                 }
1969         }
1970         /* error case */
1971         ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1972         sip_pvt_unlock(pkt->owner);
1973         return 0;
1974 }
1975
1976 /*! \brief Transmit packet with retransmits 
1977         \return 0 on success, -1 on failure to allocate packet 
1978 */
1979 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1980 {
1981         struct sip_pkt *pkt;
1982         int siptimer_a = DEFAULT_RETRANS;
1983
1984         if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1985                 return AST_FAILURE;
1986         memcpy(pkt->data, data, len);
1987         pkt->method = sipmethod;
1988         pkt->packetlen = len;
1989         pkt->next = p->packets;
1990         pkt->owner = p;
1991         pkt->seqno = seqno;
1992         if (resp)
1993                 ast_set_flag(pkt, FLAG_RESPONSE);
1994         pkt->data[len] = '\0';
1995         pkt->timer_t1 = p->timer_t1;    /* Set SIP timer T1 */
1996         if (fatal)
1997                 ast_set_flag(pkt, FLAG_FATAL);
1998         if (pkt->timer_t1)
1999                 siptimer_a = pkt->timer_t1 * 2;
2000
2001         /* Schedule retransmission */
2002         pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
2003         if (option_debug > 3 && sipdebug)
2004                 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id  #%d\n", pkt->retransid);
2005         pkt->next = p->packets;
2006         p->packets = pkt;
2007
2008         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);      /* Send packet */
2009         if (sipmethod == SIP_INVITE) {
2010                 /* Note this is a pending invite */
2011                 p->pendinginvite = seqno;
2012         }
2013         return AST_SUCCESS;
2014 }
2015
2016 /*! \brief Kill a SIP dialog (called by scheduler) */
2017 static int __sip_autodestruct(void *data)
2018 {
2019         struct sip_pvt *p = data;
2020
2021         /* If this is a subscription, tell the phone that we got a timeout */
2022         if (p->subscribed) {
2023                 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);   /* Send last notification */
2024                 p->subscribed = NONE;
2025                 append_history(p, "Subscribestatus", "timeout");
2026                 if (option_debug > 2)
2027                         ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
2028                 return 10000;   /* Reschedule this destruction so that we know that it's gone */
2029         }
2030
2031         if (p->subscribed == MWI_NOTIFICATION)
2032                 if (p->relatedpeer)
2033                         unref_peer(p->relatedpeer);     /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2034
2035         /* Reset schedule ID */
2036         p->autokillid = -1;
2037
2038         if (p->owner) {
2039                 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2040                 ast_queue_hangup(p->owner);
2041         } else if (p->refer) {
2042                 if (option_debug > 2)
2043                         ast_log(LOG_DEBUG, "Finally hanging up channel after transfer: %s\n", p->callid);
2044                 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2045                 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2046                 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2047         } else {
2048                 append_history(p, "AutoDestroy", "%s", p->callid);
2049                 if (option_debug)
2050                         ast_log(LOG_DEBUG, "Auto destroying SIP dialog '%s'\n", p->callid);
2051                 sip_destroy(p);         /* Go ahead and destroy dialog. All attempts to recover is done */
2052         }
2053         return 0;
2054 }
2055
2056 /*! \brief Schedule destruction of SIP dialog */
2057 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2058 {
2059         if (ms < 0) {
2060                 if (p->timer_t1 == 0)
2061                         p->timer_t1 = SIP_TIMER_T1;     /* Set timer T1 if not set (RFC 3261) */
2062                 ms = p->timer_t1 * 64;
2063         }
2064         if (sip_debug_test_pvt(p))
2065                 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2066         if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY))
2067                 append_history(p, "SchedDestroy", "%d ms", ms);
2068
2069         if (p->autokillid > -1)
2070                 ast_sched_del(sched, p->autokillid);
2071         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
2072 }
2073
2074 /*! \brief Cancel destruction of SIP dialog */
2075 static void sip_cancel_destroy(struct sip_pvt *p)
2076 {
2077         if (p->autokillid > -1) {
2078                 ast_sched_del(sched, p->autokillid);
2079                 append_history(p, "CancelDestroy", "");
2080                 p->autokillid = -1;
2081         }
2082 }
2083
2084 /*! \brief Acknowledges receipt of a packet and stops retransmission */
2085 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2086 {
2087         struct sip_pkt *cur, *prev = NULL;
2088         const char *msg = "Not Found";  /* used only for debugging */
2089
2090         sip_pvt_lock(p);
2091         for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2092                 if (cur->seqno != seqno || ast_test_flag(cur, FLAG_RESPONSE) != resp)
2093                         continue;
2094                 if (ast_test_flag(cur, FLAG_RESPONSE) || cur->method == sipmethod) {
2095                         msg = "Found";
2096                         if (!resp && (seqno == p->pendinginvite)) {
2097                                 if (option_debug)
2098                                         ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
2099                                 p->pendinginvite = 0;
2100                         }
2101                         if (cur->retransid > -1) {
2102                                 if (sipdebug && option_debug > 3)
2103                                         ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2104                                 ast_sched_del(sched, cur->retransid);
2105                                 cur->retransid = -1;
2106                         }
2107                         UNLINK(cur, p->packets, prev);
2108                         free(cur);
2109                         break;
2110                 }
2111         }
2112         sip_pvt_unlock(p);
2113         if (option_debug)
2114                 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n",
2115                         p->callid, resp ? "Response" : "Request", seqno, msg);
2116 }
2117
2118 /*! \brief Pretend to ack all packets
2119  * maybe the lock on p is not strictly necessary but there might be a race */
2120 static void __sip_pretend_ack(struct sip_pvt *p)
2121 {
2122         struct sip_pkt *cur = NULL;
2123
2124         while (p->packets) {
2125                 int method;
2126                 if (cur == p->packets) {
2127                         ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
2128                         return;
2129                 }
2130                 cur = p->packets;
2131                 method = (cur->method) ? cur->method : find_sip_method(cur->data);
2132                 __sip_ack(p, cur->seqno, ast_test_flag(cur, FLAG_RESPONSE), method);
2133         }
2134 }
2135
2136 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
2137 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2138 {
2139         struct sip_pkt *cur;
2140         int res = -1;
2141
2142         for (cur = p->packets; cur; cur = cur->next) {
2143                 if (cur->seqno == seqno && ast_test_flag(cur, FLAG_RESPONSE) == resp &&
2144                         (ast_test_flag(cur, FLAG_RESPONSE) || method_match(sipmethod, cur->data))) {
2145                         /* this is our baby */
2146                         if (cur->retransid > -1) {
2147                                 if (option_debug > 3 && sipdebug)
2148                                         ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
2149                                 ast_sched_del(sched, cur->retransid);
2150                                 cur->retransid = -1;
2151                         }
2152                         res = 0;
2153                         break;
2154                 }
2155         }
2156         if (option_debug)
2157                 ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
2158         return res;
2159 }
2160
2161
2162 /*! \brief Copy SIP request, parse it */
2163 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
2164 {
2165         memset(dst, 0, sizeof(*dst));
2166         memcpy(dst->data, src->data, sizeof(dst->data));
2167         dst->len = src->len;
2168         parse_request(dst);
2169 }
2170
2171 /*! \brief add a blank line if no body */
2172 static void add_blank(struct sip_request *req)
2173 {
2174         if (!req->lines) {
2175                 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
2176                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2177                 req->len += strlen(req->data + req->len);
2178         }
2179 }
2180
2181 /*! \brief Transmit response on SIP request*/
2182 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2183 {
2184         int res;
2185
2186         add_blank(req);
2187         if (sip_debug_test_pvt(p)) {
2188                 const struct sockaddr_in *dst = sip_real_dst(p);
2189
2190                 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
2191                         reliable ? "Reliably " : "", sip_nat_mode(p),
2192                         ast_inet_ntoa(dst->sin_addr),
2193                         ntohs(dst->sin_port), req->data);
2194         }
2195         if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2196                 struct sip_request tmp;
2197                 parse_copy(&tmp, req);
2198                 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), 
2199                         (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
2200         }
2201         res = (reliable) ?
2202                 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
2203                 __sip_xmit(p, req->data, req->len);
2204         if (res > 0)
2205                 return 0;
2206         return res;
2207 }
2208
2209 /*! \brief Send SIP Request to the other part of the dialogue */
2210 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
2211 {
2212         int res;
2213
2214         add_blank(req);
2215         if (sip_debug_test_pvt(p)) {
2216                 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
2217                         ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
2218                 else
2219                         ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
2220         }
2221         if (!ast_test_flag(&p->flags[0], SIP_NO_HISTORY)) {
2222                 struct sip_request tmp;
2223                 parse_copy(&tmp, req);
2224                 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
2225         }
2226         res = (reliable) ?
2227                 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
2228                 __sip_xmit(p, req->data, req->len);
2229         return res;
2230 }
2231
2232 /*! \brief Locate closing quote in a string, skipping escaped quotes.
2233  * optionally with a limit on the search.
2234  * start must be past the first quote.
2235  */
2236 static const char *find_closing_quote(const char *start, const char *lim)
2237 {
2238         char last_char = '\0';
2239         const char *s;
2240         for (s = start; *s && s != lim; last_char = *s++) {
2241                 if (*s == '"' && last_char != '\\')
2242                         break;
2243         }
2244         return s;
2245 }
2246
2247 /*! \brief Pick out text in brackets from character string
2248         \return pointer to terminated stripped string
2249         \param tmp input string that will be modified
2250         Examples:
2251
2252         "foo" <bar>     valid input, returns bar
2253         foo             returns the whole string
2254         < "foo ... >    returns the string between brackets
2255         < "foo...       bogus (missing closing bracket), returns the whole string
2256                         XXX maybe should still skip the opening bracket
2257  */
2258 static char *get_in_brackets(char *tmp)
2259 {
2260         const char *parse = tmp;
2261         char *first_bracket;
2262
2263         /*
2264          * Skip any quoted text until we find the part in brackets.
2265          * On any error give up and return the full string.
2266          */
2267         while ( (first_bracket = strchr(parse, '<')) ) {
2268                 char *first_quote = strchr(parse, '"');
2269
2270                 if (!first_quote || first_quote > first_bracket)
2271                         break; /* no need to look at quoted part */
2272                 /* the bracket is within quotes, so ignore it */
2273                 parse = find_closing_quote(first_quote + 1, NULL);
2274                 if (!*parse) { /* not found, return full string ? */
2275                         /* XXX or be robust and return in-bracket part ? */
2276                         ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
2277                         break;
2278                 }
2279                 parse++;
2280         }
2281         if (first_bracket) {
2282                 char *second_bracket = strchr(first_bracket + 1, '>');
2283                 if (second_bracket) {
2284                         *second_bracket = '\0';
2285                         tmp = first_bracket + 1;
2286                 } else {
2287                         ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
2288                 }
2289         }
2290         return tmp;
2291 }
2292
2293 /*!
2294  * parses a URI in its components.
2295  * If scheme is specified, drop it from the top.
2296  * If a component is not requested, do not split around it.
2297  * This means that if we don't have domain, we cannot split
2298  * name:pass and domain:port.
2299  * It is safe to call with ret_name, pass, domain, port
2300  * pointing all to the same place.
2301  * Init pointers to empty string so we never get NULL dereferencing.
2302  * Overwrites the string.
2303  * return 0 on success, other values on error.
2304  */
2305 static int parse_uri(char *uri, char *scheme,
2306         char **ret_name, char **pass, char **domain, char **port, char **options)
2307 {
2308         char *name = NULL;
2309         int error = 0;
2310
2311         /* init field as required */
2312         if (pass)
2313                 *pass = "";
2314         if (port)
2315                 *port = "";
2316         name = strsep(&uri, ";");       /* remove options */
2317         if (scheme) {
2318                 int l = strlen(scheme);
2319                 if (!strncmp(name, scheme, l))
2320                         name += l;
2321                 else {
2322                         ast_log(LOG_NOTICE, "Missing scheme '%s' in '%s'\n", scheme, name);
2323                         error = -1;
2324                 }
2325         }
2326         if (!domain) {
2327                 /* if we don't want to split around domain, keep everything as a name,
2328                  * so we need to do nothing here, except remember why.
2329                  */
2330         } else {
2331                 /* store the result in a temp. variable to avoid it being
2332                  * overwritten if arguments point to the same place.
2333                  */
2334                 char *c, *dom = "";
2335
2336                 if ((c = strchr(name, '@')) == NULL) {
2337                         /* domain-only URI, according to the SIP RFC. */
2338                         dom = name;
2339                         name = "";
2340                 } else {
2341                         *c++ = '\0';
2342                         dom = c;
2343                 }
2344                 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
2345                         *c++ = '\0';
2346                         *port = c;
2347                 }
2348                 if (pass && (c = strchr(name, ':'))) {  /* user:password */
2349                         *c++ = '\0';
2350                         *pass = c;
2351                 }
2352                 *domain = dom;
2353         }
2354         if (ret_name)   /* same as for domain, store the result only at the end */
2355                 *ret_name = name;
2356         if (options)
2357                 *options = uri ? uri : "";
2358
2359         return error;
2360 }
2361
2362 /*! \brief Send SIP MESSAGE text within a call
2363         Called from PBX core sendtext() application */
2364 static int sip_sendtext(struct ast_channel *ast, const char *text)
2365 {
2366         struct sip_pvt *p = ast->tech_pvt;
2367         int debug = sip_debug_test_pvt(p);
2368
2369         if (debug)
2370                 ast_verbose("Sending text %s on %s\n", text, ast->name);
2371         if (!p)
2372                 return -1;
2373         if (ast_strlen_zero(text))
2374                 return 0;
2375         if (debug)
2376                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
2377         transmit_message_with_text(p, text);
2378         return 0;       
2379 }
2380
2381 /*! \brief Update peer object in realtime storage 
2382         If the Asterisk system name is set in asterisk.conf, we will use
2383         that name and store that in the "regserver" field in the sippeers
2384         table to facilitate multi-server setups.
2385 */
2386 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
2387 {
2388         char port[10];
2389         char ipaddr[INET_ADDRSTRLEN];
2390         char regseconds[20];
2391
2392         char *sysname = ast_config_AST_SYSTEM_NAME;
2393         char *syslabel = NULL;
2394
2395         time_t nowtime = time(NULL) + expirey;
2396         const char *fc = fullcontact ? "fullcontact" : NULL;
2397         
2398         snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);   /* Expiration time */
2399         ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2400         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2401         
2402         if (ast_strlen_zero(sysname))   /* No system name, disable this */
2403                 sysname = NULL;
2404         else if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTSAVE_SYSNAME))
2405                 syslabel = "regserver";
2406
2407         if (fc)
2408                 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2409                         "port", port, "regseconds", regseconds,
2410                         "username", username, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
2411         else
2412                 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr,
2413                         "port", port, "regseconds", regseconds,
2414                         "username", username, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
2415 }
2416
2417 /*! \brief Automatically add peer extension to dial plan */
2418 static void register_peer_exten(struct sip_peer *peer, int onoff)
2419 {
2420         char multi[256];
2421         char *stringp, *ext, *context;
2422
2423         /* XXX note that global_regcontext is both a global 'enable' flag and
2424          * the name of the global regexten context, if not specified
2425          * individually.
2426          */
2427         if (ast_strlen_zero(global_regcontext))
2428                 return;
2429
2430         ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
2431         stringp = multi;
2432         while ((ext = strsep(&stringp, "&"))) {
2433                 if ((context = strchr(ext, '@'))) {
2434                         *context++ = '\0';      /* split ext@context */
2435                         if (!ast_context_find(context)) {
2436                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
2437                                 continue;
2438                         }
2439                 } else {
2440                         context = global_regcontext;
2441                 }
2442                 if (onoff)
2443                         ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2444                                  ast_strdup(peer->name), ast_free, "SIP");
2445                 else
2446                         ast_context_remove_extension(context, ext, 1, NULL);
2447         }
2448 }
2449
2450 /*! \brief Destroy peer object from memory */
2451 static void sip_destroy_peer(struct sip_peer *peer)
2452 {
2453         if (option_debug > 2)
2454                 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
2455
2456         /* Delete it, it needs to disappear */
2457         if (peer->call)
2458                 sip_destroy(peer->call);
2459
2460         if (peer->mwipvt)       /* We have an active subscription, delete it */
2461                 sip_destroy(peer->mwipvt);
2462
2463         if (peer->chanvars) {
2464                 ast_variables_destroy(peer->chanvars);
2465                 peer->chanvars = NULL;
2466         }
2467         if (peer->expire > -1)
2468                 ast_sched_del(sched, peer->expire);
2469
2470         if (peer->pokeexpire > -1)
2471                 ast_sched_del(sched, peer->pokeexpire);
2472         register_peer_exten(peer, FALSE);
2473         ast_free_ha(peer->ha);
2474         if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
2475                 apeerobjs--;
2476         else if (ast_test_flag(&peer->flags[0], SIP_REALTIME)) {
2477                 rpeerobjs--;
2478                 if (option_debug > 2)
2479                         ast_log(LOG_DEBUG,"-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
2480         } else
2481                 speerobjs--;
2482         clear_realm_authentication(peer->auth);
2483         peer->auth = NULL;
2484         if (peer->dnsmgr)
2485                 ast_dnsmgr_release(peer->dnsmgr);
2486         free(peer);
2487 }
2488
2489 /*! \brief Update peer data in database (if used) */
2490 static void update_peer(struct sip_peer *p, int expiry)
2491 {
2492         int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2493         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
2494             (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
2495                 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
2496         }
2497 }
2498
2499
2500 /*! \brief  realtime_peer: Get peer from realtime storage
2501  * Checks the "sippeers" realtime family from extconfig.conf 
2502  * \todo Consider adding check of port address when matching here to follow the same
2503  *      algorithm as for static peers. Will we break anything by adding that?
2504 */
2505 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin)
2506 {
2507         struct sip_peer *peer;
2508         struct ast_variable *var = NULL;
2509         struct ast_variable *tmp;
2510         char ipaddr[INET_ADDRSTRLEN];
2511
2512         /* First check on peer name */
2513         if (newpeername) 
2514                 var = ast_load_realtime("sippeers", "name", newpeername, NULL);
2515         else if (sin) { /* Then check on IP address for dynamic peers */
2516                 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
2517                 var = ast_load_realtime("sippeers", "host", ipaddr, NULL);      /* First check for fixed IP hosts */
2518                 if (!var)
2519                         var = ast_load_realtime("sippeers", "ipaddr", ipaddr, NULL);    /* Then check for registred hosts */
2520         }
2521
2522         if (!var)
2523                 return NULL;
2524
2525         for (tmp = var; tmp; tmp = tmp->next) {
2526                 /* If this is type=user, then skip this object. */
2527                 if (!strcasecmp(tmp->name, "type") &&
2528                     !strcasecmp(tmp->value, "user")) {
2529                         ast_variables_destroy(var);
2530                         return NULL;
2531                 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
2532                         newpeername = tmp->value;
2533                 }
2534         }
2535         
2536         if (!newpeername) {     /* Did not find peer in realtime */
2537                 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
2538                 ast_variables_destroy(var);
2539                 return NULL;
2540         }
2541
2542
2543         /* Peer found in realtime, now build it in memory */
2544         peer = build_peer(newpeername, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2545         if (!peer) {
2546                 ast_variables_destroy(var);
2547                 return NULL;
2548         }
2549
2550         if (option_debug > 2)
2551                 ast_log(LOG_DEBUG,"-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
2552
2553         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2554                 /* Cache peer */
2555                 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
2556                 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
2557                         if (peer->expire > -1) {
2558                                 ast_sched_del(sched, peer->expire);
2559                         }
2560                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
2561                 }
2562                 ASTOBJ_CONTAINER_LINK(&peerl,peer);
2563         } else {
2564                 ast_set_flag(&peer->flags[0], SIP_REALTIME);
2565         }
2566         ast_variables_destroy(var);
2567
2568         return peer;
2569 }
2570
2571 /*! \brief Support routine for find_peer */
2572 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
2573 {
2574         /* We know name is the first field, so we can cast */
2575         struct sip_peer *p = (struct sip_peer *) name;
2576         return  !(!inaddrcmp(&p->addr, sin) || 
2577                                         (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
2578                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
2579 }
2580
2581 /*! \brief Locate peer by name or ip address 
2582  *      This is used on incoming SIP message to find matching peer on ip
2583         or outgoing message to find matching peer on name */
2584 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
2585 {
2586         struct sip_peer *p = NULL;
2587
2588         if (peer)
2589                 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
2590         else
2591                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
2592
2593         if (!p && realtime)
2594                 p = realtime_peer(peer, sin);
2595
2596         return p;
2597 }
2598
2599 /*! \brief Remove user object from in-memory storage */
2600 static void sip_destroy_user(struct sip_user *user)
2601 {
2602         if (option_debug > 2)
2603                 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
2604         ast_free_ha(user->ha);
2605         if (user->chanvars) {
2606                 ast_variables_destroy(user->chanvars);
2607                 user->chanvars = NULL;
2608         }
2609         if (ast_test_flag(&user->flags[0], SIP_REALTIME))
2610                 ruserobjs--;
2611         else
2612                 suserobjs--;
2613         free(user);
2614 }
2615
2616 /*! \brief Load user from realtime storage
2617  * Loads user from "sipusers" category in realtime (extconfig.conf)
2618  * Users are matched on From: user name (the domain in skipped) */
2619 static struct sip_user *realtime_user(const char *username)
2620 {
2621         struct ast_variable *var;
2622         struct ast_variable *tmp;
2623         struct sip_user *user = NULL;
2624
2625         var = ast_load_realtime("sipusers", "name", username, NULL);
2626
2627         if (!var)
2628                 return NULL;
2629
2630         for (tmp = var; tmp; tmp = tmp->next) {
2631                 if (!strcasecmp(tmp->name, "type") &&
2632                         !strcasecmp(tmp->value, "peer")) {
2633                         ast_variables_destroy(var);
2634                         return NULL;
2635                 }
2636         }
2637
2638         user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
2639         
2640         if (!user) {    /* No user found */
2641                 ast_variables_destroy(var);
2642                 return NULL;
2643         }
2644
2645         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
2646                 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
2647                 suserobjs++;
2648                 ASTOBJ_CONTAINER_LINK(&userl,user);
2649         } else {
2650                 /* Move counter from s to r... */
2651                 suserobjs--;
2652                 ruserobjs++;
2653                 ast_set_flag(&user->flags[0], SIP_REALTIME);
2654         }
2655         ast_variables_destroy(var);
2656         return user;
2657 }
2658
2659 /*! \brief Locate user by name 
2660  * Locates user by name (From: sip uri user name part) first
2661  * from in-memory list (static configuration) then from 
2662  * realtime storage (defined in extconfig.conf) */
2663 static struct sip_user *find_user(const char *name, int realtime)
2664 {
2665         struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
2666         if (!u && realtime)
2667                 u = realtime_user(name);
2668         return u;
2669 }
2670
2671 /*! \brief Set nat mode on the various data sockets */
2672 static void do_setnat(struct sip_pvt *p, int natflags)
2673 {
2674         const char *mode = natflags ? "On" : "Off";
2675
2676         if (p->rtp) {
2677                 if (option_debug)
2678                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %s\n", mode);
2679                 ast_rtp_setnat(p->rtp, natflags);
2680         }
2681         if (p->vrtp) {
2682                 if (option_debug)
2683                         ast_log(LOG_DEBUG, "Setting NAT on VRTP to %s\n", mode);
2684                 ast_rtp_setnat(p->vrtp, natflags);
2685         }
2686         if (p->udptl) {
2687                 if (option_debug)
2688                         ast_log(LOG_DEBUG, "Setting NAT on UDPTL to %s\n", mode);
2689                 ast_udptl_setnat(p->udptl, natflags);
2690         }
2691 }
2692
2693 /*! \brief Create address structure from peer reference.
2694  *  return -1 on error, 0 on success.
2695  */
2696 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
2697 {
2698         if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
2699             (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
2700                 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
2701                 dialog->recv = dialog->sa;
2702         } else 
2703                 return -1;
2704
2705         ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
2706         ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
2707         dialog->capability = peer->capability;
2708         if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
2709                 ast_rtp_destroy(dialog->vrtp);
2710                 dialog->vrtp = NULL;
2711         }
2712         dialog->prefs = peer->prefs;
2713         if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
2714                 dialog->t38.capability = global_t38_capability;
2715                 if (dialog->udptl) {
2716                         if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_FEC )
2717                                 dialog->t38.capability |= T38FAX_UDP_EC_FEC;
2718                         else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_REDUNDANCY )
2719                                 dialog->t38.capability |= T38FAX_UDP_EC_REDUNDANCY;
2720                         else if (ast_udptl_get_error_correction_scheme(dialog->udptl) == UDPTL_ERROR_CORRECTION_NONE )
2721                                 dialog->t38.capability |= T38FAX_UDP_EC_NONE;
2722                         dialog->t38.capability |= T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF;
2723                         if (option_debug > 1)
2724                                 ast_log(LOG_DEBUG,"Our T38 capability (%d)\n", dialog->t38.capability);
2725                 }
2726                 dialog->t38.jointcapability = dialog->t38.capability;
2727         } else if (dialog->udptl) {
2728                 ast_udptl_destroy(dialog->udptl);
2729                 dialog->udptl = NULL;
2730         }
2731         do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE );
2732
2733         if (dialog->rtp) {
2734                 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) != SIP_DTMF_INFO);
2735                 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
2736                 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
2737                 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
2738                 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
2739                 /* Set Frame packetization */
2740                 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
2741                 dialog->autoframing = peer->autoframing;
2742         }
2743         if (dialog->vrtp) {
2744                 ast_rtp_setdtmf(dialog->vrtp, 0);
2745                 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
2746                 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
2747                 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
2748                 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
2749         }
2750
2751         ast_string_field_set(dialog, peername, peer->username);
2752         ast_string_field_set(dialog, authname, peer->username);
2753         ast_string_field_set(dialog, username, peer->username);
2754         ast_string_field_set(dialog, peersecret, peer->secret);
2755         ast_string_field_set(dialog, peermd5secret, peer->md5secret);
2756         ast_string_field_set(dialog, tohost, peer->tohost);
2757         ast_string_field_set(dialog, fullcontact, peer->fullcontact);
2758         if (!dialog->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
2759                 char *tmpcall;
2760                 char *c;
2761                 tmpcall = ast_strdupa(dialog->callid);
2762                 c = strchr(tmpcall, '@');
2763                 if (c) {
2764                         *c = '\0';
2765                         ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
2766                 }
2767         }
2768         if (ast_strlen_zero(dialog->tohost))
2769                 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
2770         if (!ast_strlen_zero(peer->fromdomain))
2771                 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
2772         if (!ast_strlen_zero(peer->fromuser))
2773                 ast_string_field_set(dialog, fromuser, peer->fromuser);
2774         dialog->callgroup = peer->callgroup;
2775         dialog->pickupgroup = peer->pickupgroup;
2776         dialog->allowtransfer = peer->allowtransfer;
2777         /* Set timer T1 to RTT for this peer (if known by qualify=) */
2778         /* Minimum is settable or default to 100 ms */
2779         if (peer->maxms && peer->lastms)
2780                 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2781         if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2782             (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2783                 dialog->noncodeccapability |= AST_RTP_DTMF;
2784         else
2785                 dialog->noncodeccapability &= ~AST_RTP_DTMF;
2786         ast_string_field_set(dialog, context, peer->context);
2787         dialog->rtptimeout = peer->rtptimeout;
2788         if (peer->call_limit)
2789                 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
2790         dialog->maxcallbitrate = peer->maxcallbitrate;
2791         
2792         return 0;
2793 }
2794
2795 /*! \brief create address structure from peer name
2796  *      Or, if peer not found, find it in the global DNS 
2797  *      returns TRUE (-1) on failure, FALSE on success */
2798 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2799 {
2800         struct hostent *hp;
2801         struct ast_hostent ahp;
2802         struct sip_peer *peer;
2803         char *port;
2804         int portno;
2805         char host[MAXHOSTNAMELEN], *hostn;
2806         char peername[256];
2807
2808         ast_copy_string(peername, opeer, sizeof(peername));
2809         port = strchr(peername, ':');
2810         if (port)
2811                 *port++ = '\0';
2812         dialog->sa.sin_family = AF_INET;
2813         dialog->timer_t1 = SIP_TIMER_T1; /* Default SIP retransmission timer T1 (RFC 3261) */
2814         peer = find_peer(peername, NULL, 1);
2815
2816         if (peer) {
2817                 int res = create_addr_from_peer(dialog, peer);
2818                 unref_peer(peer);
2819                 return res;
2820         }
2821         hostn = peername;
2822         portno = port ? atoi(port) : STANDARD_SIP_PORT;
2823         if (global_srvlookup) {
2824                 char service[MAXHOSTNAMELEN];
2825                 int tportno;
2826                 int ret;
2827
2828                 snprintf(service, sizeof(service), "_sip._udp.%s", peername);
2829                 ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2830                 if (ret > 0) {
2831                         hostn = host;
2832                         portno = tportno;
2833                 }
2834         }
2835         hp = ast_gethostbyname(hostn, &ahp);
2836         if (!hp) {
2837                 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2838                 return -1;
2839         }
2840         ast_string_field_set(dialog, tohost, peername);
2841         memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2842         dialog->sa.sin_port = htons(portno);
2843         dialog->recv = dialog->sa;
2844         return 0;
2845 }
2846
2847 /*! \brief Scheduled congestion on a call */
2848 static int auto_congest(void *nothing)
2849 {
2850         struct sip_pvt *p = nothing;
2851
2852         sip_pvt_lock(p);
2853         p->initid = -1;
2854         if (p->owner) {
2855                 /* XXX fails on possible deadlock */
2856                 if (!ast_channel_trylock(p->owner)) {
2857                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2858                         append_history(p, "Cong", "Auto-congesting (timer)");
2859                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2860                         ast_channel_unlock(p->owner);
2861                 }
2862         }
2863         sip_pvt_unlock(p);
2864         return 0;
2865 }
2866
2867
2868 /*! \brief Initiate SIP call from PBX 
2869  *      used from the dial() application      */
2870 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2871 {
2872         int res;
2873         struct sip_pvt *p;
2874         struct varshead *headp;
2875         struct ast_var_t *current;
2876         const char *referer = NULL;   /* SIP referrer */        
2877
2878         p = ast->tech_pvt;
2879         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2880                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2881                 return -1;
2882         }
2883
2884         /* Check whether there is vxml_url, distinctive ring variables */
2885         headp=&ast->varshead;
2886         AST_LIST_TRAVERSE(headp,current,entries) {
2887                 /* Check whether there is a VXML_URL variable */
2888                 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2889                         p->options->vxml_url = ast_var_value(current);
2890                 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2891                         p->options->uri_options = ast_var_value(current);
2892                 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2893                         /* Check whether there is a variable with a name starting with SIPADDHEADER */
2894                         p->options->addsipheaders = 1;
2895                 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
2896                         /* This is a transfered call */
2897                         p->options->transfer = 1;
2898                 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
2899                         /* This is the referrer */
2900                         referer = ast_var_value(current);
2901                 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
2902                         /* We're replacing a call. */
2903                         p->options->replaces = ast_var_value(current);
2904                 } else if (!strcasecmp(ast_var_name(current), "T38CALL")) {
2905                         p->t38.state = T38_LOCAL_DIRECT;
2906                         if (option_debug)
2907                                 ast_log(LOG_DEBUG,"T38State change to %d on channel %s\n", p->t38.state, ast->name);
2908                 }
2909
2910         }
2911         
2912         res = 0;
2913         ast_set_flag(&p->flags[0], SIP_OUTGOING);
2914
2915         if (p->options->transfer) {
2916                 char buf[BUFSIZ/2];
2917
2918                 if (referer) {
2919                         if (sipdebug && option_debug > 2)
2920                                 ast_log(LOG_DEBUG, "Call for %s transfered by %s\n", p->username, referer);
2921                         snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
2922                 } else 
2923                         snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
2924                 ast_string_field_set(p, cid_name, buf);
2925         } 
2926         if (option_debug)
2927                 ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2928
2929         res = update_call_counter(p, INC_CALL_RINGING);
2930
2931         if (res == -1)
2932                 return res;
2933
2934         p->callingpres = ast->cid.cid_pres;
2935         p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
2936         
2937         /* If there are no audio formats left to offer, punt */
2938         if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
2939                 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
2940                 res = -1;
2941         } else {
2942                 p->t38.jointcapability = p->t38.capability;
2943                 if (option_debug > 1)
2944                         ast_log(LOG_DEBUG,"Our T38 capability (%d), joint T38 capability (%d)\n", p->t38.capability, p->t38.jointcapability);
2945                 transmit_invite(p, SIP_INVITE, 1, 2);
2946                 p->invitestate = INV_CALLING;
2947                 
2948                 /* Initialize auto-congest time */
2949                 p->initid = ast_sched_add(sched, SIP_TRANS_TIMEOUT, auto_congest, p);
2950         }
2951
2952         return res;
2953 }
2954
2955 /*! \brief Destroy registry object
2956         Objects created with the register= statement in static configuration */
2957 static void sip_registry_destroy(struct sip_registry *reg)
2958 {
2959         /* Really delete */
2960         if (option_debug > 2)
2961                 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2962
2963         if (reg->call) {
2964                 /* Clear registry before destroying to ensure
2965                    we don't get reentered trying to grab the registry lock */
2966                 reg->call->registry = NULL;
2967                 if (option_debug > 2)
2968                         ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2969                 sip_destroy(reg->call);
2970         }
2971         if (reg->expire > -1)
2972                 ast_sched_del(sched, reg->expire);
2973         if (reg->timeout > -1)
2974                 ast_sched_del(sched, reg->timeout);
2975         ast_string_field_free_pools(reg);
2976         regobjs--;
2977         free(reg);
2978         
2979 }
2980
2981 /*! \brief Execute destruction of SIP dialog structure, release memory */
2982 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
2983 {
2984         struct sip_pvt *cur, *prev = NULL;
2985         struct sip_pkt *cp;
2986
2987         if (sip_debug_test_pvt(p) || option_debug > 2)
2988                 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2989
2990         /* Remove link from peer to subscription of MWI */
2991         if (p->relatedpeer && p->relatedpeer->mwipvt) 
2992                 p->relatedpeer->mwipvt = NULL;
2993
2994         if (dumphistory)
2995                 sip_dump_history(p);
2996
2997         if (p->options)
2998                 free(p->options);
2999
3000         if (p->stateid > -1)
3001                 ast_extension_state_del(p->stateid, NULL);
3002         if (p->initid > -1)
3003                 ast_sched_del(sched, p->initid);
3004         if (p->autokillid > -1)
3005                 ast_sched_del(sched, p->autokillid);
3006
3007         if (p->rtp)
3008                 ast_rtp_destroy(p->rtp);
3009         if (p->vrtp)
3010                 ast_rtp_destroy(p->vrtp);
3011         if (p->udptl)
3012                 ast_udptl_destroy(p->udptl);
3013         if (p->refer)
3014                 free(p->refer);
3015         if (p->route) {
3016                 free_old_route(p->route);
3017                 p->route = NULL;
3018         }
3019         if (p->registry) {
3020                 if (p->registry->call == p)
3021                         p->registry->call = NULL;
3022                 unref_registry(p->registry);
3023         }
3024
3025         /* Unlink us from the owner if we have one */
3026         if (p->owner) {
3027                 if (lockowner)
3028                         ast_channel_lock(p->owner);
3029                 if (option_debug)
3030                         ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
3031                 p->owner->tech_pvt = NULL;
3032                 if (lockowner)
3033                         ast_channel_unlock(p->owner);
3034         }
3035         /* Clear history */
3036         if (p->history) {
3037                 struct sip_history *hist;
3038                 while( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) )
3039                         free(hist);
3040                 free(p->history);
3041                 p->history = NULL;
3042         }
3043
3044         /* Lock dialog list before removing ourselves from the list */
3045         if (lockdialoglist)
3046                 dialoglist_lock();
3047         for (prev = NULL, cur = dialoglist; cur; prev = cur, cur = cur->next) {
3048                 if (cur == p) {