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